Visual Studio C# Programming Tips

I assume you already know how to program in C#.

I highly recommend the book Pro C# 2010 and the .Net 4 Platform by Andrew Troelsen. It is still my favorite.

On this page I share some concepts that are very powerful once you understand them. In case you want to learn the basics of C#, visit my other page.

 

IQueryable versus IENumerable

This article explains performance gains when using IQueryable versus IENumerable.

Type casting

Type casting is converting one type to another type. Converting one type into another is not always possible. Type casting can be done in two different ways as shown in below example. Casting by using the brackets notation (...)... leads to an exception when the cast is not possible, while casting by using the ... as ... notation results in a null value as the result when the cast is not possible.

var monkey = (Monkey)animal; var monkey = animal as Monkey;

String concatenation versus StringBuilder

You should be aware when adding text to a certain string by using concatenation like in the example below, that each time some text is added to the string, new memory is allocated and the result is copied to the new memory location. This is not efficient.

string MyStringVariable = String.Empty; MyStringVariable += "This"; MyStringVariable += " is"; MyStringVariable += " it.";

It is better to make use of the StringBuilder, like in the example below:

StringBuilder MyStringBuilder = new StringBuilder(); MyStringBuilder.Append("This"); MyStringBuilder.Append(" is"); MyStringBuilder.Append(" it.");
Especially in loops where a string variable gets longer, for efficiency and performance it is better to make use of StringBuilder, because no copy operation will be done. The String.Format() and String.Join() functions are also alternatives you can use instead, and are maybe better to read or maintain.

The 'using'-statement

The using-statement is commonly used for adding namespaces to your .cs files. It is also a very useful statement when you want to create an object and after using it, automatically dispose of it.

// The following code: using(MyClass MyObject = new MyClass()) { MyObject.DoSomething(); } // Does the same as: MyClass MyObject = new MyClass(); try { MyObject.DoSomething(); } finally { MyObject.Dispose(); }

Throwing exceptions and stack trace

When debugging an application, the stack trace is very useful to find what happened before e.g. an error occurred. Recently, I learned that when throwing an exception in a certain way that stack trace information is lost.

// By throwing an exception like this, the stack trace is lost try { // here is code that can throw an exception } catch (Exception ex) { // exception handling code is here throw ex; } // By throwing an exception like this, no stack trace information is lost try { // here is code that can throw an exception } catch (Exception ex) { // exception handling code is here throw; }

Coding standards and guidelines

To make your sourcecode easier to read and understand, it's always a good idea to use coding standards and guidelines or read these design guidelines for developing class libraries.

Linq

Linqpad is a very useful and free tool (standard edition) for you to help learning the C# language and writing your first LINQ statements. LINQ is short for language interpreted query, it's relatively a new concept for querying a database right in your sourcecode.

When you write a Linq statement, probably you wonder what SQL-statement is sent to the database. This can be examined easily by using the .Log property of your DataContext object. With a StreamWriter you can write the log to a textfile as explained in this article.

Delegates

To learn about delegates, visit this site.

Generics

The generics concept was introduced some time ago in C#. It's a very powerful concept and you should understand how this works. With generics you can make a generic class that makes use of an unknown type. Later on when you use this class and create an instance of this generic class, you'll pass type information.

To learn more about generics watch this video, visit this site or this site.

Threading and background tasks

On the following sites you can read much about threading and background tasks:

http://www.albahari.com/threading/
http://www.hanselman.com/blog/HowToRunBackgroundTasksInASPNET.aspx
http://stackoverflow.com/questions/601558/multithreading-reference

Dependency injection

I'm excited about dependency injection (DI) as it's a relatively new concept that makes it easy to build a loosely coupled software architecture. Once you understand object orientation and design patterns, you should learn more about DI. However, DI is not easy and it takes some time to get it. I wrote the this article about Ninject, a .Net DI-container.

For .Net there the following dependency injection (inversion of control container) frameworks exist: Ninject, Microsoft Unity, Castle Windsor, Spring.Net and Structure Map.

I am also investigating the Delphi Spring framework because for the most part I develop software under Delphi.

Please watch the following video to learn more about dependency injection. On the same site you can also watch a lot of other free Visual Studio training video's.

Also I find Rich Newman's article easy to understand.

Here you can find part 1 and part 2 of a mini Ninject tutorial.

