Friday, November 4, 2011

How to Use Mock Library For Your Unit Testing In C#

In this tutorial I assume that you have basic knowledge of writing unit testing with Visual Studio.Also note that here we will not use TDD  approach to implement our example.

Normally in software development life cycle as a software developers we have to test  every possible methods which we have written.In this point Unit test come out. In Unit testing we are ensure that our method works in expected way.To ensure that our method should be independent from others. To ensure this isolation we can use mock objects.

Think that we have method call "A" inside "A" method we call another method called "B" and get the return object from  "B"  to carry out further operation in our method "A". But since we are unit testing method "A" we can not depend on method "B". We want to test behavior of our method working as expected way.What the mock doing is,It allow us to create a mock object ( fake object) which is similar to the  return object of method "B". So our method "A" will accept this fake object as return object of method "B" and it will carry out further operation in method "A". Here remember that we have to use dependency injection design pattern heavily to success this.

Here to implement mock objects I use open source library called Moq. You can download it from here. Now we will implement the example application using Mock.

Think that in a library system we want to calculate membership cost per year and it will depend on the number of books he borrow per one time.

1. Start Visula Studio and create new Class Library called LibraryOperations.

 2. Delete the Class1 and Create new class called Member as bellow.


namespace LibraryOperations
{
    public class Member
    {
        public int MemberID { get; set; }
        public string FirstName { get; set; }
        public string SecondName { get; set; }
        public int MaximumBookCanBorrow { get; set; }
        public int Age { get; set; }
    }
}

3. Now create a interface called IMemberManager which is contain all the method required to handle library member. But here we implement only one method.


namespace LibraryOperations
{
    public interface IMemberManager
    {
        Member GetMember(int memberID);
    }
}
 
4.Implement the class called MemeberManager which is inherite from IMemberManager interface.But here we are not going to implement the method body. And you will see the reason soon.


using System;

namespace LibraryOperations
{
    public class MemberManager:IMemberManager
    {
        public Member GetMember(int memberID)
        {
            throw new NotImplementedException();
        }
    }
}

5. Now we create a class called LibraryCore and it has a public method called CalculateMemberShipCost. You can see implementation of this class bellow.


namespace LibraryOperations
{
    public class LibraryCore
    {
        private readonly IMemberManager _memberManager;

        public LibraryCore(IMemberManager memberManager)
        {
            this._memberManager = memberManager;
        }

        public double CalculateMemberShipCost(int memberID)
        {
            double membershipCost = 0;
            Member member = _memberManager.GetMember(memberID);
            membershipCost = 10 + member.MaximumBookCanBorrow * 0.5;
            return membershipCost;
        }
    }
}

Note that here we used Dependency Injection design pattern.This will allow us to create a loose couple class. So we can inject the any type of object which is implement from IMemberManager interface to class constructor.This is the main thing we use to test our method using Mock.

  6. Now add the Unit Test project called LibraryOperationsTest to your solution. 

Delete UnitTest1.cs class from your test project.

7. Now go to LibraryCore class and right click on CalculateMemberShipCost method name and select Create Unit Tests.


Now Create Unit Tests window will appear. You can select that you want to test in this class and you can select the Out put Test project that the test class want to add.Also you can add any wanted Assembly that you want to use for unit testing.(Here I will not add the our moq library here.Because i rather like to add it using add reference option.If you like you can add it in here).Now click on OK button and VS will create  LibraryCoreTest.cs for you.


8. Now we will add Moq.dll to our TestProject using add reference option. Note that here I'm using 4.0 version since I'm using .Net framework 4.Now we will implement our LibraryCoreTest class as bellow.


using LibraryOperations;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using Moq;

namespace LibraryOperationsTest
{
    
    
    /// <summary>
    ///This is a test class for LibraryCoreTest and is intended
    ///to contain all LibraryCoreTest Unit Tests
    ///</summary>
    [TestClass()]
    public class LibraryCoreTest
    {

        private LibraryCore _target;
        private Mock<IMemberManager> _mock;

