Search This Blog

Loading...

Oct 16, 2010

How to call WCF in Silverlight


Sponsored Links:
As we know Silverlight application’s are always run in client browser,
We cannot have direct access of them if we want to do any database related
action, WCF solves this problem. We can directly call WCF Methods in 
Silverlight. To get this done you have to work on two applications
  • WCFService Lib – because Silverlight can not communicate directly
  • ASP.net Silverlight Application
WCFServiceLib

Open VS2010 Select WCF ServiceLib Project then 
 
In Your WCFServiceLib Project You have define the Data Contract and

Define Data Contract

[DataContract]
public class myComboontracts
{     
[DataMember]
public string CreationDate;
[DataMember]
public string Total;
public static List<myComboontracts > ConverttoList(DataSet dsService)
{
List<myComboontracts > SList = new List<myComboontracts >();
foreach (DataRow dr in dsService.Tables[0].Rows)
{
myComboontracts sData = new myComboontracts ();
sData.CreationDate = dr["CreationDate"].ToString();
sData.Total = dr["Total"].ToString();
SList.Add(sData);
}
return SList;
}
 Define Service Contract 
[ServiceContract]
public interface IService
{
[OperationContract]
List<EDWContracts> GetDetails(string str);
}       
type following code in Service1.svc public classService1: IService, IClientAccessPolicy    {        yourdBobjDB;        public List<myComboontracts > GetDetails()        {          objDB = new yourdB();
 DataSet oDs = objDB.ReturnDataset ( “Your Query” ); /*  ReturnDataset  is my function which return * Dataset using connection * here i am not showing normal methods * like how to connect with database * I am asuming you already have your * own dataccess layer */ return myComboontracts.ConverttoList(oDs); }
Deploy/Host this service either on IIS or Windows, Now Open Asp.net 

Silverlight application
Structure of Silverlight application

  • Add Web Service Reference then open MainPage.xml file
  • Place Drop Down (I am using RadControl’s Combo) , make sure it’s should not content any thing from client side (xaml) please remove itemcontent property from xamal view
  • Now goto Mainpage.xaml.cs and add create the object of your webserice
    ServiceReference1.ServiceClient s;
  • Declare the event Handler 
public MainPage()
{s = new ServiceReference1.ServiceClient();
s.GetMissingDealAssetWidgetCompleted += new 
EventHandler<ServiceReference1.GetDetailsEventArgs>
(s_GetMissingDealAssetWidgetCompleted);
s.GetMissingDealAssetWidgetAsync();}
  • Define the definition of Event handler
private void LoadDetails()
{
s = new ServiceReference1.ServiceClient();
s.GetDetailsCompleted += 
         new EventHandler<ServiceReference1.GetDetails>
(s_GetMissingRightsAssetWidgetCompleted);
s.GetDetails();
}
That’s It

Follow by Email