Home > Articles > Web Development > ASP.NET

Silverlight Best Practices: Data-Centric Applications

In the next installment of his series covering best practices for Silverlight in the enterprise, Microsoft Silverlight MVPJeremy Likness covers data-centric applications. He shows you various approaches to packaging, transporting, and synchronizing data between the client and the server in line-of-business applications.
Like this article? We recommend

Almost all applications are data-driven. Data is produced by various sources and consumed by applications that translate the data into meaningful information. Silverlight is a client technology, and data is often produced at the server, so it must be transported to the Silverlight client. Unlike content-driven applications that focus on documents and process-driven applications that are based on workflows and algorithms, data-centric applications are built around the underlying data and expose common operations known as the CRUD operations (Create, Read, Update, and Delete).

There are three primary concerns to address within a data-centric application built with Silverlight. The first is the serialization strategy, or how the data is packaged for transport between the client and server. The second concern is the transport itself and how the server and client keep the data synchronized. The final concern is the presentation of the data to allow user interaction, whether through visualization of the data or the ability to edit the data with validations.

Serialization Strategies

Data can pass through many forms in the course of traveling from a backend system to the end user. On the server, data might be represented by a dictionary of names and values. It may also be encapsulated in a class and combined with behaviors. When data is sent from the server to the client, it must be translated into a format that can be transmitted over the network and consistently reassembled on the client-side. The easiest way to demonstrate this is to build a simple class that contains some data and a simple behavior (combining the first and last names to provide a full name):

public class Contact
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string FullName
    {
        get
        {
            return string.Format("{0} {1}",
                                    FirstName,
                                    LastName).Trim();
        }
    }
}

If you add a default Silverlight-enabled Windows Communication Foundation (WCF) web service that returns a contact and invoke the service from Silverlight, the actual data sent over the network looks like this:

<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <GetContactResponse xmlns="http://www.jeremylikness.com/examples/">
         <GetContactResult 
xmlns:a="http://schemas.datacontract.org/2004/07/DataCentricApplications.Model"  
xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
            <a:FirstName>Jeremy</a:FirstName>

            <a:Id>1</a:Id>
            <a:LastName>Likness</a:LastName>
      </GetContactResult>
   </GetContactResponse>
   </s:Body>

</s:Envelope>

This is what is referred to as SOAP, or Simple Object Access Protocol. If you’ve had to work with complicated SOAP interfaces, you know there is nothing simple about SOAP. While the underlying technology is XML, it takes some work to get to the actual information. Also notice that the behavior for the full name is not transmitted; the client must either reconstruct this, or share a common project with the server so the type that the response is mapped to can retain the desired behavior. Fortunately, Silverlight supports SOAP out of the box, and can easily connect to a SOAP service and create the appropriate proxy to interact with the interface.

A more simplified version of the API might be implemented with a handler that serializes the object directly. A handler that uses the XmlSerializer will generate the following:

<Contact xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">
   <Id>1</Id>

   <FirstName>Jeremy</FirstName>
   <LastName>Likness</LastName>
</Contact>

As you can see, the format is far more compact. This is referred to as POX for Plain Old XML. There is another format popular on the web called JSON, for JavaScript Object Notation. This format is more readable and compact than XML. It is also generated in a format that makes it easy for JavaScript to create an object from the representation (it can be directly evaluated). Silverlight can use the System.Json assembly to de-serialize JSON instances. The same contact record in JSON looks like this:

{"Id":1,"FirstName":"Jeremy","LastName":"Likness",
"FullName":"Jeremy Likness"}

The most compact way to serialize data is through binary serialization. While .NET contains a BinaryFormatter class for automatically serializing objects, Silverlight does not have the corresponding type. It is necessary to manually serialize the objects using a binary writer that produces a byte array, then reverse the process by using a binary reader on the Silverlight end. You can also use a third-party solution for packaging the content.

When you consume a third-party API, chances are you are not in control of the serialization strategy and must use one compatible with the existing API. On the other hand, if you are building your own API, there are several factors to consider:

  • How large is the data? Larger data sets can expand exponentially when they must be serialized to XML. The binary approach is preferred in this case.
  • How critical is preserving bandwidth? If you are writing an API that will be invoked by a smartphone, you’ll want to minimize the amount of cellular bandwidth that the messages consume-again, consider something like binary over JSON and XML.
  • How important is it to adhere to open standards? If you want the API to be accessible by as many clients as possible, it makes sense to use a standard like SOAP, POX, or JSON to format the data, as there are many clients that recognize data in that format.

Often choosing the right strategy is a balance. For example, you may decide to use JSON because it is more compact than XML but provides a more open standard than binary.

Transport Strategies

