Tuesday, 1 May 2012

Powerful Visual Studio 2010 Extensions



Extensions or Add Ins save application development time and make smart code. Visual Studio has vast list of these extension available. I am giving brief about some very useful and powerful extension here, but before this you need to know how to install these extensions.


How to Install Extensions
  • Open Visual Studio.
  • Go to Tools->Extension Manager.
  • You will find Installed Extensions and Online Gallery of extensions.
  • Download extension.
Indent Guides

This extension adds vertical lines at each indent of code. It is very useful to maintain indent in code.





You can read more about this extensions at http://indentguide.codeplex.com/.

VS10x Code Map v2

This is code visualizer extension that displays a graphical nested representation of the current code editor window (C# and VB.NET). It helps the developer visualize type nesting, implemented interfaces, regions, member type and scope, as well as quickly navigate to their respective positions in code
There are some good features of this extension:




Visual Assist X

This is one of great extension which reduces development time with key features like refactoring code, fast search, instant navigation etc.



AutoCode 2010

This is my favorite extension which really reduce my development effort. It can generates more code by less typing. There is enough documentation available to use this.

Features
  • More than 100 useful commands.
  • Commands invoke on ctrl+Enter.
  • Construct class, common methods with single line of code.
  • Create regions of code blocks
  • Create summary block.
  • Support custom commands.





Good luck and please, let me know your feedback!
If you have any query mail me to Sujeet.bhujbal@gmail.com     
Regards
Sujeet Bhujbal
------------------------------------------------------------------------------------------------
 Blog:  www.sujitbhujbal.blogspot.com
Personal Website :- http://sujitbhujbal.wordpress.com/
---------------------------------------------------------------------------------

Saturday, 21 April 2012


Event Routing in WPF


Hi friends,

In this article you will know how to do event routing in  WPF .

1.     What is event

Events are messages that are send by an Object to notify the code that something occur
There are so many events in WPF like MouseEnter,MouseLeave , MouseMove etc

2.      WPF Event Handling

With WPF you can assign the event handler either wih XAML or in the Code Behid
The Event handling mechanism for WPF is based on .NET events
There is new concept like Routed event
               

There are 3 types of event routing in WPF

1.     Direct events
2.     Bubbling
3.     Tunneling

1. Direct event:

    • These are like ordinary .NET events.
    • They originate in one element and don’t pass to any other.
    • For example, MouseEnter (which fires when the mouse pointer moves over 
    • an element) is a direct event.
2. Bubbling events.

§  These events travel up the containment hierarchy.
§  For example, MouseDown is a bubbling event.
§  It’s raised first by the element that is clicked. Next, it’s raised by that element’s parent, then by that element’s parent, and so on, until WPF reaches the top of
 the element tree.

3. Tunneling events.

§  These events travel down the containment hierarchy.
§  They give you the chance to preview (and possibly stop) an event before it reaches the appropriate control.
§  For example, PreviewKeyDown allows you to intercept a key press, first at the window level and then in increasingly more specific containers until you 
reach the element that had focus when the key was pressed.
§  When there is Preview Keyword always Tunneling is done
§  The tunneling event always fires before the bubbling event.
§  To make life more interesting, if you mark the tunneling event as handled, the bubbling event won’t occur. That’s because the two events share the same instance of the RoutedEventArgs class.


Example:

Step 1.    Add a new WPF Window Project => Add Window, Name it RoutedEventDemo.xaml
Step 2.    Put the following xaml
Note: Preivew and Click events are being handled at all levels

<Window x:Class="IGatePatniApp.RoutedEventDemo"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window4" Height="333" Width="550" Button.Click="Window_Click"
        PreviewMouseDown="Window_PreviewMouseDown"  PreviewMouseUp="Window_PreviewMouseUp">
    <Grid  PreviewMouseDown="Grid_PreviewMouseDown"  Button.Click="Grid_Click"
           PreviewMouseUp="Grid_PreviewMouseUp">
        <ListBox Margin="12,12,12,81" Name="listBox1" />
        <Button Margin="70,0,88,21"
                 PreviewMouseDown="btneventtest_PreviewMouseDown"  PreviewMouseUp="btneventtest_PreviewMouseUp"
                 Click="btneventtest_Click"
                Name="btneventtest" Height="30" VerticalAlignment="Bottom">Routed Event Test</Button>
    </Grid>
</Window>




Step 3.    The Event Handlers defined in the code behind


private void Window_PreviewMouseDown(object sender,
                                                                                                                MouseButtonEventArgs e)
        {
            listBox1.Items.Clear();
            listBox1.Items.Add("Window  " + e.RoutedEvent.Name);
        }
        private void Window_PreviewMouseUp(object sender,
                                                                                                                MouseButtonEventArgs e)
        {
            listBox1.Items.Add("Window  " + e.RoutedEvent.Name);
        }
        private void Grid_PreviewMouseDown(object sender,
                                                                                                                MouseButtonEventArgs e)
        {
            listBox1.Items.Add("Grid  " + e.RoutedEvent.Name);
        }
        private void Grid_PreviewMouseUp(object sender,
                                                                                                                MouseButtonEventArgs e)
        {
            listBox1.Items.Add("Grid  " + e.RoutedEvent.Name);
        }
        private void Grid_Click(object sender, RoutedEventArgs e)
        {
            listBox1.Items.Add("Grid  " + e.RoutedEvent.Name);
        }
        private void btneventtest_PreviewMouseDown(object sender,
                                                                                          MouseButtonEventArgs e)
        {
            listBox1.Items.Add("Button  " + e.RoutedEvent.Name);
        }
        private void btneventtest_PreviewMouseUp(object sender,
                                                                                                                MouseButtonEventArgs e)
        {
            listBox1.Items.Add("Button  " + e.RoutedEvent.Name);
        }
        private void btneventtest_Click(object sender, RoutedEventArgs e)
        {
            listBox1.Items.Add("Button  " + e.RoutedEvent.Name);
        }
        private void Window_Click(object sender, RoutedEventArgs e)
        {
            listBox1.Items.Add("Window  " + e.RoutedEvent.Name);
        }



Step 4.    Make this page as startup and run. click on the button and see the list of 
events in the listbox.




- After clicking button do not click anywhere because listbox will be reloaded with the 
new set of events

Good luck and please, let me know your feedback!
If you have any query mail me to Sujeet.bhujbal@gmail.com     

Regards
Sujeet Bhujbal


------------------------------------------------------------------------------------------------
 Blog:  www.sujitbhujbal.blogspot.com
Personal Website :- http://sujitbhujbal.wordpress.com/
---------------------------------------------------------------------------------




Saturday, 7 April 2012

Routed events in Silverlight 4.0


Routed events in Silverlight 4.0

Hi friends in this article I will tell you What is routed events in Silverlight in shortly


1. What is routed Events

¡  Routed events are events with more traveling power—they can tunnel down or bubble up the element tree and be processed by event handlers along the way.
¡  Event routing allows an event to originate in one element but be raised by another one.

2. Defining, Registering, and Wrapping a Routed Event






3. Wrapping a Routed Event


4. Registering

¡  When registering an event, you need to specify the name of the event, the type of routine, the delegate that defines the syntax of the event handler, and the class that owns the event.
¡  Usually, routed events are wrapped by ordinary .NET events to make them accessible to all .NET
Languages. The event wrapper adds and removes registered callers using the Add Handler() and
Remove Handler () methods, both of which are defined in the base Framework Element class and Inherited by every WPF element.

5. Raising a Routed Event

¡  The defining class needs to raise it at some point.
¡  Exactly where this takes place is an implementation detail.
¡  However, the important detail is that your event is not raised through the traditional .NET event wrapper. Instead, you use the RaiseEvent() method that every element inherits from the UIElement class.
¡  RoutedEventArgs e = new RoutedEventArgs(ButtonBase.ClickEvent, this);
base.RaiseEvent(e);
¡  The RaiseEvent() method takes care of firing the event to every caller that’s been registered with the AddHandler() method.
¡  All WPF events use the familiar .NET convention for event signatures.
¡  That first parameter of every event handler provides a reference to the object that fired the event (the sender).
¡  The second parameter is an EventArgs object that bundles together any additional details that might be important.
¡  private void img_MouseUp(object sender, MouseButtonEventArgs e)


6. Handling a Routed Event

¡  The most common approach is to add an event attribute to your XAML markup.
                <Image Source="happyface.jpg" Stretch="None“ Name="img" MouseUp="img_MouseUp" />
¡  img.MouseUp += new MouseButtonEventHandler(img_MouseUp);
¡  img.MouseUp += img_MouseUp;
¡  img.AddHandler(Image.MouseUpEvent, new MouseButtonEventHandler(img_MouseUp));

The code approach is useful if you need to dynamically create a control and attach an event handler at some point during the lifetime of your window. By comparison, the events you hook up in XAML are always attached when the window object is first instantiated. The code approach also allows you to keep your XAML simpler and more streamlined, which is perfect if you plan to share it with nonprogrammers, such as a design artist. The drawback is a significant amount of boilerplate code that will clutter up your code files.

Regards
Sujeet Bhujbal

Wednesday, 21 March 2012

Dynamically Generating Forms in WPF and Silverlight


Dynamically Generating Forms in WPF and Silverlight


Hi friends,

In this article you will know how to generate WPF form dynamically from property field.
Suppose we have requirement that create WPF form

First, we'll start with how to create form in XAML.

Creating forms at Design Time in XAML

 

Below form shows how to create form in XAML


<Grid Margin="10">
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="100" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
              
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="Auto" />
        <RowDefinition Height="*" />
    </Grid.RowDefinitions>
  
    <TextBlock Text="First Name"    Height="19"
                Margin="0,7,31,4" />           
    <TextBox x:Name="FirstName"      Margin="3"
                Grid.Row="0"
                Grid.Column="1" />
              
    <TextBlock Text="Last Name"      Margin="0,7,6,3"
                Grid.Row="1"
                Height="20" />
    <TextBox x:Name="LastName"       Margin="3"
                Grid.Row="1"
                Grid.Column="1" />   
  
    <TextBlock Text="EmailId"      Grid.Row="2"
                Margin="0,9,0,0"
                Height="21" />
<TextBox x:Name=" EmailId "       Margin="3"
                Grid.Row="1"
                Grid.Column="1" />   
  
    <Button x:Name="Save"        Grid.Row="3"
            Grid.Column="3"   HorizontalAlignment="Right"
            VerticalAlignment="Top"     Margin="3"
            Width="80"        Height="25"
            Content="Save" />
</Grid>




Below diagram shows the how form shows




Creating forms at runtime using XAML strings

Below example shows the how to create form at runtime by using property class

1.  create a person class which has 10 properties


    public class Person
    {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public bool isDefault { get; set; }
        public string EmailId { get; set; }
        public string EmployeeNo { get; set; }
        public string Age { get; set; }

        public string EmailId2 { get; set; }
        public bool isMale { get; set; }
        public string MobileNo { get; set; }
        public string TelephoneNo { get; set; }
    }



2. Creating Controls at runtime



We created following functions for creating textbox, textblock, row definition and for checkbox

functions CreateCheckBox() creates checkbox runtime

        private CheckBox CreateCheckBox(int row, int column)
        {
            CheckBox cb = new CheckBox();
            cb.Margin = new Thickness(5);
            cb.Height = 22;
            cb.MinWidth = 50;

            Grid.SetColumn(cb, column);
            Grid.SetRow(cb, row);

            return cb;
        }

        private RowDefinition CreateRowDefinition()
        {
            RowDefinition RowDefinition = new RowDefinition();
            RowDefinition.Height = GridLength.Auto;
            return RowDefinition;
        }




This will create a text block

private TextBlock CreateTextBlock(string text, int row, int column)
        {
            string[] aa = BreakUpperCB(text);
            string prop = "";
            for (int i = 0; i < aa.Length; i++)
            {
                 prop = prop +" "+ aa[i];
            }
TextBlock tb = new TextBlock() { Text = prop, Margin = new Thickness(5, 8, 0, 5) };
            tb.MinWidth = 90;
            tb.FontWeight = FontWeights.Bold;              
            tb.Margin = new Thickness(5);
            var bc = new BrushConverter();
            tb.Foreground = Brush)bc.ConvertFrom("#FF2D72BC");
            Grid.SetColumn(tb, column);
            Grid.SetRow(tb, row);          
            return tb;
        }
  






