Silverlight 4: Using Commanding Parameters for Performing Insert Operations

Posted by: Mahesh Sabnis , on 6/24/2010, in Category Silverlight 2, 3, 4 and 5
Views: 23075
Abstract: In my previous article, Silverlight 4 – Using Commanding Feature to Fetch data from a WCF 4.0 service, we explored the new commanding support provided to Silverlight 4.0 applications and how commanding provides easy and flexible code-less development mechanism. In this article, we will explore how to use the Commanding Parameters to perform DML Operations (Insert).
In my previous article, Silverlight 4 – Using Commanding Feature to Fetch data from a WCF 4.0 service, we explored the new commanding support provided to Silverlight 4.0 applications and how commanding provides easy and flexible code-less development mechanism. We also discussed the new pair of properties added to the ButtonBase and Hyperlink classes named Command and CommandParameter and discussed how to fetch data using the Commanding feature.
In this article, we will explore how to use the Commanding Parameters to perform DML Operations (Insert).
Please note that the article uses the same WCF 4.0 service created in the previous article Silverlight 4 - Commanding Feature to Fetch data from a WCF 4.0 service. So make sure you glance through that article before reading this one.
Step 1: To the SL client project, add two new classes, ‘CreateNewEmployeeViewModel’ and ‘CreateEmployeCommand’ as shown below:
CreateNewEmployeeViewModel.cs or vb
C#
using System;
using System.Windows.Input;
using Silverlight.Com.View.Client.MyRef;
 
namespace Silverlight.Com.View.Client
{
    public class CreateNewEmployeeViewModel
    {
        public clsEmployee Employee { get; set; }
 
        ServiceClient Proxy;
 
        int Res = 0;
       
        public CreateNewEmployeeViewModel()
        {
            Employee = new clsEmployee();
            Proxy = new ServiceClient();
        }
 
 
        public ICommand CreateEmployee
        {
            get
            {
                return new CreateEmployeeCommand(this);
            }
        }
 
 
        public void InsertEmployee(clsEmployee objEmp)
        {
            Proxy.InsertEmployeeCompleted += new EventHandler<InsertEmployeeCompletedEventArgs>
                (Proxy_InsertEmployeeCompleted);
            Proxy.InsertEmployeeAsync(objEmp);
 
        }
 
        void Proxy_InsertEmployeeCompleted(object sender, InsertEmployeeCompletedEventArgs e)
        {
           
                Res = e.Result;
            
        }
    }
}
 
 
VB.NET
Imports System
Imports System.Windows.Input
Imports Silverlight.Com.View.Client.MyRef
 
Namespace Silverlight.Com.View.Client
      Public Class CreateNewEmployeeViewModel
            Public Property Employee() As clsEmployee
 
            Private Proxy As ServiceClient
 
            Private Res As Integer = 0
 
            Public Sub New()
                  Employee = New clsEmployee()
                  Proxy = New ServiceClient()
            End Sub
 
 
            Public ReadOnly Property CreateEmployee() As ICommand
                  Get
                        Return New CreateEmployeeCommand(Me)
                  End Get
            End Property
 
 
            Public Sub InsertEmployee(ByVal objEmp As clsEmployee)
                  AddHandler Proxy.InsertEmployeeCompleted, AddressOf Proxy_InsertEmployeeCompleted
                  Proxy.InsertEmployeeAsync(objEmp)
 
            End Sub
 
            Private Sub Proxy_InsertEmployeeCompleted(ByVal sender As Object, ByVal e As InsertEmployeeCompletedEventArgs)
 
                        Res = e.Result
 
            End Sub
      End Class
End Namespace
 
The above class makes an async call to WCF service and passes a clsEmployee object to it. 
CreateEmployeeCommand.cs or vb
C#
using System;
using System.Windows.Input;
 
namespace Silverlight.Com.View.Client
{
    public class CreateEmployeeCommand :ICommand
    {
 
        CreateNewEmployeeViewModel NewEmpViewModel;
 
