Silverlight 4.0 Data Manipulation Using WCF RIA Services

This article focuses on manipulating data (inserting, updating, deleting, saving and refreshing) using WCF RIA Services and Silverlight 4.0 in a raw manner. By this I mean that we will not use the DomainDataSource and DataForm controls of Silverlight 4.0.

Contributed by
Rating: 5 stars5 stars5 stars5 stars5 stars / 4
July 14, 2010
Rate this Article:
MEH MEH++


SEARCH ASP FREE
TOOLS YOU CAN USE

advertisement

To keep this article simple, I created a simple Silverlight 4.0 application which consumes a WCF RIA Service created using the WCF RIA Service Library. If you are not familiar with developing applications using the WCF RIA Service Library and Silverlight 4.0, check out a beginner’s article available at http://jagchat.spaces.live.com/blog/cns!41050F68F010A662!4439.entry.

This is an extension to my previous article titled “Retrieving Data from WCF RIA Services using Silverlight 4.0.”  You can view my previous articles at http://www.aspfree.com/cp/bio/Jagadish-Chatarji

The solution was developed using Microsoft Visual Studio 2010 Ultimate Edition with Microsoft Silverlight 4.0 on Windows 7 Ultimate edition. I didn’t really test it in any other environment. I request that you post in the discussion area if you have any problems with execution.

Modifying Entities at Silverlight application

In my previous article, I explained how to retrieve data from WCF RIA Services in various ways.  In this section, we are going to edit/modify entities available in a Silverlight application.

The following would send a request to a WCF RIA Service for all “emp” entities and make them available locally (at the Silverlight application):

   Private oCtxt As New BusinessLib.Web.EmpMgrDomainSvc

 

    Public Sub New()

        InitializeComponent()

 

        Me.dgEmp.ItemsSource = oCtxt.emps

        oCtxt.Load(oCtxt.GetEmpsQuery())

    End Sub

From the above, we understand that “oCtxt” holds all entities, and we can use the same object to add/modify/remove various entities.

