WCF REST based services is one of the most important features/usages of WCF services. WCF REST is also known as Web style WCF services. WCF REST outputs in Plain Old (POX) form. One nice feature of WCF REST is that now any client application which understands XML, can send a request to WCF services. If you have developed applications using WCF 3.0, you must have added the service reference of WCF service in client applications. This creates a proxy class and configuration file. Client application makes request to WCF service using this proxy class and information from configuration file. In this case now if the interface is changed, then the service reference needs to be updated. But if WCF REST is used, then the client application can directly make a call to WCF service using repository (URL) and the operation (Operationcontract). For WCF REST programming ‘Syatem.ServiceModel.Web’, namespace is provided. This namespace provides the ‘WebGet’ and ‘WebInvoke’ classes. ‘WebGet’ helps to retrieve data from the WCF service in the form of XML. ‘WebInvoke’ is used to perform ‘POST’,’PUT’ and ‘DELETE’ HTTP calls.
In this article, we will create a WCF REST service that contains various methods to read data from a database server. The WPF client application will work as dash-board and consume this service. The client application will output as below:
Consider that you are working for the end user client and this client wants the UI as shown above. In this case, the data is coming from a database and the client is expecting a loosely coupled service communication over http.The Client application need not have any proxy class and any endpoint knowledge. If the UI application were to be changed in future, the proxy should not to be created again. To make this possible, WCF REST can be the best solution in this case.
Task 1: Database Table creation.
Step 1: Create database ‘Company’.
Step 2: Add the following tables with columns. The description of each table is given below the image:
The above table is used to store Employee information.
The above table is used to store company wise quarter wise sales information.
The above table is used to store ItemName wise sales quantity data.
The above table is used to store state wise sales quantity.
Task 2: Creating DataContract.
Step 1: Open VS 2008 and create a blank solution, name this as ‘WPF_WCFRESTApplication’.
Step 2: In this project add a class library project, name this as ‘clsDataContracts’. Rename ‘Class1.cs’ to ‘clsEmployee.cs’. In this project, add reference for ‘System.Runtime.Serialization’.
Step 3: Add following ‘DataContract’ classes:
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization;
namespace clsDataContracts
{
[DataContract]
public class clsEmployee
{
[DataMember]
public int EmpNo { get; set; }
[DataMember]
public string EmpName { get; set; }
[DataMember]
public int Salary { get; set; }
[DataMember]
public int DeptNo { get; set; }
}
[DataContract]
public class clsSales
{
[DataMember]
public int CompanyId { get; set; }
[DataMember]
public string CompanyName { get; set; }
[DataMember]
public decimal Q1 { get; set; }
[DataMember]
public decimal Q2 { get; set; }
[DataMember]
public decimal Q3 { get; set; }
[DataMember]
public decimal Q4 { get; set; }
}
[DataContract]
public class clsSalesData
{
[DataMember]
public string ItemName { get; set; }
[DataMember]
public int SalesQty { get; set; }
}
[DataContract]
public class clsStatewiseSales
{
[DataMember]
public string StateName { get; set; }
[DataMember]
public decimal SalesQuantity { get; set; }
}
}
VB.NET
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Runtime.Serialization
Namespace clsDataContracts
<DataContract> _
Public Class clsEmployee
Private privateEmpNo As Integer
<DataMember> _
Public Property EmpNo() As Integer
Get
Return privateEmpNo
End Get
Set(ByVal value As Integer)
privateEmpNo = value
End Set
End Property
Private privateEmpName As String
<DataMember> _
Public Property EmpName() As String
Get
Return privateEmpName
End Get
Set(ByVal value As String)
privateEmpName = value
End Set
End Property
Private privateSalary As Integer
<DataMember> _
Public Property Salary() As Integer
Get
Return privateSalary
End Get
Set(ByVal value As Integer)
privateSalary = value
End Set
End Property
Private privateDeptNo As Integer
<DataMember> _
Public Property DeptNo() As Integer
Get
Return privateDeptNo
End Get
Set(ByVal value As Integer)
privateDeptNo = value
End Set
End Property
End Class
<DataContract> _
Public Class clsSales
Private privateCompanyId As Integer
<DataMember> _
Public Property CompanyId() As Integer
Get
Return privateCompanyId
End Get
Set(ByVal value As Integer)
privateCompanyId = value
End Set
End Property
Private privateCompanyName As String
<DataMember> _
Public Property CompanyName() As String
Get
Return privateCompanyName
End Get
Set(ByVal value As String)
privateCompanyName = value
End Set
End Property
Private privateQ1 As Decimal
<DataMember> _
Public Property Q1() As Decimal
Get
Return privateQ1
End Get
Set(ByVal value As Decimal)
privateQ1 = value
End Set
End Property
Private privateQ2 As Decimal
<DataMember> _
Public Property Q2() As Decimal
Get
Return privateQ2
End Get
Set(ByVal value As Decimal)
privateQ2 = value
End Set
End Property
Private privateQ3 As Decimal
<DataMember> _
Public Property Q3() As Decimal
Get
Return privateQ3
End Get
Set(ByVal value As Decimal)
privateQ3 = value
End Set
End Property
Private privateQ4 As Decimal
<DataMember> _
Public Property Q4() As Decimal
Get
Return privateQ4
End Get
Set(ByVal value As Decimal)
privateQ4 = value
End Set
End Property
End Class
<DataContract> _
Public Class clsSalesData
Private privateItemName As String
<DataMember> _
Public Property ItemName() As String
Get
Return privateItemName
End Get
Set(ByVal value As String)
privateItemName = value
End Set
End Property
Private privateSalesQty As Integer
<DataMember> _
Public Property SalesQty() As Integer
Get
Return privateSalesQty
End Get
Set(ByVal value As Integer)
privateSalesQty = value
End Set
End Property
End Class
<DataContract> _
Public Class clsStatewiseSales
Private privateStateName As String
<DataMember> _
Public Property StateName() As String
Get
Return privateStateName
End Get
Set(ByVal value As String)
privateStateName = value
End Set
End Property
Private privateSalesQuantity As Decimal
<DataMember> _
Public Property SalesQuantity() As Decimal
Get
Return privateSalesQuantity
End Get
Set(ByVal value As Decimal)
privateSalesQuantity = value
End Set
End Property
End Class
End Namespace
All the above classes provide property mapping with data tables on database server.
Task 3: Creating WCF REST Service.
Step 1: To the solution, add a new WCF Service Application project from ‘Web Project Types'. Name this as ‘WCF_Service’. In this project, add a reference to ‘System.ServiceModel.Web’. Rename ‘IService1.cs’ to ‘IService.cs’. Rename ‘Service1.svc’ to ‘CService.svc’.
Step 2: Right click on ‘CService.svc’ and select ‘View Markup’ and make following changes:
<%@ServiceHost="" Language="C#" Debug="true" Service="WCF_Service.CService" CodeBehind="CService.svc.cs"
Factory="System.ServiceModel.Activation.WebServiceHostFactory"%>
Replace the appropriate values for VB.NET. The ‘WebServiceHostFactory’ represents here that the WCF service will be hosted in a Web environment.
Step 3: Write following methods in ‘IService.cs’:
C#
[ServiceContract]
public interface IService
{
[OperationContract]
[WebGet]
List<clsEmployee> GetAllEmployee();
[OperationContract]
[WebGet]
List<clsSales> GetSalesDetails();
[OperationContract]
[WebGet]
List<clsSalesData> GetSalesData();
[OperationContract]
[WebGet]
List<clsStatewiseSales> GetStatewiseSales();
}
VB.NET
<ServiceContract> _
Public Interface IService
<OperationContract, WebGet> _
Function GetAllEmployee() As List(Of clsEmployee)
<OperationContract, WebGet> _
Function GetSalesDetails() As List(Of clsSales)
<OperationContract, WebGet> _
Function GetSalesData() As List(Of clsSalesData)
<OperationContract, WebGet> _
Function GetStatewiseSales() As List(Of clsStatewiseSales)
End Interface
‘WebGet’ attribute specifies that data from these methods will be returned in the form of XML.
Step 4: Write the following code in the ‘CService.cs’ file. The ‘CService’ class implements ‘IService’ interface and writes implementation for all the methods.
C#
public class CService : IService
{
SqlConnection Conn;
SqlCommand Cmd;
SqlDataReader Reader;
#region IService Members
public List<clsEmployee> GetAllEmployee()
{
Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
Conn.Open();
Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "Select * from Employee";
List<clsEmployee> lstEmp = new List<clsEmployee>();
Reader = Cmd.ExecuteReader();
while (Reader.Read())
{
lstEmp.Add
(
new clsEmployee()
{
EmpNo = Convert.ToInt32(Reader["EmpNo"]),
EmpName = Reader["EmpName"].ToString(),
Salary = Convert.ToInt32(Reader["Salary"]),
DeptNo = Convert.ToInt32(Reader["DeptNo"])
}
);
}
Reader.Close();
Conn.Close();
return lstEmp;
}
#endregion
#region IService Members
public List<clsSales> GetSalesDetails()
{
Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
List<clsSales> lstSales = new List<clsSales>();
Conn.Open();
Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "Select * from Sales";
Reader = Cmd.ExecuteReader();
while (Reader.Read())
{
lstSales.Add
(
new clsSales()
{
CompanyId = Convert.ToInt32(Reader["CompanyId"]),
CompanyName = Reader["CompanyName"].ToString(),
Q1 = Convert.ToInt32(Reader["Q1"]),
Q2 = Convert.ToInt32(Reader["Q2"]),
Q3 = Convert.ToInt32(Reader["Q3"]),
Q4 = Convert.ToInt32(Reader["Q4"])
}
);
}
Reader.Close();
Conn.Close();
return lstSales;
}
public List<clsSalesData> GetSalesData()
{
Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
List<clsSalesData> lstSalesData = new List<clsSalesData>();
Conn.Open();
Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "Select Top 8 ItemName,SalesQty from SalesData";
Reader = Cmd.ExecuteReader();
while (Reader.Read())
{
lstSalesData.Add
(
new clsSalesData()
{
ItemName = Reader["ItemName"].ToString(),
SalesQty = Convert.ToInt32(Reader["SalesQty"])
}
);
}
Reader.Close();
Conn.Close();
return lstSalesData;
}
#endregion
#region IService Members
public List<clsStatewiseSales> GetStatewiseSales()
{
Conn = new SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI");
List<clsStatewiseSales> lstStatewiseSales = new List<clsStatewiseSales>();
Conn.Open();
Cmd = new SqlCommand();
Cmd.Connection = Conn;
Cmd.CommandText = "Select StateName,Salesquantity from Statewisesales";
Reader = Cmd.ExecuteReader();
while (Reader.Read())
{
lstStatewiseSales.Add
(
new clsStatewiseSales()
{
StateName = Reader["StateName"].ToString(),
SalesQuantity = Convert.ToInt32(Reader["Salesquantity"])
}
);
}
Reader.Close();
Conn.Close();
return lstStatewiseSales;
}
#endregion
}
VB.NET
Public Class CService
Implements IService
Private Conn As SqlConnection
Private Cmd As SqlCommand
Private Reader As SqlDataReader
#Region "IService Members"
Public Function GetAllEmployee() As List(Of clsEmployee)
Conn = New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
Conn.Open()
Cmd = New SqlCommand()
Cmd.Connection = Conn
Cmd.CommandText = "Select * from Employee"
Dim lstEmp As New List(Of clsEmployee)()
Reader = Cmd.ExecuteReader()
Do While Reader.Read()
lstEmp.Add (New clsEmployee() With {.EmpNo = Convert.ToInt32(Reader("EmpNo")), .EmpName = Reader("EmpName").ToString(), .Salary = Convert.ToInt32(Reader("Salary")), .DeptNo = Convert.ToInt32(Reader("DeptNo"))})
Loop
Reader.Close()
Conn.Close()
Return lstEmp
End Function
#End Region
#Region "IService Members"
Public Function GetSalesDetails() As List(Of clsSales)
Conn = New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
Dim lstSales As New List(Of clsSales)()
Conn.Open()
Cmd = New SqlCommand()
Cmd.Connection = Conn
Cmd.CommandText = "Select * from Sales"
Reader = Cmd.ExecuteReader()
Do While Reader.Read()
lstSales.Add (New clsSales() With {.CompanyId = Convert.ToInt32(Reader("CompanyId")), .CompanyName = Reader("CompanyName").ToString(), .Q1 = Convert.ToInt32(Reader("Q1")), .Q2 = Convert.ToInt32(Reader("Q2")), .Q3 = Convert.ToInt32(Reader("Q3")), .Q4 = Convert.ToInt32(Reader("Q4"))})
Loop
Reader.Close()
Conn.Close()
Return lstSales
End Function
Public Function GetSalesData() As List(Of clsSalesData)
Conn = New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
Dim lstSalesData As New List(Of clsSalesData)()
Conn.Open()
Cmd = New SqlCommand()
Cmd.Connection = Conn
Cmd.CommandText = "Select Top 8 ItemName,SalesQty from SalesData"
Reader = Cmd.ExecuteReader()
Do While Reader.Read()
lstSalesData.Add (New clsSalesData() With {.ItemName = Reader("ItemName").ToString(), .SalesQty = Convert.ToInt32(Reader("SalesQty"))})
Loop
Reader.Close()
Conn.Close()
Return lstSalesData
End Function
#End Region
#Region "IService Members"
Public Function GetStatewiseSales() As List(Of clsStatewiseSales)
Conn = New SqlConnection("Data Source=.;Initial Catalog=Company;Integrated Security=SSPI")
Dim lstStatewiseSales As New List(Of clsStatewiseSales)()
Conn.Open()
Cmd = New SqlCommand()
Cmd.Connection = Conn
Cmd.CommandText = "Select StateName,Salesquantity from Statewisesales"
Reader = Cmd.ExecuteReader()
Do While Reader.Read()
lstStatewiseSales.Add (New clsStatewiseSales() With {.StateName = Reader("StateName").ToString(), .SalesQuantity = Convert.ToInt32(Reader("Salesquantity"))})
Loop
Reader.Close()
Conn.Close()
Return lstStatewiseSales
End Function
#End Region
}
Step 5: Make following changes in ‘Web.Config’ file.
<system.serviceModel>
<services>
<service behaviorConfiguration="ServBehave" name="WCF_Service.CService">
<endpoint address="" binding="webHttpBinding" contract="WCF_Service.IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServBehave">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
The above configuration uses ‘webHttpBinding’ which is based on ‘basicHttpBinding’. This is designed for WCF REST.
Task 4: Creating WPF client application.
Step 1: To the solution, now add a new WPF application. Name this as ‘WPF_RESTCLient’.
Step 2: In the ‘Window.xaml’ write the following xaml:
<Windowx:Class="WPF_RESTCLient.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="700" Width="700"
xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;
assembly=System.Windows.Controls.DataVisualization.Toolkit">
<Window.Resources>
<DataTemplate x:Key="EmployeeDataTemplate">
<Border BorderBrush="Red" Margin="2" BorderThickness="1" HorizontalAlignment="Center">
<StackPanel Orientation="Horizontal">
<TextBlock Width="100" Text="{Binding EmpNo}"></TextBlock>
<TextBlock Width="150" Text="{Binding EmpName}"></TextBlock>
<TextBlock Width="100" Text="{Binding Salary}"></TextBlock>
<TextBlock Width="100" Text="{Binding DeptNo}"></TextBlock>
</StackPanel>
</Border>
</DataTemplate>
<Style TargetType="ListViewItem">
<Style.Triggers>
<Trigger Property="IsMouseOver" Value="true">
<Setter Property="Background" Value="Red"></Setter>
<Setter Property="FontSize" Value="20"></Setter>
<Setter Property="FontWeight" Value="Bold"></Setter>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
<GridHeight="{Binding Path=ActualHeight}" Width="{Binding Path=ActualWidht}" ShowGridLines="True">
<Grid.RowDefinitions>
<RowDefinition Height="350"></RowDefinition>
<RowDefinition Height="350"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="350"></ColumnDefinition>
<ColumnDefinition Width="350"></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid x:Name="grdEmp" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="320"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="Employee Information" TextAlignment="Center" Grid.Row="0" Width="350" TextWrapping="Wrap"
Foreground="Blue" FontFamily="Times New Roman" FontSize="25" FontWeight="Bold" FontStyle="Italic"
Background="Gold"></TextBlock>
<ListView Grid.Row="1"
Name="lstEmpData" ItemsSource="{Binding}" ItemTemplate="{StaticResource EmployeeDataTemplate}">
</ListView>
</Grid>
<GridGrid.Column="0" Grid.Row="0" x:Name="grdQtewiseChart">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="320"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="Quarter Wise Sales Statics" TextAlignment="Center" Grid.Row="0" Width="350" TextWrapping="Wrap"
Foreground="Blue" FontFamily="Times New Roman" FontSize="25" FontWeight="Bold" FontStyle="Italic"
Background="Gold"></TextBlock>
<chartingToolkit:Chart Grid.Row="1"
Name="chartQtrwiseSalesColumn" >
<chartingToolkit:Chart.Series>
<chartingToolkit:ColumnSeries x:Name="columnQtrWiseSalesChart"
DependentValuePath="Value"
IndependentValuePath="Key"
IsSelectionEnabled="True">
</chartingToolkit:ColumnSeries>
</chartingToolkit:Chart.Series>
</chartingToolkit:Chart>
</Grid>
<Grid Grid.Column="1" Grid.Row="0" x:Name="grdSalesDataChart">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="320"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="Itemwise Sales Statics" TextAlignment="Center" Grid.Row="0" Width="350" TextWrapping="Wrap"
Foreground="Blue" FontFamily="Times New Roman" FontSize="25" FontWeight="Bold" FontStyle="Italic"
Background="Gold"></TextBlock>
<chartingToolkit:ChartGrid.Row="1"
Name="chartSalesDataColumn"Width="350" >
<chartingToolkit:Chart.Series>
<chartingToolkit:LineSeries x:Name="lineSalesDataChart"
DependentValuePath="Value"
IndependentValuePath="Key"
IsSelectionEnabled="True">
</chartingToolkit:LineSeries>
</chartingToolkit:Chart.Series>
</chartingToolkit:Chart>
</Grid>
<Grid Grid.Row="1" Grid.Column="1" x:Name="grdStatewiseSales">
<Grid.RowDefinitions>
<RowDefinition Height="30"></RowDefinition>
<RowDefinition Height="320"></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Text="State Sales Statics" TextAlignment="Center" Grid.Row="0" Width="350" TextWrapping="Wrap"
Foreground="Blue" FontFamily="Times New Roman" FontSize="25" FontWeight="Bold" FontStyle="Italic"
Background="Gold"></TextBlock>
<chartingToolkit:Chart Grid.Row="1"
Name="chartStatewiseSalesColumn" Width="350" >
<chartingToolkit:Chart.Series>
<chartingToolkit:PieSeries x:Name="pieStateSalesChart"
DependentValuePath="Value"
IndependentValuePath="Key"
IsSelectionEnabled="True">
</chartingToolkit:PieSeries>
</chartingToolkit:Chart.Series>
</chartingToolkit:Chart>
</Grid>
</Grid>
</Window>
In the above xaml, the grid is divided into two rows and two clients. These contains various graphs and ListView. (Note:When you drag-drop Graph controls, you get a reference to ‘System.Windows.Controls.DataVisualization.Toolkit. If not, add the reference explicitly and add ’xmlns:chartingToolkit="clr-namespace:System.Windows.Controls.DataVisualization.Charting;
assembly=System.Windows.Controls.DataVisualization.Toolkit"’, into Window tag)
Following are classes used in the client application for making request to WCF REST Service:
1. WebRequest: Used to make response to URI.
2. WebResponse: Provides response from URI.
3. DataContractSerialiser:Used to serialize and deserialize instance of a type into an XML stream.
In the Window1.Xaml.cs, use following interfaces:
C#
using System.Net;
using System.Runtime.Serialization;
VB.NET
Imports System.Net
Imports System.Runtime.Serialization
Step 3: In the ‘Windows1.xaml.cs’ write the following code:
C#
//Method for making request for 'GetAllEmploye' operations from the service
private void LoadAndDisplayEmployeeInformation()
{
//USed to make request to URI
WebRequest myRequest = WebRequest.Create("http://localhost/WCF_Rest_WPF/CService.svc/GetAllEmployee");
//Provides response from a URI.
WebResponse myResponse = myRequest.GetResponse();
//USed to Serialize and Deserialize instance of a type into an XML stream
DataContractSerializer RecData = new DataContractSerializer(typeof(List<clsDataContracts.clsEmployee>));
var CollectionEmployees = RecData.ReadObject(myResponse.GetResponseStream());
this.lstEmpData.DataContext = CollectionEmployees;
}
//Method for making request for 'GetSalesDetails' operations from the service
private void LoadAndDisplayQuarterWiseSalesStatatics()
{
WebRequest myRequest = WebRequest.Create("http://localhost/WCF_Rest_WPF/CService.svc/GetSalesDetails");
WebResponse myResponse = myRequest.GetResponse();
DataContractSerializer RecData = new DataContractSerializer(typeof(List<clsDataContracts.clsSales>));
var CollectionSales = RecData.ReadObject(myResponse.GetResponseStream());
#region Code for putting data from 'CollectionSales' to KeyValuePair
//Convert the received object into the original collection
List<clsDataContracts.clsSales> lstQtrwiseSales = (List<clsDataContracts.clsSales>)CollectionSales;
//Set the size as the number of records in the received collection
KeyValuePair<string, decimal>[] arrGraphData = new KeyValuePair<string, decimal>[lstQtrwiseSales.Count];
int i = 0;
foreach (var item in lstQtrwiseSales)
{
arrGraphData[i] = new KeyValuePair<string, decimal>(item.CompanyName, item.Q1);
arrGraphData[i] = new KeyValuePair<string, decimal>(item.CompanyName, item.Q2);
arrGraphData[i] = new KeyValuePair<string, decimal>(item.CompanyName, item.Q3);
arrGraphData[i] = new KeyValuePair<string, decimal>(item.CompanyName, item.Q4);
i++;
}
chartQtrwiseSalesColumn.DataContext = arrGraphData;
columnQtrWiseSalesChart.ItemsSource = arrGraphData;
#endregion
}
//Method for making request for 'GetSalesData' operations from the service
private void LoadAndDisplaySalesDataStatatics()
{
WebRequest myRequest = WebRequest.Create("http://localhost/WCF_Rest_WPF/CService.svc/GetSalesData");
WebResponse myResponse = myRequest.GetResponse();
DataContractSerializer RecData = new DataContractSerializer(typeof(List<clsDataContracts.clsSalesData>));
var CollectionSalesData = RecData.ReadObject(myResponse.GetResponseStream());
#region Code for putting data from 'CollectionSales' to KeyValuePair
//Convert the received object into the original collection
List<clsDataContracts.clsSalesData> lstSalesData = (List<clsDataContracts.clsSalesData>)CollectionSalesData;
//Set the size as the number of records in the received collection
KeyValuePair<string, decimal>[] arrGraphData = new KeyValuePair<string, decimal>[lstSalesData.Count];
int i = 0;
foreach (var item in lstSalesData)
{
arrGraphData[i] = new KeyValuePair<string, decimal>(item.ItemName, item.SalesQty);
i++;
}
chartSalesDataColumn.DataContext = arrGraphData;
lineSalesDataChart.ItemsSource = arrGraphData;
#endregion
}
//Method for making request for 'GetStatewisesales' operations from the service
private void LoadAndDIsplayStatewiseSales()
{
WebRequest myRequest = WebRequest.Create("http://localhost/WCF_Rest_WPF/CService.svc/GetStatewisesales");
WebResponse myResponse = myRequest.GetResponse();
DataContractSerializer RecData = new DataContractSerializer(typeof(List<clsDataContracts.clsStatewiseSales>));
var CollectionStatewiseSales = RecData.ReadObject(myResponse.GetResponseStream());
#region Code for putting 'CollectionStatewiseSales' in KeyValuePair
//Convert the received object into the original collection
List<clsDataContracts.clsStatewiseSales> lstStatewiseSales = (List<clsDataContracts.clsStatewiseSales>)CollectionStatewiseSales;
//Set the size as the number of records in the received collection
KeyValuePair<string, decimal>[] arrGraphData = new KeyValuePair<string, decimal>[lstStatewiseSales.Count];
int i = 0;
foreach (var item in lstStatewiseSales)
{
arrGraphData[i] = new KeyValuePair<string, decimal>(item.StateName, item.SalesQuantity);
i++;
}
chartStatewiseSalesColumn.DataContext = arrGraphData;
pieStateSalesChart.ItemsSource = arrGraphData;
#endregion
}
VB.NET
'Method for making request for 'GetAllEmploye' operations from the service
Private Sub LoadAndDisplayEmployeeInformation()
'USed to make request to URI
Dim myRequest As WebRequest = WebRequest.Create("http://localhost/WCF_Rest_WPF/CService.svc/GetAllEmployee")
'Provides response from a URI.
Dim myResponse As WebResponse = myRequest.GetResponse()
'USed to Serialize and Deserialize instance of a type into an XML stream
Dim RecData As New DataContractSerializer(GetType(List(Of clsDataContracts.clsEmployee)))
Dim CollectionEmployees = RecData.ReadObject(myResponse.GetResponseStream())
Me.lstEmpData.DataContext = CollectionEmployees
End Sub
'Method for making request for 'GetSalesDetails' operations from the service
Private Sub LoadAndDisplayQuarterWiseSalesStatatics()
Dim myRequest As WebRequest = WebRequest.Create("http://localhost/WCF_Rest_WPF/CService.svc/GetSalesDetails")
Dim myResponse As WebResponse = myRequest.GetResponse()
Dim RecData As New DataContractSerializer(GetType(List(Of clsDataContracts.clsSales)))
Dim CollectionSales = RecData.ReadObject(myResponse.GetResponseStream())
' #Region "Code for putting data from 'CollectionSales' to KeyValuePair"
'Convert the received object into the original collection
Dim lstQtrwiseSales As List(Of clsDataContracts.clsSales) = CType(CollectionSales, List(Of clsDataContracts.clsSales))
'Set the size as the number of records in the received collection
Dim arrGraphData(lstQtrwiseSales.Count - 1) As KeyValuePair(Of String, Decimal)
Dim i As Integer = 0
For Each item In lstQtrwiseSales
arrGraphData(i) = New KeyValuePair(Of String, Decimal)(item.CompanyName, item.Q1)
arrGraphData(i) = New KeyValuePair(Of String, Decimal)(item.CompanyName, item.Q2)
arrGraphData(i) = New KeyValuePair(Of String, Decimal)(item.CompanyName, item.Q3)
arrGraphData(i) = New KeyValuePair(Of String, Decimal)(item.CompanyName, item.Q4)
i += 1
Next item
chartQtrwiseSalesColumn.DataContext = arrGraphData
columnQtrWiseSalesChart.ItemsSource = arrGraphData
' #End Region
End Sub
'Method for making request for 'GetSalesData' operations from the service
Private Sub LoadAndDisplaySalesDataStatatics()
Dim myRequest As WebRequest = WebRequest.Create("http://localhost/WCF_Rest_WPF/CService.svc/GetSalesData")
Dim myResponse As WebResponse = myRequest.GetResponse()
Dim RecData As New DataContractSerializer(GetType(List(Of clsDataContracts.clsSalesData)))
Dim CollectionSalesData = RecData.ReadObject(myResponse.GetResponseStream())
' #Region "Code for putting data from 'CollectionSales' to KeyValuePair"
'Convert the received object into the original collection
Dim lstSalesData As List(Of clsDataContracts.clsSalesData) = CType(CollectionSalesData, List(Of clsDataContracts.clsSalesData))
'Set the size as the number of records in the received collection
Dim arrGraphData(lstSalesData.Count - 1) As KeyValuePair(Of String, Decimal)
Dim i As Integer = 0
For Each item In lstSalesData
arrGraphData(i) = New KeyValuePair(Of String, Decimal)(item.ItemName, item.SalesQty)
i += 1
Next item
chartSalesDataColumn.DataContext = arrGraphData
lineSalesDataChart.ItemsSource = arrGraphData
' #End Region
End Sub
'Method for making request for 'GetStatewisesales' operations from the service
Private Sub LoadAndDIsplayStatewiseSales()
Dim myRequest As WebRequest = WebRequest.Create("http://localhost/WCF_Rest_WPF/CService.svc/GetStatewisesales")
Dim myResponse As WebResponse = myRequest.GetResponse()
Dim RecData As New DataContractSerializer(GetType(List(Of clsDataContracts.clsStatewiseSales)))
Dim CollectionStatewiseSales = RecData.ReadObject(myResponse.GetResponseStream())
' #Region "Code for putting 'CollectionStatewiseSales' in KeyValuePair"
'Convert the received object into the original collection
Dim lstStatewiseSales As List(Of clsDataContracts.clsStatewiseSales) = CType(CollectionStatewiseSales, List(Of clsDataContracts.clsStatewiseSales))
'Set the size as the number of records in the received collection
Dim arrGraphData(lstStatewiseSales.Count - 1) As KeyValuePair(Of String, Decimal)
Dim i As Integer = 0
For Each item In lstStatewiseSales
arrGraphData(i) = New KeyValuePair(Of String, Decimal)(item.StateName, item.SalesQuantity)
i += 1
Next item
chartStatewiseSalesColumn.DataContext = arrGraphData
pieStateSalesChart.ItemsSource = arrGraphData
' #End Region
End Sub
Step 4: Call all these methods in the Loaded event as below (no best practices involved here):
C#
void Window1_Loaded(object sender, RoutedEventArgs e)
{
LoadAndDisplayEmployeeInformation();
LoadAndDisplayQuarterWiseSalesStatatics();
LoadAndDisplaySalesDataStatatics();
LoadAndDIsplayStatewiseSales();
}
VB.NET
Private Sub Window1_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)
LoadAndDisplayEmployeeInformation()
LoadAndDisplayQuarterWiseSalesStatatics()
LoadAndDisplaySalesDataStatatics()
LoadAndDIsplayStatewiseSales()
End Sub
Step 5: Run the application and the following output will be displayed.
Conclusion:
WCF REST services need not to added as a service reference to client applications. This provides loosely coupled behavior to the client application. The client application, which understand XML can make request to the WCF service using HTTP. WCF REST can be used in JavaScript, PHP, AJAX etc.
The entire source code of this article can be downloaded over here
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Mahesh Sabnis is a DotNetCurry author and a Microsoft MVP having over two decades of experience in IT education and development. He is a Microsoft Certified Trainer (MCT) since 2005 and has conducted various Corporate Training programs for .NET Technologies (all versions), and Front-end technologies like Angular and React. Follow him on twitter @
maheshdotnet or connect with him on
LinkedIn