Thursday, July 29, 2010

Visual Studio 2010 Trace Options for WPF 4.0

Visual Studio is one of the most popular and interesting IDE that Microsoft has build to enhance the productivity of Developers. The Visual Studio IDE is not created just to help the developers, but if you see the survey of how and where the Visual Studio is been used, you would be surprised to see that how much it is used by even non-technical persons.

Microsoft always makes me happy with certain things that I might have always wanted. Just today, I saw the same. Visual Studio 2010 now comes with inbuilt Tracer for WPF applications, to trace the internal calls to the Binding DataElements to the debug output window. There are options to turn on trace settings especially for WPF applications to trace WPF animations, Bindings etc which were more or less abstract to us. So if you put a tracer on to these settings, it will automatically log steps that it does while doing WPF steps. Lets look into how you could do this :

  1. Open your WPF Application.
  2. Go to Tools -> Options.


  3. In the Left side treeView, choose Debugging - > Output window
  4. Now, you can see WPF Trace Settings Section. 
This section lists all the abstract WPF steps, which every developer would love to see and those which have very less or even no trace option from code. In the above figure you can see we can also enable tracer to certain levels like, Critical, Error, Warning, Information, Verbose, Activity, All... each of them will trace to the extent we provide.

Article Selected @WindowsClient.net

So,

I am sorry I forgot to mention that for the last few weeks, there are few more articles selected in WindowsClient.net. As there were more and more articles are getting selected to Microsoft Community, it might annoy you if I post it everytime. But today, I saw one of my Blog post from this site is been posted to www.windowsclient.net. So, it is a great occasion to me that an article from my own blog has got selected as Article of the Day.

A few days back, I wrote one post in this site where I introduced a tool which will help you to create ResourceDictionary on the fly. The tool uses Bing Translate Services to fetch data from one language and translate to another and hence makes this readily available as ResourceDictionary of XAML application. You can read the article from :

Resource Generator Tool for Language Translate


Today, July 28, 2010, the article is listed to WindowsClient.Net.

For last few weeks the articles that are selected are :

Layout Panel Containers - & Layout Transformation
Design Patterns in C#

So, I am thinking to create a separate section in the site to list all the articles that are selected specially for Microsoft WebSites. I hope this would give more help to the visitors.

What do you think guys? Write your feedback.

Also thanks for all your support.  Thank you.

Monday, July 26, 2010

WPF Tutorial : Dependency Property

WPF comes with a lots of new features and alternatives that the normal windows applications do not have. As we have already discussed some of the features of WPF, its time to go a bit further to introduce other new features. After reading the previous articles of this tutorial, I hope you are more or less familiar with WPF architecture, borders, Effects, Transformation, Markup extensions etc.

So in this article I am going to introduce you with a new property system that underlay the WPF property system. We will go further to introduce how easily you can use these properties to produce custom callbacks, create attached properties, apply animations and styles etc using the all new Dependency properties.  Finally we will discuss about Binding alternatives that were left behind in the previous article to finis it totally. I hope you will like this article as well as you did for all the tutorials that I provided.

A new Property System


Well, you must have surprised to to see this title. Yes, WPF comes with a completely new technique of defining a property of a control. The unit of the new property system is a Dependency property and the wrapper class which can create a Dependency property is called a DependencyObject. We use to register a Dependency property into the property system to ensure that the object contains the property in it and we can easily get or set the value of those properties whenever we like. We even use normal CLR property to wrap around a dependency property and use GetValue and SetValue to get and set values passed within it.

This is almost same as CLR property system. So what is the advantages of the new property system. Lets see the difference between Dependency property and CLR property.

To Work with dependency property, you must derive the class from DependencyObject as the whole observer which holds the new Property System is defined within the DependencyObject.

Difference between Dependency property and CLR property


CLR property is just a wrapper around private variables. It uses Get / Set methods to retrieve and store value of a variable into it. So to be frank with you a CLR property gives you only one block in which you can write code to invoke whenever a property is get or set. Hence CLR property system is fairly straight forward.

On the other hand, the capabilities of Dependency property system is huge. The idea of Dependency property is to compute the value of the property based on the value of other external inputs. The external inputs might be styles, themes, system properties, animations etc. So, you can say a dependency property works with most of the WPF inbuilt features that were introduced.

READ The Full Article

Sunday, July 25, 2010

Another MVP Award @DNF

Guys,

Its time to celebrate again. After putting lots of efforts to write good articles for DotNetFunda, I finally been awarded as MVP this year. 