        public CreateEmployeeCommand(CreateNewEmployeeViewModel newEmpViewModel)
        {
            NewEmpViewModel = newEmpViewModel;
        }
 
 
        public bool CanExecute(object parameter)
        {
            bool action = false;
 
            if (NewEmpViewModel.Employee != null)
            {
                action = true;
            }
            return action;
 
        }
 
        public event EventHandler CanExecuteChanged;
 
        public void Execute(object parameter)
        {
            //Make call to the ViewModel
            NewEmpViewModel.InsertEmployee(NewEmpViewModel.Employee); 
        }
    }
}
 
 
VB.NET
 
Imports System
Imports System.Windows.Input
 
Namespace Silverlight.Com.View.Client
      Public Class CreateEmployeeCommand
            Implements ICommand
 
            Private NewEmpViewModel As CreateNewEmployeeViewModel
 
            Public Sub New(ByVal newEmpViewModel As CreateNewEmployeeViewModel)
                  Me.NewEmpViewModel = newEmpViewModel
            End Sub
 
 
            Public Function CanExecute(ByVal parameter As Object) As Boolean Implements ICommand.CanExecute
                  Dim action As Boolean = False
 
                  If NewEmpViewModel.Employee IsNot Nothing Then
                        action = True
                  End If
                  Return action
 
            End Function
 
            Public Event CanExecuteChanged As EventHandler Implements ICommand.CanExecuteChanged
 
            Public Sub Execute(ByVal parameter As Object) Implements ICommand.Execute
                  'Make call to the ViewModel
                  NewEmpViewModel.InsertEmployee(NewEmpViewModel.Employee)
            End Sub
      End Class
End Namespace
 
In the above command class, the CanExecute() method returns true if the clsEmployee object from UI is not null. The Execute() method makes a call to the ‘InsertEmployee()’ method from ‘CreateNewEmployeeViewModel’ class and passes the ‘clsEmployee’ object to it.
Step 2: To the SL project, add a new user control and name it as ‘NewEmployeeView.xaml’.
Step 3: Register the namespace and create an instance of ‘CreateNewEmployeeViewModel’ as shown below:
xmlns:src="clr-namespace:Silverlight.Com.View.Client"
 
<UserControl.Resources>
    <src:CreateNewEmployeeViewModel x:Key="EmployeeKey"></src:CreateNewEmployeeViewModel>
</UserControl.Resources>
Step 4: Write the following Xaml for the UserControl:
<UserControl x:Class="Silverlight.Com.View.Client.NewEmployeeView"
    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"
    xmlns:src="clr-namespace:Silverlight.Com.View.Client"         
    mc:Ignorable="d"
    d:DesignHeight="520" d:DesignWidth="522">
   
<UserControl.Resources>
    <src:CreateNewEmployeeViewModel x:Key="EmployeeKey"></src:CreateNewEmployeeViewModel>
