Sign Silverlight XAP with TFS Build

I have a Silverlight application that is set up for Continuous Integration with Team Foundation Server. As part of the build, I needed to sign the XAP with a certificate. To accomplish this I will be using a command line tool SignTool.exe. The tool is automatically installed with Visual Studio and it has to exist on the TFS Server.

Steps below walk through the setup process.

1) Check-in the certificate into TFS. This must be done so that the build server downloads it into the workspace.

2) Update the Post-build event on the Silverlight project

In Project Properties, select ‘Compile’ option, then select the ‘Build Events…’ button.

image

We will be modifying Post-build event command line.  Select the ‘Edit Post-build …’ button.

clip_image004

Enter the SignTool command to execute:

"C:\Program Files (x86)\Windows Kits\8.0\bin\x86\SignTool.exe" sign /v /f
$(SolutionDir)\..\MyCert.pfx /p CertPassword $(TargetName).xap

Specify the path to the certificate relative to the solution directory so that it can be found during the Build.

3) Verify that your build definition is set up to download the certificate into its workspace.

Silverlight WebAqua – Unlicensed Version

We have been using a WebAqua Silverlight Navigation control in our application for several years.  Recently, after implementing a few changes to the application and deploying to our test server, we started seeing an “Unlicensed Version” message in the middle of the application.  Our version was licensed and had no issues until the most recent set of changes.

Over last few weeks I’ve been emailing WebAqua Tech Support and spent several hours on their Live Chat trying to resolve the issue without any success.  After all licensing attempts have failed, I went down the path of backtracking through our code, which led me to my solution.

Solution

The issue was caused by the levels of nesting.   To begin with, the FishEye control was nested 11 layers deep inside Border controls and Grids.  We have 10 Border controls with a Grid inside used for layout.  The issue came up when I added another layer of nesting by wrapping everything in a Grid to add a “Loading…” message that overlays the whole User Control.  This seems very odd, but the message went away after I removed the outer Grid.

I hope that this solution will come in handy for someone with a similar issue.

Silverlight Telerik Transitions with User Controls

 

I was looking to implement Silverlight Telerik Transitions in my Silverlight 5 application with User Controls to walk a user through a wizard.  My initial approach was to use a Visual State Manager, which would allow me to keep all the UI logic in the XAML.  This did not work well with Telerik Transitions.  I decided to use DataTriggers that modified the state of the UI  based on a WizardState enumeration on my View Model.

View Model

 
Namespace ViewModels.Employee
 
    Public Class EmployeeViewModel
        Inherits BaseViewModel
 
 
#Region "Properties"
 
        Private _employeeSetupState As EmployeeSetupStateEnum
 
        Public Property EmployeeSetupState As EmployeeSetupStateEnum
            Get
                Return _employeeSetupState
            End Get
            Set(ByVal value As EmployeeSetupStateEnum)
                If _employeeSetupState <> value Then
                    _employeeSetupState = value
                    NotifyPropertyChanged("CanMoveForward")
                    NotifyPropertyChanged("CanMoveBack")
                    NotifyPropertyChanged("EmployeeSetupState")
                End If
            End Set
        End Property
 
        Public ReadOnly Property CanMoveForward() As Boolean
            Get
                Dim newState As Integer = EmployeeSetupState + 1
                If [Enum].IsDefined(GetType(EmployeeSetupStateEnum), newState) Then
                    Return True
                End If
 
                Return False
            End Get
        End Property
 
        Public ReadOnly Property CanMoveBack() As Boolean
            Get
                Dim newState As Integer = EmployeeSetupState - 1
                If [Enum].IsDefined(GetType(EmployeeSetupStateEnum), newState) Then
                    Return True
                End If
 
                Return False
            End Get
        End Property
 
        ' The Properties for the View Models are defined here.
 
#End Region
 
#Region "Base Overrides/Overloads"
 
        Public Overrides Sub Initialize()
            MyBase.Initialize()
 
            EmployeeSetupState = 0
            InitializeStep()
        End Sub
 
