Page view counter

Silverlight Tips of the Day - Blog by Mike Snow

Game Programming with Silverlight

Silverlight Tip of the Day #42: How to Create a Web Service for your Silverlight App

Web services are essentially API’s that can be accessed over a network such as the Internet. Due to security Silverlight restricts a lot of important features such as saving to the disk. However, you can get around these restrictions by making calls to web services instead to accomplish these features.

This Tip of the Day will step you through how to create a web service in your web site and I will show you how to reference and make calls to API’s in that web service.

Step 1. Create a Silverlight Application Project using Visual Studio 2008. (See Tip of the Day #2 for details).

Step 2. Add a Web Service to your Web Site.

  • In your Solution Explorer, right click on your Web Site node, Choose Add-> New Item…
  • There are 3 templates that offer Web Service functionality:
    • Silverlight-enabled WCF Service.
    • WCF Service
    • Web Service.

Choose “Silverlight-enabled WCF Service” as it has specific support for Silverlight which we will explore in our next Tip of the Day.

  • Change the name to  something like “MyService.asmx” and click the “Add” button.

image

Step 3. Add a Service Reference

  • Rebuild your Solution (Ctrl+Shift+B). If you proceed to the next bullet point without rebuilding you will get the following dialog:

image

  • In your solution explorer, right click on your Silverlight Application node and choose “Add Service Reference…”.
  • This will bring up the “Add Service Reference” dialog. Click the “Discover” button to find your web service.
  • Change the Namespace to be whatever you want for this reference and click the “OK” button.

image

At this point you have your web service setup that is properly referenced from your Silverlight application.

Step 4. Making a call from your Silverlight application into your web service.

  • In your Solution Explorer, from your web site open up MyService1.svc. By default there is one method made available called DoWork(). This doesn’t do much yet so let’s add a new function called HelloWorld() that will return a string. Make certain to include the [OperationContract] attribute in order to make this function visible:
[OperationContract]
public string HelloWorld()
{
    // Add your operation implementation here
    return "Hello World";
}
  • In your Silverlight application project under your Service References, right click on ServiceReference1 and choose “Update Service Reference”.

image

  • Next, let’s make a call from our Silverlight app to this HelloWorld() method. The following code which goes in Page.xaml.cs shows you how to make an async call to HelloWorld().
public partial class Page : UserControl
{
    public Page()
    {
        InitializeComponent();
 
        ServiceReference1.MyService1Client client = new SilverlightApplication9.ServiceReference1.MyService1Client();
 
        client.HelloWorldCompleted += new EventHandler<SilverlightApplication9.ServiceReference1.HelloWorldCompletedEventArgs>(client_HelloWorldCompleted);
 
        client.HelloWorldAsync();
        
    }
 
    void client_HelloWorldCompleted(object sender, SilverlightApplication9.ServiceReference1.HelloWorldCompletedEventArgs e)
    {
        string message = e.Result;
    }
}

Note that all web services calls must be done asynchronously.

Thank you,
--Mike Snow

 Subscribe in a reader

Comments

Microsoft Weblogs said:

Web services are essentially API’s that can be accessed over a network such as the Internet. Due to security

# September 17, 2008 1:44 PM

2008 September 18 - Links for today « My (almost) Daily Links said:

Pingback from  2008 September 18 - Links for today &laquo; My (almost) Daily Links

# September 18, 2008 1:08 AM

Webservice f??r eine Silverlight Applikation erstellen at Blog von J??rgen Ebner said:

Pingback from  Webservice f??r eine Silverlight Applikation erstellen at Blog von J??rgen Ebner

# September 18, 2008 5:58 AM

Mirrored Blogs said:

Post: Approved at: Sep-18-2008 Silverlight Game: Diver While this Silverlight game can be entertaining

# September 18, 2008 8:04 AM

Silverlight news for September 18, 2008 said:

Pingback from  Silverlight news for September 18, 2008

# September 18, 2008 9:45 AM

Dew Drop – September 18, 2008 | Alvin Ashcraft's Morning Dew said:

Pingback from  Dew Drop &ndash; September 18, 2008 | Alvin Ashcraft's Morning Dew

# September 18, 2008 11:49 AM

Community Blogs said:

Joseph Ghassan on SL Full Screen, Adam Cooper on ListBox bug, Gerard Leblanc on image visual effects

# September 18, 2008 3:35 PM

Stephane GUNET said:

Shouldn't the HelloWorld function in step 4 have a string return type ?

# September 18, 2008 4:59 PM

mike.snow said:

Stephane - Yes, it should.. fixed :)

# September 18, 2008 6:50 PM

mike.snow said:

Stephane - Yes, it should.. fixed :)

# September 18, 2008 6:50 PM

Silverlight Tips of the Day - Blog by Mike Snow said:

In Tip of the Day #42 I talked about how to create and use a web service using WCF for your Silverlight

# September 22, 2008 2:39 PM

Visual Web Developer Team Blog said:

Silverlight Tip of the Day #46 Title: Font Support in Silverlight Silverlight Tip of the Day #45: Title:

# September 25, 2008 1:55 PM

Silverlight Tips of the Day - Blog by Mike Snow said:

In Tip of the Day #42 I discussed how to create Silverlight-enabled WCF web service. In this tip I will

# October 21, 2008 4:20 PM

Silverlight Tips of the Day - Blog by Mike Snow said:

The purpose of this post is to create an outline summary all the blogs from my Silverlight tips of the

