C#: Fun with Indexers

This post refers to an interesting situation when you create a class in C# with an indexer and a property named “Item”. Let’s see why this is not possible simultaneously.
Read the rest of this entry »

Advertisements
Posted in Dotnet. Tags: , , . 6 Comments »

TSQL: Error handling with Try Catch from a .NET perspective

Starting with SQL 2005, we can handle unexpected situations in our TSQL scripts/procedures/functions in an structured manner using the famous Try/Catch methodology, similar to what we are used to in our object oriented programming languages (C#, Java, etc). This post will describe certain similarities and how to enjoy the features that look absent at the first look. The MSDN document that describes error handling in TSQL in much detail is: Using TRY…CATCH in Transact-SQL
Read the rest of this entry »

.NET Framework 4: A first look at the new features

Visual Studio 2010 Release Candidate has been made available a few weeks back. The .NET Framework 4 is arriving with some great new enhancements for all of us, and in this post, I plan to briefly discuss some of those exciting features that caught my eye. Let’s begin:

Parallel extensions
Introducing parallelism in our applications was never this much easier. The new Task Parallel Library offers a lot more control over the work items (called Tasks) as compared to our classic Thread Pooling techniques. The semantics of the new parallel loops are much similar to our existing sequential loops and hence our existing logic can be parallelized with minimal effort. I have discussed the new parallel programming features in .NET framework 4 in my followup post here.

Entity framework 4
The new version of Entity Framework seems to have quite a number of enhancements. It is great that Microsoft has addressed the user responses regarding the current limitations of Entity Framework 3.5. We are getting support for POCO (Plain Old CLR/C# Objects) and self-tracking entities which are great features for our enterprise and LOB applications having more than one tier. The new foreign key associations are another great enhancement since the users were finding it difficult to set associations without grabbing the entity from database. Model first development, lazy loading, code only abilities, complex types handling, better naming of entities, improvement in generated TSQL queries, ability to directly run store commands are some other wonderful features of the upcoming version of Entity Framework.

Managed Extensibility Framework
The Managed Extensibility Framework offer an excellent way for our enterprise LOB applications to dynamically expand. In previous versions of .NET, and without MEF, we need to manually load external assemblies and use reflective techniques to instantiate and use their objects/features. This has been made really easy with Managed Extensibility Framework in .NET 4. When an MEF enabled application is launched, it automatically discovers and loads all the extensions and hence allows us to easily add new features to an already deployed application. Here’s an excellent article by Glenn Block from last month’s MSDN magazine: Building Composable Apps in .NET 4 with the Managed Extensibility Framework. MEF seems quite promising I really look forward to use MEF in my future applications.

Silverlight 4
Wow!! We haven’t yet been able to fully digest Silverlight 3 and SL 4 is approaching. Microsoft is doing a lot of investment in Silverlight and the upcoming version has quite great features. The ability to consume COM objects has greatly reduced the limitations of Silverlight that were inherently present due to being a browser based technology. Tim Heuer once did a wonderful job by covering all the features of Silverlight 4 in this post. I will simply list a few ones here:

  • Drag and Drop support from desktop to a Silverlight App: This one would allow us for better UI experiences for some interactive applications. Imagine that we have got some Rich Text Editor application running and we drag a photo from our desktop and it finds its place in the current document. Cool!
  • COM integration: COM support in out-of-browser mode can lead us to achieving some very powerful interaction with the programs on the user machine. We can now access a SQL server database residing on user’s computer, we can now open a certain document in user’s MsProject app, and many more. For some insight, have a look at Justin’s wonderful post here.
  • MEF support: Now our Silverlight apps are extendable via MEF which is really cool.
  • Right click support: A perfect feature for our interactive applications, we now can control the context menu items as well.
  • Desktop Notifications: The Silverlight application can now show Taskbar notifications as well.
  • ICommand support : A great feature for MVVM lovers, we now have commanding support for in XAML without requiring any external MVVM framework.
  • Printing support: We can even control printing from our Silverlight application.

DLR and dynamic keyword
The CLR (Common Language Runtime) is now accompanied with DLR (Dynamic Language Runtime) in .NET Framework 4. This is going to allow easy interaction with dynamic languages and COM objects without explicitly using the reflection methods. More on this on this MSDN doc: DLR Overview.

Code contracts
This is a great enhancement for our architects who are always cautious about design principles. The new version of .NET now support specifying pre-conditions, post-conditions, and object invariants. This can result in improved testing and better contract verification in design-by-contract programming. More info on this MSDN doc: Code Contracts.

Optional Parameters
Like Visual Basic, we are getting support for optional parameters in C# with .NET 4. Although this is a debatable topic but it can be helpful in cases where we needed to develop several overloads of a single method. More on this topic in this MSDN doc: Named and Optional Arguments.

That’s all. These were my initial thoughts on the new features of .NET Framework. The full official list of the new enhancements can be viewed on MSDN here. Of course, the views and opinions will get richer by the passage of time when we start building our application in .NET 4. So let’s download Visual Studio 2010 RC from here and start enjoying the new features. Happy programming!

C#: Left outer joins with LINQ

I always considered Left Outer Join in LINQ to be complex until today when I had to use it in my application. I googled and the first result gave a very nice explanation. The only difference between ordinary joins (inner joins) and left joins in LINQ is the use of “join into” and “DefaultIfEmpty()” expressions.

Consider this very simple query (Assuming a scenario that not all the TimesheetLines are associated with a Job)

Select TL.EntryDate, TL.Hours, J.JobName
From TimeSheetLines TL
Left Join Jobs J on TL.JobNo=J.JobNo

A LINQ query using inner join is

var lines =
    from tl in db.TimeSheetLines
    join j  in db.Jobs on tl.JobNo equals j.JobNo
    where tl.ResourceNo == resourceNo

    select new
    {
        EntryDate = tl.EntryDate,
        Hours = tl.Hours,
        Job = j.JobName
    };

And a LINQ query performing left join is

var lines =
    from tl in db.TimeSheetLines
    join j  in db.Jobs on tl.JobNo equals j.JobNo into tl_j
    where tl.ResourceNo == resourceNo

    from j in tl_j.DefaultIfEmpty()
    select new
    {
        EntryDate = tl.EntryDate,
        Hours = tl.Hours,
        Job = j.JobName
    };

Notice that the only difference is the use of “into” with the join statement followed by reselecting the result using “DefaultIfEmpty()” expression. And here’s the generated SQL for the above LINQ expression.

SELECT [t0].[EntryDate] as [EntryDate], [t0].[Hours] as [Hours], [t1].[JobName] AS [Job]
FROM [dbo].[TimeSheetLine] AS [t0]
LEFT OUTER JOIN [dbo].[Jobs] AS [t1] ON [t0].[JobNo] = [t1].[JobNo]
WHERE [t0].[ResourceNo] = @p0

Another LINQ version which is more compact is:

var lines =
    from tl in db.TimeSheetLines
    from j in db.Jobs.Where(j=>j.JobNo == tl.JobNo).DefaultIfEmpty()
    select new
    {
        EntryDate = tl.EntryDate,
        Hours = tl.Hours,
        Job = j.JobName
    };

Similarly, this concept can be expanded for multiple left joins. Assuming that a TimeSheetLine will either have a JobNo or an IndirectCode, consider this SQL query:

Select TL.EntryDate, TL.Hours, J.JobName, I.IndirectName
From TimeSheetLines TL
Left Join Jobs J on TL.JobNo=J.JobNo
Left Join Indirects I on TL.IndirectCode=I.IndirectCode

The equivalent LINQ query is:

var lines =
    from tl in db.TimeSheetLines
    join j in db.Jobs      on tl.JobNo        equals j.JobNo         into tl_j
    join i in db.Indirects on tl.IndirectCode equals i.IndirectCode  into tl_i
    where tl.ResourceNo == resourceNo

    from j in tl_j.DefaultIfEmpty()
    from i in tl_i.DefaultIfEmpty()
    select new
    {
        EntryDate = tl.EntryDate,
        Hours = tl.Hours,
        Job = j.JobName,
        Indirect = i.IndirectName,
    };

And the generated SQL is:

SELECT [t0].[EntryDate] as [EntryDate], [t0].[Hours] as [Hours], [t1].[JobName] AS [Job], [t2].[IndirectName] As [Indirect]
LEFT OUTER JOIN [dbo].[Jobs] AS [t1] ON [t0].[JobNo] = [t1].[JobNo]
LEFT OUTER JOIN [dbo].[Indirects] AS [t2] ON [t0].[IndirectCode] = [t2].[IndirectCode]
WHERE [t0].[ResourceNo] = @p0

That’s all, left outer joins in LINQ are as easy as in T-SQL. Happy joining.

Update:
Notice that this post describes the approach to perform a Left Outer Join in LINQ To SQL as well as Entity Framework (version 4). The same is not true for Entity Framework version 3.5 since it does not support the DefaultIfEmpty keyword. To perform Left Outer Joins with Entity Framework 3.5, we need to create appropriate relationships (e.g 0..1 to 0..Many) in our Entity Model and they will be automatically translated into TSQL’s Left Join clause.

C#: Executing batch T-SQL Scripts containing GO statements

At times, we developers need to run SQL scripts from our .NET applications, in, say Installer Applications. This is not always easy since large SQL scripts typically contain a GO statement to separate individual batches and our ADO.NET classes under System.Data namespace do not know how to handle it. The reason is that the “GO” statement is not a native T-SQL statement but rather used by SQL Server Management Studio to terminate the batches it is sending to the server. To tackle this situation, we have the following choices:

1. Split the script on “GO” command into smaller scripts and execute those individual scripts

A very primitive solution would be to split the script on “GO” text and run the individual sub-scripts in sequence. The problem is how to get a robust split mechanism. Generally, a line break before and after the GO works fine. Here’s how to do this:

//get the script
string scriptText = GetScript();

//split the script on "GO" commands
string[] splitter = new string[] { "\r\nGO\r\n" };
string[] commandTexts = scriptText.Split(splitter,
  StringSplitOptions.RemoveEmptyEntries);
foreach (string commandText in commandTexts)
{
  //execute commandText
}

The above code can produce unnecessary splitting in some situations, thus creating an incorrect SQL Command. A more better approach would be to use Regular Expressions. Again, the problem is how to create a pattern that is robust enough to tackle all sort of scripts. Lets look into the second solution now.

2. Use the Server class from SQL Server Management Objects (SMO)

For this, we need to add the following references in our project:

  • Microsoft.SqlServer.Smo
  • Microsoft.SqlServer.ConnectionInfo
  • Microsoft.SqlServer.Management.Sdk.Sfc

After that, we can simply execute the entire script (with all the “GO” statements) using the code below:

string connectionString, scriptText;
SqlConnection sqlConnection = new SqlConnection(connectionString);
ServerConnection svrConnection = new ServerConnection(sqlConnection);
Server server = new Server(svrConnection);
server.ConnectionContext.ExecuteNonQuery(scriptText);

This is a fairly generic and robust solution and the great thing is that it does not require any change in our original script. Hooray!!!

How to create and use Extension Methods in C#

As I promised in my previous post, here’s a simple example to create and use extension methods. Extension methods are a powerful feature introduced in Dot Net 3.0/3.5 that allow us to inject/add a custom method in any existing type (even if the type is Sealed/NotInheritable). Lets say, we want to add a new method IsPrime to the existing int (System.Int32) type, then we need to write an static method in an static class like this:

 public static class MyExtensions
    {
        public static bool IsPrime(this int integer)
        {
            //implementation here
            return true;
        }
    }
 

Now, this IsPrime method will be associated with every int type in our project, as depicted in the following screenshot:

Extension Method Demo

Thats all. I just wanted to demonstrate extension methods using a very basic example; if you need more information, try msdn or google.

C# Coding Standards

I recently came across this post from Clint Edmonson. It presents a reference document for coding standards (for C# as well as VB) you may find useful.