Implementation of an Observer

Hi Folks,

As few people told me to implement an observer in my last post where I just showed how to use it, here is the post where I am going to clear out confusions for you. If you have read my other post, you might already know what is an Observer and why it is required. Lets recap this a bit more.

An observer is a container which observes each element individually and notifies you when the object state is modified. The observer should contain methods that enables you to subscribe or unsubscribe individually so that when you subscribe for a  notification, it will keep on creating notification until you explicitly unsubscribe the Observer.

In .NET base class library, there are two interfaces introduced viz, IObservable and IObserver. These interfaces gives you a standard to develop Observable pattern and also recommends you to use it rather than doing it of your own. Microsoft also builds forth its Reactive Framework (I will discuss about it later) based on Observer pattern and lets us use it when Observer is required. 

In this post, I will discuss how you could use IObserver and IObservable to implement you own notifiers.

Download Sample - 33KB
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Working with CollectionView in WPF(Filter,Sort, Group, Navigate)

If you are working with WPF for long, you might already have come across with ICollectionView. It is the primary Data object for any WPF list controls (like ComboBox, ListBox, ListView etc) that allows flexibilities like Sorting, Filtering, Grouping, Current Record Management etc. Thus it ensures that all the related information like filtering, sorting etc is decoupled from the actual control.  It is been very popular to those working with data object because of inbuilt support for all WPF List controls. So I thought I would consider to describe it a bit so that people might easily plug in the same to their own solution.

What is a CollectionView ? 

It is a layer that runs over the Data Objects which allows you to define rules for Sorting, Filtering, Grouping etc and manipulate the display of data rather than modifying the actual data objects. Therefore in other words, a CollectionView is a class which takes care of the View totally and giving us the capability to handle certain features incorporated within it.

How to Get a CollectionView ?

Practically speaking, getting a CollectionView from an Enumerable the most easiest thing I ever seen in WPF. Just you need to pass the Enumerable to CollectionViewSource.GetDefaultView. Thus rather than defining

this.ListboxControl.ItemsSource = this.Source;

you need to write :

this.ListboxControl.ItemsSource = CollectionViewSource.GetDefaultView(this.Source);

The List will get the CollectionView it requires.

So the CollectionView actually separates the View object List Control with the actual DataSource and hence gives an interface to manipulate the data before reflecting to the View objects. Now let us look how to implement the basic features for the ICollectionView.

Download Sample - 74KB

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

IObserver and IObservable - A New addition to BCL

With the introduction of new interfaces, it is time to get it on with discussion. With the current release of VS2010, there were two interfaces that were introduced viz, IObservable and IObserver. Here in the post, I am going to discuss about these interfaces and its connection to Push based approach on Reactive Framework.

IObserver and IObservable as a Dual to Enumerables

First, it should be noted, IObserver and IObservable is actually the mathematical dual of IEnumerable and IEnumerator. Based on iterator pattern, IEnumerable is actually a repository of elements that made up the objects. The IEnumerable holds all the objects and it uses IEnumerator to get each individual objects from the repository. The few methods in IEnumerator which the IEnumerable uses is MoveNext and Current. So for each iteration, the Enumerator calls MoveNext and assigns it to Current which is later on sent back to the external environment.

So if you consider the interface IEnumerable and IEnumerator it looks like :

public interface IEnumerator<out T> : IDisposable
          T Current { get; }
          bool MoveNext();
          void Reset();

public interface IEnumerable<out T> : IEnumerable
     IEnumerator<T> GetEnumerator();

So the IEnumerator has MoveNext which is called every when we need to yield next element from the store. The MoveNext sets the Current item and sends it back to the Environment. So IEnumerable might be considered as Pull based approach and it is used for sequential retrieval of objects.

IObservable and IObserver introduced to BCL recently as stated is mathematical dual of IEnumerable and IEnumerator. Lets see the interfaces a bit :

