Sunday, August 29, 2010

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

Wednesday, August 25, 2010

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

Tuesday, August 24, 2010

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.

Friday, August 20, 2010

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


Thursday, August 19, 2010

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 
tag.
After body tag place the following html :


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

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);
    obj.style.visibility = !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;
    obj.style.left = theLeft + &#39;px&#39; ;
    obj.style.top = theTop + &#39;px&#39; ;
    setTimeout(&quot;placeIt(&#39;layer1&#39;)&quot;,500);
}

function loadFirstTime(){
x = 0;
y = 0;
var visit=GetCookie(&quot;COOKIE1&quot;);
  if (visit==null){
    var expire=new Date();
    window.name = &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(){
   placeIt(&#39;layer1&#39;);
  }
}
<script>

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;
        color:#FFF;
 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.

Monday, August 16, 2010

WPF Tutorial : Concept Binding

Introduction


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.

Thursday, August 12, 2010

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

GC.Collect()

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()

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