Step 1:- Create the Service and Data service contract
Below is a simple customer table which has 3 fields ‘CustomerId’ which is an identity column, ‘CustomerCode’ which holds the customer code and ‘CustomerName’ which has the name of the customer. We will fire a simple select query using WCF and then display the data on the SilverLight grid.
Field |
Datatype |
CustomerId |
int |
CustomerCode |
nvarchar(50) |
CustomerName |
nvarchar(50) |
As per the customer table specified above we need to first define the WCF data contract. Below is the customer WCF data contract.
[DataContract]
public class clsCustomer
{
private string _strCustomer;
private string _strCustomerCode;
[DataMember]
public string Customer
{
get { return _strCustomer; }
set { _strCustomer = value; }
}
[DataMember]
public string CustomerCode
{
get { return _strCustomerCode; }
set { _strCustomerCode = value; }
}
}
We also need to define a WCF service contract which will be implemented by WCF concrete classes.
[ServiceContract]
public interface IServiceCustomer
{
[OperationContract]
clsCustomer getCustomer(int intCustomer);
}
Step 2:- Code the WCF service
Now that we have defined the data contract and service contract it’s time to implement the service contract. We have implemented the ‘getCustomer’ function which will return the ‘clsCustomer’ datacontract. ‘getCustomer’ function makes a simple ADO.NET connection and retrieves the customer information using the ‘Select’ SQL query.
public class ServiceCustomer : IServiceCustomer
{
public clsCustomer getCustomer(int intCustomer)
{
SqlConnection objConnection = new SqlConnection();
DataSet ObjDataset = new DataSet();
SqlDataAdapter objAdapater = new SqlDataAdapter();
SqlCommand objCommand = new SqlCommand("Select * from Customer where CustomerId=" + intCustomer.ToString());
objConnection.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["ConnStr"].ToString();
objConnection.Open();
objCommand.Connection = objConnection;
objAdapater.SelectCommand = objCommand;
objAdapater.Fill(ObjDataset);
clsCustomer objCustomer = new clsCustomer();
objCustomer.CustomerCode = ObjDataset.Tables[0].Rows[0][0].ToString();
objCustomer.Customer = ObjDataset.Tables[0].Rows[0][1].ToString();
objConnection.Close();
return objCustomer;
}
}
Asked In: Many Interviews |
Alert Moderator