The following book by Mark Seemann is a must read when you're interested in dependency injection and it's completely dedicated to DI under .Net, however the Ninject DI-container is not discussed in detail in this book, while others are.

Lambda's

 

Useful keyboard shortcuts

Recently I learned some very helpful keyboard shortcuts in order to assist writing your code.

In case you want to make a new class it's very easy to do so by writing the name of the new class somewhere in your code where you will be needing an instance of your class, e.g. Person. At the moment you write this Person statment and the class Person is not yet defined, just type Ctrl+. and then Visual Studio displays a little popup allowing you to generate the skeleton for your new class in a separate file. This keyboard combination can also be used when you make use of a class that's not in the list your using statments on top of your sourcefile. After you press Ctrl+. after you typed the unknown class, a pop-up shows the possiblity to add a certain using statement to your code. Of cource the class must be a valid .Net class.

What's also useful are code snippets. When you type: prop (for property) and press the Tab key twice, the skeleton for a new property will be displayed in your sourcecode. By pressing the Tab key again you can navigate in the inserted code.

With the keyboard combination Ctrl+K Ctrl+D you can easily format your sourcecode, so that it's more readable.

 

Solution for Visual Studio problem with find in files

At work I encountered a problem that in Visual Studio 2012 the find or find in files function was not working anymore. This is one of the functions is essential during software development. Just restarting the PC or VS2010 didn't solve the problem. It annoyed me for a couple of days so I had to rely on Agent Ransack (my favorite alternative free find in files tool), until I found a simple solution for it. I just opened the Visual Studio command prompt after closing Visual Studio and typed:

devenv /resetsettings

After restarting Visual Studio the find functionality worked again like I was used to.

 

Creating a login page with ASP.Net MVC 3 (using the Razor view engine)

In case you want to develop websites with Visual Studio, you should investigate about the MVC (model - view - controller) plugin. MVC is actually a design pattern. Combined with the Razor view engine (MVC 3) you can separate data, business logic and presentation very easily and code maintenance is very easy. I followed the Nerddinner tutorial for MVC 1.0 and learned quite a lot from it. MVC 1.0 didn't use the newer Razor view engine, however it's still worth reading this tutorial. There's also a newer tutorial on the Nerddinner site. This site has also good ASP.Net MVC3 introductions and several videos.

Entity framework and Linq can be used to connect your ASP.Net MVC application to a database. Automapper and NHibernate (ORM - object relational mapper) and Micro ORM's: Dapper (simple object mapper for .Net), Massive, PetaPoco, Simple.Data and FluentData are also commonly used.

I watched and enjoyed the following video's on YouTube that explains very clearly how you can build your own login page using MVC. I also made this project on my computer and learned a lot while doing so.

 

MVC and MVC Grids in a webshop

For a general introduction into MVC look here.

Building a webshop: for us performance comes first, then the looks!

At work we're building a webshop which has to be capable of displaying thousands of rows of data. We used Silverlight for the webshop, however our customers were not happy with the performance. Now we're back to Asp.Net and were using a DevExpress grid, and still performance was not good enough (while using paging, 80 rows on a page). We found out the it was not the amount of data that was transferred from the server to the client, but the rendering of the table especially in Internet Explorer was very slow. In Chrome and Firefox the perfomance was a little better.

It seemed to come from the amount of Javascript generated by the DevExpress grid. Especially when we loaded more than 100 rows at a time with an older computer (XP with 256 Mb of RAM). It looked like IE had to make a lot of calculations in order to render the grid properly, CPU was for a long time near 100% for Internet Explorer activity, while the Fiddler webdebugger tool showed that the data was already transferred from the server to the client.

It became clear we had to go yet for another solution, the grid was definitely the bottleneck. After testing with a plain HTML table with fixed size and fixed column width we saw a drastic perfomance improvement. We used an ASPX repeater to construct the table. Also using a plain MVC datagrid showed a much better perfomance compared to the DevExpress grid or the Silverlight solution.

Most important additional requirements of the grid we need is that it must be capable of displaying an image and it must be capable of updating a single row after entering an amount in a certain column.

