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 »

A brief overiew of the new Parallel Extensions in .NET Framework 4

This post is followup of my previous post that described some of the exciting new features of .NET Framework 4. We have been creating multi-threaded applications with the previous versions of .NET framework, but most of the times, the objective of such multi-threading was to keep the user interface active in case of any IO or network operation going on. However, to cope with the current era of multi-core processors, we need to additionally parallelize our business logic operations to best utilize the computational powers. This post will walk through some of the inconveniences with the traditional multi-threading techniques and will then discuss how the new parallel extensions in .NET Framework 4 help us to introduce parallelism in a better, manageable, scalable and efficient way.
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#: Using reflection with COM objects

Yesterday, I was trying to use reflection to access some properties of a COM object but was getting the following exception:

Object reference not set to an instance of an object

Debugging into, I noticed that GetProperty() method was returning null in the following call:

var propertyInfo = comObject.GetType().GetProperty("PropertyName")

After some searching, I found that we need to use the more generic InvokeMember() method to get or set the properties of a COM object. Here’s the simplest example of the usage:

//get the value of comObject.PropertyName
object propertyValue = comObject.GetType().InvokeMember("PropertyName", System.Reflection.BindingFlags.GetProperty, null, comObject, null);

//set the value of comObject.PropertyName
comObject.GetType().InvokeMember("PropertyName", System.Reflection.BindingFlags.SetProperty, null, comObject, new object[] { propertyValue });

I hope this post helps someone who is trapped into the same situation.

Control.Invoke and BeginInvoke using lamba and anonymous delegates

Working constantly with LINQ and .NET 3.5 these days, I sometimes forget how to do things without lamda expressions. Today, I was working on a WinForms application and I needed to update the UI from a separate thread, so I wrote the following code:

    this.BeginInvoke( ()=>
        {
            //code to update UI
        });

This gave me the following error:

Cannot convert lambda expression to type 'System.Delegate' because it is not a delegate type

I, then tried the anonymous delegate syntax:

    this.BeginInvoke( delegate ()
        {
            //code to update UI
        });

Still incorrect, as it gave me this error:

Cannot convert anonymous method to type 'System.Delegate' because it is not a delegate type

A quick google revealed that Control.Invoke and Control.BeginInvoke take a System.Delegate as parameter that is not a delegate type and we need to cast our lambas or anonymous delegates to MethodInvoker or Action like this:

    this.BeginInvoke( (Action) (()=>
        {
            this.txtLongestWord.Text = this.longestWord;
        }));

The above code does not look good due to lot of brackets, so let’s use the anonymous delegate syntax:

    this.BeginInvoke( (Action) delegate ()
        {
            //code to update UI
        });

//or

    this.BeginInvoke( (MethodInvoker) delegate ()
        {
            //code to update UI
        });

Note that the same syntax holds for Dispatcher’s Invoke or BeginInvoke method that can be used in WPF to marshall calls on the UI thread.

Avoiding hard-coded strings while raising or handling PropertyChanged event

While developing WPF/Silverlight applications, and more specifically while following the Model-View-ViewModel (MVVM) pattern we will find ourselves implementing INotifyProprertyChanged most of the times. The default implementation of PropertyChanged event takes the property name as string in the PropertyChangedEventArgs which is not much robust. There are several ways to address the issue:

  • Use reflection to verify that the property actually exists, as demonstrated once by Josh Smith.
  • Use Injection using some Aspect Oriented Programming framework, like PostSharp
  • Use Expression Trees as described by Michael Sync and Davy Brion

Personally, I prefer using expression trees. So, instead of writing this:

public string MyProperty
{
    get { return this.myProperty; }
    set { this.myProperty = value; this.RaisePropertyChanged("MyProperty"); }
}

We can write:

public string MyProperty
{
    get { return this.myProperty; }
    set { this.myProperty = value; this.RaisePropertyChanged( MyObj => MyObj.MyProperty ); }
}

The same issue exists looking at the other side. When we subscribe to PropertyChanged event of an object, we get the property name again as a string. One way is to use the GetPropertyName( ExpressionTree ) extension method from the above implementation in our if and case statements. Also, Josh nicely addressed the issue in this post, thus allowing us to write:

MyClass myObject = new MyClass();
PropertyObserver<MyClass> observer = new PropertyObserver<MyClass>(myObject)
    .RegisterHandler(myObj => myObj.MyProperty1, myObj => { /* handle change in MyProperty1 */ })
    .RegisterHandler(myObj => myObj.MyProperty2, MyProperty2HandlerMethod  );

Notice that Josh used IWeakEventListener that isn’t available for Silverlight but luckily Pete O’ Hanlon provided us with a Silverlight version of Josh’s work here.

So, combining the great efforts of all these people, we are going to have a better MVVM experience.

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!!!