To see all my articles, just click on the link. 

 I must thank Owner of DNF, Sheo Narayan and all my well wishers for this honor. I have also been Codeproject MVP last year. I am hoping, I would continue with the good work that I am doing.

Thank you all for your appreciation.

Follow my blog.

Cheers.

Friday, July 23, 2010

Code Snippet in VS Studio

Code Snippet is one of the best and easiest way for any developer to increase code productivity. As far I know, there are lots of people who dont know about this feature in VS studio. It is interesting feature which helps you to get a template of your method or property to code it quickly.

I believe everyone knows about intellesense feature that is already there with Visual Studio. There is nothing more I could tell about this lovely feature. While browsing the list of objects in the intellesense window, you would have already seen few icons. These icons provide special meaning. Some of them signifies keywords, some are custom types/classes, some are methods. One of these are Code snippets.






In the above figure, you can see how a code snippet looks like.  Here in the above code, I have just started typing pro.... You will see a prop menu item should be there, which is actually a code snippet for a property stub. If you use TAB to select prop and then press Tab again, you will see something similar to one below:



A new Property will be created which has return type as int and name of the property is MyProperty. As I am using VS 2010 to do this, you will see the automatic property initializer here. But for previous version, you might see a little longer than this property. It will create a variable and also a Property to access that variable. In VS 2010, if you want that property snippet, you will have to use propfull.




In either case, use TAB to stop to each of the literals. If you change the int to float, the return type of the property will also change likewise. Similarly if you press TAB again, and change the name of the variable, it will also reflect to the property.


Just similar to properties, you can also apply Code snippets to methods, structs, classes etc.





Thus in the above figure you can see that testm produces a TestMethod. Hence you can say code snippets enhances the code production in a huge extent.

You can now even add code snippet in the asp.net page.




Here using code snippet  I have added a new update panel. But to remind you, code snippet is added in aspx page in VS 2010.

Code Snippet Manager

Visual Studio comes with Code-snippet manager. This is a tool which enables you to change an existing code snippet and also enlist all the code snippets that are available within the IDE. To check the Code snippet manager, go to Tools menu of Visual studio IDE and choose Code Snippet Manager.





In the above figure you can see you can easily manage the property / code snippets from within the Manager. You can get the location where the actual code snippets are installed. You can even import a new code snippet to your Visual Studio IDE.  By default the custom VS code snippets are loaded from MyDocuments/Visual Studio/Code Snippets.


Custom Code Snippet

Yes, in spite of large number of code snippets available for the IDE, I always find something short while writing my code. All of us has unique coding styles. Visual Studio IDE offers custom Code snippets that you can produce just by writing an XML schema definition and placing it on Code Snippets folder inside MyDocuments folder with custom extension .snippet.

Let us write an snippet which we need most of the times while writing code in WPF. We need to invoke events called OnPropertyChanged and OnPropertyChanging. Inspite of writing this several times lets fix this issue somewhat.

<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets  xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <CodeSnippet Format="1.0.0">
        <Header>
            <Title>propnch</Title>
            <Shortcut>propnch</Shortcut>
            <Description>Code snippet for property and backing field and ensure that it invokes INotifyPropertyChanigng and INotifyPropertyChanged</Description>
            <Author>Abhishek</Author>
            <SnippetTypes>
                <SnippetType>Expansion</SnippetType>
            </SnippetTypes>
        </Header>
        <Snippet>
            <Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
                <Literal>
                    <ID>field</ID>
                    <ToolTip>The variable backing this property</ToolTip>
                    <Default>myVar</Default>
                </Literal>
            </Declarations>
            <Code Language="csharp"><![CDATA[

    private $type$ $field$;

    public $type$ $property$
    {
        get 
        { 
            return $field$;
        }
        set 
        { 
            this.OnPropertyChanging("$property$");
            $field$ = value;
            this.OnPropertyChanged("$property$");
        }
    }
    $end$]]>
            </Code>
        </Snippet>
    </CodeSnippet>
</CodeSnippets>

So from the above code you can see a new Property Snippet is added to the system. To try that you just go to the code window and type propnch. It will produce the output.



Now lets explain this a bit.

We divide the whole XML into three parts :

1. The header section :

<Header>
    <Title>propnch</Title>
    <Shortcut>propnch</Shortcut>
    <Description>Code snippet for property and backing field and ensure that it invokes INotifyPropertyChanigng and INotifyPropertyChanged</Description>
    <Author>Abhishek</Author>
    <SnippetTypes>
        <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
</Header>