public interface IObserver<in T>
    void OnCompleted();
    void OnError(Exception error);
    void OnNext(T value);

and for IObservable it is :
public interface IObservable<out T>
      IDisposable Subscribe(IObserver<T> observer);

Hence, if you see the difference between the two Interfaces, IEnuerator has Current and MoveNext. These methods are used to Pull objects from the repository. IObserver has OnNext which is used to Push objects to the repository. Again, if you look into IEnumerable, it uses GetEnumerator to pull back the object of IEnumerable, while IObservable has a Subscribe method which is used to push an Observer to the Observable. Hence you can easily say, Observable interfaces in BCL is a dual to Enumerables where the Former uses Push based approach and the later uses pull based approach.

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

How to Render Bitmap or to Print a Visual in WPF

Working with WPF never become so easy if there was no inbuilt capability to take snaps or print a visual object. Microsoft made a very constructive class hierarchy to add functionality in each of the classes and hence building the solid foundation of WPF presentation model. Every element that we place in WPF is  inherited from a Visual. BCL added inbuilt functionality for a visual to render itself as Bitmapsource or to print the same Visual directly to the printer. In this post I will discuss how easily you could render a Visual as BitmapSource and later use it as source of an Image control.

Using Sample Application

RenderTargetBitmap is a class that is basically used to render a Visual to a bitmap object. Lets demonstrate this using an InkCanvas. You might already know, there is a special canvas element called InkCanvas which lets the user draw image on the screen. So before we proceed with the code lets discuss the sample application a bit.

In the above snap you can see that I have placed one InkCanvas which allows you to write dynamically on the screen. The buttons will Render the bitmap image from the Canvas and add the item on the ListBox on the Right. You can see after I click on Render as Bitmap button, it actually places the same visual as BitmapSource on the Right hand side ListBox.

Similar to what we worked on, I changed the content a bit and took another shot, and it exactly does the same.
Finally when I click on Render the Grid as Bitmap, it actually renders the whole Grid including the listbox and all as Grid. There are few buttons more, like Save Selection as JPEG / Print as Visual, each of them have its own functionality.

Download the Sample - 60KB

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Welcome Message for First Time Visitor in Blogger

Hi Guys,

In this blog, I am not going to talk about anything about C#, ASP.NET or any of the technical or architectural stuffs. This is actually a post for my refreshment. Recently I have added a new feature to my blog to ensure that the users who visits my site for the first time gets a warm welcome message telling about the features of the site. Lets show you how to do that, so that others who are using the same to blog their content can benefit from it.

The Funda
 Here are the steps to do : 
  1.  Add a small div element to the blogger template which contains the message. 
  2. Add a css for the div to ensure the message is hidden.
  3. Try to find a cookie through javascript after the page loads.
  4. If cookie is found, we do nothing, otherwise we unhide the message and store the cookie in the browser.
So, whenever the user hits the site for the first time, he will be prompted with the welcome message which will not be present on subsequent visits. 

The steps 
In blogger's console, click on Design. Next go to Edit Template. 

Try to find 
After body tag place the following html :

<div id='layer1'>
<p>Welcome to my site. Thanks for visiting.(Dismiss)</a></p>

Now move up, and before end of head place a script block :