Serializing the type is only part of the strategy. The type must be transported. All of the above examples use the Hypertext Transfer Protocol (HTTP) to transfer the payloads. There are more complex protocols layered on top of HTTP such as SOAP. If you wanted to secure the transfer, you could use HTTPS to provide a secured sockets layer (SSL) over the HTTP channel. Representational State Transfer, or REST, is a simple protocol for sharing data that can also be used in conjunction with HTTP. Unlike SOAP, which is considered a remote procedure call (RPC) protocol, REST is a resource-based protocol. The API is based on well-defined locations that contain resources, rather than procedure calls with method signatures.

For high-performance applications that move a lot of real-time data, you may want to go to a lower level than the HTTP protocol and communicate directly over sockets. Sockets are accessible through the System.Net.Sockets namespace. Sockets provide real-time duplex communication using either TCP (Transmission Control Protocol) or UDP (Universal Datagram Protocol). Like other communication methods in Silverlight, socket communication is asynchronous. The lifecycle of a socket starts with a connection, continues through a series of asynchronous send and receive operations, and concludes when the socket is shut down. For more information on programming with sockets in Silverlight, read the MSDN reference Working with Sockets.

There are other services that are layered on top of existing protocols to facilitate ease of communication between the client and the server. A popular standard for exposing data on networks is called the Open Data Protocol (OData). The protocol provides a standard for exposing data as resources on the web using an HTTP-based REST interface. Visual Studio provides an item called WCF Data Services for exposing existing data models using OData. You can read a walkthrough of this in the MSDN reference How to: Create the Northwind Data Service.

The service that is exposed can be consumed as a service reference in the Silverlight client. The client will query the service and generate the necessary classes and operations to parse, query, and update the service. It is even possible to manipulate binary data as a stream. To learn more about using Silverlight to consume OData, read the MSDN reference WCF Data Services Client Library for Silverlight.

Another popular way to share data in Silverlight is by using WCF RIA Services. WCF RIA is significant because it allows rapid development across common backend data systems and integrates directly with Entity Framework. WCF RIA allows you to use data annotations to set validations and uses a technique called projection to share code between the client and the server. Your code on the client is written as if the data connection were local, and WCF RIA handles the underlying tasks of wiring up web services and marshaling calls between the client and the server.

Visualization Strategies

Silverlight provides a number of controls out of the box to help interact with data. These controls can automatically recognize data types, generate columns and rows, and even provide CRUD functionality out of the box. They are capable of working with data annotations to provide extended descriptions as well as performing validations. Using these controls in data-centric applications can significantly accelerate the development lifecycle.

DataGrid

The DataGrid control provides a grid-style view of data. The items source of the control can be bound to any class that implements IEnumerable, such as lists and observable collections. For the grid to recognize inserts and updates, the collection should implement the ICollectionChanged interface, and individual elements should implement INotifyPropertyChanged. The column generation recognizes data annotations so user-friendly names can be displayed in the header using the DisplayAttribute. If the source data implements ICollectionView, the grid will also provide grouping, sorting, and filtering.

The grid will support paging if the source collection implements IPagedCollectionView. An easy way to add paging is to use the PagedCollectionView to wrap the source data. You can then set that as the source for the grid and add a DataPager control to display the paging controls. The pager control supports several different styles of paging. Refer to the MSDN Documentation to see what the different options look like. All options can be further styled using the parts and templates system.

The most significant functionality of the data grid is that it will allow inline editing of records within the grid if the underlying objects implement IEditableObject. This is automatically implemented when you use WCF RIA. The edits support full validation using any data annotations set for the properties on the target object.

DataForm

The data form is similar to the data grid, but it works with a single record at a time. It allows you to bind to a collection of items and will provide the controls for navigating between items to edit one at a time. It supports all CRUD modes, and like the data grid will use data annotations to display labels for fields. It will also recognize the DescriptionAttribute and provide an icon with a tooltip to provide the user with additional information about the item. The data form is advanced enough to recognize underlying data types and expose Boolean values as checkboxes, provide calendar pickers for date fields, and provide a combo-box when a data relationship exists.

The data form can be used in conjunction with the data grid. It is a common pattern to use the data grid to display the list of items and expand the row to a detail view when the user selects it. The expanded selection then uses the data form to provide a detailed surface for editing the data.

ValidationSummary

The validation summary object works with the Silverlight validation system to provide a summary of validation issues detected on the page. The data form integrates the validation summary by default, but it can be added to your own custom pages as well. By default it provides a stacked list of validation details for items that failed validation on the current form, but it can be completely styled to fit your custom look and feel.

Summary

The ability of Silverlight to interface with multiple protocols and methods for serializing data makes it ideal for building line-of-business applications that interact with both internal and external web-based services. The addition of features like WCF RIA makes it a viable platform for rapid development of data-centric applications. Using a combination of WCF RIA and the DataGrid and DataForm controls, it is possible to build a fully functional CRUD application that supports full editing and validation in well under an hour. For customized applications and workflows, you can easily connect to legacy systems and services to marshal data between the client and the server.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020