        /// <summary>
        ///A test for CalculateMemberShipCost
        ///</summary>
        [TestMethod()]
        public void CalculateMemberShipCostTest()
        {
            _mock = new Mock<IMemberManager>();
            _target = new LibraryCore(_mock.Object);
            Member member = new Member()
            {
                MemberID=1,
                FirstName="Erandika",
                SecondName="Sandaruwan",
                Age=25,
                MaximumBookCanBorrow=4,
            };

            _mock.Setup(x => x.GetMember(It.IsAny<int>())).Returns(member);
    
            int memberID = 1; 
            double expected = 12; 
            double actual;
            actual = _target.CalculateMemberShipCost(memberID);
            Assert.AreEqual(expected, actual);  
        }
    }
}

Here first we create a mock object using IMemberManager interface and we pass it to LibraryCore constructor.Since we are using dependency Injection in LibraryCore class we can perform this operation.



            Mock<IMemberManager> _mock = new Mock<IMemberManager>();
            LibraryCore _target = new LibraryCore(_mock.Object);

Then we Create  a Member object and tell the assing that object to _mock object. Here you can pass any integer type parameter to our GetMember method and Mock framwork will return  member object that we created in all the time when we are calling to the GetMember method.


            Member member = new Member()
            {
                MemberID=1,
                FirstName="Erandika",
                SecondName="Sandaruwan",
                Age=25,
                MaximumBookCanBorrow=4,
            };

            _mock.Setup(x => x.GetMember(It.IsAny<int>())).Returns(member);

So other part of our method we can implement in normal way and if we run the unit test now we will get successfully message like this.


Happy Coding :)

Download Source Code here.




Sunday, October 30, 2011

MVVM with Silverlight (Start to End)

Why we use MVVM?

 1. MVVM provide application to code reuse.
2. Simplifies the application.
3. Easy to maintenance and provide maximum support for the testing.

What is MVVM?
Model-View-ViewModel (MVVM) is a design pattern which can be use in WPF and Silverlight.

Model : Entities (Most of the time directly connect with the application backend.)
View : Your silverlight screens.
ViewModel : The glue between the Model and View.

In Silverlight View and ViewModel will located in the client side and Model will located in server side.So We have to use Communication method to communicate between the Client and server side. Most of the time we user WCF Service for this.

Now we will implement a simple silverlight application using MVVM pattern.This example I will explain the Command and Property Binding using MVVM.

Business Requirement : We want to find the person information using person ID and we want to display person information in web form..Here Person information is stored in the server side.



Solution :
1. Create a new Silverlight application and name it as MVVMSample.Now Visual Studio will create Silverlight project and Web Application project for you.


2. Now right click on the MVVMSample.Web project and add New Class named by PersonData and implement the class as bellow.


namespace Index.Web
{
    public class PersonData
    {
        public int PersonID { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public int Age { get; set; }
        public string Address { get; set; }
    }
}


3.Again Right Click on the MVVMSample.Web project and add New Class named by PersonRepository and implement the class as bellow.


using System.Collections.Generic;

namespace Index.Web
{
    public class PersonRepository
    {
        public IList<PersonData> Person{get;set;}

        public PersonRepository()
        {
            GeneratePersonList();
        }

        private void GeneratePersonList()
        {
            Person = new List<PersonData>() 
            {
                new PersonData() { PersonID = 1, FirstName = "Erandika",    LastName = "Sandaruwan", Age=25,     Address = "Delgoda"    },
                new PersonData() { PersonID = 2, FirstName = "Niluka",      LastName = "Dilani",     Age = 30,   Address = "Kandy"      },
                new PersonData() { PersonID = 3, FirstName = "Chathura",    LastName = "Achini",     Age = 27,   Address = "Colombo"    },
                new PersonData() { PersonID = 4, FirstName = "Florina",     LastName = "Breban",     Age = 25,   Address = "Romania"    },
            };
        }
    }
}


4.Finally we want to add our silverlight enable WCF service to MVVMSample.Web project.To do that right click on the MVVMSample.Web project Select the Add New Item and then in Installed Template under Visual C# select the Silverlight.Now select the  Silverlight-enable WCF Service and name it as PersonDataService.svc and click on the Add button.



Now implement the service class as bellow.


using System;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;

namespace Index.Web
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class PersonDataService
    {
        [OperationContract]
        public PersonData FindPerson(int personID)
        {
            return new PersonRepository().Person.Where(x => x.PersonID == personID).SingleOrDefault();
        }
    }
}

