Introducing DotNetFunda.com on mobile http://m.dotnetfunda.com ! Be with DotNetFunda.com on the go !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 602 |  Welcome, Guest!   Register  Login
Home > Articles > Silverlight > How to create and consume Web Service in Silverlight?

How to create and consume Web Service in Silverlight?

Article posted by SheoNarayan on 1/3/2012 | Views: 2099 | Category: Silverlight | Level: Beginner | Points: 250 red flag


In this article, we are going to learn about how to work with Services in Silverlight.

Working with Services in Silverlight

As we know that Silverlight doesn’t support working directly with ADO.NET, it means you can’t use ADO.NET code like SqlConnection, SqlCommand or SqlDataAdapter to connect to the database and fetch records or manipulate records. So the only option left is to interact with the services (either web or wcf).

NOTE: In case you are creating services in different project than the Silverlight hosting project, you need to specify the client access policy (in the client/consumer project) and cross domain policy (in the server project).

This article is the continuation of my last article in Silverlight controls series, read last article here.

Get 500+ ASP.NET web development Tips & Tricks and ASP.NET Online training here.

Client access policy - clientaccesspolicy.xml

<?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>

Cross domain policy - crossdomain.xml

<?xml version="1.0"?>

<! DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">

<cross-domain-policy>

<allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>

<!--<allow-http-request-headers-from domain="*" headers="*" secure="true" />-->

</cross-domain-policy>

 

How to create and consume Web Service in Silverlight?

In order to create a web service, right click the project and click on Add New Item … (this project can be the Silverlight hosting project or a separate project altogether). In this demonstration, I am creating my web service in a separate project so we will have to deal with cross domain issue (explained later in this demo).

Look at the picture below to see how to create a Web Service.

Copy-paste following code in the Web Service (assuming your web service name is DemoServices.asmx).

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Services;

using System.Data;

using System.Data.SqlClient;

namespace SilverlightWcfService

{

/// <summary>

/// Summary description for DemoServices

/// </summary>

[WebService(Namespace = "http://tempuri.org/")]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.ComponentModel.ToolboxItem(false)]

// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.

// [System.Web.Script.Services.ScriptService]

public class DemoServices : System.Web.Services.WebService

{

string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString;

[WebMethod]

public string HelloWorld()

{

return "Hello World";

}

[WebMethod]

public List<Person> GetRecords()

{

List<Person> list = new List<Person>();

using (SqlConnection conn = new SqlConnection(ConnStr))

{

using (SqlCommand cmd = new SqlCommand("Select * FROM PersonalDetail", conn))

{

conn.Open();

using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))

{

while (reader.Read())

{

list.Add(new Person()

{

FirstName = reader.GetString(reader.GetOrdinal("FirstName")),

LastName = reader.GetString(reader.GetOrdinal("LastName")),

Age = reader.GetInt32(reader.GetOrdinal("Age")),

Active = reader.GetBoolean(reader.GetOrdinal("Active"))

});

}

}

}

}

return list;

}

}

}

 

In the above code we are using ADO.NET code to fetch the data from the database and forming a generic collection.

As in this case we are going to return the Generic list collection of Person class so here is the Person class. Note that in order to make this class transferable via Web Services, we will need to set its attribute as Serializable.

[Serializable]

public class Person

{

public string FirstName { get; set; }

public string LastName { get; set; }

public int Age { get; set; }

public bool Active { get; set; }

} 

Browse this service and copy the url.

Now right click the Silverlight application project and click on Add Service Reference …

Enter the url of the service in the Address TextBox and click on Go. You should see your web service in the Services box and methods in Operations box. Enter proper Namespace (in my case DemoServiceReference) and click OK.

You will see a Service Reference folder as well as ServiceReferences.ClientConfig file added into the Silverlight project.

<configuration>

<system.serviceModel>

<bindings>

<basicHttpBinding>

<binding name="DemoServicesSoap" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">

<security mode="None" />