In this section, I defined the Title, which represents the name of the snippet. The shortcut defines what will appear in the intellesense menu. The description comes as a tooltip.
SnippetTyes defines the type of the snippet. In general we leave it as Expansion, but it also has few other types like : Surroundswith and Refactoring.

2. Variables :
In the second part we define variables for which we want to input during the use of it.

<Declarations>
                <Literal>
                    <ID>type</ID>
                    <ToolTip>Property type</ToolTip>
                    <Default>int</Default>
                </Literal>
                <Literal>
                    <ID>property</ID>
                    <ToolTip>Property name</ToolTip>
                    <Default>MyProperty</Default>
                </Literal>
                <Literal>
                    <ID>field</ID>
                    <ToolTip>The variable backing this property</ToolTip>
                    <Default>myVar</Default>
                </Literal>
            </Declarations>

You can see in the above XML segment, I have defined literals like type which defaults to int, property which defaults to MyProperty and field which defaults to myVar. These variables can be accessed using $ sign, which indicates where these variables will be placed. In code, anything written inside $ sign will be replaced by users action.

3. Declaration:

<Code Language="csharp"><![CDATA[

    private $type$ $field$;

    public $type$ $property$
    {
        get 
        { 
            return $field$;
        }
        set 
        { 
            this.OnPropertyChanging("$property$");
            $field$ = value;
            this.OnPropertyChanged("$property$");
        }
    }
    $end$]]>
            </Code>
        </Snippet>

In the final part we define the code. You can see, in my example I used C# as my language. The code is written inside the Code element and we put parameters wrapped within $ sign as I have already told you that these will be replaced when we use it in code.
Thus you can see, the variables are replaced within the code while you use it. You can use TAB to move from one variable to another.

I hope you can create more snippets like this to enhance your IDE capabilities.

Thanks for reading.

Sunday, July 18, 2010

XML Binding in WPF with Sample RSS reader

XAML being getting more and more popular is also introduced for Mobile applications. Recently while I was exploring on the internet, I found that the recent version of Windows 7 mobile interfaces uses Silverlight to deal with the interface. Just after the initial thought, I thought to try it for just to increase my knowledge base. Hence, I installed it to my machine and tried. It works great and I am really excited to see that Silverlight is again introduced with this mobile.

Inspite of having XNA for truely 3D style of application building, I tried simple programs to use this edition of silverlight and it worked greatly. It works in the most simplest way as with normal silverlight applications.

While doing the simple application, I found the XML binding within WPF application as an interesting part of XAML bindings. In this post, I will discuss how you can implement binding of a property with an XMLDataSource.

XML is very important part for any application. While you create your application, we generally need to write lot of code to handle XML data stream. May be from your local machine, or using WebClient to download data from your web server. WPF has in built support for XML bindings. Lets discuss XML bindings in detail using sample code.

Say you have an XML like this :

<data>
  <packet id="names">
    <Names description="All are selected">
      <nametype id="1" firstname="raja" lastname="das">58</nametype>
      <nametype id="2" firstname="anjan" lastname="chowdhuri">67</nametype>
      <nametype id="3" firstname="charu" lastname="singh">38</nametype>
      <nametype id="4" firstname="manju" lastname="sen">69</nametype>
      <nametype id="5" firstname="sanju" lastname="sharma">89</nametype>
      <nametype id="6" firstname="sanjana" lastname="mathur">77</nametype>
    </Names>
  </packet>
</data>

Now let us create a code that binds each elements of the above xml.

<Window.Resources>
        <XmlDataProvider Source="myxmldata.xml" x:Key="xdata" XPath="/data/packet/Names"></XmlDataProvider>
    </Window.Resources>

So first of all we have added a new window, and added the XmlDataSource as resource. Please note that we can also use x:Data to define the XmlDataSource Xml directly within the file itself like :

<XmlDataProvider x:Key="xdata" XPath="/data/packet/Names">
            <x:XData>
                <data xmlns="">
                    <packet id="names">
                        <Names description="All are selected">
                            <nametype id="1" firstname="raja" lastname="das">58</nametype>
                            <nametype id="2" firstname="anjan" lastname="chowdhuri">67</nametype>
                            <nametype id="3" firstname="charu" lastname="singh">38</nametype>
                            <nametype id="4" firstname="manju" lastname="sen">69</nametype>
                            <nametype id="5" firstname="sanju" lastname="sharma">89</nametype>
                            <nametype id="6" firstname="sanjana" lastname="mathur">77</nametype>
                        </Names>
                    </packet>
                </data>
            </x:XData>
        </XmlDataProvider>