To modify a particular entity, we need to make textboxes bind to the properties of the same entity. As all of our entities are currently listed in datagrid, I would like to make textboxes bind to the selected row of the datagrid. This can be achieved as shown below:

    Private Sub dgEmp_SelectionChanged(ByVal sender As System.Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles dgEmp.SelectionChanged

        If dgEmp.SelectedItem IsNot Nothing Then

            Me.lytEmpForm.DataContext = dgEmp.SelectedItem

        End If

    End Sub

All textboxes (except txtEmpno) are two-way bound to the properties of the “Emp” entity type, and all of those are contained in “lytEmpForm.” Once we set the “DataContext” property of “lytEmpForm” to an entity object, all textboxes will pull information (using properties) from the same object and get bound automatically.  This is illustrated in the following figure:

Apart from the selected row, I also added functionality to search for an employee.  This is illustrated below:

    Private Sub btnSearch_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSearch.Click

        Dim oEmp = oCtxt.emps.SingleOrDefault(Function(p) p.empno = Me.txtEmpno.Text)

        If oEmp Is Nothing Then

            MessageBox.Show("Employee not found")

        Else

            Me.lytEmpForm.DataContext = oEmp

        End If

    End Sub

In the above case, I search for an entity in the list of entities owned by “oCtxt” and directly assign the same as “DataContext” to “lytEmpForm.” You can understand this from the following figure:

Once the textboxes reflect the data from the selected entity, you can directly edit the data available in the textboxes. Modifying the data in the textboxes will automatically reflect back to the entities, and finally to the datagrid, too!

NOTE:  All of the modifications are preserved at the client (in this case, it is the Silverlight application) unless they are explicitly saved (which is covered in upcoming sections).

Adding or Deleting Entities in a Silverlight Application

In the previous section, we saw how to modify existing entities. In this section, we will work on adding or deleting entities from the “oCtxt” object.

Adding or removing entities is a straightforward process.  All we have to do is  manipulate the entity set (which similar to collection) available in the context.

The following is the code that lets you add a new entity:

    Private Sub btnAddNew_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnAddNew.Click

        Dim oEmp As New BusinessLib.Web.emp

        oCtxt.emps.Add(oEmp)

        Me.txtEmpno.SetBinding(TextBox.TextProperty,

                               New System.Windows.Data.Binding With

                               {

                                   .Path = New PropertyPath("empno"),

                                   .Mode = Data.BindingMode.TwoWay

                               })

        Me.lytEmpForm.DataContext = oEmp

    End Sub

In the above code, we cause “txtEmpno” to be dynamically bound to the “empno” property of the newly-created “emp” entity object.  Adding a new entity would give the result shown below:

The following is the code required to delete an existing entity:

    Private Sub btnDelete_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnDelete.Click

        If Me.lytEmpForm.DataContext Is Nothing Then

            MessageBox.Show("Employee not selected to delete")

            Exit Sub

        End If

        oCtxt.emps.Remove(Me.lytEmpForm.DataContext)

    End Sub

NOTE:  All of the modifications are preserved at the client (in this case, it is the Silverlight application) unless they are explicitly saved (which is covered in the next section).

Saving Changes Back to the Database

In all of the previous sections, we modified entities available at the Silverlight application, and none of them were really saved to the database.

The following is the code that lets you save to the database:

    Private Sub btnSave_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSave.Click

        Try

            oCtxt.SubmitChanges(AddressOf OnSubmitCompleted, Nothing)

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

    End Sub

 

    Private Sub OnSubmitCompleted(ByVal so As SubmitOperation)

        If (so.HasError) Then

            MessageBox.Show(String.Format("Save Failed: {0}", so.Error.Message))

            so.MarkErrorAsHandled()

        Else

            Me.txtEmpno.ClearValue(TextBox.TextProperty)

            Me.lytEmpForm.DataContext = Nothing

        End If

    End Sub

Imagine that I am adding a new employee with an already-existing empno (Primary key validation). The error is displayed as follows:

The above code would save the current changes to the content to the database, but not the other way around.  That is, the content will not reflect the changes made at the database level (while the user is locally manipulating the Silverlight application).

The following is the code required to save and refresh the contents of “Context” objects based on database changes (which are unknown to the Silverlight application):

Private Sub btnSaveAndRefresh_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnSaveAndRefresh.Click

        Try

            oCtxt.SubmitChanges(AddressOf RefreshAfterSubmitCompleted, Nothing)

        Catch ex As Exception

            MessageBox.Show(ex.Message)

        End Try

 

    End Sub

 

    Private Sub RefreshAfterSubmitCompleted(ByVal so As SubmitOperation)

        If (so.HasError) Then

            MessageBox.Show(String.Format("Save Failed: {0}", so.Error.Message))

            so.MarkErrorAsHandled()

        Else

            Me.txtEmpno.ClearValue(TextBox.TextProperty)

            Me.lytEmpForm.DataContext = Nothing

            oCtxt.Load(oCtxt.GetEmpsQuery(),

                       LoadBehavior.RefreshCurrent,

                       AddressOf EmployeeRefreshCallback,

                       Nothing)

        End If

    End Sub

 

    Private Sub EmployeeRefreshCallback(ByVal lo As LoadOperation(Of BusinessLib.Web.emp))

        Dim results = oCtxt.emps.Where(Function(o) Not lo.Entities.Contains(o)).ToList

        For Each p In results

            oCtxt.emps.Detach(p)

        Next

    End Sub

The above logic is taken from the great explanation provided at http://weblogs.asp.net/fredriknormen/archive/2009/11/24/refresh-the-cached-entityset-after-a-submitchanges-wcf-ria-services.aspx

Can We Track and List All Changes Made to the EntitySet?

We can always track/list all of the modifications made to the EntitySet. The following is the code:

    Private Sub btnViewChanges_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnViewChanges.Click

        If oCtxt.HasChanges Then

            MessageBox.Show(oCtxt.EntityContainer.GetChanges().ToString())

        Else

            MessageBox.Show("No changes occurred")

        End If

    End Sub

In the above code, I am calling the “GetChanges()” method available in the “EntityContainer” of the “oCtxt” object to list all of the modifications I made to the entire context.

After modifying one entity and removing another, the output from the above code would look like the following:

We can also reject all changes made to EntitySet as shown below:

    Private Sub btnReject_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnReject.Click

        If oCtxt.HasChanges Then

            oCtxt.RejectChanges()

            MessageBox.Show("Cancelled/Rejected all changes")

        Else

            MessageBox.Show("No changes to reject")

        End If

 

    End Sub

Make sure that “RejectChanges” of “oCtxt” object will cancel all modifications (throughout all entity sets) available locally and will not touch any at the server level.

After a successful cancellation of all changes, the output would look like this:

I hope you enjoyed the article and any suggestions, bugs, errors, enhancements etc. are highly appreciated at http://jagchat.spaces.live.com

blog comments powered by Disqus
SILVERLIGHT ARTICLES

- With Silverlight Gone, Whither SharePoint?
- Silverlight in the News
- Silverlight Has a Bright Future
- Windows 8 Effects on .Net and Silverlight De...
- Microsoft`s SkyDrive Abandons Silverlight
- Silverlight Developers Unhappy with Windows ...
- Best Silverlight Examples
- How to install Silverlight for Windows Phone
- Microsoft Reveals Silverlight 5 Features
- Silverlight News: SRS and Microsoft to Bring...
- Silverlight 4.0: Paging Through Data using D...
- Silverlight 4.0: Navigating Data Using Domai...
- Silverlight 4.0: Filtering Data Using Domain...
- Silverlight 4.0: Sorting and Grouping Data w...
- Silverlight 4.0: Query Parameters of DomainD...

ASP Web Hosting ASP.Net Web Hosting Windows Web Hosting
 
 
 

ASP Free Forums 
 RSS  Tutorials RSS
 RSS  Forums RSS
 RSS  All Feeds
Site Map 
Request Media Kit
Write For Us Get Paid 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Privacy Policy 
Support 


© 2003-2012 by Developer Shed. All rights reserved. DS Cluster 1 - Follow our Sitemap
Most Popular Topics
All ASP.Net Tutorials