Wednesday, May 20, 2009

Consuming Web Services in Silverlight 2.0.

In this lab, we will try to Consume Web Service in Silverlight application. But, I don’t want to do a lab for “Hello World” kind of Web Service. So, let’s create something good.

First, let’s write a Web Service which will insert a record in the database. For this demonstration I will be using a database called “Customers” which is already there with my SQL Express named instance installed on my machine.


This database contains a table called CustomerInformation with following attributes-


















CustomerIDVARCHAR(5)
CustomerNameVARCHAR(20)
AddressVARCHAR(30)
ContactNoINT
CityVARCHAR(20)

So, Let’s start writing web service.


1) Open Visual Studio 2008 and create a new Web site and make a choice of ASP.NET Web Service Template from template window. Make a language choice as per your convenience. I am using C#. Make sure that you will be creating a web service at http://localhost location as shown bellow-


CreateWebService


2)  Once you have successfully created the Web Service, Add a new item into Web Service project called “Web Service” by the Name “CustomerInformation.asmx”.


3) In the code file of CustomerInformation service add following “Web Method”.


Note –: Make sure you will be changing the Connection String and table name as per your implementation!!



[WebMethod]
public string InsertCustomerInformation(string CustomerID,string CustomerName,
string Address,int ContactNo,string City)
{
try
{
SqlConnection CN=new
SqlConnection(@"Server=.\SQLExpress;Database=Customers;UID=sa;Pwd=P@ssw0rd");
SqlCommand CMD=new SqlCommand();
CN.Open();
CMD.Connection=CN;
CMD.CommandText=
"Insert into CustomerInformation values('" + CustomerID + "','" +
CustomerName + "','" + Address + "'," + ContactNo + ",'" + City + "')";
CMD.ExecuteNonQuery();
return "Customer Information stored successfully !!";
}
catch (Exception ex)
{
return "Exception :-" + ex.Message;
}

}

4) Once you have finished writing Web Method, Hit F5 and test your service. Now as we are done with Writing Web Service, Let’s start designing the entry screen by Silverlight application.

5) So, let’s create Silverlight project with the name CustomerSLApplication and design the screen as shown bellow-


CustomerEntry


6) You can see the code for the Customer Entry screen bellow-


<UserControl x:Class="CustomerSLApplication.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Width="400" Height="350">
<Grid x:Name="LayoutRoot" Background="Black">
<StackPanel Orientation="Vertical">
<StackPanel Orientation="Horizontal">
<TextBlock Text="CustomerID" Margin="10" Foreground="White"/>
<TextBox x:Name="CustID" Margin="38,10,0,10" Width="200"/>
</StackPanel>
<StackPanel
Orientation="Horizontal">
<TextBlock Text="Customer Name" Margin="10" Foreground="White"/>
<TextBox x:Name="CustName" Margin="13,10,0,10" Width="200"/>
</StackPanel>
<StackPanel
Orientation="Horizontal">
<TextBlock Text="Address" Margin="10" Foreground="White"/>
<TextBox x:Name="CustAddress" Margin="57,10,0,10" Width="200"/>
</StackPanel>
<StackPanel
Orientation="Horizontal">
<TextBlock Text="Contact No." Margin="10" Foreground="White"/>
<TextBox x:Name="CustContNo" Margin="35,10,0,10" Width="200"/>
</StackPanel>
<StackPanel
Orientation="Horizontal">
<TextBlock Text="City" Margin="10" Foreground="White"/>
<TextBox x:Name="CustCity" Margin="77,10,0,10" Width="200"/>
</StackPanel>
<StackPanel
Orientation="Horizontal">
<Button
Content="Clear" Width="100" x:Name="btnClear" Click="btnClear_Click" Margin="20" Foreground="Purple"/>
<Button Content="Insert Data" Margin="20" x:Name="btnInsert" Click="btnInsert_Click" Width="150" Foreground="Purple"/>
</StackPanel>
<StackPanel
Orientation="Horizontal">
<TextBlock x:Name="Notification" Margin="20" Foreground="White" Text="Notification"/>
</StackPanel>
</StackPanel>
</Grid>
</UserControl>


7) Now as we have finished designing screen, let’s write the code to utilize the Web Service which we have created to insert the Customer Information into our Customers Database-But before that you will have to add Customer Service Web reference into Silverlight application as shown bellow by the name CustomerInformationProxy.


AddServiceRef


8) So, to use this proxy let’s write code in Page.xaml.cs file on “Insert” button click event.


Imp. Note-: Silverlight application always works at client side. Whenever it needs to access any resources from Server, it will allow you to call those resources by making a Asynchronous call to the server.

CustomerInformationProxy.CustomerInformationSoapClient proxy = new CustomerSLApplication.CustomerInformationProxy.CustomerInformationSoapClient();

private void btnInsert_Click(object sender, RoutedEventArgs e)
{
proxy.InsertCustomerInformationCompleted += new EventHandler<CustomerSLApplication.CustomerInformationProxy.InsertCustomerInformationCompletedEventArgs>(proxy_InsertCustomerInformationCompleted);
proxy.InsertCustomerInformationAsync(CustID.Text, CustName.Text, CustAddress.Text, int.Parse(CustContNo.Text), CustCity.Text);

}

void proxy_InsertCustomerInformationCompleted(object sender, CustomerSLApplication.CustomerInformationProxy.InsertCustomerInformationCompletedEventArgs e)
{
Notification.Text = e.Result;
}
9) Hit F5, Make a entry of new Customer and see the Result-
You got Exception ????
PolicyException




10) Silverlight application will never allow any resources which you are trying to access through Cross Domain. Once Silverlight detects that the request is made for Cross Domain Service, It will look for the policy file. There are two different ways of writing the policy file as shown bellow-



i) Silverlight Cross domain Policy file called clientaccesspolicy.xml.


Or


ii) Adobe Cross domain Policy file called crossdomain.xml file.


Copy any one of the file at a domain root level of Web Service.


11) However, Always try to Keep you Web contents separate than your Services domain due to security reasons. And I guess that’s how you might be working !!


12) clientaccesspolicy.xml file code-

<?xml version="1.0" encoding="utf-8"?>
<access-policy>
<cross-domain-access>
<policy >
<allow-from http-request-headers="*">
<domain uri="*"/>
</allow-from>
<grant-to>
<resource path="/" include-subpaths="true"/>
</grant-to>
</policy>
</cross-domain-access>
</access-policy>

13) crossdomain.xml file code-

<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM
"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<allow-access-from domain="*" headers="*"
secure="true">
</cross-domain-policy>
14) Create anyone of the .xml by the same name given above and copy it to the root directory of Web site as follows-
CopyClientAccessPolicyfile






15) Now Hit F5, and see the output once again !!


OutputofWS


17) Now try out the same steps for crossdomain.xml file and See your application working !!


18) For “Clear” button click event write following code-

private void btnClear_Click(object sender, RoutedEventArgs e)
{
CustID.Text = "";
CustName.Text = "";
CustAddress.Text = "";
CustContNo.Text = "";
CustCity.Text = "";
CustID.Focus();
}






19) That’s all !! you are done with the assignment !!


Now as you have completed writing the ninth Silverlight Lab, let’s have a closer look on tenth lab “Consuming WCF Services in Silverlight 2.0.

No comments:

Post a Comment