Please note that I have added the xmlns in data tag intentionally, as if you dont the xml will inherit from the base Namespace.
The XPath within the XmlDataProvider induces the read of XML from that path. So for our XML the data will be read after /data/packet/names.

So lets begin with bindings.
<Grid DataContext="{StaticResource xdata}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <TextBlock Text="{Binding XPath=@description, StringFormat='{}Status: {0}'}" Grid.Row="0"/>
        <ListBox x:Name="lstNames" ItemsSource="{Binding XPath=nametype}" IsSynchronizedWithCurrentItem="True" Grid.Row="1" SelectionChanged="lstNames_SelectionChanged">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock>
                        <TextBlock.Text>
                            <MultiBinding StringFormat="{}{0} {1} Got {2}">
                                <Binding XPath="@firstname"></Binding>
                                <Binding XPath="@lastname"></Binding>
                                <Binding XPath="text()"></Binding>
                            </MultiBinding>
                        </TextBlock.Text>
                    </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
        <StatusBar Grid.Row="2">
            <TextBlock Text="Roll Number :"></TextBlock>
            <TextBlock x:Name="txtRoll"></TextBlock>
            <Separator/>
            <TextBlock Text="You Got : "></TextBlock> 
            <TextBlock Text="{Binding ElementName=lstNames, Path=SelectedItem.InnerText}"/> 
        </StatusBar>
    </Grid>

In the above XAML code, you can see I have put the datacontext of the Grid to the XmlDataProvider resource.

Keep in mind @ is used for attributes and / is used for tags. So the first TextBlock shows @description which means the string written within the description attribute of Names tag.

Now as we are in a collection of names, lets take a listbox to show all the elements within the XML data. The ItemsSource allows you to bind data with specific XPath. Here we have used nametype, as our main collection is of nametype. Within the datatemplate, we place one TextBlock for which the data is multi-bound. We use firstname and lastname attribute to put binding on the TextBlock Text property. In this situation, you can see, I have used @firstname and @lastname which will ensure that the binder will evaluate the Attribute rather than the innerText. The StatusBar allow you to show the bound data for the SelectedItem of the ListBox.

Things to Remember :
  1. Use XPath to move to a particular node path.
  2. Move to currentElement using XPath and choose @ for attribute and text() to get the InnerText.
  3. / is used to move to the child nodes. 
  4. In case you define your xml within XAML, be sure to specify the namespace to blank. Otherwise it will inherit from XAML namespace.

A little RSS Reader

So as things are now clear, lets build a sample RSS reader.



RSS is a special XML schema, so when we load RSS into our XMLDataProvider, we need to parse it in a special format. So lets see how the XAML looks like.

<Window.Resources>
        <XmlDataProvider x:Key="dnt" 
                     Source="http://www.abhisheksur.com/feeds/posts/default?alt=rss" 
                     XPath="/rss/channel" />
    </Window.Resources>
    <StackPanel DataContext="{Binding Source={StaticResource dnt}}">
        <StackPanel>
            <TextBlock Text="Title : " />
            <Label Content="{Binding XPath=title}"/>
            <TextBlock Text="Description : "/>
            <Label Content="{Binding XPath=description}"/>
        </StackPanel>
        <ListBox    IsSynchronizedWithCurrentItem="True" 
                    ItemsSource="{Binding XPath=item}"
                    MaxHeight="500" 
                    ScrollViewer.CanContentScroll="False">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding XPath=title}" FontSize="30" />
                        <TextBlock Text="{Binding XPath=link}" FontSize="12" />
                        <Expander Header="Read..">
                            <TextBlock Text="{Binding XPath=./description}" TextWrapping="Wrap" TextTrimming="WordEllipsis" MaxWidth="520"/>
                        </Expander>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
</StackPanel>

The sample code looks almost similar to what we have already discussed. The major difference is how you parser the XML coming from the RSS feed. Here the XMLDataProvider points to an external Web address. The program once starts takes a second to load the rss from the external source. Once it is loaded, the specific nodes are bound to the Title, description and items shown on the ListBox.

Download Sample Application

I hope this would help you understanding how you could load your XML using Binding.
If you have any query, please let me know. Thanks for reading.

Sunday, July 11, 2010

Operator Overloading with Implicit and Explicit Casts in C#

Its been a very common mistake of not declaring implicit and explicit cast operator overloads while working with data types which might take part in some calculations in long run. I found many of the developers don't know why we use checked or unchecked while doing calculations. On this regard, I thought to post an article on how you can use Cast overloads to get your job done easily when you require your type to take part in arithmetic operations and casts to arithmetic data types.