So here now we have completed our model part.So next we have to implement our View and ViewModel part.

5.First We will add our PersonDataService to our silverlight project.To do that In MVVMSample project right click on References and click on Add Service Reference and then Add References Window will open for you and click on Discover button and VS will display all the services that have been added to current solution. But here we have only one service.Give the Namesapce as PersonDataService and click OK button.(Remember before this you have to build your web application project first) and then service reference will added to the your silverlight project.

6. Now add new folder to Silverlight project and named it as ViewModel and add two classes named by MainPageViewModel. and ViewModelBase. Again add new folder called ServiceAgent and add a Interface called IPersonService.and implement the interface as bellow.


using System;
using MVVMSample.PersonDataService;

namespace MVVMSample.ServiceAgent
{
    public interface IPersonService
    {
        void FindPerson(int personID,EventHandler<FindPersonCompletedEventArgs> callBack);
    }
}

Now we want to implement PersonService class using IPersonService interface.So to do that add a new class to ServiceAgent folder and named it as PersonService and then implement the class as bellow.


using System;
using MVVMSample.PersonDataService;

namespace MVVMSample.ServiceAgent
{
    public class PersonService:IPersonService
    {
        private PersonDataServiceClient client = new PersonDataServiceClient();

        public void FindPerson(int personID, EventHandler<FindPersonCompletedEventArgs> callBack)
        {
            client.FindPersonCompleted += callBack;
            client.FindPersonAsync(personID);
        }
    }
}


7. Now we have to implement our ViewModel.Note that here we want to use ICommand interface for the implement the command which it bind to Search button. Here we will use Prism Framework.So we do not want to implement the Command and we can directly use DelegateCommand.You can download the Prism framework from following URL http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=4922
And you have to add as Microsoft.Practice.Prism.dll which is belongs to silverlight as reference to your silverlight project.Now we will start implement our MainPageViewModel and ViewModelBase classes.So First we will implement our ViewModelBase class as bellow.


using System.ComponentModel;

namespace MVVMSample.ViewModel
{
    public class ViewModelBase : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
        public bool IsDesignTime
        {
            get
            {
                return DesignerProperties.IsInDesignTool;
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            var propertyChanged = PropertyChanged;

            if (propertyChanged != null)
            {
                propertyChanged(this,new PropertyChangedEventArgs(propertyName));
            }
        }


        
    }
}

Here you can see that our ViewModelBase class in implemented from INotifyPropertyChanged interface.This is very important in silverlight data binding  to notify  controls and other objects when a bound property value changes.So by using our ViewModelBase class we can reuse it across the multiple ViewModel. So Now we will implement our MainPageViewModel as bellow.




using System.Windows.Input;
using MVVMSample.PersonDataService;
using MVVMSample.ServiceAgent;
using Microsoft.Practices.Prism.Commands;

namespace MVVMSample.ViewModel
{
    public class MainPageViewModel : ViewModelBase
    {

        private PersonService _personService;
        public MainPageViewModel()
        {
            if (IsDesignTime != true)
            {
                this._personService = new PersonService() ;
                this.FindPersonCommand = new DelegateCommand<object>(this.FindPersonByID);
            }
        }

        private PersonData _personData;
        public PersonData PersonData
        { 
            get
            {
                return _personData;
            }
            set
            {
                if (_personData != value)
                {
                    _personData = value;
                    OnPropertyChanged("PersonData");
                }
            }
        }

