Blue Theme Orange Theme Green Theme Red Theme
 
MindFusion's Components
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » .NET 3.0/3.5 » Silverlight 2 Web Service Part I - The Beginning

Silverlight 2 Web Service Part I - The Beginning

This tutorial is meant to shed some light upon how you can build you own Web Service using a WCF Service class. This is the first turtorial in a series of tutorials on how to access remote data with a Web Service. In this tutorial we start by simply returning a string from a Web Service method and displaying the value in the silverlight page, using a TextBlock, when the user clicks on a button. We also look at how you can dynamically use the current port alotted by Visual Studio in Debug mode without having to change he endpoint data in the configuration file.

Total page views :  3062
Total downloads :  113
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WebService Part I.zip
 
Become a Sponsor


We are now going to have a look at how you can build and call a Web Service. We will display the returned data in a TextBlock when the user clicks a button. We will use a Silverlight-enabled WCF Service as the Web Service.

WebS1.gif 
The Silverlight application before the user clicks the button

WebS2.gif

The Silverlight application after the user has clicked the button

Creating the Silverlight application

Let's start by creating a new Silverlight application that will host our control.

  1. Open Visual Studio 8 and create a new Silverlight project called WebService.
  2. Make sure that the Add a new ASP.NET Web project to the solution to host Silverlight option is selected. Make sure the Project Type dropdown is set to ASP.NET Web Application Project, then click OK.

Two projects will be added to the solution. The WebService project is the Silverlight application project and the WebService.Web project is the ASP.NET application hosting the Silverlight application. The WebService.Web project contains one .aspx and one .html page, which one you choose to use as the container is up to you; in this example however we will use the WebServiceTestPage.aspx page, so make sure it is set as the start page.

The page.axml page is the main page in the Silverlight application, and it should contain the basic framework for hosting Silverlight controls. We will later use this page to test our Web Service.

Adding the WCF Service to the Silverlight application.

The first step in creating a Web Service is to add the Silverlight-enabled WCF Service to the WebService.Web project.

  1. Right click on the WebService.Web project name and select Add-New Item.
  2. Select Silverlight-enabled WCF Service in the Add-New Item dialog box.
  3. Name the Web Service wsData in the Name field and click Add.

    This will add the required references and the two Web Service files; wsData.svc and wsData.svc.cs.
    wsData.svc doesn't contain any code; it contains one line of mark-up code that tells ASP.NET where to find the code behind file for the Web Service.

    wsData.svc.cs is the code behind file for the Web Service; here you write the logic.

WebS3.gif

Adding a test method to the Web Service

We are now going to add a method that we can call from the client. Start by opening the wsData.svc.cs file. Notice the two attributes on the wsData class. The ServiceContract attribute states that you intend to add methods to the class that remote callers can call access as part of a service. The AspNetCompatibilityRequirements attribute indicate that the class will have access to ASP.NET platform features such as session state, file authorization and url authorization similar to an ASMX service.

Each Web Service method needs to be decorated with the OperationContract attribute when adding it to the WCF class.

Let's add a method called GetText that returns a string value to test the service. Start by deleting the default DoWork method.

[OperationContract]
public string GetText()
{
  return "The returned text.";
}

Build the solution by pressing Ctrl+B on the keyboard.

Testing the WCF Service

Let's try to call the GetText method from the Silverlight application. Open the Page.xaml page in the WebService project and add a button and a TextBlock control. When the user clicks the button the text returned from the Web Service method will be displayed in the TextBlock control. Add the following xaml code to the Page.xaml page.

<StackPanel>
  <Button Content="Call WebService" Width="120" Height="30"
     Margin="5" Click="Button_Click"></Button>
  <TextBlock Name="lblResult" HorizontalAlignment="Center"
     Margin="5">The result will be displayed here.</TextBlock>
</StackPanel>

Now let's add some logic to call the Web Service. Right click on the Button_Click event name in the Button tag and select Navigate to Event Handler, this takes us to the code behind page of the Page.xaml page and the corresponding event method.

In the Button_Click event we need to add code to call the method asynchronously, all Web Methods need to be called asynchronously.

Add a reference to the Web Service

