Blogger news

Blogger templates

Wednesday, March 2, 2011

Silverlight DataBase Connectivity


One of the ways that a Silverlight application can access data is through web services. These can be ASP.NET Web Services (ASMX), Windows Communication Foundation (WCF) services, or representational state transfer (REST) services. My example is using WCF service. Let's start with step by step explanation on Accessing Data Through a WCF Service.

Click images to expand while travelling through this article.

Step 1: Open Visual studio 2010 for Silverlight application and name it "DataBaseTest" as shown below, Step 2:
Allow silverlight to create a web application project named DataBaseTest.Web as shown below, Click ok. Step 3: Right-click the WCFService.Web project and select Add ➤ New Item. Create a new class with the Class Diagram template, or create a new empty Code File. Name the new class Associate.cs, as shown below,
In the created class paste the code below,

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

namespace DataBaseTest.Web

{

public class Associate

{

public int AssociateId { get; set; }

public string FirstName { get; set; }

public string LastName { get; set; }

public static List<Associate> GetAssociates()

{

List<Associate> associates = new List<Associate>

{

new Associate

{

AssociateId=1,

FirstName="Sanjaykanth",

LastName = "Somanpillai",

} ,

new Associate

{

AssociateId=2,

FirstName="Sreelas",

LastName = "Sreekumar",

},

new Associate

{

AssociateId=3,

FirstName="Serosh",

LastName = "K Vikraman",

}

};

return associates;

}

}

}


Step 4:

Next, you need to add the WCF service that will call the Associate.GetAssociates() method. Right-click the WCFService.Web project and select Add ➤New Item. In the Add New Item dialog box, select the template named “Silverlight-enabled WCF Service” and name it AssociateService.svc, as below. Then click the Add button.


Step 5:

This will add a service named AssociateService.svc to the project with an attached code-behind file named AssociateService.svc.cs. View that code behind. You will see that Visual Studio has already created the base WCF service, including a sample method called DoWork(), as follows,

using System;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Activation;

namespace DataBaseTest.Web

{

[ServiceContract(Namespace = "")]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class AssociateService

{

[OperationContract]

public void DoWork()

{

// Add your operation implementation here

return;

}

// Add more operations here and mark them with [OperationContract]

}

}

Step 6:

Replace the DoWork() method with a GetAssociates() method that returns a List collection, as follows,

using System;

using System.Linq;

using System.Runtime.Serialization;

using System.ServiceModel;

using System.ServiceModel.Activation;

using System.Collections.Generic;

namespace DataBaseTest.Web