        private int _personID;
        public int PersonID
        {
            get 
            {
                return _personID;
            } 
            set
            {
                if (_personID != value)
                {
                    _personID = value;
                    OnPropertyChanged("PersonID");
                }
            } 
        }

        public ICommand FindPersonCommand{get;set;}


        private void FindPersonByID(object obj)
        {
            if (PersonID != 0)
            {
                _personService.FindPerson(PersonID, (s, e) => PersonData = e.Result);
            }
        }

    }
}

You can see that we we inherit our MainPageViewModel class from ViewModelBase class  and we reuse IsDesignTime property and OnPropertyChanged method in here. Also note that we are using DelegateCommand here.Which is come from Microsoft.Practice.Prism.dll and so we do not want to worry to implement this event.So now our MainPageViewModel is ready now and we have to bind data to our silverlight View.In this example we are going to bind PersonData and PersonID property and FindPersonCommand command to silverlight View.

8. Now we will create our silverlight View and Bind the Data from our ViewModel.You implement our view as bellow.




<UserControl x:Class="MVVMSample.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    xmlns:viewModel="clr-namespace:MVVMSample.ViewModel"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    
    <UserControl.DataContext>
        <viewModel:MainPageViewModel/>
    </UserControl.DataContext>
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="25"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="5"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="5"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="5"/>
            <RowDefinition Height="25"/>
            <RowDefinition Height="5"/>
            <RowDefinition Height="25"/>
        </Grid.RowDefinitions>
        
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        
        <sdk:Label Height="25" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Right" Name="label1" VerticalAlignment="Center" Width="120" Content="Person ID :" />
        <TextBox Height="25" Grid.Row="1" Grid.Column="1"  HorizontalAlignment="Left" Name="txtPersonID" VerticalAlignment="Top" Width="150" Text="{Binding PersonID, Mode=TwoWay}" />
        <Button Grid.Row="1" Grid.Column="2" Content="Search" Height="25" HorizontalAlignment="Left" Name="btnSearch" VerticalAlignment="Top" Width="75" Command="{Binding FindPersonCommand}" />
        
        <sdk:Label Height="25" Grid.Row="3" Grid.Column="0" HorizontalAlignment="Right" Name="label2" VerticalAlignment="Center" Width="120" Content="First Name :" />
        <TextBox  Height="25" Grid.Row="3" Grid.Column="1" HorizontalAlignment="Left" Name="txtFirstName" VerticalAlignment="Top" Width="200" Text="{Binding Path=PersonData.FirstName, Mode=TwoWay}" />
        
        <sdk:Label Height="25" Grid.Row="5" Grid.Column="0" HorizontalAlignment="Right" Name="label3" VerticalAlignment="Center" Width="120" Content="Last Name :" />
        <TextBox  Height="25" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Left" Name="txtLastName" VerticalAlignment="Top" Width="200" Text="{Binding Path=PersonData.LastName, Mode=TwoWay}" />
        
        <sdk:Label Height="25" Grid.Row="7" Grid.Column="0" HorizontalAlignment="Right" Name="label4" VerticalAlignment="Center" Width="120" Content="Age :" />
        <TextBox  Height="25" Grid.Row="7" Grid.Column="1" HorizontalAlignment="Left" Name="txtAge" VerticalAlignment="Top" Width="200" Text="{Binding Path=PersonData.Age, Mode=TwoWay}" />
        
        <sdk:Label Height="25" Grid.Row="9" Grid.Column="0" HorizontalAlignment="Right" Name="label5" VerticalAlignment="Center" Width="120" Content="Address :" />
        <TextBox Height="25" Grid.Row="9" Grid.Column="1" HorizontalAlignment="Left" Name="txtAddress" VerticalAlignment="Top" Width="200" Text="{Binding Path=PersonData.Address, Mode=TwoWay}" />
        
    </Grid>
</UserControl>

Now if all the things are working correctly you can run the application. And you will see the nice interface without having exceptions.

You can download the source code from here for this example : Download Here

Tuesday, October 11, 2011