The first thing we need to do is to add a reference to the Web Service.

  1. Right click on the References folder in the WebService project.
  2. Select Add Service Reference in the context menu.
  3. Click on the Discover button. This searches the solution for available services. Alternatively you can write the address to the service in the Address field.
  4. Select the wsData service in the list of services.
  5. Name the namespace DataService in the Namespace field.
  6. Click on the OK button to crate the necessary proxy classes for the Web Service.

A proxy to the service should appear under the Service References folder in the Solution Explorer. Click on the Show All Files button in the Solution Explorer to see all the files added to the proxy. There will also be a ServiceReferences.ClientConfig file added to the project root folder. This file configures the connection to the Web Service.

Writing the Web Service code

Now that we have a proxy to the Web Service we can begin to write the logic to handle the calls to the Web Service methods. The first thing we need to do is to add a couple of using statement to the Page.xaml.cs page. The following using statements are needed:

DataService: Makes it easier to access the Web Service classes.

System.Windows.Browser: To gain access to the HtmlPage class needed to get the current port.

System.ServiceModel: To gain access to the EndpointAddress and the BasicHttpBinding classes needed when creating the Web Service proxy object in code. We will override the settings in the ServiceReferences.ClientConfig file. We need to do that to prevent the Web Service from stop working when the port changes.

using WebService.DataService;
using System.Windows.Browser;
using System.ServiceModel;

Code in the Button_Click event

Next we will create an EndpointAddress object to define where the Web Service is located. We do this to ensure that we can call the service even if the port changes. You could change this endpoint address and base the URL on the current Silverlight page so that it will work wherever you deploy it.

private void Button_Click(object sender, RoutedEventArgs e)
{
  System.ServiceModel.EndpointAddress endpoint = new
    EndpointAddress("http://localhost:" +
    HtmlPage.Document.DocumentUri.Port + "/wsData.svc");
}

Next we need to create a proxy object that will handle the call to the service. On the proxy object we will create an event handler for the GetTextCompleted event that will fire when the call returns from the service method call. It is named after the GetText method we created earlier in the Web Service class.

The default time out is 60 seconds, which might be a tad long, so we will change that to 30 seconds using the OperationTimeout property of the proxy object.

All calls to Web Services need to be done asynchronously so we will call the GetTextAsync method on the proxy object. When calling a method asynchronously we need to have a callback method present, in our case it is the GetTextCompleted method.

private void Button_Click(object sender, RoutedEventArgs e)
{
  System.ServiceModel.EndpointAddress endpoint = new
     EndpointAddress("http://localhost:" +
     HtmlPage.Document.DocumentUri.Port + "/wsData.svc");
  wsDataClient proxy = new wsDataClient(new BasicHttpBinding(), endpoint);
  proxy.GetTextCompleted += new
     EventHandler<GetTextCompletedEventArgs>(proxy_GetTextCompleted);
  proxy.InnerChannel.OperationTimeout = TimeSpan.FromSeconds(30);
  proxy.GetTextAsync();
}

Callback method code

The last thing we need to do is to write the code in the callback method. Let's place the result in the TextBlock called lblResult we added to the Page.xaml page.

void proxy_GetTextCompleted(object sender, GetTextCompletedEventArgs e)
{
  try { lblResult.Text = e.Result.ToString(); }
  catch { lblResult.Text = "Error calling Web Service"; }
}

Press F5 on the keyboard to run the application and test the Web Service.


Login to add your contents and source code to this article
 About the author
 
Jonas Fagerberg
Jonas Work as a Developer consultant at KnowIT Stockholm AB in Stockholm, Sweden. He has 18 years experience working in IT and 10 years experience as a solution devloper. He has both worked as a developer and as a Microsoft Certified Trainer (MCT), and holds MCAD and MCSD certificates. HE has written two IT books and a number of course manuals.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WebService Part I.zip
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
thanks by ronan On June 20, 2009
great set of articles Jonas. thanks a million.
Reply | Email | Delete | Modify | 
Re: thanks by Jonas On June 22, 2009

Hi,
Glad you liked the articles, it's always nice to get feedback. If you have ideas for new articles let me know.

Have a fantastic day!
Jonas

Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.