How to pass objects in Silverlight application initialization parameters

In my post How to supply startup parameters to Silverlight applications using InitParams I explained how you can supply some initialization parameters to a silverlight application using InitParams. I showed an example of supplying two parameters with some simple values. Well there are times when you wish to supply some bussiness object to your silverlight application to initialize it. Or you may need to provide more than one. In some cases your object may have some complete structure and may have embedded objects in it. Well, you still can provide all that information in InitPrams. You definitely would like some technique that makes it easier for you to set these parameter values in Silverlight control and then in silverlight application, it will be really cool if you could recreate the same business object.

You probably already are saying, if I could just serialize the object and then deserialize it, I am good to go. Exactly thats what you are going to be. Well now the question is how to serialize and in what format to serialize. Definitely it is not going to be binary formatting. So now what kind of text formatting you are going to do. You can think of XML serialization but that will incease the payload in InitParams string. This is where JSON serialization will come handy. And you do not need any third party libraries to work that magic. All the tools are provided in the Framework itself. Lets see how we are going to achieve it.

I will explain everything based on a real application that I am working on. This is a silverlight application that performs search against a search engine based on some input parameters. The input parameter for search is not a simple query text. The applicaion has the ability to accept a complex structure with lot of properties to control how search should be performed. It also takes another parameter where you can specify a URL on the cluster where search should be executed for load balancing.

Input Parameters Object

I have 2 .Net objects SearchParameters and SearchDataSurce that existing web application takes. Here is toned version of both objects.


[DataContract]
public class SearchDataSource
{
	[DataMember]
	public string ServiceUrl { get; set; }
	[DataMember]
	public int ServicePort { get; set; }
	[DataMember]
	public string ServiceHandler { get; set; }
	[DataMember]
	public string ServiceVersion { get; set; }
}

[DataContract]
public class SearchParameters
{
	[DataMember]
	public string QueryTerm { get; set; }
	[DataMember]
	public int MaxResults { get; set; }
	[DataMember]
	public int PageSize { get; set; }
	[DataMember]
	public bool ShowDiagnostics { get; set; }
}

You can see use of DataContract and DataMember attributes on class and auto-properties. Yes, these are same attributes that you define interface for your WCF objects. I have same objects in client web application as well as silverlight application.

Setup InitParams

Using DataMember and DataContract attributes on these classes sets them up for JSON serialization using DataContractJsonSerializer object. You can see it from following code snippet, how these two input objects are being serialized and then populated in InitParams of silverlight application.


protected void Page_Load(object sender, EventArgs e)
{
 if (!IsPostBack)
 {
  // Serialize search parameters.
  SearchParameters sp = GetSearchParameters();
  DataContractJsonSerializer spSer = 
   new DataContractJsonSerializer(typeof(SearchParameters));
  MemoryStream msSP = new MemoryStream();
  spSer.WriteObject(msSP, sp);
  string spJson = ConvertMemoryStreamToString(msSP);
  // Serialize search data source.
  SearchDataSource ds = GetDataSource();
  DataContractJsonSerializer dsSer = 
   new DataContractJsonSerializer(typeof(SearchDataSource));
  MemoryStream msDS = new MemoryStream();
  dsSer.WriteObject(msDS, ds);
  string dsJson = ConvertMemoryStreamToString(msDS);
  // Set the input in SL initparameters.
  string initParams = CreateInitParam("SearchParameters", spJson);
  initParams += ",";
  initParams += CreateInitParam("SearchDataSource", dsJson);
  Xaml1.InitParameters = initParams;
 }
}

Receiving input parameters in Silverlight application

When your silverlight application starts you will get these initializaton parameters in Application_Startup event of application. Now you can read InitParams from StartupEventArgs argument. Following code snippet how I read these parameters and deserialzed directly them into SearchParameters and SearchDataSource objects. These are the same objects that I used to serialze into JSON format.


private void ExtractInitPrams(StartupEventArgs e)
{
 string data = null;
 byte[] parmsBytes;
 MemoryStream ms = null;
 DataContractJsonSerializer ser = null;
 if (null != e.InitParams["SearchParameters"])
 {
	data = e.InitParams["SearchParameters"].Replace("%2c", ",");
	parmsBytes = Encoding.UTF8.GetBytes(data);
	ms = new MemoryStream();
	ms.Write(parmsBytes, 0, parmsBytes.Length);
	ser = new DataContractJsonSerializer
	 (typeof (SearchData.SearchParameters));
	_searchParams = ser.ReadObject(ms) as SearchParameters;
 }
 if (null != e.InitParams["SearchDataSource"])
 {
	data = e.InitParams["SearchDataSource"].Replace("%2c", ",");
	parmsBytes = Encoding.UTF8.GetBytes(data);
	ms = new MemoryStream();
	ms.Write(parmsBytes, 0, parmsBytes.Length);
	ser = new DataContractJsonSerializer
	 (typeof(SearchData.SearchDataSource));
	_searchDataSource = ser.ReadObject(ms) as SearchDataSource;
 }
}

You can see from this example how it is easy to pass in your existing .Net objects directly into your silverlight application through InitParams. In next article I will show you some more advanced features.

blog comments powered by Disqus