Let us explain the concept using an example. Say I declare a class that would take Feet and inches in one single type. C# doesn't expose such type to us. So let us create one for us to demonstrate the concept.


public class Finch
    {
        private int feet;
        private int inch;

        public int Feet
        {
            get { return this.feet; }
            set
            {
                this.feet = value;
            }
        }
        public int Inches
        {
            get { return this.inch; }
            set
            {
                if (value > 11)
                {
                    this.feet += (value / 12);
                    this.inch = (value % 12);
                }
                else
                    this.inch = value;
            }
        }
        public override string ToString()
        {
            return string.Format("{0}''{1}'", this.Feet, this.Inches);
        }
    }

So you can see I have declared a class Finch which has two members Feet and Inches. The class is used to hold. As a matter of fact, the value of inches cannot be made over 11. So in the setter of inches, we strip the values which is greater than 11 to add up to the feet. So that we always get the proper value for Feets and inches.

Lets take the class a bit further.
Download Source Code - 30KB

Monday, July 5, 2010

Dynamic Behaviour on Objects at Runtime With Custom ExpandoObject

.NET 4.0 comes with lots of new features. One of the interesting things that it comes with is the Dynamic Behaviour of an object. If you have already read my article on C# 4.0 you know the basics of how to work with dynamic keyword in your application. In this post I will introduce how you could use ExpandoObjects, a new way of writing your truly dynamic code and also take you deep into how you could create your own ExpandoObject.

Being C# a strongly typed language, you might wonder how you could make it dynamic. In C# everything that we define will have a strong signature. There are numerous languages available like Python, Ruby, and most notably Javascript which are not strongly typed and you can change the object anytime whenever you require. C# 3.5 or below doesn't support changing the type dynamically during runtime. But as a developer we generally miss this flexibility of the language. But seriously that shouldn't change the class of the language like what C# is. I mean, by adding up features like dynamic language we shouldn't be compromise with C# as a strongly typed language.

Microsoft introduced dynamic in C# with C# 4.0. But believe me, C# is not a truly a dynamic language now. Hopefully they will introduce it in .NET 5.0. Let us talk about dynamic keyword a bit for time being.

Difference Between Object and Dynamic

When I first came across with dynamic in C# 4.0, I have wonder why do we require this. We have object which can hold any objects into it as it is called as mother of all objects. Objects can hold anonymous types or even call properties or methods of an anonymous type easily, so what exactly do we  require for dynamic. To demonstrate the situation let us take the example on how you can call properties or methods of an object for which you don't know the exact type.
Let I have a class Person which looks like :

internal class Person
{
     public string Name { get; set; }
     public int Age { get; set; }
     public double Weight { get; set; }
     public string GreetMe()
     {
         return string.Format("Hello {0}", this.Name);
     }
}

Now let our method GetObject returns an object of Person class as object. So to call properties or Methods we would write like :


public void ResolveStatic(object obj)
{
      PropertyInfo pinfo = obj.GetType().GetProperty("Name");

      //To Get from a property Name
      object value = pinfo.GetValue(obj, null);
      string content = value as string; 
Console.WriteLine(content);

       // To Set to Property Name
      pinfo.SetValue(obj, "Abhijit", null);

      //Invoke a method 
      MethodInfo minfo = obj.GetType().GetMethod("GreetMe");
      string retMessage = minfo.Invoke(obj, null) as string;

      Console.WriteLine(retMessage);
}

This is really what you expect to write. Does it looks complex to you? Yes, it is. Probably if you have more flexibility like Static Method, or multiple argument for a method, or even an indexer your code will look horrendous.

dynamic keyword helps you in this regard. Yes, you can simply call methods and properties in your code without writing the whole Reflection methods, and the compiler will do them for us. So doing the same thing with dynamic the code will look like :

public void ResolveDynamic(dynamic obj)
{
      Console.WriteLine(obj.Name);
      obj.Name = "Abhijit";

      Console.WriteLine(obj.GreetMe());
}

So the code looks the simplest and same as to known types. Actually if you see through the reflector, you will see that the same code is created by the compiler for us. So dynamic keyword makes our code look simple for dynamic types and also make the code easy to understand.

So, are you thinking this is the end of this ? Nope... Its the beginning of capabilities of dynamic. Let us discuss the true feature of dynamic in detail.

ExpandoObject, A true Dynamic Object

