Congratulations to all the winners of April 2013, they have won INR 3400 cash and INR 20147 worth prizes !
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 10061 |  Welcome, Guest!   Register  Login
Home > Articles > Silverlight > How to create and consume WCF Service in Silverlight?

How to create and consume WCF Service in Silverlight?

Article posted by SheoNarayan on 1/6/2012 | Views: 6152 | 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 (being a sandbox technology) doesn’t support working directly with ADO.NET, it implies that 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 WCF Service in Silverlight?

To create a WCF Service, right click the project (In my case I am creating in a separate project) and select WCF Service, enter name and click Add.

This will add DemoDatabaseWCFService.svc, DemoDatabaseWCFService.svc.cs and IDemoDatabaseWCFService.cs file. Add a new method called GetRecords into the Interface with OperationContract attribute (this attribute expose this method as service). Now write the implementation of this method as shown below in the DemoDatabaseWCFService.svc.cs.

public List<PersonWCF> GetRecords()

{

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

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 PersonWCF()

{

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;

}

Build the project and View the DemoDatabaseWCFService.svc in browser.

Now add a Silverlight page in the Silverlight project and retain the code snippet as below.

<StackPanel>

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

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

<TextBlock x:Name="TextBlock1"/>

</StackPanel>

 

Add the reference of the WCF Service by right clicking the project and selecting “Add Service Reference…”

Give proper namespace and click OK.

Now write below code snippet in the Code behind of the Silverlight page.

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;

}

}

Before you do this, you need to add the namespace of the WCF Service namespace (in our case SilverlightDemo.DemoServiceReference)

Now run the Silverlight application.

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

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

In this post I teach you how can you add a computed property in WCF ria services

Silverlight is a Cross-Browser, Cross-Platform plug-in from Microsoft. It supports many features that cannot be done in a normal browser it helps Web Applications to give Rich User Experience using WPF and uses client GPUs to provide this. It also enhances the productivity with the support of .NET APIs, Visual Studio and Expression Blend.

In this article, we are going to learn how to interact with Audio and Video devices in Silverlight

Must be this article is very basic. But I have seen many silver light developers struggling to layout controls and objects in silver light. In section we will quickly walk through 3 different methods of layout for silverlight. In this article we will go through each of these layout implementation and do a simple sample for the same.

Recently I was interested to work with the Physics Helper for Silverlight. I saw couple of demos on net which uses the Physics library for Silverlight to create good animations with Friction logic. Yeah, friction. You can drop a ball on a surface which will bounce over that surface. I found it very interesting and thought to create a Simple Demo for it. Here I will demonstrate you creating a Sample Application using Expression Blend. You don’t have to write a Single line of Code using Visual Studio.

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 find 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/19/2013 6:16:34 AM