Handling Events


private TextBox CreateTextBox( int row, int column)
        {
            TextBox tb = new TextBox();
            tb.Margin = new Thickness(5);
            tb.Height = 22;
            tb.Width = 150;
            Grid.SetColumn(tb, column);
            Grid.SetRow(tb, row);
            return tb;
        }

// this will break the property text by upper
   public string[] BreakUpperCB(string sInput)
        {
            StringBuilder[] sReturn = new StringBuilder[1];
            sReturn[0] = new StringBuilder(sInput.Length);
            const string CUPPER = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
            int iArrayCount = 0;
            for (int iIndex = 0; iIndex < sInput.Length; iIndex++)
            {
                string sChar = sInput.Substring(iIndex, 1); // get a char
                if ((CUPPER.Contains(sChar)) && (iIndex > 0))
                {
                    iArrayCount++;
                    System.Text.StringBuilder[] sTemp = new System.Text.StringBuilder[iArrayCount + 1];
                    Array.Copy(sReturn, 0, sTemp, 0, iArrayCount);
                    sTemp[iArrayCount] = new StringBuilder(sInput.Length);
                    sReturn = sTemp;
                }
                sReturn[iArrayCount].Append(sChar);
            }
            string[] sReturnString = new string[iArrayCount + 1];
            for (int iIndex = 0; iIndex < sReturn.Length; iIndex++)
            {
                sReturnString[iIndex] = sReturn[iIndex].ToString();
            }
            return sReturnString;
        }

      void button_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Saved Successfully");
        }

        private Button CreateButton(string text, int row, int column )
        {
            Button tb = new Button() { Content = text, VerticalAlignment = VerticalAlignment.Top, HorizontalAlignment = HorizontalAlignment.Left, Margin = new Thickness(5, 8, 0, 5) };
            tb.Width = 90;
            tb.Height = 25;
            tb.Margin = new Thickness(5);
            Grid.SetColumn(tb, column);
            Grid.SetRow(tb, row);           
            return tb;
        }





