Archive for the ‘c#’ Category

Interop & IDataErrorInfo

September 17, 2011 Leave a comment

Despite of all the interop support available sometimes you will still come across some tricky issues which will be difficult to overcome. One such problem I faced recently. I had to configure the Dialog with MFC PropertySheet control. This PropertySheet control was holding few Property pages. These property pages didn’t had any MFC controls as content but hosting the user controls developed in WPF. First I will write very briefly about how to load the WPF user control inside the MFC container and then I will explain about my tricky problem and how I fixed it.

Hosting of WPF user control as content of PropertyPage wasn’t that challenging. In order to host the WPF content inside property page, first HwndSource needs to be configured. In order to create HwndSource, first you need to create HwndSourceParameter. Typical configuration for HwndSourceParameter can be as under :

System::Windows::Interop::HwndSourceParameters^ sourceParams = gcnew System::Windows::Interop::HwndSourceParameters (<Window Name>);

// X position where WPF content to be placed
sourceParams->PositionX = x;
// Y position where WPF content to be placed
sourceParams->PositionY = y;
// height of the WPF content
sourceParams->Height = height;
// width of the WPF content
sourceParams->Width = width;
// Handle for the Parent window inside which WPF content to be hosted
sourceParams->ParentWindow = IntPtr(parent);
// style attributes as needed (“WS_TABSTOP” style needs to be set if WPF content needs to get focus while tabbing
sourceParams->WindowStyle = WS_VISIBLE | WS_CHILD | WS_TABSTOP;

Another important property for HwndSourceParams is “ResetFocusMode”. Default value for this property is “Auto”. Setting this property to “Auto” makes sure that when when the PropertySheet control (in my case) looses the focus and receives focus back the control which had focus prior to loosing focus retains the focus back. If you set this property to “None” then, none of the controls inside the page will have focus when propertysheet control receives the focus.

// now create HwndSource using this parameters
System::Windows::Interop::HwndSource^ hwndSource = gcnew HwndSource(*sourceParams)

Now suppose I have a WPF user control named “PageUserControl” then create instance of this user control.

PageContentUserControl^ pageContent = gcnew PageContentUserControl();
//Now set this user control as RootVisual of HwndSource object. 
hwndSource->RootVisual = pageContent ;

With above code in place it is possible to host the WPF content inside MFC control. This is just basic information which one should know in order to host the WPF content inside MFC container however somewhat plumbing work will be needed depending upon MFC container control in which you are placing the WPF control.

After hosting the control I had one more issue to deal with. My User control developed in WPF had few checkboxes, text boxes, etc. as it’s content. In order to validate my inputs and giving visual indication about the data validation failure, I had implemented interface “IDataErrorInfo”. (Now how this interface is implemented and how it works is not covered in this Post. Google it to find more on it)

When “IDataErrorInfo” interface implemented and bound value to the control is invalid, control will have a red border around it to indicate user about the validation failure. Also, when you set focus on the control like check box through tabbing, you will not be able to see the dotted line around check box when it receives the focus. Following figure shows the focus styles for each case. When User Control is hosted within MFC container, you will assume that “IDataErrorInfo” implementation should work but infect it won’t.

The problem of not being able to see all such decoration is absence of Adorner layer. All these error templates and focus styles etc. are drawn inside the AdornerLayer. The WPF window has an AdornerLayer by default, so we can always see validation errors in WPF. When hosting a user control in MFC, adornerlayer is not available by default and need to add an AdornerLayer into your UserControl to support adorners.

So in order to view all such Focus styles / Error template styles, we need to decorate the UserControl with AdornerDecorator. So following code should do the fix for you :

<UserControl x:Class="TestPjt.TestUC"
             d:DesignHeight="50" d:DesignWidth="300">
              <TextBox x:Name="txtbox"/>

This fix will start showing the expected focus and error template style for each control. HTH!!

Destructor – Finalize & IDispose

October 3, 2010 1 comment

This post is about techniques on how managed/unmanaged resources used/referenced by objects can be released. There are two ways to do this. They are namely,

1. Implement IDisposable

2. Implement Destructor (Finalize) for object.

This post describes how both gets implemented and what are the pros n cons of both ways.

Destructor & Finalize :

Destructor in managed code can be written in similar way as unmanaged code.

 class TestClass
    ~TestClass()  // destructor implementation
        // free resources

When destructor is written in managed code, it ultimately translates into following code post compilation :

protected override void Finalize()
        // free resources here

(So this means both destructor & Finalize are same in managed context.)

How destructor works :

When reference count becomes zero for the object which implements destructor then that object is marked for collection and object is put into the finalization queue. When garbage collector start collecting the memory, at that time destructor for the objects in the finalization queue will be called. When destructor is called then unmanaged resources can be freed and object memory is collected.

IDispose :