{

[ServiceContract(Namespace = "")]

[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class AssociateService

{

[OperationContract]

public List<Associate> GetAssociates()

{

return Associate.GetAssociates();

}

// Add more operations here and mark them with [OperationContract]

}

}

This method simply returns the results from calling the Associate.GetAssociates() method. Note that you will need to add a using statement for System.Collections.Generic.


Step 7:

Now that you have a Silverlight-enabled WCF service, you need to add a reference in your Silverlight project so that your Silverlight application can access the service. To do this, right-click References within the DataBaseTest Solution Explorer and select Add Service Reference, as shown below.
This brings up the Add Service Reference dialog box.

Step 8:

In the Add Service Reference dialog box, click the Discover button, Visual Studio will find the AssociateService.svc and will populate the Services list in the Add Service Reference dialog box. Note that you may need to build the solution before Visual Studio will find your service. Expand the AssociateService.svc node to show the AssociateService. Click AssociateService to see the GetAssociates() web method in the Operations listing, as shown below. Enter StartingHandServiceReference as the Namespace field, and then click OK to continue.




Step 8:

Open the Visual Studio Object Browser by selecting View ➤ Object Browser from the main menu. Navigate to DataBaseTest entry and expand the tree. You will find DataBaseTest .AssociateService under your project. Within that, you will see an object named AssociateServiceClient. Select this object to examine it, as shown below,

Look at the members listed on the right side of the Object Browser. There are a number of items that are added, but take specific note of the method named GetAssociatesAsync() and the event named GetAssociatesCompleted. You will need to use both of these in order to call your web service from Silverlight.

Step 10:

Now we can create the Silverlight application’s UI. Open the MainPage.xaml file in Visual Studio. Place the cursor within the root Grid and double-click the DataGrid control in the Toolbox. Once the DataGrid has been added, right-click on it in designer and select Reset Layout ➤ All. This adds the following XAML:

<Grid x:Name="LayoutRoot" Background="White">

<sdk:DataGrid AutoGenerateColumns="False" Name="dgAssociates" />

Grid>

step 11:

Next, add the following Column definitions, DataGrid contains three columns: one template column
containing the AssociateId and two text columns containing the FirstName and LastName as shown below XAML,

<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk" x:Class="DataBaseTest.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">

<Grid x:Name="LayoutRoot" Background="White">

<sdk:DataGrid AutoGenerateColumns="False" Name="dgAssociates">

<sdk:DataGrid.Columns>

<sdk:DataGridTemplateColumn Header="AssociateId">

<sdk:DataGridTemplateColumn.CellTemplate>

<DataTemplate>

<Grid>

<Grid.ColumnDefinitions>

<ColumnDefinition />

<ColumnDefinition />

<ColumnDefinition />

Grid.ColumnDefinitions>

<Border

Margin="2" CornerRadius="4"

BorderBrush="Black"

BorderThickness="1" />

<Rectangle

Margin="4" Fill="White"

Grid.Column="0" />

<Border

Margin="2" CornerRadius="4"

BorderBrush="Black"

BorderThickness="1"

Grid.Column="1" />

<Rectangle

Margin="4" Fill="White"

Grid.Column="1" />

<TextBlock Text="{Binding AssociateId}"

HorizontalAlignment="Center"

VerticalAlignment="Center" Grid.Column="0">TextBlock>

Grid>

DataTemplate>

sdk:DataGridTemplateColumn.CellTemplate>

sdk:DataGridTemplateColumn>

<sdk:DataGridTextColumn

Header="FirstName"

Binding="{Binding FirstName}" />

<sdk:DataGridTextColumn

Header="LastName"

Binding="{Binding LastName}" />

sdk:DataGrid.Columns>

sdk:DataGrid>

Grid>

UserControl>

Step 11:

Save the MainPage.xaml file and navigate to the code behind for the application, located in the MainPage.xaml.cs file. Wire up the Loaded event handler for the page, as follows:

namespace DataBaseTest

{

public partial class MainPage : UserControl

{

public MainPage()

{

InitializeComponent();

this.Loaded += new RoutedEventHandler(MainPage_Loaded);

}

void MainPage_Loaded(object sender, RoutedEventArgs e)

{

throw new NotImplementedException();

}

}

}


Step 12:

Next, you need to call the WCF service. In Silverlight, web services can be called only asynchronously, so the browser’s execution is not blocked by the transaction. In order to do this, you need to get an instance of the service reference (commonly referred to as the web service proxy class) named AssociateService, which you added earlier. You will then wire up an event handler for the service’s GetAssociatesCompleted event, which you examined in the
Object Browser . This is the event handler that will be called when the service has completed execution. Finally, you will execute the GetAssociatesAsync() method.

Step 13:
Within the Page_Loaded event handler, first obtain an instance of AssociateService. Then, in the GetAssociatesCompleted event handler, bind the ItemsSource of the DataGrid to the result returned from the service call, as shown in the following code. Note that normally you will want to check the result to make certain that the web service call was successful, and alert the user accordingly in case of failure.

add this name space in MainPage.XAML.CS
using DataBaseTest.AssociateService;

and

the code for MainPage.XAML is as follow,

using System;

using System.Windows;

using System.Windows.Controls;

using DataBaseTest.AssociateService;

namespace DataBaseTest

{

public partial class MainPage : UserControl

{

public MainPage()

{

InitializeComponent();

this.Loaded += new RoutedEventHandler(MainPage_Loaded);

}

void MainPage_Loaded(object sender, RoutedEventArgs e)

{

AssociateServiceClient service = new AssociateServiceClient();

service.GetAssociatesCompleted += new

EventHandler<GetAssociatesCompletedEventArgs>(

service_GetAssociatesCompleted);

service.GetAssociatesAsync();

}

void service_GetAssociatesCompleted(object sender, GetAssociatesCompletedEventArgs e)

{

this.dgAssociates.ItemsSource = e.Result;

}

}

}

Step 13:

Run the application. You can see that data from DataBaseTest.Web project is binded to the grid of DataBaseTest silverlight application.

No comments:

Post a Comment