ExpandoObject is a new class added to enhance the dynamic capabilities of C# 4.0. ExpandoObject lets you to add methods or members to an object dynamically during runtime. Let us discuss this in detail using an example :
Let us create our class Person dynamically in runtime using ExpandoObject. To do this, we just need to write:


dynamic d = new ExpandoObject();
d.Name = "Abhishek Sur";
d.Age = 26;
d.Weight = 62.5d;
d.GreetMe = new Action(delegate()
{
      Console.WriteLine("Hello {0}", d.Name);
});
p.ResolveDynamic(d);

So here you can see, the object ExpandoObject is extended in runtime to add properties and methods dynamically.Isn't it cool. Now the language is truly flexible and dynamic in true sense.

If you are wondering how it is possible, or the depth behind creating the ExpandoObject class, lets read further to create your own Dynamic object.

Create Object that Extend in RunTime(Custom ExpandoObject)

To understand how a statically typed language can extend properties and class in runtime, or how this could be made possible, you need to delve deep into the internal structure of ExpandoObject.

Actually ExpandoObject is a Collection of KeyValuePair where the Key represents the interface through which the objects are called for and the Value is the object which might be a string, an object or a method depending on what you pass. When we pass the methods, properties to an ExpandoObject it actually adds those as a KeyValuePair into its collection, and when the object is invoked it calls up the method or property dynamically. 

Now to create your own Custom ExpandoObject you need to inherit your class from IDynamicMetaObjectProvider. This interface has a method called GetMetaObject, which you need to implement to create DynamicMetaObject from the Linq expression. On the first instant, it seemed to me as a trivia, but it is not. You actually need to parse the complex Linq Expression to create your Meta object.  I must thank Microsoft for giving an implementation of IDynamicMetaObjectProvider as DynamicObject. So for simplicity, you can inherit your class from DynamicObject and do your job done.

Let us implement our class from DynamicObject :

public class CustomExpando : DynamicObject
 {
        public IDictionary<string, object> Dictionary { get; set; }

        public CustomExpando()
        {
            this.Dictionary = new Dictionary<string, object>();
        }

        public int Count { get { return this.Dictionary.Keys.Count; } }

        public override bool TryGetMember(GetMemberBinder binder, out object result)
        {
            if (this.Dictionary.ContainsKey(binder.Name))
            {
                result = this.Dictionary[binder.Name];
                return true;
            }
            return base.TryGetMember(binder, out result); //means result = null and return = false
        }

        public override bool TrySetMember(SetMemberBinder binder, object value)
        {
            if (!this.Dictionary.ContainsKey(binder.Name))
            {
                this.Dictionary.Add(binder.Name, value);
            }
            else
                this.Dictionary[binder.Name] = value;

            return true;
        }

        public override bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
        {
            if (this.Dictionary.ContainsKey(binder.Name) && this.Dictionary[binder.Name] is Delegate)
            {
                Delegate del = this.Dictionary[binder.Name] as Delegate;
                result = del.DynamicInvoke(args);
                return true;
            }
            return base.TryInvokeMember(binder, args, out result);
        }

        public override bool TryDeleteMember(DeleteMemberBinder binder)
        {
            if (this.Dictionary.ContainsKey(binder.Name))
            {
                this.Dictionary.Remove(binder.Name);
                return true;
            }

            return base.TryDeleteMember(binder);
        }

        public override IEnumerable<string> GetDynamicMemberNames()
        {
            foreach (string name in this.Dictionary.Keys)
                yield return name;
        }
}

Here we have overridden Methods
  1. TryGetMember : Called when Get method of a Property is called. If returned true the value in result will be returned.  
  2. TrySetMember : Called when Set method of a property is called. If returned true the value in result will be set to the member.
  3. TryInvokeMember : Called when a delegate/method is called. The result will be returned.
Unless others are required, you can use these  members only to have an ExpandoObject.Quite easy huh? Yes. To use this class we use :

dynamic expandoObject = new CustomExpando();
expandoObject.Name = "Akash";
expandoObject.CallMe = new Func<string, string>(delegate(string name)
{
       expandoObject.Name = name;
      return expandoObject.Name;
});

            Console.WriteLine(expandoObject.Name);
            Console.WriteLine(expandoObject.CallMe("Hello"));

Now to remove a member you just need to use

expandoObject.Dictionary.Remove("Name");

So this is it. Now you can handle your ExpandoObject yourself.

Download Sample Application