IDispose is basically .net framework interface which defines the method to release the allocated resources. Inside the interface method implementation should be present to release the resources.

How IDispose work :

Let’s consider following code to understand how IDispose and destructor work in tandem. In following example “TestClass” implements IDisposable and also implements destructor. This code uses managed resource StreamReader and unmanaged some Integer pointer which needs to be freed before object is freed after it’s use.

    public class TestClass: IDisposable
        // Pointer to an external unmanaged resource.
        private IntPtr intPointer;
        // managed resource
        System.IO.StreamReader stream;
        // Track whether Dispose has been called.
        private bool disposed = false;

        // The class constructor.
        public TestClass()
            this.intPointer = /* assign some integer pointer*/;
            stream = new System.IO.StreamReader(@"C:\Test.txt");

        // Implement IDisposable.
        public void Dispose()
            // as dispose has already been called supress finalizer

        private void Dispose(bool disposing)
                // If disposing equals true, dispose all managed
                // and unmanaged resources.
                    // Dispose managed resources.

                // dispose unmanaged resources here.
                intPointer = IntPtr.Zero;

                // Note disposing has been done.
                disposed = true;


        // destructor

Dispose method with private accessor is being called from both interface Dispose method as well as destructor. When Dispose is called, first managed resource is freed and after that unmanaged resource is freed. Thus both managed and unmanaged resources are freed. After clearing the resources, GC.SupressFinalize is called so that the object is removed from finalize queue.

Now the question is when IDisposable and destructor are doing the same thing then why two separate things are required. Answer of this question lies in the nature of the execution of both these implementation.

Difference between Descturctor-Finalize & IDisposable :

Destructor is not deterministic way of freeing the resource. When object with destructor is marked for garbage collection, it will be put inside the finalization queue. Whenever garbage collector runs, object inside the finalization queue will free the resources. Because time when the garbage collector will run is not sure, it can not be predicted when resources will be freed.

IDisposable is deterministic way of freeing the resource. IDisposable is useful when some shared resources or some high memory consuming resources needs to be freed. Calling the dispose on the object will ensure that resources are freed immediately (however memory associated to the object may not get collected until garbage collector runs).

Some Finer points about Destructor-finalize & IDisposable :

Destructor – Finalize :

  1. Finalize is not a good option to use when shared resources / memory consuming resources needs to be freed because of it’s non deterministic nature.
  2. Releasing the resources using Finalize is costly from performance point of view. Why implementing Finalize is costly is explained here (last para) in MSDN.
  3. In finalize method, finally block has been put and it calls the Finalize on base class also. This makes sure that all the hierarchy of objects release the resources properly.
    IDisposeable :
  1. As mentioned above, IDispose can only free the resources and can not free the memory consumed by the object itself.
  2. Onus of calling Dispose method on the object still remains with the user. Just implementing IDisposable will not make sure that all resources are released properly. Dispose method will not be called automatically by framework except object is called with “using”.
  3. Calling dispose is not thread-safe.
  4. It is better to consider implementing try..finally block inside the dispose method because if during the execution of dispose method any exception occurs there is no way left to free the resources.

References :



May 1, 2009 1 comment

I was looking to copy some bulk data from one of the data table in memory to my SQL DB table. I tried using DBAdapter.Update but it didn’t work as in my source datatable none of the row was in updated/new stage. Then after searching a lot, I found “SQLBulkCopy”.

The SqlBulkCopy class can be used to write bulk data only to SQL Server tables. However, the data source is not limited to SQL Server; any data source can be used, as long as the data can be loaded to a DataTable instance or read with a IDataReader instance. To copy the source data to destination table in the sql server, need to set destination table name and execute “WriteToServer” method. Following code snippet

// create sqlBulkCopy object
SqlBulkCopy bulkCopy = new SqlBulkCopy(connString);

// set destination table name for sqlBulkcopy object
bulkCopy.DestinationTableName = "[Table Name]";

// write source data to destination sql table

Performancewise using SQLBulkCopy is far better than using normal Insert/Update commands.

Categories: c#, SQL Tags: , ,

Reading csv file in datatable

May 1, 2009 10 comments

Recently I had to work on one problem where I had to read the csv file and filling up the data table with the csv file data. I used the OLEDBAdapter to accomplish that with just few lines of code. Following is the code :

            string query = "SELECT Symbol, [Name of Company], FROM [just file name with extension]";
            string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + [csv file path without file name] + ";" + "Extended Properties=’text;HDR=YES;’";

            //create dataadapter object
            OleDbDataAdapter adapter = new OleDbDataAdapter(query, connStr);

            // create table
            DataTable dtSymbolDetails = new DataTable("ScriptDetails");
            dtSymbolDetails.Columns.Add("Name of Company");

            // fill the table with data using adapter

