DCSIMG
July 2008 - Posts - Ran Wahle's blog

Ran Wahle's blog

July 2008 - Posts

Sending complex typed data from web service to SilverLight client - Part II

Sending complex typed data from web service to SilverLight client - Part II

On my previous post I've explained the first steps of creating the service and methods on the server side, and the client
corresponding objects in the Silverlight project. Here I'll go further on the JavaScript mediator side.

After making the Web method for getting the employee, we have to call it from out JavaScript mediator,  convert the objects received from the server to the SilverLight corresponding ones, and serialize the objects for our SilverLight component.

Step 3 - Create the JavaScript mediator:

Here is the code for the service call (very simple one but nevertheless...)

function loadEmployees()
{
    Billing.GetAllEmployees(onGettingAllEmployeesSuccess, onError);   
}

Step 4 - Write the Databind Method on the SilverLight control code

In order to operate methods of your Silverlight control from 
JavaScript code, you have to decorate your control class with
ScriptableType attribute and your methodswhich you want to access
with ScriptableMember attribute
 [ScriptableType]
    public partial class Page
    {
.
.
.

//Method to access from JavaScript
 [ScriptableMember]
        public void BindListBox(string employeesString)
        {
            MemoryStream memStr = null;
           
            try
            {
               //Deserialize the data received from the JavaScript mediator
                var jSer = new DataContractJsonSerializer(typeof(Employee[]));
                memStr = new MemoryStream(Encoding.Unicode.GetBytes(employeesString));
                var employees = jSer.ReadObject(memStr) as Employee[];
                
               //Bind the deserialized object with a control (Listbox in that case) 
                Employee.ItemsSource = employees;
               
                Employee.Width = GetMaxWidth();
            }
            catch (Exception ex)
            {
               //This is for debuging, you can operate JavaScript methods of the page
              // as an HtmlPage public methods
                var message = ex.Message;
                HtmlPage.Window.Alert(message);
            }
            finally
            {
               //Close the memory stream to release resources
                if (memStr != null)
                {
                    memStr.Close();
                }
            }
        }
}
On my next and last post I'll go into the JavaScrip mediator
and sum everything up.

Sending complex typed data from web service to SilverLight client - Part I

Sending complex typed data from web service to SilverLight client - Part I

In this post I'll explain in how to send complex typed data between web service and SilverLight  client
code. In order to avoid security issues I'll use JavaScript as mediator between my server code and SilverLight
code.

 

First - Let's have a look at a solution contains web server side code with all layers (Presentation that will host
silverlight  control , BL, DAL, Structures)
and another SilverLight project

Solution screenshot

Now, leaving out all server-side lower layers and focusing on presentation layer
and SilverLight code, let's have a look at what we'll demonstrate:

1. Getting complex typed data from the server via JavaScript .
2. Sending some of the data to SilverLight control
3. Presenting data on Silverlight control (A simple ListBox for that matter).

Step 1 - Create a server web method to provide as with the data we need:

[WebMethod(EnableSession = true)]   
 public List<Employee> GetAllEmployees()    
{        
        var result = new List<Employee>();       
        //Adding some employees to the collection       
        result.Add(new Employee()
       {EmployeeNumber = 1,   FirstName = "Ran", LastName = "Wahle"});        
        result.Add(new Employee()    
       {EmployeeNumber = 2,  FirstName = "Anonymous", LastName = "Employee"        });                                           result.Add(new Employee() 
        {EmployeeNumber = 3 , FirstName = "Known", LastName = "Employee"});               
                
         return result;   
 } 



 

Step 2 - Create object similar to the one in the server site.
At this stage the word "Why" might come to mind followed by a question mark...
The reason for that is simple - we cannot make reference from SilverLight project to
a regular .Net one because SilverLight runs on compact framework and therefore can have referenced to SilverLight projects only.

However, You might of course use the service referenced object if you   connect to a service, here we don't do it to avoid security failures may caused by connection service
directly from the Silverlight object.

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

On the second part I'll explain how to serialize the objects through JSON.

kick it on DotNetKicks.com

Technorati Tags: ,

גם אני רוצה ללמוד

שלום לכם.

קוראים לי רן, ואני רוצה להיות תלמיד שלכם.

אני מבטיח (להשתדל) להיות חרוץ, להמציא לעצמי עבודות ולהציג אותן כאן
לחקור דברים חדשים, גם אם הם חדשים רק בשבילי, לשתף בחיי המקצועיים
.כמה שיותר ואם יהיה באפשרותי - גם לתרום קצת

 

SRL קצת על עצמי - אני מועסק כמפתח בחברת
."זאת לאחר תקופה ארוכה כאיש סיסטם ב"ממשל זמין"  ,  WEB בפיתוח
.מעבר לכך - אני נשוי, גר בתל אביב עם עבר ירושלמי וקיבוצניקי עשיר

.תגובות והערות בעברית, ערבית ואנגלית תתקבלנה בברכה - את השאר פשוט לא אבין

.רן