C# Programming for beginners: Silverlight Child Windows (Modal Windows)

C# Programming for beginners: Silverlight Child Windows (Modal Windows): Silverlight Child Window provide functionality to pop up a window and it will disable the rest of the application until the window is closed...

Silverlight Child Windows (Modal Windows)

Silverlight Child Window provide functionality to pop up a window and it will disable the rest of the application until the window is closed.(Introduced with Silverlight 3).  

Create Sample Application

1. First create a new silverlight application and named it as SilverlightChildWindow.
2. Right Click on silverlight project and add a new ChildWindow from Add New Item dialog.

3. Now we will design our MainPage.xaml layout as below.
<UserControl x:Class="SilverlightChildWindow.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="40"/>
            <RowDefinition Height="40"/>
        </Grid.RowDefinitions>
        <TextBlock x:Name="lblInfo" Margin="10" FontSize="13" TextWrapping="Wrap">
            Please Enter your user information.
        </TextBlock>
        <Button Content="Enter Your Information" Height="23" Grid.Row="1" HorizontalAlignment="Left" Margin="10,10,0,0" Name="button1" VerticalAlignment="Top" Width="150" Click="button1_Click"  />
    </Grid>
</UserControl>

4. After that we will design our ChildWinodw.xaml page as below.
<controls:ChildWindow x:Class="SilverlightChildWindow.ChildWindow1"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"           
           Title="ChildWindow1">
    <Grid x:Name="LayoutRoot" Margin="2">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        
        <TextBlock Grid.Row="0" Grid.Column="0" Margin="3">First Name:</TextBlock>
        <TextBox  x:Name="txtFirstName" Grid.Row="0" Grid.Column="1" Margin="3" Width="150"></TextBox>
        <TextBlock Grid.Row="1" Grid.Column="0" Margin="3">Last Name:</TextBlock>
        <TextBox  x:Name="txtLastName" Grid.Row="1" Grid.Column="1" Margin="3" Width="150"></TextBox>


        <Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Left" Margin="3" Grid.Row="2" Grid.Column="1" />
        <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="3" Grid.Row="2" />
    </Grid>
</controls:ChildWindow>

5 . To show a Child Window, we need to create an object of the child window and call its Show() method. Here the Show()  method act as as asynchronous call and it returns immediately, since that we will not get the result from the dialog using this method. So we need to implement the Closed event from the Child Window and check the DialogResult there. So we will implement this in MainPage.xaml.cs page.
using System;
using System.Windows;
using System.Windows.Controls;

namespace SilverlightChildWindow
{
    public partial class MainPage : UserControl
    {
        private ChildWindow1 childWindow = new ChildWindow1();

        public MainPage()
        {
            InitializeComponent();
            childWindow.Closed += new EventHandler(childWindow_Closed);
        }

        void childWindow_Closed(object sender, EventArgs e)
        {
            if (childWindow.DialogResult == true)
            {
                lblInfo.Text ="Hi " +childWindow.UserName+",";
            }
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            childWindow.Show();
        }
    }
}

6. Also we need to add property to ChildWindow.xaml.cs.
using System.Windows;
using System.Windows.Controls;