In the below example we have created one function CreateControlsUsingObjects(Person obj) which create dynamic form based on the

Create Controls




        private void CreateControls(Person obj)
        {
            List<Person> objList=new List<Person>();

            objList.Add(obj);
            Grid rootGrid = new Grid();
            rootGrid.Margin = new Thickness(10.0);

            rootGrid.ColumnDefinitions.Add(
               new ColumnDefinition() { Width = new GridLength(100.0) });
            rootGrid.ColumnDefinitions.Add(
                 new ColumnDefinition() { Width = new GridLength(1, GridUnitType.Star) });

            rootGrid.ColumnDefinitions.Add(
                new ColumnDefinition() { Width = new GridLength(100.0) });
            rootGrid.ColumnDefinitions.Add(
                   new ColumnDefinition() { Width = new GridLength(100.0) });
  

                PropertyInfo[] propertyInfos;
                propertyInfos = typeof(Person).GetProperties();
                rootGrid.RowDefinitions.Add(CreateRowDefinition());
                int j = 1;
              
                foreach (PropertyInfo propertyInfo in propertyInfos)
                {
                    if (propertyInfo.PropertyType.Name == "String")
                    {

                        rootGrid.RowDefinitions.Add(CreateRowDefinition());

                        var Label = CreateTextBlock(propertyInfo.Name, j, 0);
                        rootGrid.Children.Add(Label);

                        var Textbox = CreateTextBox(j, 1);
                        rootGrid.Children.Add(Textbox);
                        j++;
                    }
                    if (propertyInfo.PropertyType.Name == "Boolean")
                    {
                        rootGrid.RowDefinitions.Add(CreateRowDefinition());

                        var Label = CreateTextBlock(propertyInfo.Name, j, 0);
                        rootGrid.Children.Add(Label);

                        var Textbox =  CreateCheckBox(j, 1);
                        rootGrid.Children.Add(Textbox);
                        j++;
                    }

                   
                   
                }
                rootGrid.RowDefinitions.Add(CreateRowDefinition());
                var Button = CreateButton("Save",j + 1, 1);
                Button.Click += new RoutedEventHandler(button_Click);

                rootGrid.Children.Add(Button);
                LayoutRoot.Children.Add(rootGrid           
        }
}





In the above example we have shown that how to create WPF form dynamically.
Below output screen shows the output as we want

Output Screen



Summary

So, we've seen that there are three different ways you can display controls in Silverlight and WPF.
  • Use the design surface / XAML Editor / Blend and create them prior to compiling
  • Load XAML at runtime
  • Use CLR Objects at runtime



Good luck and please, let me know your feedback!
In this way you can learn difference between proxy and channel factory

If you have any query mail me to Sujeet.bhujbal@gmail.com     

Regards
Sujeet Bhujbal


------------------------------------------------------------------------------------------------
 Blog:  www.sujitbhujbal.blogspot.com
Personal Website :- http://sujitbhujbal.wordpress.com/
Contact me on 9822663535
---------------------------------------------------------------------------------