For further Reference :
http://tomlev2.wordpress.com/2009/10/08/c-4-0-implementing-a-custom-dynamic-object/
http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject.aspx
http://blogs.msdn.com/b/csharpfaq/archive/2009/10/01/dynamic-in-c-4-0-introducing-the-expandoobject.aspx

I hope you like this article. Please put your comment. Thanks for reading.

Difference between Hidden and Collapse

While doing code, developers always find problems on what might be the difference between the concept of Hiding an element and Collapsing an element. Every UIElement has two visibility states, you can do Collapsed or you can do Hidden. Hidden and collapsed are two similar approach in which the UIElement will not be visible to the user. In this article I am going to show how both of the concepts are different in WPF, and later on we will relate the same with ASP.NET.

Notion of Hidden and Collapsed

Hidden means hiding an object but the area in which the object will be placed will be remain expanded. This means, when the object is hidden, the placeholder will remain intact with the same size which the actual object will require when it is placed on the same portion.

Collapsed on the other hand, removes the space of the placeholder, and thus when an object is collapsed, the subsidiary objects will move towards the object and hence the empty space will be filled up with other UIElements. (It depends on the layout you choose).






Demonstration

In the above 2 pictures of the sample application, you can see there are 4 boxes, Box1, Box2, Box3 and Box4. The first window will appear when we write the following code :

<StackPanel Orientation="Vertical">
    <Border Background="Goldenrod" Width="50" Height="50">
        <TextBlock Text="Box1"></TextBlock></Border>
    <Border Background="SlateBlue" Width="50" Height="50">
        <TextBlock Text="Box2"></TextBlock>
    </Border>
    <Border Background="SaddleBrown" Width="50" Height="50">
       <TextBlock Text="Box3"></TextBlock>
    </Border>
    <Border Background="LemonChiffon" Width="50" Height="50">
      <TextBlock Text="Box4"></TextBlock>
    </Border>
</StackPanel>

Now if you make a slight adjustment to the code to hide and collapse the boxes in the middle so that it turns to the image next to it. Lets make Box2 as Hidden and Box3 as Collapsed. 


<StackPanel Orientation="Vertical">
    <Border Background="Goldenrod" Width="50" Height="50">
        <TextBlock Text="Box1"></TextBlock></Border>
    <Border Background="SlateBlue" Width="50" Height="50" Visibility="Hidden">
        <TextBlock Text="Box2"></TextBlock>
    </Border>
    <Border Background="SaddleBrown" Width="50" Height="50" Visibility="Collapsed">
       <TextBlock Text="Box3"></TextBlock>
    </Border>
    <Border Background="LemonChiffon" Width="50" Height="50">
      <TextBlock Text="Box4"></TextBlock>
    </Border>
</StackPanel>

The 2nd Box as been made as Hidden, reserves its portion, while Box3 leaves its portion. Thus Box 4 can move up a bit to make room in place of Box 3 but it cannot move up to Box2 as Hidden will not collapse the space where the Box2 will appear.

In Relation with HTML

In HTML elements, UI objects can be made invisible using either of the two CSS properties. You can either make Visibility:hidden or display:none.
display:none  makes the object hidden while the other object will fill up the space just like what we have just discussed with Collapsed.  On the other hand visibility:hidden will make the object hidden while the space for its allocation remains reserved as we have discussed in case of Hidden.


In the above figure, you can see how the text behaves when we click on the radiobuttons to make the object hidden or collapsed using javascript.

The code looks like :

<script type="text/javascript">
        function DoHandle(stat) {
            var elem = document.getElementById('btn');
            if (elem) {
                switch (stat) {
                    case 'collapse':
                        elem.style.visibility = 'collapse'; // Does not work in most cases.
                        elem.style.display = 'none';        //alternate that works
                        break;
                    case 'hidden':
                        elem.style.visibility = 'hidden'; //works in most cases
                        elem.style.display = 'block';
                        break;
                    case 'visible':
                        elem.style.visibility = 'visible'; //works in most cases
                        elem.style.display = 'block';
                        break;
                }
            }
        }
    </script>
   <p>
      The Button <input type="button" value="The Button" id="btn" style="clear:none;"/> will remain expanded. 
      <br />
      <input type="radio" name="rd" value="Collapse" onclick="javascript:DoHandle('collapse');"/> Collapse
      <input type="radio" name="rd" value="Hidden" onclick="javascript:DoHandle('hidden');"/> Hidden
      <input type="radio" name="rd" value="Visible" onclick="javascript:DoHandle('visible');"/> Visible
    </p>

Thus you can see how I did make the object hidden or collapsed and how the UI gets modified.

Download Sample - 214 KB