namespace SilverlightChildWindow
{
    public partial class ChildWindow1 : ChildWindow
    {
        public ChildWindow1()
        {
            InitializeComponent();
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        public string UserName
        {
            get { return txtFirstName.Text + " " + txtLastName.Text; }
        }
    }
}

7 . Now you can Run the application and if everything work fine you will get following type pop up after you click on button.

Download source Code Here.

Sunday, September 25, 2011

C# Programming for beginners: Web Service Example

C# Programming for beginners: Web Service Example: Introduction Web service , which promote software re-usability in distributed systems where applications execute across multiple computers ...

C# Programming for beginners: Simple Two Way Data Binding Application in Silverl...

C# Programming for beginners: Simple Two Way Data Binding Application in Silverl...: Using this simple application I hope to explain basic data binding technique in silverlight. 1. First create a new silverlight application ...

C# Programming for beginners: DataGrid Control In Silverlight

C# Programming for beginners: DataGrid Control In Silverlight: Before we start we will discuss some basic about silverlight Datagrid. Column Collection If you want to have some additional control over ...

DataGrid Control In Silverlight

Before we start we will discuss some basic about silverlight Datagrid. Column Collection If you want to have some additional control over the columns in silverlight DataGrid we want to use Column collection.But first you need to AutogenerateColumns property on grid to false (Otherwise you will get all the auto-generated columns with you define columns). After that you can generate the columns manually. In DataGrid columns are define using the Columns collection. In silverlight you can use three type of columns within a Columns collection and all of them are inherit from DataGridColumn.
  • DataGridTextColumn
  • DataGridCheckBoxColumn
  • DataGridTemplateColumn
  • Example :
                <sdk:DataGrid Name="grid" Margin="10" AutoGenerateColumns="False">
                    <sdk:DataGrid.Columns>
                        <sdk:DataGridTextColumn Header="Name" Binding="{Binding FristName}" />
                        <sdk:DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
                        <sdk:DataGridCheckBoxColumn Header="Male" Binding="{Binding Male}"/>
    
                        <sdk:DataGridTemplateColumn Header="TwoName">
                            <sdk:DataGridTemplateColumn.CellTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Padding="5,0,5,0" Text="{Binding FristName,Mode=TwoWay}"/>
                                        <TextBlock Text="{Binding SecondName,Mode=TwoWay}"/>
                                    </StackPanel>
                                </DataTemplate>
                            </sdk:DataGridTemplateColumn.CellTemplate>
                            <sdk:DataGridTemplateColumn.CellEditingTemplate>
                                <DataTemplate>
                                    <StackPanel Orientation="Horizontal">
                                        <TextBlock Padding="5,0,5,0" Text="{Binding FristName,Mode=TwoWay}"/>
                                        <TextBlock Text="{Binding SecondName,Mode=TwoWay}"/>
                                    </StackPanel>
                                </DataTemplate>
                            </sdk:DataGridTemplateColumn.CellEditingTemplate>
                        </sdk:DataGridTemplateColumn>
                    </sdk:DataGrid.Columns>
                </sdk:DataGrid>
    
    Now we will start our sample application. 1.Create a new Silverlight project and Name it as SilverlightDataGrid. 2. Add new class called Person to your silverlight project and implement the class as below.
        public class Person
        {
            public string FirstName { get; set; }
            public string SecondName { get; set; }
            public int Age { get; set; }
            public bool Male { get; set; }
    
            public static ObservableCollection<Person> GetData()
            {
                ObservableCollection<Person> data = new ObservableCollection<Person>();
                data.Add(new Person() { FirstName = "Erandika", SecondName = "Sandaruwan", Age = 25, Male = true});
                data.Add(new Person() { FirstName = "Sachinthana", SecondName = "Vidulakshi", Age = 23, Male = false});
                data.Add(new Person() { FirstName = "Chathura", SecondName = "Achini", Age = 27, Male = false});
                data.Add(new Person() { FirstName = "Niluka", SecondName = "Dilani", Age = 30, Male = false});
                data.Add(new Person() { FirstName = "Krishantha", SecondName = "Nawarathne", Age = 33, Male = true});
                data.Add(new Person() { FirstName = "Lahiru", SecondName = "Kariyawasam", Age = 30, Male = true});
    
                return data;
            }
        }
    
    3. Add the DataGrid to the MainPage.xaml. And designed the DataGrid as below.
        <Grid x:Name="LayoutRoot" Background="White">
    
            <sdk:DataGrid Name="grid" Margin="10" AutoGenerateColumns="False">
                <sdk:DataGrid.Columns>
                    <sdk:DataGridTextColumn Header="First Name" Binding="{Binding FirstName}" />
                    <sdk:DataGridTextColumn Header="Second Name" Binding="{Binding SecondName}" />
                    <sdk:DataGridTextColumn Header="Age" Binding="{Binding Age}"/>
                    <sdk:DataGridCheckBoxColumn Header="Male" Binding="{Binding Male}"/>
                </sdk:DataGrid.Columns>
            </sdk:DataGrid>
    
