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

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