This Blog Has A New Home!

This blog has been moved to www.SoftwareRockstar.com. Articles already here will remain intact, while new content will only be added to the new location at www.SoftwareRockstar.com.

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Saturday, March 14, 2009

Learn APS.NET MVC

ScottGu  just made available a free downloadable eBook in PDF format as well as a simple and easy-to-understand sample project called Nerddinner.  This eBook is actually a chapter from his upcoming book on MVC, but it is an end-to-end tutorial that walks through building a small but complete ASP.NET MVC application from scratch.

Download eBook.

Download Nerddinner sample code.

Thursday, March 12, 2009

C# 3.0 Automatic Properties

OK, so better later than never! Somehow I missed the automatic properties feature of C# 3.0, and just discovered it while I was reading up on something unrelated. It’s a nice feature of C# 3.0 that saves you a few key strokes hence enhances developer productivity as well as allows for more clear and concise code.

Using this new feature, instead of defining private variables and creating explicit getters and setters, you can create properties like this:

Wednesday, March 11, 2009

Free Visual Studio 2008 Productivity Add-in

Developer Express and Microsoft provide a new version of CodeRush licensed exclusively for C# developers working in Visual Studio. The new product is called CodeRush Xpress, and it includes a slew of useful features to boost your productivity under Visual Studio.

You can download CodeRush Xpress here.

Friday, August 17, 2007

The Castle Project

In the last couple of years I have noticed a steadily growing interest in the .NET community around the Inversion of Control (IoC) and Dependency Injection (DI) patterns.  This is partly due to the fact that a number of excellent frameworks have emerged and gained popularity that allow us to use these designs in our applications relatively painlessly.  One such framework is the open source Castle Project.  In my opinion Castle is the best implementation of IoC and DI among many others that I have come across including Spring.NET, NInject, and ObjectBuilder.  This is however my opinion; which framework you use largely depends upon your requirements and your preferences.

If you are just getting started with Castle or are curious about why the heck one should use IoC and DI, I strongly suggest you check out the 3-part article series by Simone Busoli.  I just came across these articles and I can't stress enough how well they are written.

Wednesday, April 18, 2007

SQL Server Database Comparison and Synchronization

Since database are usually designed in development environments, migrating changes over to other environments (e.g. QA and production) is not a trivial task.  This is because SQL Server does not have any built-in tools to compare database schemas. 

There are quite a few third-party tools that would make your life easier, most notably, Red Gate's SQL Compare (reasonably priced around $300).

At times, buying a commercial tool is not really an option, so one must resort to googling for free tools.  There are three such tools that I am aware of:

  1. SQLDBDiff by SQLDBTools
    A very decent tool that comes in both freeware and shareware versions.  Freeware version is not badly crippled; only advanced features such as multi-database comparison, data content comparison, etc. are disabled.

  2. Database Schema Comparison Utility
    This is a Code Project article that comes with C# source code of a schema comparison utility.  The utility itself is pretty bare-bone, but gets the job done.

  3. StarInix Free Database Compare 2.0
    I have not used this tool, but from the advertised feature list, it looks pretty good.  Most notably, in addition to SQL Server, this tool works with Access and MySQL databases.

Tuesday, February 06, 2007

JScript Eval Method In C#

JavaScript and JScript languages provide a convenient Eval method that allows for dynamic evaluation of expressions. This functionality can be duplicated in C# using Microsoft's JScript CodeDomProvider and Reflection. Following class automatically compiles an in-memory assembly using JScript CodeDomProvider. The Eval method uses this assembly to dynamically evaluate specified expressions:

Using this class, we can execute statements such as:

Sunday, December 10, 2006

Using IXmlSerializable To Overcome "not expected" Error On Derived Classes

This article extends upon Simon Hewitt's article on CodeProject. It is strongly recommended that you read Simon's article also in order to fully understand the concepts. BACKGROUND XML serialization is an indispensable technique that has built-in support for in the .NET Framework. Using XML serialization, objects can be serialized to XML streams that may be persisted to permanent storage such as files, as well as XML streams can be converted back to objects with exactly the same state as at the time of serialization. With .NET Framework's built-in support for XML serialization, all this can be achieved with only a few lines of code using the System.Xml.Serialization.XmlSerializer object. PROBLEM The problem with XmlSerializer is, however, that it works by generating an on-the-fly assembly behind the scenes at compilation time, that has logic for serialization and deserialization of a given type. For this reason, the exact (concrete) type of the object and it's public properties must be known to the compiler at the time of compilation. If we try to serialize an object that, for example, has a public member of a given base type, then at run-time we receive a System.InvalidOperationException if the public member was set to a derived type. WORKAROUND The workaround to above problem has generally been resorting to custom XML serialization, which can get pretty complicated at times. SOLUTION An ingenious solutions was discovered by Simon Hewitt using the System.Xml.Serialization.IXmlSerializable interface that allows us to mitigate the by-design issue of XmlSerializer object. While this solution works very well, it requires that a new class be created for each base class that we need serialization support for. Using C# generics, I took the liberty of extending Simon's solution, eliminating the need for such new classes, and encapsulating the grunt work into just one class. Once this class has been added to our project (our referenced from another assembly), all we really need to do is decorate any of our public members of base type (that may be substituted with derived types at runtime) with an attribute. Once the above class has been added to our project, all we need to do is add an attribute directly on the base class property as follows:

Monday, October 02, 2006

.NET 2.0: On-demand Configuration Encryption

In .NET 2.0, apsnet_regiis can encrypt and decrypt sections of web.config and machine.config using RSA, DPAPI, or any other custom encryption provider. However, how do we encrypt/decrypt a custom application configuration (e.g. app.config of a WinForms application)? We are in luck, since the System.Configuration namespace provides everything we need to accomplish this task. The following class, for example, can be used to encrypt/decrypt any .NET configuration file:

Thursday, September 14, 2006

Adding Controls To ASP.NET GridView Pager Row

ASP.NET 2.0 GridView control contains the AllowPaging property. Setting this property to a value of true enables the paging feature of the GridView and displays data split across multiple pages if the number of rows in the underlying data source is greater than the PageSize property. By default ASP.NET automatically displays numeric paging controls at the bottom of the GridView. While automatic paging is a very handy feature of GridView, if you want to display any additional paging controls than those inherently supported by automatic paging, you must resort to specifying your own PagerTemplate and write some additional code to preform the same functionality that GridView would otherwise handle for you. In certain situations, a better option, however, is to simply inject your custom control(s) into the pager generated by the GridView. The following example shows how we can inject a "View All" LinkButton into GridView's pager row that allows users to view all rows in the underlying data source at the same time:

ASP.NET GridView And Conditional Images

Depending upon a value in the data source, we can conditionally display images in GridView columns. For example, the following TemplateField declaration conditionally displays approved.gif or unapproved.gif based on IsApproved flag in the DataSet that the GridView is bound to:

Wednesday, September 13, 2006

Enumerating Cache Items

System.Web.Caching.Cache object implements the IDictionary interface, hence we can retreive a list of cached item keys as follows:

Saturday, September 09, 2006

ADO.NET Calculated Columns

ADO.NET offers the capability to add calculated columns in typed DataSets and use the Expression property of the those columns to specify the formulae for calculations. What I did not realize is that you must use the Fill method of the adapter instead of the Get method for calculated columns to properly populate. For example:

Sunday, August 27, 2006

DIP: Dependency Inversion Principle

The Dependency Inversion Principle deals with how to correctly design classes such that their dependency on one another causes the least amount of work in case of a change. Uncle Bob's definition of DIP states:
  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.
Essentially what this principle means is that in a tiered design, higher level modules and lower level modules should not directly depend on each other; instead they should only depend on abstractions. Moreover, abstractions should not have any knowledge of details (other classes in the system). This principle closely relates to some of the other design principles I discussed previously in that it yields a design that is highly decoupled ensuring that minor changes in one part of the application do not cause a domino effect in other parts of the application. Moreover such a design is extensible -- as new business entities are added, usually such as design scales well by requiring only new code to be added rather than existing code to be modified. ASP.NET 2.0's Provider Model is a great example of such a design that provides a default implementation for various sub-systems such as Membership, Personalization, Navigation, etc. but also allows developers to modify the default behavior by extending certain classes.

Wednesday, August 23, 2006

LSP: Liskov Substitution Principle

The Liskov Substitution Principle dictates when and where it is correct to derive a subtype from an existing supertype. As defined by Barbara Liskov and Jeannette Wing, it essentially states that:
Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T.
What it means is that if S is a subtype of T, then a function q(x) must behave in the same manner irrespective of the type of x whether it be S or T. In other words, if a piece of code behaves differently for a subtype than a supertype, then that code violates the LSP (and consequently the OCP). Let's say that we work for a bank and that we have a simple teller application. Currently the teller application works with checking and savings account types. Our bank just entered the mortgage business so we need to modify our teller application to support this new account type. During the short analysis phase we decide that since mortgage account is type of an account (IS-A relationship), we can simply create a new mortgage class deriving from the Account abstract class, override a method and a property, and we should be in business. We add a new class as follows: Everything sounds logical, that is until we come across this code in the teller application: Based on our pre-existing code, the ReceiveMoney() method is making a reasonable assumption that the new balance should be equal to the old balance plus the newly deposited amount. This assumption is, however, violated if we pass an instance of the Mortgage class to this method. This is a clear violation of the LSP.

Monday, August 21, 2006