        </Grid>
    
    4. We already implemented our Person class and designed our XAML. Now we need to bind the data to DataGrid.To do that we need to do some coding in MainPage.xaml.cs class. First We need to implement the Load event for the page.Then inside the Load event we will bind data to the DataGrid.
        public partial class MainPage : UserControl
        {
            public MainPage()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            }
    
            void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                this.PersonGrid.ItemsSource = Person.GetData();
            }
        }
    
    5. Now Run your application and you will see output like below. [caption id="attachment_79" align="aligncenter" width="557" caption="Final Output"]Final Output[/caption] Download Source Code : Here

    Saturday, September 24, 2011

    Simple Two Way Data Binding Application in Silverlight

    Using this simple application I hope to explain basic data binding technique in silverlight. 1. First create a new silverlight application and named it as BasicSilverlightApp. 2. Now design your main grid like bellow
        <Grid x:Name="LayoutRoot" Background="White">
            <Grid.RowDefinitions>
                <RowDefinition />
                <RowDefinition />
                <RowDefinition />
            </Grid.RowDefinitions>
    
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
    
            <TextBlock Text="Name:" VerticalAlignment="Center" Margin="5"/>
            <TextBox Text="{Binding Name,Mode=TwoWay}" VerticalAlignment="Center" Grid.Column="1" Margin="5"/>
    
            <TextBlock Text="Age:" VerticalAlignment="Center" Grid.Row="1" Margin="5"/>
            <TextBox Text="{Binding Age,Mode=TwoWay}" VerticalAlignment="Center" Grid.Column="1" Grid.Row="1" Margin="5"/>
    
            <TextBlock Text="Location" VerticalAlignment="Center" Grid.Row="2" Margin="5"/>
            <TextBox Text="{Binding Location,Mode=TwoWay}" VerticalAlignment="Center" Grid.Column="1" Grid.Row="2" Margin="5"/>
    
        </Grid>
    
    3. Now we do some coding in MainPage.xaml.cs page.First we will add a loaded event handler to the page.
        public partial class MainPage : UserControl
        {
            public MainPage()
            {
                InitializeComponent();
                this.Loaded += new RoutedEventHandler(MainPage_Loaded);
            }
    
            void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                throw new NotImplementedException();
            }
        }
    
    Now we will add a class called Person to define a Person object and to enable the Two way binding we have to implement Person has from INotifyPropertyChanged interface.This will help to create a change event for each property.
        public class Person : INotifyPropertyChanged
        {
            private string _name;
            private int _age;
            private string _location;
    
            public event PropertyChangedEventHandler PropertyChanged;
    
            private void CatchPropertyChange(string property)
            {
                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs(property));
                }
            }
    
            public string Name
            {
                get
                {
                    return _name;
                }
                set
                {
                    _name = value;
                    CatchPropertyChange("Name");
                }
            }
    
            public int Age
            {
                get
                {
                    return _age;
                }
                set
                {
                    _age = value;
                    CatchPropertyChange("Age");
                }
            }
    
            public string Location
            {
                get
                {
                    return _location;
                }
                set
                {
                    _location = value;
                    CatchPropertyChange("Location");
                }
            }
    
        }
    
    4.Now we created out Person class and now we will create an instance of the Person class and set it to the LayoutRoot's DataContext.
            void MainPage_Loaded(object sender, RoutedEventArgs e)
            {
                Person person = new Person()
                {
                    Name="Erandika Sandaruwan",
                    Age=25,
                    Location="Gampaha"
                };
    
                this.LayoutRoot.DataContext = person;
            }
    
    5. Now you can run your silverlight application and then you will see the following output. [caption id="attachment_66" align="aligncenter" width="557" caption="Output"]Output[/caption] Download Source Code Here : Download