Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts
Scott Allen's 10 favorite C# rules for developing software

Scott Allen's 10 favorite C# rules for developing software


From Scott Allen's C# Fundamentals Part 2 course on Pluralsight -

Rule #10: Avoid Regions - as they are typically used to hide ugly code or classes that've exploded in size or responsibility. Think if you should break the regions into seperate classes
Rule #9: Use exceptions for errors..instead of status code or booleans...but not for control flow
Rule #8: Avoid boolean parameters
Rule #7: Avoid too many parameters - beyond 4, consider grouping
Rule #6: Warnings are errors - Go to a Project's Properties and in the Build tab of the dialog box that opens up, change "Treat warnings as errors" to All from the default None
Rule #5: Encapsulate complex expressions - Instant recognition is good
Rule #4: Try to avoid multiple exits - have just one
Rule #3: Try to avoid comments - A meaningful method name is more effective than comments. Triple slash comments in VS are ok as they help in documentation of an API. Other developers can see your comments through Intellisense when they reference your assembly.
Rule #2: Keep methods short - general rule of thumb: 1 to 10 lines
Rule #1: Keep classes small

+ The foundation for most C# coding standards is Microsoft's "Design Guidelines for Developing Class Libraries"
+ ReSharper VS Plugin & StyleCop can help you enforce naming conventions
+ Names contain meaning & adding meaning to code is what readability is all about - use meanigful names
+ Embedding type in the name of a variable is not a good idea especially for primitive types. Name should indicate what an variable or object can do & what it represents.
+ How to improve readability of your code - read other people's code to figure what is good & what is bad. Be introspective.
Read More
Head First Design Patterns - C# & VB.NET Code Examples

Head First Design Patterns - C# & VB.NET Code Examples

Books in O'Reilly's Head First series are like "For Dummies" books, covering technical topics in an unconventional way. They contain goofy pictures and their content generates extreme reactions - readers love it or hate it. Going by the reviews on Amazon, Head First Design Patterns, a majority of the readers like it. The code samples in the book are in Java. So if you pick the book, be aware that the same samples have been ported to C# & VB.NET by volunteers -


Also see:
Learning resources on Design Patterns for .NET Developers
Opening Questions For A Design Patterns Study Group
Read More
Comparison of Microsoft Data Access Technologies

Comparison of Microsoft Data Access Technologies

Deciding which data access strategy to choose is not always an easy job. Here's a compilation of articles that discuss this topic -
  • This Infosys whitepaper presents a SWOT (Strengths, Weaknesses, Opportunities, Threats) analysis of ADO.NET, LINQ, Entity Framework & WCF Data Services. There is also a comparison of Entity Framework & NHibernate. Excerpt - ADO.NET offers best performance amongst its peers (LINQ to SQL, Entity Framework, WCF Data Services) 
  • C# guru, John Skeet's post in StackOverlow on the pros and cons of LINQ 
(work in progress..)
Read More
HOW TO extract  only specific files from a .ZIP using C#

HOW TO extract only specific files from a .ZIP using C#

"Well, it's better to be silent than to be a fool." - Harper Lee

Online Forums are a great place to learn new tricks.

I learnt today that DotNetZip is an open source class library and toolset for manipulating zip files or folders that's easier to use than the other popular library SharpZipLib. Built by Dino Chiesa, it is hosted on CodePlex and has extensive documentation & samples. It takes just a few lines & the ZipFile.ExtractSelectedEntries Method to filter specific files from a zipped file using a selection criteria expression.

Talking of  open source compression\decompression Libraries, there is yet another Library on SourceForge that has been immensely popular - 7-Zip. The code is available in C++ for whoever wants to tinker. Like 7-Zip, there is a ready to use WinForms sample app based on DotNetZip which can be a free replacement for the commercial WinZip utility.

Rant: At a lot of places in CodePlex, like the Issue Tracker & Reviews sections of a project, the year part is not shown for timestamps of posts. If you are tracking a discussion thread, viewing the date is meaningless without the year. If you feel strongly about this issue with CodePlex like I do, please vote it up so that it gets addressed faster. 

Also see:
Regular Expression to negate non-matching characters
Enclose email attachment as text in the body


200
Read More

Book Review - CSharp for Sharp Kids

Using real-world analogies, Martin Dreyer does a great job of explaining the introductory concepts of C# & OOP to absolute beginners in the free E-Book C# for Sharp Kids. The 2.9 MB MSI file, containing the E-Book in MS Word format & code samples, can be downloaded from the Kid's Corner of MSDN's Beginner Developer Learning Center. The code samples are expected to run with Visual C# 2005 Express Edition but you can get it to work on a newer version of the Express Edition as well.