Thank you for reading this post. I hope you like it.

Thursday, July 1, 2010

Unhandled Exception Handler For WPF Applications

Exception handling is very vital for any software. We use our traditional way of handling exceptions of our code using Try/ Catch / Finally block to handle runtime exceptions.We write our code inside try block and wait for the error being generated from the code, and write our proper handler to handle the Exception if generated while running the code. Compiler handles all these problems and calls the appropriate catch automatically. We write various Catch blocks which handles the exception based on the type of exception that occurs. After the exception is handled properly, the normal execution of the program remains unaffected.

Well this is very normal for any program. Even though we always try to make our code Ultra-Defensive, sometimes we fall in a prank when our client tells us about an Weird Exception that took place in their environment. May be you browse the whole solution to find the problem, and didn't find the actual issue. Yes, there are lots of exceptions that you cannot handle from your code.

Exception on UI Thread (Dispatcher)

Say your client could not install your application properly and missed out a couple of dlls or missed out themes that you might have used from your code. In these scenarios, we need to use a global handler which you want to be executed whenever any exception that is not handled by your code, or exception which is generated in extreme cases. In case of WPF applications, Application.DispatcherUnhandledException comes the most handy in this situation.

WPF application object comes with DispatcherUnhandledException, an event which is generated automatically whenever application is going to be crashed after an exception is generated. Let us generate see the code on how you could handle these situations :

<Application x:Class="UnhandledExceptionHandler.App"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    StartupUri="Window1.xaml"
    Startup="Application_Startup"
    DispatcherUnhandledException="Application_DispatcherUnhandledException">
    <Application.Resources>
         
    </Application.Resources>
</Application>

In the above code you can see, I have added an Eventhandler for the application. The DispatcherUnhandledException is called whenever the UI thread of the application generated an unhandled exception. To handle the exception we write :


public bool DoHandle { get; set; }
        private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            if (this.DoHandle)
            {
                //Handling the exception within the UnhandledExcpeiton handler.
                MessageBox.Show(e.Exception.Message, "Exception Caught", MessageBoxButton.OK, MessageBoxImage.Error);
                e.Handled = true;
            }
            else
            {
                //If you do not set e.Handled to true, the application will close due to crash.
                MessageBox.Show("Application is going to close! ", "Uncaught Exception");
                e.Handled = false;
            }
        }

In the above code, I have placed a boolean property to determine if we need to handle the exception or not. You can see, if the value of DoHandle is true, I have set e.Handled = true and vice-versa.

DispatcherUnhandledExceptionEventArgs comes with few arguments.
1. Exception : This object is the actual Exception that is generated from the application.
2. Dispatcher : You might already know, Dispatcher points to the UI thread.
3. Handled : It determines if the block has already handled the exception. The default value for e.Handled = false, which means, the application still have the exception.


Thus in our case, if you do not put e.Handled = true, the application will eventually crash down.  So it is very important to set the property e.Handled = true after you handle the exception.

Please note : Sometimes, even though you did set e.Handled = true, the application might crash down. This depends on the severity of the Exception.


Exception on Custom Threads


In case of your custom Threads, your exception will not be caught by the DispatcherUnhandledException. This event hooks only the UI thread, and only be called when the UI thread gets an exception which crashes the program. If you need to handle the Exception occurring from Non UI Thread, you can handle the UnhandledException that comes with AppDomain.


If you are not running your Threads in a new AppDomain, you might handle the UnhandledException event of AppDomain, and this would be called whenever any thread that runs on the AppDomain gets an Exception Object. To make it most simple, I have used AppDomain.CurrrentDomain.UnhandledException.

private void Application_Startup(object sender, StartupEventArgs e)
        {
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = e.ExceptionObject as Exception;
            MessageBox.Show(ex.Message, "Uncaught Thread Exception", MessageBoxButton.OK, MessageBoxImage.Error);
        }

In the above code you can see I have handled the CurrentDomain.UnhandledException. This event will get executed whenever any UnhandledException occurs inside a NonUI Thread.

Sample Application



To demonstrate, I have provided with a sample application. The application has a Button, which generates Exception, three RadioButton to demonstrate the exception on various scenario and one CheckBox to invoke the Exception from inside a Non-UI thread.

If you run the application, you will see the first RadioButton gives you a MessageBox that it is handled within the block which generates the Exception. The 2nd RadioButton will catch the Exception on DispatcherUnhandledException handler, and 3rd will crash the whole application.

Download Sample Application - 50KB

I hope you like this article. Thank  you all for reading.

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