# January 2, 2009 5:57 PM

Silverlight Tips of the Day - Blog by Mike Snow said:

The purpose of this post is to create an outline summary all the blogs from my Silverlight tips of the

# January 2, 2009 5:57 PM

o UAU nosso de cada dia said:

essa lista eu copiei desse blog bárbaro (acompanhe por RSS você também): uma lista de dicas super úteis

# January 3, 2009 6:26 AM

ScCrow said:

Hi Mike.  I have a question.

Ive created the Web service and it's working in the IDE just great.  But when I publish this to IIS, Im having problems.

So, here is what Ive done.

I created a project and created my WebService within that structure.  

Then, I build a User control in a 2nd project within the same solution.  Its an Ad Rotator user control and retrieves images from an Sql Database.  This will be used on the other projects in the solution.  Obviously, it uses the web service that Ive created to get the images.

The project has several pages, so I created these in separate projects in this solution. I navigate to pages on a button press.  The web service serves images to the Ad rotator, and  other things on other pages.

With this setup on IIS, the Ad Rotator is not retreiving images and my navigation doesnt work.  It all works in the IDE.

So, I thought you may have a suggeston.

Thanks  

ScCrow

# March 25, 2009 2:37 PM

mike.snow said:

What error do you get?

I am not certain but you may need the clientacccesspolicy file to be present:

<?xml version="1.0" encoding="utf-8" ?>

<access-policy>

 <cross-domain-access>

   <policy>

     <allow-from>

       <domain uri="*"/>

     </allow-from>

     <grant-to>

       <socket-resource port="4502-4534" protocol="tcp"/>

     </grant-to>

   </policy>

 </cross-domain-access>

</access-policy>

# March 25, 2009 3:36 PM

scvinod said:

Hi Mike,

      Thanks a lots for this article.I just did exactly what you have done here.But I'm not able to make a call to the HelloWorld() method after creating the client proxy.I'm not getting the intellisense for the HelloWorld method after the client proxy.Can you please let me know the solution.By the way both service and the client are in the same machine.Thank you.

# September 11, 2009 2:35 PM

mike.snow said:

Did you put the web service in your web site and not your SL app?

Also, when clicking "Discover" for Add Service Reference did it find the web service?

Make certain you are using the full namespace when declaring the HelloWord.

Thanks.

# September 11, 2009 2:44 PM

scvinod said:

Yes, I have very much done what you told but still I'm not getting the output.I have the screenshots over here.

i27.tinypic.com/10d5tvk.jpg  i27.tinypic.com/246ouiq.jpg

# September 14, 2009 12:56 AM

scvinod said:

Mike,

   I got the result now.The mistake I did was that i created a ASP.Net Web Application project instead of Web Site.

# September 14, 2009 2:22 AM

ecarson said:

I'm able to call the .HelloWorldAsync method, but the .HelloWorldCompleted method is not shown in the intellisense and an error ocurrs when calling it.

# October 30, 2009 12:41 AM

ecarson said:

Figure out the result (for VB). Use the AddHandler expression first then the .HelloWorldCompleted will show.

AddHandler client.HelloWorldCompleted, AddressOf client_HelloWorldCompleted

client.HelloWorldAsync

Private Sub client_HelloWorldCompleted(ByVal sender As Object, ByVal e As HelloWorldCompletedEventArgs)

'Do something here

End Sub

# October 30, 2009 1:08 AM

JoshGold said:

Hi Mike, thanks for the tip.  Definitely helped out this newbie Silverlight developer.  I'm struggling to grasp why it's async only though.  If I have something dependent on the data coming back, how can I get my data out of the completed function?  It's hard to work around when the completed function does not have a return type and you can't pass in additional arguments.

I'm hoping I'm just missing something.

thanks.

# November 17, 2009 10:36 AM

mike.snow said:

There is a event that is called when the call is complete. Wait until the event is fired before proceedding.

Example (check out the LoginCompleted event):

ServiceReferenceMyApp.ServiceWebClient client = new ServiceReferenceMyAPp.ServiceWebClient();

client.LoginAsync(UserEmail.Text, UserPassword.Password);

client.LoginCompleted += new EventHandler<ServiceReferenceMyApp.LoginCompletedEventArgs>(client_LoginCompleted);

void client_LoginCompleted(object sender, ServiceReferenceFlair.LoginCompletedEventArgs e)

{

...

}

           }

# November 17, 2009 11:23 AM

LetsBlogAbout.NET said:

Silverlight Tips of the Day Update 3

# October 15, 2010 11:01 AM

LetsBlogAbout.NET said:

Silverlight Tips of the Day

# October 15, 2010 11:08 AM

mrbr0nz said:

Where did MyService1Client come from I can see no reference to it other that it suddenly appearing.

Please explain this line :

SilverlightApplication9.ServiceReference1.MyService1Client();

what is SilverlightApplication9 and where is!

I'm Still confused how to make a simple call to what is supposed to be a simple service.

A better and in-depth explanation of the code would have gone a long way to resolve most of the question raised in the article

# February 26, 2011 8:43 AM

sameer17 said:

Hi Mike,I have a question

I have created web service for my silver light application as you told above and i am getting the result when i run application from VS2010.But when i add this silver light application as web part on share point site i am getting error 'Unhanded Error in Silver light Application An exception occurred during the operation, making the result invalid.'

so if you have any suggestion tell it to me

thanks in advance.

# May 11, 2012 5:48 AM