</UserControl.Resources>
   
    <Grid x:Name="MainGrid" Background="White" Width="522"
           DataContext="{Binding Source={StaticResource EmployeeKey}}">
        <Grid Height="394" HorizontalAlignment="Left" Margin="10,10,0,0"
              Name="grdinput" VerticalAlignment="Top" Width="477"
               DataContext="{Binding Path=Employee,Mode=TwoWay}">
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="22,15,0,0" Name="textBlock1" Text="EmpNo:" VerticalAlignment="Top" Width="110" />
            <TextBlock Height="23" HorizontalAlignment="Left" Margin="22,57,0,0" Name="textBlock2" Text="EmpName:" VerticalAlignment="Top" Width="110" />
            <TextBlock Height="27" HorizontalAlignment="Left" Margin="22,98,0,0" Name="textBlock3" Text="Salary" VerticalAlignment="Top" Width="110" />
            <TextBlock Height="24" HorizontalAlignment="Left" Margin="22,142,0,0" Name="textBlock4" Text="DeptNo:" VerticalAlignment="Top" Width="110" />
            <TextBox Height="23" HorizontalAlignment="Left"
                     Margin="231,15,0,0" Name="txteno"
                     VerticalAlignment="Top" Width="120"
                      Text="{Binding EmpNo,Mode=TwoWay}"/>
            <TextBox Height="23" HorizontalAlignment="Left"
                     Margin="231,53,0,0" Name="txtename"
                     VerticalAlignment="Top" Width="120"
                     Text="{Binding EmpName,Mode=TwoWay}"/>
            <TextBox Height="23" HorizontalAlignment="Left"
                     Margin="231,98,0,0" Name="txtsal"
                     VerticalAlignment="Top" Width="120"
                     Text="{Binding Salary,Mode=TwoWay}"/>
            <TextBox Height="23" HorizontalAlignment="Left"
                     Margin="231,142,0,0" Name="txtdno"
                     VerticalAlignment="Top" Width="120"
                      Text="{Binding DeptNo,Mode=TwoWay}"/>
            <Button Content="Create New Employee"
                    Height="23" HorizontalAlignment="Left"
                    Margin="22,199,0,0" Name="btnInsert"
                    VerticalAlignment="Top" Width="441"
                     Command="{Binding  Path=DataContext.CreateEmployee,ElementName=MainGrid}"
                     CommandParameter="{Binding Path=Employee,ElementName=grdinput}"/>
        </Grid>
    </Grid>
</UserControl>
 
If you carefully note, you will find that  the parent grid ‘MainGrid’ is bound with the object of the ‘CreateNewEmployeeViewModel’ class. This instance is associated with the constructor of clsEmployee class.
Every TextBox is bound with an independent property of the ‘clsEmployee’ class with a TwoWay mode communication. The TwoWay mode will automatically update the bind property values. The important point here is the Command and CommandParameter is set for the button and the Command is making call to ‘CreateEmployee’ public property from the ‘CreateNewEmployeeViewModel’ class. This action actually returns a  ‘CreateEmployeeCommand’ class object. This class defines execution for the ‘InsertEmployee()’ method of ‘CreateNewEmployeeViewModel’ class.
CommandParamater is bound with the ‘Employee’ object of the ‘CreateNewEmployeeViewModel’ class. So here when the ’Create New Employee’ button is clicked after entering values in textboxes, the employee object will be constructed and it will be passed to the Execute() method of the command class. The Execute() method class makes call to the ’InsertEmployee()’ method from ‘CreateNewEmployeeViewModel’ class and finally the object will be sent to the WCF service.
Step 5: In the ‘MainPage.xaml’ , add one more button and name it as ‘btnCreateEmployee’ and code the click event as shown below:
C#
private void btnCreateEmployee_Click(object sender, RoutedEventArgs e)
{
    NewEmployeeView objNewEmpView = new NewEmployeeView();
    grdNewEmp.Children.Add(objNewEmpView); 
}
 
VB.NET
Private Sub btnCreateEmployee_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)
      Dim objNewEmpView As New NewEmployeeView()
      grdNewEmp.Children.Add(objNewEmpView)
End Sub
This will load the ‘NewEmployeeView’ user control.
Step 6: Run the application > click on the ‘Create Employee’ button and if everything has been done as explained in the steps above, the following result will be displayed:
Employee
Step 7: Enter valid values in the textboxes and click on ‘Create New Employee’ button. The object will be inserted into the database through WCF service.
Conclusion: Silverlight 4.0 commanding provides easy and flexible code-less development mechanism. No compiled code is required for handling Xaml elements on the View. If you isolate the command classes and business action classes in separate layers, then each layer can be tested separately reducing dependency between these layers.  
The entire source code of both the articles can be downloaded over here
Give a +1 to this article if you think it was well written. Thanks!
Recommended Articles


Page copy protected against web site content infringement by Copyscape


User Feedback
Comment posted by sri on Tuesday, October 12, 2010 4:02 AM
If you provide command line(description about coding),It is very useful to us,We can understand  easily

Post your comment
Name:  
E-mail: (Will not be displayed)
Comment:
Insert Cancel