#End Region
 
#Region "Public Methods"
 
        Public Sub NextStep()
 
            If CanMoveForward Then
                EmployeeSetupState = CType(EmployeeSetupState + 1, EmployeeSetupStateEnum)
                InitializeStep()
            End If
 
        End Sub
 
        Public Sub PreviousStep()
 
            If CanMoveBack Then
                EmployeeSetupState = CType(EmployeeSetupState - 1, EmployeeSetupStateEnum)
                InitializeStep()
            End If
 
        End Sub
 
#End Region
 
#Region "Private Methods"
 
        Private Sub InitializeStep()
 
            Select Case EmployeeSetupState
                Case EmployeeSetupStateEnum.EmployeeGeneralInformationState
                    EmployeeGeneralInformationViewModel.Initialize()
                Case EmployeeSetupStateEnum.EmployeeAddressInformationState
                    EmployeeAddressInformationViewModel.Initialize()
                Case EmployeeSetupStateEnum.EmployeeContactInformationState
                    EmployeeContactInformationViewModel.Initialize()
                Case EmployeeSetupStateEnum.EmployeeCommentsState
                    EmployeeCommentsViewModel.Initialize()
            End Select
 
        End Sub
 
#End Region
 
    End Class
 
    ''' <summary>
    ''' States of the Employee setup process. These steps
    ''' are executed in the order specified.
    ''' </summary>
    ''' <remarks></remarks>
    Public Enum EmployeeSetupStateEnum
        EmployeeGeneralInformationState
        EmployeeAddressInformationState
        EmployeeContactInformationState
        EmployeeCommentsState
    End Enum
 
End Namespace

In the code above, I have an enumeration that specifies valid states for my employee setup process (specified in the order I want to show these states) and a property in my View Model that holds the current state of the employee setup process. I have a trigger that calls the Initialize() method on my View Model when the page loads.  During the initialization process, my EmployeeSetupState is set to the first step and the view model for that step is initialized by calling the InitializeStep() method.  I have a property that determines if the current EmployeeSetupState has a previous or next step.  My View Model also holds a reference to the View Models for each of the User Controls that make up my employee setup states (not shown in the code above).

View

<UserControl.Resources>
    <vm:EmployeeViewModel x:Name="ViewModel"/>
</UserControl.Resources>
 
<Grid xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" x:Name="LayoutRoot">
 
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition Height="*" MinHeight="250" />
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
 
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Loaded">
            <ic:CallMethodAction MethodName="Initialize"
                                 TargetObject="{Binding Mode=OneWay}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
 
    <telerik:RadTransitionControl Content="{Binding EmployeeSetupState}">
        <telerik:RadTransitionControl.Transition>
            <telerik:FadeTransition />
        </telerik:RadTransitionControl.Transition>
        <telerik:RadTransitionControl.ContentTemplate>
            <DataTemplate>
                <Grid Margin="5,10,5,10">
 
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="*" />
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="*" />
                    </Grid.RowDefinitions>
 
 
                    <uc:EmployeeGeneralInformationView x:Name="EmployeeGeneralInformationView"
                        Visibility="Collapsed"
                        DataContext="{Binding Source=ViewModel, Path=EmployeeGeneralInformationViewModel, Mode=TwoWay}" />
                    <uc:EmployeeAddressInformationView x:Name="EmployeeAddressInformationView"
                        Visibility="Collapsed"
                        DataContext="{Binding Source=ViewModel, Path=EmployeeAddressInformationViewModel, Mode=TwoWay}" />
                    <uc:EmployeeContactInformationView x:Name="EmployeeContactInformationView"
                        Visibility="Collapsed"
                        DataContext="{Binding Source=ViewModel, Path=EmployeeContactInformationViewModel, Mode=TwoWay}" />
                    <uc:EmployeeCommentsView x:Name="EmployeeCommentsView"
                        Visibility="Collapsed"
                        DataContext="{Binding Source=ViewModel, Path=EmployeeCommentsViewModel, Mode=TwoWay}" />
 
                    <i:Interaction.Triggers>
                        <ei:DataTrigger Binding="{Binding Converter={StaticResource EnumToStringConverter}}"
                                        Value="EmployeeGeneralInformationState">
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Visible"
                                TargetName="EmployeeGeneralInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeAddressInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeContactInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeCommentsView" />
                        </ei:DataTrigger>
                        <ic:DataTrigger Binding="{Binding Converter={StaticResource EnumToStringConverter}}"
                                        Value="EmployeeAddressInformationState">
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeGeneralInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Visible"
                                TargetName="EmployeeAddressInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeContactInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeCommentsView" />
                        </ic:DataTrigger>
                        <ic:DataTrigger Binding="{Binding Converter={StaticResource EnumToStringConverter}}"
                                        Value="EmployeeContactInformationState">
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeGeneralInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeAddressInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Visible"
                                TargetName="EmployeeContactInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeCommentsView" />
                        </ic:DataTrigger>
                        <ic:DataTrigger Binding="{Binding Converter={StaticResource EnumToStringConverter}}"
                                        Value="EmployeeCommentsState">
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeGeneralInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeAddressInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Collapsed"
                                TargetName="EmployeeContactInformationView" />
                            <ic:ChangePropertyAction
                                PropertyName="Visibility" Value="Visible"
                                TargetName="EmployeeCommentsView" />
                        </ic:DataTrigger>
                    </i:Interaction.Triggers>
 
                </Grid>
            </DataTemplate>
        </telerik:RadTransitionControl.ContentTemplate>
    </telerik:RadTransitionControl>

    <StackPanel Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
        <Button x:Name="PreviousButton" Content="&lt; Previous"  HorizontalAlignment="Right"
                Visibility="{Binding CanMoveBack, Converter={StaticResource BoolToVisibilityConverter}}"
                Margin="5"  Style="{StaticResource ButtonPrimaryStyle}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <ic:CallMethodAction MethodName="PreviousStep"
                                         TargetObject="{Binding Mode=OneWay}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
        <Button x:Name="NextButton" Content="Next &gt;" Width="70" HorizontalAlignment="Right"
                Visibility="{Binding CanMoveForward, Converter={StaticResource BoolToVisibilityConverter}}"
                Margin="5" Style="{StaticResource ButtonPrimaryStyle}">
            <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <ic:CallMethodAction MethodName="NextStep"
                                         TargetObject="{Binding Mode=OneWay}"/>
                </i:EventTrigger>
            </i:Interaction.Triggers>
        </Button>
 
    </StackPanel>
 
</Grid>

In my View, I bind the Content property of RadTransitionControl to the EmployeeSetupState from my View Model.  The transitions happen each time the state change occurs.  The data triggers control what view displays depending on the current employee setup state.  In the data triggers I use the ChangePropertyAction to set the Visibility of the User Controls.  This separates my View Model code to only determine and set the state of the setup process and my View handles the display.

Silverlight 4 Telerik Scheduler Issue

Telerik controls version 2010.1.422.1040

I recently took over a Silverlight Telerik scheduler which was having an issue with displaying appointments on a resource view.   The only way I could get appointments to display is if “DisplayEmptyGroup” property on the scheduler was set to true.  All the appointments were assigned to a resource, but would not display on the scheduler.

The issue was the assignment of the resources to appointments.  The appointments were loaded and added to the Telerik appointment collection.  Then each appointment in the collection was looped through and assigned to the resource.  So as the appointments were added to the collection, they defaulted to an empty resource group since it was not yet assigned to the resource.  For some reason, since the empty group is not displayed (“DisplayEmptyGroup”  set to false), the appointments did not show up on the scheduler when the resource was eventually assigned to the appointment.

To fix the problem, I assigned the resource to an appointment before adding it to the collection.  Problem solved!!!

Upgrading Silverlight 3 Project to Silverlight 4

Recently I upgraded our Silverlight 3 project with WCF services to Visual Studio 2010 Silverlight 4.  Overall the upgrade went smoothly with a few glitches.  Following are some basic steps:

  • Install Blend 4 (if using blend references)
  • Install Silverlight 4 toolkit
  • Run the Visual Studio conversion wizard
  • Update broken references
  • Change all Silverlight projects to target Silverlight 4 in the project properties
  • Delete all WCF references and re-add them
    • When adding a service reference, choose “Reuse types in referenced assemblies" and select specific assemblies instead of the "Always generate message contracts" option.

WCFConfigureService If attached to source control, you may need to name newly added references differently or re-name existing references before deleting.

After running the solution through the conversion wizard I was getting several errors with the WCF services.  I tried removing and re-adding the services several times with the “Always generate message contracts” option selected, which worked fine with Silverlight 3 in Visual Studio 2008.  By selecting the option to reuse types and checking the specified assemblies, I was able to resolve my issue with WCF in Visual Studio 2010.

Silverlight Telerik Editable GridView with MVVM – Part 3

This is the final part of the Telerik Editable GridView Series. In Part 1 I talked about the Model and in Part 2 I covered the View Model. In this post I will be discussing the View portion of the MVVM pattern.

I will start out with the xaml for the GridView.

[sourcecode language=’vb’]

xmlns:telerikGridView=”clr-namespace:Telerik.Windows.Controls;
assembly=Telerik.Windows.Controls.GridView”
xmlns:telerikData=”clr-namespace:Telerik.Windows.Controls;
assembly=Telerik.Windows.Controls.Data”

[/sourcecode]

[sourcecode language=’xml’]





















[/sourcecode]

I bind the GridView item source to the “EmployeeList” in the View Model. Each column is bound to a property on the Employee Model. Since my model implements System.ComponentModel.INotifyPropertyChanged, the GridView is updated each time any property that I am bound to on the model changes. I used a templated column to represent the “IsActive” boolean column. For the templated column I specify binding in each of the cell templates and on the column. The binding on the column is used by the GridView for filtering and sorting.

Next, I will go through the code-behind of the View.

[sourcecode language=’vb’]

Partial Public Class EmployeeMaintenancePage
Inherits UserControl

Private _vm As EmployeeMaintenanceViewModel

”’

”’ Constructor
”’

”’
Public Sub New()
InitializeComponent()
End Sub

#Region “Event Handlers”

”’

”’ I clear my sort and filter before adding a new Employee. This is
”’ necessary because if the new row does not fit the current filter, it
”’ will not display. Also, by clearing the sort, we force the newly added
”’ row to the bottom of the grid.
”’

”’ ”’ ”’
Private Sub EmployeeGridView_AddingNewDataItem(ByVal sender As System.Object, ByVal e As Telerik.Windows.Controls.GridView.GridViewAddingNewEventArgs)
EmployeeGridView.FilterDescriptors.Clear()
EmployeeGridView.SortDescriptors.Clear()
e.NewObject = _vm.GetNewEmployee()
End Sub

”’

”’ Reload from the row cache if edit was cancelled, otherwise
”’ save to the database.
”’

”’ ”’ ”’
Private Sub EmployeeGridView_RowEditEnded(ByVal sender As System.Object, ByVal e As Telerik.Windows.Controls.GridViewRowEditEndedEventArgs)
If e.EditAction = Telerik.Windows.Controls.GridView.GridViewEditAction.Cancel Then
_vm.ReloadEmployeeFromCache(CType(e.Row.DataContext, EmployeeModel))
Else
_vm.UpdateEmployee(TryCast(e.Row.DataContext, EmployeeModel))
End If
End Sub

”’

”’ Call the delete method on the View Model to delete employee. GridView will get
”’ updated when the item is removed from the “EmployeeList” on the view model.
”’

”’ ”’ ”’
Private Sub EmployeeGridView_Deleting(ByVal sender As System.Object, ByVal e As Telerik.Windows.Controls.GridViewDeletingEventArgs)
_vm.DeleteEmployee(CType(e.Items(0), EmployeeModel).Id)
e.Cancel = True
End Sub

”’

”’ Store the current copy of the row on Selection Changed. In a case when an edit
”’ is cancelled, the stored value is used to reload row with original values.
”’

”’ ”’ ”’
Private Sub EmployeeGridView_SelectionChanged(ByVal sender As System.Object, ByVal e As Telerik.Windows.Controls.SelectionChangeEventArgs)
If e.AddedItems.Count > 0 Then
_vm.CurrentRowCache = CType(e.AddedItems(0), EmployeeModel).Clone()
End If
End Sub
#End Region

#Region “Public Methods”

”’

”’ Load the View Model and bind it to the View.
”’

”’
Public Sub Load()
_vm = New EmployeeMaintenanceViewModel()
_vm.Load()
Me.DataContext = _vm
End Sub

#End Region

End Class

[/sourcecode]

In the code-behind of the View, I mainly handle the events and call my View Model to process the logic. This allows me to unit test the logic in my View Model.

Silverlight Telerik Editable GridView with MVVM – Part 2

This is the continuation from Part 1 where I walked through creating my Model. The next step is to create a View and a View Model. There should only be one View Model per View. I will try to take advantage of xaml binding where possible.

Following is my View Model.

View Model
  1. Imports System.Collections.ObjectModel
  2. Imports System.ComponentModel
  3.  
  4. Public Class EmployeeMaintenanceViewModel
  5.     Implements INotifyPropertyChanged
  6.  
  7.     Public Event PropertyChanged( _
  8.             ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
  9.  
  10.     Protected Sub NotifyPropertyChanged(ByVal propertyName As String)
  11.         RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
  12.     End Sub
  13.  
  14. #Region "Private Members"
  15.  
  16.     Private _employeeGateway As EmployeeGateway
  17.     Private _currentRowCache As EmployeeModel
  18.     Private _employeeList As ObservableCollection(Of EmployeeModel) =  _
  19.             New ObservableCollection(Of EmployeeModel)
  20.  
  21. #End Region
  22.  
  23. #Region "Constructors"
  24.  
  25.     Public Sub New()
  26.  
  27.     End Sub
  28.  
  29. #End Region
  30.  
  31. #Region "Properties"
  32.  
  33.     Public Property CurrentRowCache() As EmployeeModel
  34.         Get
  35.             Return _currentRowCache
  36.         End Get
  37.         Set(ByVal value As EmployeeModel)
  38.             _currentRowCache = value
  39.         End Set
  40.     End Property
  41.  
  42.     Public Property EmployeeList() As ObservableCollection(Of EmployeeModel)
  43.         Get
  44.             Return _employeeList
  45.         End Get
  46.         Set(ByVal value As ObservableCollection(Of EmployeeModel))
  47.             _employeeList = value
  48.         End Set
  49.     End Property
  50.  
  51. #End Region
  52.  
  53. #Region "Public Methods"
  54.  
  55.     'use WCF to load all employees.
  56.     Public Sub Load()
  57.         'clear the list prior to loading.
  58.         EmployeeList.Clear()
  59.  
  60.         _employeeGateway = New EmployeeGateway()
  61.         _employeeGateway.FindAllEmployees(AddressOf OnEmployeesLoaded)
  62.  
  63.     End Sub
  64.  
  65.     Public Function GetNewEmployee() As EmployeeModel
  66.         Dim emp As New EmployeeModel()
  67.  
  68.         'default to active, set uniqueId to map employee back
  69.         'when returned from a save
  70.         emp.IsActive = True
  71.         emp.UniqueId = Guid.NewGuid
  72.         Return emp
  73.     End Function
  74.  
  75.     Public Sub UpdateEmployee(ByVal emp As EmployeeModel)
  76.         emp.IsModified = True
  77.         SaveEmployee(emp)
  78.     End Sub
  79.  
  80.     Public Sub DeleteEmployee(ByVal id As Integer)
  81.         Dim emp As EmployeeModel = EmployeeList.Where(Function(x) x.Id = id).SingleOrDefault()
  82.         If id > 0 Then
  83.             emp.IsDeleted = True
  84.             SaveEmployee(emp)
  85.         Else
  86.             EmployeeList.Remove(emp)
  87.         End If
  88.  
  89.     End Sub
  90.  
  91.     'in a case of a cancel edit, i reload employee with the values stored in the
  92.     'row cache before edit.
  93.     Public Sub ReloadEmployeeFromCache(ByVal emp As EmployeeModel)
  94.         If CurrentRowCache Is Nothing Then
  95.             Exit Sub
  96.         End If
  97.  
  98.         With emp
  99.             .IsActive = CurrentRowCache.IsActive
  100.             .FirstName = CurrentRowCache.FirstName
  101.             .LastName = CurrentRowCache.LastName
  102.         End With
  103.     End Sub
  104.  
  105. #End Region
  106.  
  107. #Region "Private Methods"
  108.  
  109.     'Call WCF to save employee
  110.     Private Sub SaveEmployee(ByVal emp As EmployeeModel)
  111.         _employeeGateway = New EmployeeGateway()
  112.         _lookupGateway.SaveEmployee(AddressOf OnEmployeeSaved, emp)
  113.     End Sub
  114.  
  115.     Private Sub UpdateRecord(ByVal updatedEmployee As EmployeeModel)
  116.         Dim emp As EmployeeModel
  117.  
  118.         'if uniqueId is not Guid.Empty, it's a new add, use the guid to find it in the list.
  119.         If updatedEmployee.UniqueId <> Guid.Empty Then
  120.             emp = EmployeeList.Where(Function(l) l.UniqueId = _
  121.                                          updatedEmployee.UniqueId).SingleOrDefault
  122.         Else
  123.             emp = EmployeeList.Where(Function(l) l.Id = _
  124.                                          updatedEmployee.Id).SingleOrDefault
  125.         End If
  126.  
  127.         'check if employee was found
  128.         If emp IsNot Nothing Then
  129.             If updatedEmployee.IsDeleted Then
  130.                 EmployeeList.Remove(emp)
  131.             Else
  132.                 'This data will be updated on the grid since I implemented
  133.                 'INotifiyPropertyChanged interface on my Model.
  134.                 With emp
  135.                     .Id = updatedEmployee.Id
  136.                     .FirstName = updatedEmployee.FirstName
  137.                     .LastName = updatedEmployee.LastName
  138.                     .IsActive = updatedEmployee.IsActive
  139.                 End With
  140.             End If
  141.         End If
  142.     End Sub
  143.  
  144. #End Region
  145.  
  146. #Region "Event Handlers"
  147.  
  148.     Private Sub OnEmployeesLoaded(ByVal employees As ObservableCollection(Of EmployeeModel))
  149.  
  150.         'each employee must be added to the observable collection so that
  151.         'it is reflected on the Grid.
  152.         For Each emp As EmployeeModel In employees
  153.             EmployeeList.Add(emp)
  154.         Next
  155.  
  156.     End Sub
  157.  
  158.     Public Sub OnEmployeeSaved(ByVal updatedEmployee As EmployeeModel)
  159.         If updatedEmployee IsNot Nothing Then
  160.             UpdateRecord(updatedEmployee)
  161.         End If
  162.     End Sub
  163.  
  164. #End Region
  165.  
  166. End Class

Review the comments in the code snippet for explanation. The goal is to place all the logic specific to UI in the View Model. The View Model should not be accessing any controls directly. The View knows about the View Model, but the View Model does not have a reference back to the View. The View Model basically bridges the gap between the View and the Model.

The View code behind will access controls in a case where direct binding is not available, but any logic should still be placed in the View Model. The View code behind will generaly handle events and make calls to the View Model. I will cover that in Part 3 of the post.

Silverlight Telerik Editable GridView with MVVM – Part 1

Over last few days I’ve been working with the Telerik GridView control in a Silverligt 3 project. The goal was to implement an editable grid using MVVM (Model-View-View Model) pattern. A user must be able to Add/Edit/Delete rows from the grid.

I will be using the Telekik controls version 2009.3.1208.1030

I will start by creating my Model.

Model
  1. Imports System.Globalization
  2. Imports System.ComponentModel
  3. Imports System.ComponentModel.DataAnnotations
  4.  
  5. Public Class EmployeeModel
  6.     Implements INotifyPropertyChanged
  7.  
  8.     Public Sub New()
  9.  
  10.     End Sub
  11.  
  12.     Public Sub New()
  13.         ._isModified = False
  14.         ._isDeleted = False
  15.         ._isNew = False
  16.     End Sub
  17.  
  18.     Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
  19.  
  20.     Protected Sub NotifyPropertyChanged(ByVal propertyName As String)
  21.         RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
  22.     End Sub
  23.  
  24.     Private _isModified As Boolean
  25.     Public Property IsModified() As Boolean
  26.         Get
  27.             Return (_isModified)
  28.         End Get
  29.         Set(ByVal value As Boolean)
  30.             _isModified = value
  31.             NotifyPropertyChanged("IsModified")
  32.         End Set
  33.     End Property
  34.  
  35.     Private _isDeleted As Boolean
  36.     Public Property IsDeleted() As Boolean
  37.         Get
  38.             Return _isDeleted
  39.         End Get
  40.         Set(ByVal value As Boolean)
  41.             _isDeleted = value
  42.             NotifyPropertyChanged("IsDeleted")
  43.         End Set
  44.     End Property
  45.  
  46.     Private _id As Integer
  47.     Public Property Id() As Integer
  48.         Get
  49.             Return _id
  50.         End Get
  51.         Set(ByVal value As Integer)
  52.             _id = value
  53.             NotifyPropertyChanged("Id")
  54.         End Set
  55.     End Property
  56.  
  57.     Private _firstName As String
  58.  
  59.     <Required(ErrorMessage:="First Name is Required.")> _
  60.     <StringLength(15, ErrorMessage:="First Name cannot be greater than 15 characters.")> _
  61.     Public Property FirstName() As String
  62.         Get
  63.             Return _firstName
  64.         End Get
  65.         Set(ByVal value As String)
  66.             _firstName = value
  67.             NotifyPropertyChanged("FirstName")
  68.         End Set
  69.     End Property
  70.  
  71.     Private _lastName As String
  72.  
  73.     <Required(ErrorMessage:="Last Name is Required.")> _
  74.     <StringLength(20, ErrorMessage:="Last Name cannot be greater than 20 characters.")> _
  75.     Public Property LastName() As String
  76.         Get
  77.             Return _lastName
  78.         End Get
  79.         Set(ByVal value As String)
  80.             _lastName = value
  81.             NotifyPropertyChanged("LastName")
  82.         End Set
  83.     End Property
  84.  
  85.     Private _uniqueId As Guid
  86.     Public Property UniqueId() As Guid
  87.         Get
  88.             Return _uniqueId
  89.         End Get
  90.         Set(ByVal value As Guid)
  91.             _uniqueId = value
  92.             NotifyPropertyChanged("UniqueId")
  93.         End Set
  94.     End Property
  95.  
  96.     Private _isActive As Boolean
  97.     Public Property IsActive() As Boolean
  98.         Get
  99.             Return _isActive
  100.         End Get
  101.         Set(ByVal value As Boolean)
  102.             _isActive = value
  103.             NotifyPropertyChanged("IsActive")
  104.         End Set
  105.     End Property
  106.  
  107.     Public Function Clone() As EmployeeModel
  108.         Return New EmployeeModel With { _
  109.         .Id = Id, _
  110.         .FirstName = FirstName, _
  111.         .LastName = LastName, _
  112.         .IsActive = IsActive, _
  113.         .UniqueId = UniqueId}
  114.     End Function
  115.  
  116. End Class


I added validation directly to my model for the First Name and Last Name using Attributes. I also implemented System.ComponentModel.INotifyPropertyChanged to notify my view when a property changes.

In Part 2 of the post I will go through creating a View Model.