<script type='text/javascript'>
function GetCookie(name) {
   var arg=name+&quot;=&quot;;
   var alen=arg.length;
   var clen=document.cookie.length;
   var i=0;
   while (i&lt;clen) {
    var j=i+alen;
    if (document.cookie.substring(i,j)==arg)
      return &quot;here&quot;;
    i=document.cookie.indexOf(&quot; &quot;,i)+1;
    if (i==0) break;
   return null;

function setVisible(obj,isopen)
    obj = document.getElementById(obj); = !isopen ? &quot;hidden&quot; : &quot;visible&quot;;
function placeIt(obj)
    obj = document.getElementById(obj);
    if (document.documentElement)
        theLeft = document.documentElement.scrollLeft;
        theTop = document.documentElement.scrollTop;
    else if (document.body)
        theLeft = document.body.scrollLeft;
        theTop = document.body.scrollTop;
    theLeft += x;
    theTop += y; = theLeft + &#39;px&#39; ; = theTop + &#39;px&#39; ;

function loadFirstTime(){
x = 0;
y = 0;
var visit=GetCookie(&quot;COOKIE1&quot;);
  if (visit==null){
    var expire=new Date(); = &quot;thiswin&quot;;
    setVisible(&#39;layer1&#39;, true);
    expire=new Date(expire.getTime()+7776000000);
    document.cookie=&quot;COOKIE1=here; expires=&quot;+expire;
 window.onscroll = function(){

Replace the body tag with  
Thus the body tag calls loadFirstTime when the page loads up.

Finally in the style section add

#layer1 {
 position: absolute;
 visibility: hidden;
 width: 100%;
 height: 60px;
 left: 0px;
 top: 0px;
 background-color: #AF7817;
 border: 1px solid #000;
 padding: 0px;

Now when you visit the site after deleting the browser cookie, you will see the welcome message. Try clicking on dismiss to dismiss the message.

Thank you for reading the content.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

WPF Tutorial : Concept Binding


Before this article, I have discussed about the architecture of WPF, Markup extensions, dependency properties, logical trees and Visual trees, layout, transformation etc. Today I will discuss what we call the most important part of any WPF application, the binding. WPF comes with superior DataBinding capabilities which enables the user to bind objects so that whenever the other object changes, the main object reflects its changes. The main motive of DataBinding is to ensure that the UI is always synchronized with the internal object structure automatically.

DataBinding was present before introduction of WPF. In ASP.NET we bind data elements to render proper data from the control. We generally pass in a DataTable and bind the Templates to get data from individual DataRows. On the other hand, in case of traditional windows forms application, we can also bind a property with a data element. The Bindings can be added to properties of objects to ensure whenever the property changes the value, the data is internally reflected to the data. So in one word, DataBinding is nothing new to the system. The main objective of DataBinding is to show data to the application and hence reducing the amount of work the application developer needs to write to just make the application properly display data. In this article, I will discuss how you could use the Databinding in WPF application and also create a sample application to demonstrate the feature in depth.

Binding in WPF

WPF puts the concept of Binding further and introduced new features, so that we could use the Binding feature extensively. Binding establishes the connection between the application and the business layers. If you want your application to follow strict design patter rules, DataBinding concept will help you to achieve that. We will look into greater detail with how to do that in a while.

In WPF we can bind two Properties, One Property and one DependencyProperty, two DependencyProperties etc. WPF also supports Command Binding.

To Read More about the article please visit the Link
WPF Tutorial : Concept Binding 6

 I hope you will like this article as well.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Garbage Collection Notifications in .NET 4.0

Memory management is primary for any application. From the very beginning, we have used destructors,  or deleted the allocated memory whilst using the other programming languages like C or C++.  C# on the other hand being a proprietor of .NET framework provides us a new feature so that the programmer does  not have to bother about the memory deallocation and the framework does it automatically. The basic usage is :

  1. Always leave local variable.
  2. Set class variables, events etc to null. 
This leaves us with lots of queries. When does the garbage collection executes? How does it affect the current application? Can I invoke Garbage collection when my system / application is idle ?

These questions might come to any developer who has just came to .NET environment. As for me too, I was doing the application just blindly taking it account that this might be the basic usage of .NET applications, and there might be a hidden hand for me who works for me in background. Until after few days, I got an alternative to call the Garbage collection using


But according to the documentation, GC.Collect() is a request.It is not guaranteed that the Collection process will start after calling the method and the memory is reclaim So, there is still uncertainty whether actually the Garbage Collection will occur or not.

Why GC.Collect is discouraged ? 

GC.Collect actually forces the Garbage collection to invoke its collection process out of its regular cycle. It potentially decreases the performance of the application which calls it. As GC.Collect runs in the thread on which it is called, it starts and quickly finishes the call. In such phase of GC collection, actually the memory is not been reclaimed, rather it just produces a thorough scan on objects that are out of scope. The memory ultimately freed whenever Full Garbage collection takes place.
For reference you can read Scotts blog entry.

Whats new in .NET 4.0 (or .NET 3.5 SP1)
 Well, GC is changed a bit with the introduction of .NET 4.0, so that the programmer have better flexibility on how to use GC. One of such changes is the signature of GC.Collect()

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Garbage Collection Algorithm with the use of WeakReference

We all know .NET objects deallocates memory using Garbage Collection. Garbage collection is a special process that hooks in to the object hierarchy randomly and collects all the objects that are not reachable to the application running. Let us make Garbage collection a bit clear before moving to the alternatives.

Garbage Collection Algorithm

In .NET, every object is allocated using Managed Heap. We call it managed as every object that is allocated within the .NET environment is in explicit observation of GC. When we start an application, it creates its own address space where the memory used by the application would be stored. The runtime maintains a pointer which points to the base object of the heap. Now as the objects are created, the runtime first checks whether the object can be created within the reserved space, if it can it creates the object and returns the pointer to the location, so that the application can maintain a Strong Reference to the object. I have specifically used the term Strong Reference for the object which is reachable from the application. Eventually the pointer shifts to the next base address space.

When GC strikes with the assumption that all objects are garbage, it first finds all the Strong References that are global to the application, known as Application Roots and go on object by object. As it moves from object to object, it creates a Graph of all the objects that it finds from the application Roots, such that every object in the Graph is unique. When this process is finished, the Graph will contain all the objects that are somehow reachable to the application. Now as the GC already identified the objects that are not garbage to the application, it goes on Compaction. It linearly traverses to all the objects and shifts the objects that are reachable to non reachable space which we call as Heap Compaction. As the pointers are moved during the Heap compaction, all the pointers are reevaluated again so that the application roots are pointing to the same reference again.

WeakReference as an Exception

On each GC cycle, a large number of objects are collected to release the memory pressure of the application. As I have already stated, that it finds all the objects that are somehow reachable to the Application Roots. The references that are  not collected during the Garbage Collection are called StrongReference, as by the definition of StrongReference, the objects that are reachable to the GC are called StrongReference objects.

This creates a problem. GC is indeterminate. It randomly starts deallocating memory. So say if one have to work with thousand bytes of data at a time, and after it removes the references of the object it had to rely on the time when GC strikes again and removes the reference. You can use GC.Collect to request the GC to start collecting, but this is also a request.

Now say you have to use the large object once again, and you removed all the references to the object and need to create the object again. Here comes huge memory pressure. So in such situation you have :
  1. Already removed all references of the object.
  2. Garbage collection didnt strike and removed the address allocated.
  3. You need the object again.
In such a case, even though the object still in the application memory area, you still need to create another object.  Here comes the use of WeakReference.

Download Sample Application - 27 KB

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Article Selected


I am very happy to announce that another article is selected for "Article of the Day" section in I am happy as my articles are getting more and more been selected, so I am thinking of creating a new section for all those articles that have achieved the honour.

For the time being, You can check the article that is selected:

WPF Tutorial - TypeConverter & Markup Extension 4

Thanks to DotnetFunda, Microsoft and all my readers, without them this might not be possible.

Glad that you all are here.
Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Introducing Ribbon UI Control for WPF


After reading Pete Brown in his post on 2nd Aug announcing the new RibbonUI feature in his post, Announcing:Microsoft Ribbon for WPF, I thought why not try this cool control set myself. So on this note, I tried the control set that Microsoft just introduced and created an application. It is time to introduce with the new control, so that for you it would be easier to start working with it.

Ribbon Bar was introduced with Office 2007 has lately been very much popular for latest UI development. Microsoft has replaced the old Menu based application tool with more flexible and easy to learn Ribbon strips in many of its applications. So it is time for other developers to use it in their own applications. The Ribbon UI feature that was released recently bridges this to us.

In this article I am going to introduce you with the Ribbon Control in WPF. If you are not familiar with WPF, please read
WPF Article Series

What is Ribbon ?

Ribbon is a sort of Toolbar or rather Command Bar which arranges different Command buttons, gallaries, etc in Tabs at the top of the application Window. The controls in the Tabs can further be grouped and also introduces Contextural Tabs etc. So in short, Ribbon replaces toolbar and menu controls that are there with windows and gives a solid look on the application UI.

This is the default Ribbon Template that comes when you first create your application and also gives you a better idea on how the new RibbonWindow looks like.

Download RibbonTestApplication Source

Shout it Submit this story to DotNetKicks Bookmark and Share
Read Disclaimer Notice

Publish Desktop Application - SmartClient

For any desktop application the first concern that comes to your mind is how you would deploy the application to your clients. We create setups and distribute the application to our clients and want our client to get any updates that we publish. But there are lots of dependency in updates. Say you want your application to get a regular updates. In such a situation, you have to distribute the setup again, so that the user installs it and get the update. You publish your application in Version, so that every time the user logs in to your site, it will get informed about the update and install it. Rather than that, you might have already tried to create a logic on your application to fetch the current version from the server and get the update in background. Yes, this would be the best way to do. Many application does this. It checks for the latest version and allows the user to get the update. Those are called Smart Client Application.

So what is required  to create such installer?
  1. You need a web folder where the current installer should be kept. 
  2. The web folder must have access from the application.
  3. The installer could be downloaded and auto launched.
  4. Force the application to update itself.
So there are lots of things that you need to create to do this simple task. You need create a brand new setup project that you want to be downloaded to the client and consumed.  You also need to write a logic of when the server should be checked and how it should be downloaded. You also need to ensure that the version it downloads is correct. So there is a huge task that you need to do for this simple task.

Microsoft comes with a solution to easily address this issue and solve it. In this article, I will show how you could do this using Visual Studio without writing a single line of code.


  • Open the application in Visual Studio.
  • Create a setup if you can. Alternatively you can also use click once deployment on Web.
  •  Now for Updates, Create a FTP location and an HTTP location. 
  • Right Click on Project and Select Properties
  • You will see a separate Tab for publish. 
  • Put your FTP location on Publishing location, so that the publish could upload the application files to the server. 
  • Use Installation Location as HTTP so that the application from client site can easily download the file when required and install it. 
  • You can select Publish version to ensure there is no version conflict. 
  • From Options button you can configure a page which enables you to setup the application. By default the publish page will be Publish.html.

    You can configure the settings with the Publisher name, Product Name etc, which will appear in the Publish page.
  • Finally click on Publish or Publish wizard. The command will ask for Ftp UserId and Password (if any) and deploy the application on the ftp site. 
  • After the application is published, you will see the launch page as below:

In the page, you can use Install Button to install in the client location.

Now if your client has the application installed in the machine, the application will automatically update itself whenever any new version is updated in the server.

This is the most basic click once deployment approach provided by Microsoft. Please note, you need to give strong name to any external assembly you produce.

To create custom Updater, you need to mimic the approach. I am also creating a self updater. I will share that once I am done with it.

Thank you for reading.
    Shout it Submit this story to DotNetKicks Bookmark and Share
    Read Disclaimer Notice

    Author's new book

    Abhishek authored one of the best selling book of .NET. It covers ASP.NET, WPF, Windows 8, Threading, Memory Management, Internals, Visual Studio, HTML5, JQuery and many more...
    Grab it now !!!