Next we stumbled upon the wonderful Slickgrid, because we wanted to load the data asynchronously and we were once again very impressed. It's performance is amazing. The way things looks now we are going for the Slickgrid for the webshop we're developing. I encourage you to look at this wonderful grid, it's very impressive. I found out that there's also a jQGrid (a jQuery plugin). According to opinions of several developers the Slickgrid is better than the jQGrid.I know Telerik is also offering a RadGrid that looks promising. For the meantime we'll first figure out whether Slickgrid is satisfying for our customers. Loading of data is asynchronous, which really impacts the speed of displaying the data in the grid: only the rows are retrieved from the database which are displayed (and some extra).

For more information about the Slickgrid, visit its website or developers Q&A on this site. On this page you can see some working examples and see Slickgrid in action.

EJS Treegrid is another Javascript Treegrid that looks interesting and seems to be performing fast. Maybe we'll do an investigation in this grid later on.

The jQuery grid, jQWidgets, Datatables (jQuery plugin), Flexigrid (also for jQuery), MVCControlsToolkit, Syncfusion, Griffin table, jqGrid and Infragistics jQuery controls are yet another ones that we might investigate on later. Someone advised me in case you use Flexigrid then fill it with JSON data. It should also be fast according to him. The MVCControlsToolkit supports complex row templates. I learned from another person that he's very fond of the Infragistics jQuery controls and that these are packed with features and easy to configure.

On this page you'll see a flexigrid sample solution.

Somebody advised me to use the .BinToLINQ() method from the DevExpress GridView. The purpose of this method to get only the information needed from your database to render each page of the grid and using inside it Linq (IQueryable).

SlickGrid seems to be the fastest grid (also according to others), however this probably comes with a price. As I understand now, the grid is not very useful for SEO (search engine optimization) and it also doesn't allow for complex row templates. Speed is obtained at the cost of flexibility. If speed it top priority (and this is the case in at my job), I think you should go for SlickGrid.

Here you can find a Visual Studio 2010 example how you can build a simple MVC application with the SlickGrid. I was able to build and run this application, however I am having a Javascript issue with Internet Explorer 8. Works fine with Firefox or Chrome. After some days I found the cause of the problem of this example with IE8. In the column definition there was one comma too much at the end of the second column definition line. This caused SlickGrid to think that there will be more than two columns, however there are just two columns in the example.

Other sites with C# tips

This Microsoft site contains anything you want to learn about C#. A C# programming guide can be found here.
DotNetUncle contains a lot of frequently asked .Net questions.
http://www.charlespetzold.com/dotnet/index.html
http://channel9.msdn.com/Series/C-Sharp-Fundamentals-Development-for-Absolute-Beginnershttp://www.csharp-examples.net/
http://www.csharp-station.com/Tutorial/CSharp
http://www.c-sharpcorner.com/
http://www.dotnetperls.com/
http://en.wikibooks.org/wiki/C_Sharp_Programming
http://www.homeandlearn.co.uk/csharp/csharp.html
http://jayeshsorathia.blogspot.com/
http://msdn.microsoft.com/en-us/library/kx37x362
http://visualcsharptutorials.com/
https://channel9.msdn.com/VisualStudio

Useful Tools

Automapper (used for copying properties from one object to another - read this article for an introduction)
DPack  is a FREE collection of Microsoft Visual Studio tools. DPack is designed to greatly increase developer's productivity, automate repetitive processes and expand upon some of Microsoft Visual Studio features. I like the numbered bookmarks functionality that allows me to jump to a 'bookmarked' sourceline - simply by pressing Ctrl+1, Ctrl+2, and so on - like I am used to in Delphi. This is much more convenient than using Visual Studio's standard functionality of Ctrl+K+K and Ctrl+K+N that does not allow you to jump to a certain sourcecode line by a single keystroke.
NuGet(package manager for Visual Studio, very useful)
Elmah (error logging, can be installed easily when you have NuGet installed)
Fiddler (web-traffic logger)
Firebug (inspect scripts, sourcecode and CSS from any element on a certain webpage)
FileZilla (ftp)
Moq (mocking library, necessary when you do test driven development TDD)
.Net Reflector (.Net debugging tool)
NUnit (unit testing)
Resharper (code refactoring)
SketchFlow (prototyping)
Ultramon (useful in case you have more than one monitor)
XMind (mind-mapping, brainstorming)
XUnit (unit testing)

 

 

Visual Studio C# Programming Tips • MVC Grids in a webshop