ASP .NET PostBack Performance – Part 1

I ran into a performance issue with an ASP.Net website that was experiencing a slow down on some of the data heavy screens.  I was not able to recreate this performance issue from my office, but it was very noticeable at the client site.  The pages that were extremely slow were doing a significant number of postacks within AJAX Update Panels.

After some research, I was able to narrow down the cause of this issue to be related to the following:

    1. The internet connection at the client site
    2. Number of postbacks
    3. Size of the ViewState

I was able to rule out the performance of the SQL Server and the Web Server since I was not able to reproduce the issue from my office. 

After testing the bandwidth at the client site, it appeared that their upload bandwidth was low and highly utilized.  The application was doing several postbacks on most utilized screens.  The AJAX Update Panel enhanced user experience by doing partial updates to the screen, therefore minimizing the flicker, but it also caused performance issues since each request to the server was a full ASP.Net postback.

To determine the size of each postback I used a Fiddler to record my HTTP traffic.  Fiddler can be downloaded for free here

After recording the traffic, I looked at the “TextView” of the request in Fiddler to determine the size of my postback. I did this for all slow performing screens. The size of the postback for each of the slow performing screens was as follows:

    • 143K per postback
    • 188K per postback
    • 700k per postback
    • 244K per postback

These are fairly large and can eat up the upload bandwidth quickly.  At this point I could either re-work these screens to eliminate these postbacks or find a way to minimize the size of my ViewState on these pages.

I will discuss my solution to this issue in the Part 2 of this post.

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

LINQ Lazy Loading

I was experiencing some performance issues in my Silverlight application and got it narrowed down to the mapping of the domain objects.  After running SQL profiler and doing some research I figured out that it was due to Linq lazy loading.

As an example if I have the following data structure:

Employee_EmployeePosition

I would have an “EmployeePosition” domain object and an “Employee” domain object.  I will use the following Linq statement to bring back all Employee Positions:

  1. using (var dc = new DataClasses1DataContext())
  2. {
  3.     var postiions = dc.EmployeePositions.ToList();
  4. }

Linq lazy loading is enabled by default, so by executing the above query Linq will only bring back Employee Positions.  If I am only looking for Employee Positions everything works as expected.  The issue appears if I want to bring back the Employee information for each position.  Since I have a foreign key relationship between “Employee” and “EmployeePosition”, my dbml has “one to many” association between them.  This allows me to write the following mapping to my object that I return to my Silverlight application:
  1. var myEmployees = postiions.Select(x => new EmployeeWithPosition
  2.                     {
  3.                         FirstName = x.Employee.FirstName,
  4.                         LastName = x.Employee.LastName,
  5.                         Position = x.Position
  6.                     }).ToList();

When executing above code, there is a separate call made to the database to get the “FirstName” then another call to get the “LastName” for each of the “EmployeePosition” objects due to LINQ lazy loading (default).  So if I have 10 employee positions, there are 20 additional calls made to the database.

There are a few solutions to solve this issue:

    1. Disable lazy loading for the entire dbml file. 
    2. Specify “DataLoadOptions” on the Data Context.  This is a valid option if you do not re-use the Data Context.
    3. Use projection to load only necessary data.

The best option for my situation was to use projection to load my data.  To do this I extended my existing Employee domain object by creating a partial “Employee” class and adding a string “Position” property.  Then I used projection to load my data to the Employee domain object.

  1. using (var dc = new DataClasses1DataContext())
  2. {
  3.     var myEmployees = dc.EmployeePositions.Select(x => new Employee
  4.     {                    
  5.         FirstName = x.Employee.FirstName,
  6.         LastName = x.Employee.LastName,                    
  7.         Position = x.Position
  8.     }).ToList();
  9. }

When I executed above code I got the following run-time error:

Explicit construction of entity type ‘Employee’ in query is not allowed.

After doing a little research I discovered that projection to a domain object is not allowed. As a work around, I used my “EmployeeWithPosition” custom object which only contains properties that I am interested in from the “Employee” and “EmployeePosition” domain objects to project my data.

  1. using (var dc = new DataClasses1DataContext())
  2.             {
  3.                 var myEmployees = dc.EmployeePositions.Select(x => new EmployeeWithPosition
  4.                 {                    
  5.                     FirstName = x.Employee.FirstName,
  6.                     LastName = x.Employee.LastName,                    
  7.                     Position = x.Position
  8.                 }).ToList();
  9.             }

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.

CRM Asynchronous Service Not Running

After doing a database move for Microsoft CRM 4 to a separate server we were experiencing issues with the CRM Asynchronous Service which is responsible for processing asynchronous jobs like the workflows. The cause for the issue was the service dependency on MSSQLSERVER.   To resolve the issue I had to perform the following registry  change to remove the dependency.

  1. Run the “regedit” command to open the Registry Editor
  2. Navigate to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\MSCRMAsyncService
  3. Delete the Value (MSSQLSERVER) for the “DependOnService” Name
  4. Restart the server

The service should come up running after the restart.

Empty “Create Unit Tests” Window in VS2008

I went to add unit tests to my Solution by right clicking my method and choosing a “Create Unit Tests…” option in Visual Studio 2008 and received a following blank pop-up window.

UnitTestEmpty 

After doing research I determined that this was due to a Silverlight project which was part of my solution.  This issue only comes up when a solution contains a Silverlight project, even if you are trying to create unit tests for a non Silverlight project.  A hot fix for this issue can be found in the following KB article http://code.msdn.microsoft.com/KB962866.

Casting IQueryable List

Occasionally I run into situations where I have a List of objects that I need to cast to a list of specific types. One option would be to iterate through the list of objects and cast each item individually and add them to a new list of the specific type. 

  1. Dim countries As New List(Of Country)
  2. For Each item As Object In items
  3.     countries.Add(DirectCast(item, Country))
  4. Next

Another more cleaner option would be to use a Linq statement.

  1. Dim countries As New List(Of Country)
  2. countries = items.Cast(Of Country).ToList()

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.