Although this text is targeted at young developers (aged between 12-16), it is equally good for folks of any age wanting to learn about programming with C#. Spread across 5 parts & about 165 pages, it is light-hearted & filled with meaningful cartoons. Here are a couple of samples -





Once readers finish the book, they will be able to build simple Console & Windows applications. It will also whet their appetite to know more about C#.

I highly recommend this book to those starting to learn programming with C#. What's more, it's free as well.
90
Read More
"Export to Excel" without using components in a WinForms app

"Export to Excel" without using components in a WinForms app

Way back in 2004, I wrote a program to generate a Word file dynamically without using any components in a Web application. The technique I used makes use of the fact that documents can be converted from Word/Excel to HTML (File->Save As) and vice versa.  When you manually save an Office document as a Web page, you can see from its source that it renders some interesting HTML, CSS & Office XML. By understanding and emulating this conversion technique programmatically, we can generate Word or Excel documents through web pages.

This snippet shows how you can generate a report in Excel format in a web application after fetching data from a data source using the Office XML technique -

System.Data.DataTable workTable = new System.Data.DataTable();

//The tablename specified here will be set as the worksheet name of the generated Excel file.
workTable.TableName = "Customers";
workTable.Columns.Add("Id");
workTable.Columns.Add("Name");
System.Data.DataRow workRow;

for (int i = 0; i <= 9; i++)
{
workRow = workTable.NewRow();
workRow[0] = i;
workRow[1] = "CustName" + i.ToString();
workTable.Rows.Add(workRow);
}

string strBody = DataTable2ExcelString(workTable);

Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
Response.AppendHeader("Content-disposition", "attachment; filename=my.xls");
Response.Write(strBody);


A complete working sample & a detailed explanation of the code are available.

A developer wanted to know how this method of converting a datatable to Excel can be adapted for a Windows Forms application.

The trick to generating the Excel file in a web application involves creating a HTML page containing some special CSS & Office XML and triggering a file download with the help of the following Response.AppendHeader statements -
Response.AppendHeader("Content-Type", "application/vnd.ms-excel");
Response.AppendHeader("Content-disposition", "attachment; filename=my.xls");


To use this technique in a Winforms application, the string content representing the HTML page (containing the special CSS & Office XML) needs to be saved as a text file and the file should be given an extension of ".xls". The last 3 lines in the snippet above which are irrelevant in a WinForms app  can be replaced with this line -
System.IO.File.WriteAllText(@"C:\Report.xls", strBody);

Also see:
HOW TO send an email with a Word or Excel file attachment built on the fly
60
Read More
The Beauty of Command-line Utilities

The Beauty of Command-line Utilities

I like the way command-line tools can be adapted for automating complex tasks.

For instance, if you had to populate the list of names of computers in your LAN in a combo box, the net.exe command can be utilized with the Process.Start() method in C#

Process netsend = new Process();
netsend.StartInfo.FileName = "net.exe";
netsend.StartInfo.CreateNoWindow = true;
netsend.StartInfo.Arguments = "view";
netsend.StartInfo.RedirectStandardOutput = true;
netsend.StartInfo.UseShellExecute = false;
netsend.StartInfo.RedirectStandardError = true;
netsend.Start();

StreamReader sr = new StreamReader(netsend.StandardOutput.BaseStream, netsend.StandardOutput.CurrentEncoding);

string sss = "";
while ((sss = sr.ReadLine()) != null)
{
if (sss.StartsWith("\\"))
comboBox1.Items.Add(sss.Substring(2).Substring(0, sss.Substring(2).IndexOf(" ")).ToUpper();
}

sr.Close();

Setting the CreateNoWindow property to true hides the console window.

Here is a list of command-line tools that I've found helpful (work in progress) -
Dear Reader, what are your favorite command-line tools?
Read More
Regular Expression to negate non-matching characters

Regular Expression to negate non-matching characters

While constructing a regular expression pattern, sometimes it may be easier to write a pattern that negates the non-matching characters (did I just write a double negative?) rather than write a more complex pattern to pick matching characters. Let's say you want to ignore a word that has vowels.

The following pattern will match any single character NOT in the specified set of characters.
[^aeiou]

There is some nice info on Character Classes on MSDN.

[^character_group] represents a Negative character group. It matches any character not in the specified character group

Now we want the pattern to match not just a single character but a complete word so we use the + to indicate there are multiple characters. The ^ sign represents start of a string and $ denotes end of a string, so our final pattern to ignore a whole word that has vowels becomes this -
^[^aeiou]+$

Regular expressions can drastically replace several lines of validation code. However we need to test our pattern aggressively to avoid among other things, false positives.

Over the years, the RegExLib.com's Regular Expression Cheat Sheet has been a good reference for me.

Also see: Book Review: Teach Yourself Regular Expressions in 10 Minutes
Read More