Tuesday, March 22, 2011

Silverlight - Web Service in Silverlight

In this article i will show you how to create a web service in Silverlight 4.

Step 1
Download Silverlight 4 tools from the following link

Download Silverlight 4 toolkit from the following link
http://silverlight.codeplex.com/

Note : Select only April 2010 Toolkit Silverlight 4


Step 2
Download northwind database from the following link.
http://www.microsoft.com/downloads/details.aspx?FamilyID=06616212-0356-46a0-8da2-eebc53a68034&displaylang=en

Step 3
Attach a northwind database into MS-SQL server.

Step 4
Create a Silverlight Application and give the solution name as WebServiceinSilverlight.




Click on image for better view

Note: Select Web Project Type as ASP.NET Web site.

Step 5
Select a ASP.net Web application(WebServiceinSilverlight.Web) and Add a Linq to Sql class,right click on solution then Add new Item,select LINQ to SQL classes from installed Visual Studio templates and name it NorthwindDC and click on add button,it is look like this



Click on image for better view

Step 6
Open a O/R Designer by double click on NorthwindDC.dbml,it is look like this















Click on image for better view




















Click on image for better view

Visual stdio provides an object-relational mapping designer,called the O/R Designer which allows you to visually design the object to database mapping.

Step 7
Create a employee object that will use LINQ to SQL to map to this table.go to the Server explorer,select northwind database,go to the tables and select Employees table,it is look like this


























Click on image for better view

Drag and drop Employee table from Server explorer onto the design surface of the O/R Designer,it is look like this


















Click on image for better view

Step 8
Select a ASP.net Web application(WebServiceinSilverlight.Web) and Add  a new asmx file for web service and name it as WSEmployee.asmx,it is look like this




















Click on image for better view
Step 9
In the below code snippet, write GetEmployeeData() method of a WSEmployee class to return Employee data from northwind database,it is look like this





using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

/// <summary>
/// Summary description for WSEmployee
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WSEmployee : System.Web.Services.WebService {

    public WSEmployee () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    /// <summary>
    /// Get Employee data from Northwind Database
    /// </summary>
    /// <returns>List</returns>
    [WebMethod]
    public List<Employee> GetEmployeeData()
    {
        try
        {
            // Create a Object of NorthwindDataContext
            NorthwindDCDataContext DC = new NorthwindDCDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString.Trim());

            // Create a Select Query
            var Query = from Q in DC.Employees
                        select new Employee
                        {
                            FirstName=Q.FirstName,
                            LastName=Q.LastName,
                            City=Q.City
                        };

         
            return Query.ToList<Employee>();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message);  
        }
    }
    
}

Step 10
Next step is add reference of web service in the Silverlight Application(WebServiceinSilverlight).Right click the Silverlight project and add a Service reference,it is look like this


























Click on image for better view

Step 11
Add a web service in the silverlight application.Add Service Reference dialog box will open and click on Discover button and give the namesapace name as SREmployee.























Click on image for better view

Now web service is ready,Lets design the Silverlight Page.

Step 12
Add a DataGrid and button on page,it is look like this
<Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid AutoGenerateColumns="False" Height="249" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dgEmployee" VerticalAlignment="Top" Width="376" ItemsSource="{Binding}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}" Width="Auto" />
                <sdk:DataGridTextColumn Header="LastName" Binding="{Binding LastName}" Width="Auto" />
                <sdk:DataGridTextColumn Header="City" Binding="{Binding City}" Width="Auto" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
        <Button Content="Data" Height="23" HorizontalAlignment="Left" Margin="313,270,0,0" Name="btnData" VerticalAlignment="Top" Width="75" Click="btnData_Click" />
    </Grid>






















In this DataGrid we bind the employee data on button click event.

Step 13
In Code Behind,On btnData click event call the service,it is look like this

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace WebServiceinSilverlight
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void btnData_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                // Call a Web Service
                SREmployee.WSEmployeeSoapClient WSProxy = new SREmployee.WSEmployeeSoapClient();

                // Wire up the Async DataCompleted  handler
                WSProxy.GetEmployeeDataCompleted += new EventHandler<SREmployee.GetEmployeeDataCompletedEventArgs>(WSProxy_GetEmployeeDataCompleted);

                // Call a WebService Method
                WSProxy.GetEmployeeDataAsync();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

        void WSProxy_GetEmployeeDataCompleted(object sender, SREmployee.GetEmployeeDataCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null)
                {
                    // Bind Employee Data in DataGrid
                    dgEmployee.DataContext = e.Result;
                    // The arguments provide us a e.Result object that represents the return type, in this case a List object.
                }

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);  
            }
        }

       
    }
}


Run the Project.

Output




















Full XAML Code

<UserControl x:Class="WebServiceinSilverlight.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

    <Grid x:Name="LayoutRoot" Background="White">
        <sdk:DataGrid AutoGenerateColumns="False" Height="249" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dgEmployee" VerticalAlignment="Top" Width="376" ItemsSource="{Binding}">
            <sdk:DataGrid.Columns>
                <sdk:DataGridTextColumn Header="FirstName" Binding="{Binding FirstName}" Width="Auto" />
                <sdk:DataGridTextColumn Header="LastName" Binding="{Binding LastName}" Width="Auto" />
                <sdk:DataGridTextColumn Header="City" Binding="{Binding City}" Width="Auto" />
            </sdk:DataGrid.Columns>
        </sdk:DataGrid>
        <Button Content="Data" Height="23" HorizontalAlignment="Left" Margin="313,270,0,0" Name="btnData" VerticalAlignment="Top" Width="75" Click="btnData_Click" />
    </Grid>
</UserControl>



Download
Download Source Code

No comments:

Post a Comment