OCP Open-Closed Principle

Another fundemental principle of object-oriented software design is the Open-Closed Principle. According to Uncle Bob (Robert Martin), this principle states that:
Software entities (classes, modules, functions, etc.) should be
open for extension, but closed for modification.
Essentially, what this means is that software's design should be such that it's behavior can be modified by extending the existing source code rather than modifying it. Consider the following example: Notice that the ReceiveMoney() method of the Bank class has to determine the type of account passed in. Only based on that information it can perform the appropriate business logic. Later if we add another account type then we may need to modify this code in order for it to work properly. The above code is, hence, in violation of the Open-Closed principle. So how can we revise our code to conform to the Open-Closed Principle? Abstraction is the answer. Let's take a look: Notice how we got rid of all conditional logic in the ReceiveMoney() method. Also notice that if we later add a new account type, the ReceiveMoney() method will work without any modifications. The revised version of our code above, hence, conforms to the Open-Closed Principle. Let's now consider what happens to our code if a new business rule is added that requires an e-mail notification to be sent to the account holder whenever a deposit is made. Obviously, we'll have to modify the ReceiveMoney() method to perform that logic. Since we can't account for all possible scenarios, we can never acheive perfect closure. With that in mind, design the simplest software that will do the job, and conform to OCP or other such design principles where you see the need.

Saturday, August 19, 2006

Generic Collection<T> and ReadOnlyCollection<T> Are Actually Not Misplaced

Since I started using generic collections in .NET Framework 2.0, it always bothered me that Collection<T> and ReadOnlyCollection<T> objects reside in the System.Collections.ObjectModel namespace rather than where they actually belong in the System.Collections.Generic namespace. Today I came across this blog by Krzysztof Cwalina that explains why Microsoft made this decission. Now it makes good sense to me.

Friday, August 18, 2006

Get Table Schema Programatically

In order to retreive table schema programatically, we can use the GetSchemaTable method of the DataReader as follows:

Thursday, August 17, 2006

Client Side Reports in Visual Studio 2005

Perhaps the best kept secret (or at least the least discussed feature) of Visual Studio 2005 is the client-side reports. Client-side reports consists of the Report Viewer Control and it's accompanying Report Designer that comes standard with Visual Studio 2005 Professional and up. This feature can be used to develop ASP.NET or WinForms solutions that sport SQL Server Reporting Services style reports, without having to deploy those reports to a Reporting Server. Reports are deployed as RDLC files with your solutions. In fact one doesn't even need SQL Server, since these reports can be programatically bound to objects such as DataSets, a huge plus for ditributed n-tier designs where the UI layer does not have direct access to the data store. This also means that one can use any imaginable back-end data store including XML and CSV files as long as data can be loaded into binable objects. The report viewer control is similar to Reporting Services report viewer, with nifty features such as paging, searching, and export (PDF, Excel, CSV) features. My only complain with the ASP.NET version of the report viewer is that it does not directly support printing. Reports have to be exported to PDF in order for one to print. This was a gotcha with the first versions of Reporting Services report viewer as well, but later they added printing support to the control (perhaps through ActiveX) in Reporting Services SP1. You can find more information about this feature at GotReportViewer.

Wednesday, July 19, 2006

Write Black and Blue Get Green Free

GhostDoc is a free Visual Studio add-in that automatically generates XML comments by intelligently deducing comments from member name and type or by using existing documentation written by someone else in a base class or an interface. This tool is purely intelligent and simply amazing. With tools such as this there simply is no excuse for developers whose code looks all black and blue to not add some green for free! Checkout this GhostDoc PDC demo video on Channel9.

Tuesday, July 18, 2006

Inherit With Care

I was asked to look at an ASP.NET 1.1 application that was designed with a distributed architecture using .NET Remoting. Over a period of a few hours of heavy usage, this production application would intermittently bring the Windows 2003 Server that it was being hosted on to a screeching halt. Cause unknown. No event log entries, nothing suspicious in IIS logs, nothing too special about the application that would indicate this behavior. Performance monitoring, however, indicated that the handles on the OS would gradually increase to dangerous levels of 50,000+ before the application would crash. Hmmm, what could be using so many handles and not releasing them? My first instinct was to make sure that all the remoting objects were disposed properly after use. Upon closer investigation, however, I found out that all ASP.NET pages in the application were inheriting from a custom base class. The base class was overriding the page's Init method, and guess what I found in that method? A call to RemotingConfiguration.Configure() method. At first I was surprised why would someone configure remoting every single time a page is instantiated? Soon it hit me why system handles were astronomically increasing. Once that line of code was moved to Application_Start event, the application hasn't crashed in weeks. Moral of the story? Inheritance is a good OO concept, but only we as developers can decide how badly we want to abuse it!

New Articles On Software Rockstar