So above code fills up the details of the csv file in the data table for further use.

Also note the text in red above. If column name contains the space then in query the column name should be put between [ ]. I learned it in bit hard way. It shows I’m so poor in my sql knowledge.

Categories: c#, SQL Tags: , ,

Attached Properties

February 11, 2009 Leave a comment

Attached property is a special type of dependency property that is intended to be used as global property. One of the purpose of Attached property is to allow child elements to set different value for property which has been defined on parent element. Examples of Attached properties are DockPanel.Dock, Grid.Row, Grid.Column, Canvas.Left, Canvas.Top etc. The use of Attached property is similar to static property and it can not be accessed through instance object.

Attached properties don’t implement wrappers for property because Attached property may not be part of the clr namespaces for the instances on which it is set. However, attached property implementer provides the accessors to access the property value.

DockPanel dockPanel = new DockPanel();

Button myButton = new myButton();


DockPanel.SetDock(myButton, Dock.Left);

Defining  attached property is almost same as defining the dependency property. The only change is during the registration instead of ‘Register’ use ‘RegisterAttached’ method of DependencyProperty. Also, don’t implement the property wrapper for the attached property. But instead of property wrapper implement the Get and Set accessor for the property.

Categories: c#

Difference between String and string

October 15, 2008 Leave a comment

This is what MSDN has to say about this :

In C#, the string keyword is an alias for String. Therefore, String and string are equivalent, and you can use whichever naming convention you prefer.

So in other words string is equivalent to System.String ( data type defined in .net framework).

using System;


string s1 = “ABC”;
String s2 = “DEF”;

above line of code will compile and work as expected.

// using System;


string s1 = “ABC”;
String s2 = “DEF”;

but above line of code will produce compile time error as it can not identify the “String” data type.

So in short, (in c#) use either “string” or “System.String”. Functionally, using any of these doesn’t make any difference. The same explaination applies to other data types i.e. char & Char, object & Object etc.


P.S. : I have heard that this same question being asked many time during interviews. I really don’t see any logic in testing the knowledge of candidate with such question. Programmer will never be able to see any difference in using “String” or “string” unless he/she has not added the directive “using System;” which is there by default when new class is created. But anyway if someone doesn’t know the difference this post should help them.

Categories: c# Tags: , ,

Nullable Types

October 11, 2008 Leave a comment

Nullable types are special types of value type variables (including struct) which can accept the correct range of values for its underlying value type, plus an additional null value. For example, a Nullable<Int32> (pronounced “Nullable of Int32”) can be assigned any value from -2147483648 to 2147483647, or it can be assigned the null value. A Nullable<bool> can be assigned the values true/false, or null.

Nullable type variables can only be defined for value types and not for the reference types because reference types any way accept the null as valid value. Each nullable type is constructed from the >)>Nullable<T> structure where T is underlying variable type for which Nullable type to be created. Nullable types can be defined by appending ‘?’ to datatype text in declaration as shown below :

int? nullableInt = 4;

double? nullableDouble = 9.2;

Properties :

Nullable<T> structure has two read only properties defined namely ‘HasValue’ and ‘Value’.

HasValue : returns true/false depending upon the value stored inside the nullable variable. If value of the variable is null it returns false else it will return true.

Value : returns underlying value of the nullable variable if it is not null. If underlying value for the variable is null then it will throw “InvalidOperationException”.

Method :

Nullable<T> structure has one method named as ‘GetValueorDefault”.

GetValueorDefault : This method has got two overloads.

GetValueorDefault() : This method returns the underlying value of the variable if ‘HasValue’ is true else it will return the default value of underlying variable. e.g. when this method is called on nullable<int> and ‘HasValue’ is false then this method will return 0. If the underlying data type is Boolean then default value returned will be ‘false’.

GetValueorDefault(T) : In this method, default value is passed as an argument. So whenever ‘HasValue’ is false, it will return the passed value as default value.

Boxing and UnBoxing :

Nullable type variable is also an example of boxing and unboxing. When value is assigned to Nullable type variable, CLR boxes this value assigned to variable and stores it. It means, if ‘HasValue’ property is true, boxed value for the variable is present and if it is false, null is boxed. When nullable varaiable’s value is retrieved, CLR UnBox the previously Boxed value and return.

Explicit Conversion :

int? x = null;

int y = x; (This statement gives compile time error because conversion to int data type from Nullable<int> data type requires explicit conversion i.e. int y = (int)x. If during explicit conversion value of nullable variable’s (y in our case), value is null then it will throw exception. So it is better practices to use int x = y.GetValueorDefault();

Alternatively, to get the default value for the underlying variable type ?? can be used.

int? i = null;

int y = i?? – 1;

Return value for the y in above code will be -1 because as i is null and i?? will return 0 (default value for int data type).

Categories: c# Tags: , ,