</binding>

</basicHttpBinding>

</bindings>

<client>

<endpoint address="http://localhost:10042/DemoServices.asmx"

binding="basicHttpBinding" bindingConfiguration="DemoServicesSoap"

contract="DemoServiceReference.DemoServicesSoap" name="DemoServicesSoap" />

</client>

</system.serviceModel>

</configuration>

 

Now create a new Silverlight page and paste following code

<StackPanel>

<Button Content="Get Data from Service" Click="Button_Click" />

<sdk:DataGrid x:Name="DataGrid1" />

<TextBlock x:Name="TextBlock1"/>

</StackPanel>

 

In the code behind use the web service namespace (In my case SilverlightDemo.DemoServiceReference ) and write following code.

private void Button_Click(object sender, RoutedEventArgs e)

{

DemoServicesSoapClient client = new DemoServicesSoapClient();

client.GetRecordsCompleted += new EventHandler<GetRecordsCompletedEventArgs>(client_GetRecordsCompleted);

client.GetRecordsAsync();

}

void client_GetRecordsCompleted(object sender, GetRecordsCompletedEventArgs e)

{

if (e.Error != null)

{

TextBlock1.Text = "Sorry, an error occured. " + e.Error.Message;

}

else

{

DataGrid1.ItemsSource = e.Result;

}

}

In the above code snippet we have instantiated the DemoServiceSoalClient object and attached a method to the web service method event (Our method is GetRecords so its completed event name will be GetRecordsCompleted) and called Async method (in our case GetRecordsAsync method).

In the client_GetRecordsCompleted method that is attached with completed event we are checking for error and if not setting the ItemsSource of the DataGrid to the result of the Web service method.

Output

Hope this article was useful. Thanks for reading and hoping that you liked it.

Keep an eye on forth coming articles on Silverlight. To read my series of articles,click here.

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About Sheo Narayan

Experience:8 year(s)
Home page:http://www.snarayan.com
Member since:Tuesday, July 08, 2008
Level:HonoraryPlatinum
Status: [Microsoft_MVP] [Administrator]
Biography:Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001.

Connect me on Facebook | Twitter | LinkedIn | Blog

 Responses
Posted by: MBA Updates | Posted on: 11 Jan 2012 12:55:32 AM | Points: 25

I have a silverlight application that uses a silverlight enabled WCF service. all in one solution. It works with no problem on the visual studio development server (localhost with a random port number).

If I deploy the entire website (App and WCF) to IIS, the Silverlight app works correctly, but it can't access/use the WCF service properly and an error occurs. I haven't been able to figure out what's wrong with it.


http://www.mbaupdates.com/index.aspx


>> Write Response - Respond to this post and get points
Related Posts

In this article we will look how we can do database operations using SilverLight. We will first try to understand why we cannot call ADO.NET directly from a silverlight application and then we will browse through 7 steps which we need to follow to do database operation from silverlight.

Microsoft released Windows 7 last year which has lots of functionalities including a nice UI. Among those features one of the most user friendly feature is Pin/Unpin application to Taskbar. You can develop WPF or Windows Forms applications in which you can implement this feature. But do you know that this is also possible in Silverlight? Yes, Silverlight 4 has the power to talk with any other application using the COM API. In this Article, I will demonstrate you the Power of Silverlight to talk with the Windows 7 Taskbar API's. Please read the complete article and leave your Feedbacks. Don't forget to vote for it.

This article will talk about 4 simple steps which will assist you to consume WCF service in a Silverlight application. It also had a simple sample source code which demonstrates all the 4 steps practically.

Pinging a network IP or Hostname is not available in Silverlight. But you can do this using WCF service. In this post I am going to implement the same thing for you. I am using Silverlight 4 here. But this can also be possible in Silverlight 3.

In this article, we are going to explore the Silverlight controls like TextBox,PasswordBox, RichTextBox and their related properties.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you found plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/27/2012 7:39:44 PM