How to call WCF Services in AJAX


JavaScript can communicate with services in JSON(JavaScript Object Notation) format. JSON is the best serialization format in performance and preferred wherever possible because of this fact. WCF supports JSON format because of which its services can be accessed by any AJAX clients.

To make a WCF service AJAX-enabled, we can use the WebServiceHostFactory class in ServiceHost directive of the .svc file or else create an ajax endpoint with WebHttpBinding and configure it accordingly.

In VS.NET, creating AJAX-enabled WCF Service is really made easy by providing a separate template for the purpose. When we use this template VS.NET takes care of configuring the right endpoints and behaviours. It creates a new system.serviceModel tag in web.config for this purpose. Moreover, all the parameters and results are serialized in JSON format when this template is used.

Demo:

In this demo we create an Ajax-enabled WCF service and consume it from ASP.NET AJAX.

Our aim in this program is to show that when we input a country name in the text box and press the html button, it should fetch the details of that country from the WCF service and display them to the user. For this we need to create a AJAX-enabled WCF service as we are interacting with the service through JavaScript. The steps for our demo are as follows:

First Create DataBase and add table as follows

Then Enter Data into table as follows:

1. Start a website normally and create the forms and databases as required.

Here we design a form with a html texbox and button to input the Player name. The results will be displayed in the provided label and image html controls.

The form looks as given below:

2. For our service we’ll use EDM for accessing data from SQL Database. We have a database called Countries from which we need to get details from Images table. To create an Entity Data Model right click the project in Solution Explorer and select Add New Item ADO.NET Entity Data Model and give name as CountriesModel. Then select Generate from Database option and choose the required database. In the final step choose the tables you want the data from. In

our demo we have selected Images from Countries database. This step will create an object of our table in the program. The advantage of usingentities here is that they are automatically serialized and there is no need of using [DataContract] attribute for them.

3. Now we’ll create a WCF service which retrieves the data and provides to the clients. For this again from Add New Item, choose AJAX-enabled WCF Service and name it as CountriesService.

This step will create a .svc file which is needed for our service get hosted in IIS. It will also create endpoints for the service with WebHttpBinding and its behaviours. This can be seen in web.config file as follows:

4. Along with .svc file, by default a .cs file with the same is created in App_Code folder to write the code. In this file we write methods necessary to get data from the Entities.

Whatever methods need to be exposed to the client should be decorated with [OperationContract] attributes.

We write the following method in our service:

[OperationContract]
    public List<string> GetData(string name)
    {
        MySampleDBModel.MySampleDBEntities obj = new MySampleDBModel.MySampleDBEntities();
        var x = (from n in obj.Images where n.PlayerName == name select n).FirstOrDefault();
        List<string> str = new List<string>();
        if (x != null)
        {
            str.Add(x.PlayerName);
            str.Add(x.CountryName);
            str.Add(x.Play);
            str.Add(x.ImagePath);
            return str;
        }
        else
            return null;
    }

This method gets the details of a given country from the created entities and returns in the form of a list.

Now the WCF service is ready and all that is remaining is to consume it from our web form using JavaScript which can interact with the service asynchronously.

5. For consuming, write the following code in the page source:

function Button1_onclick() {
            Service.GetData($get("Text1").value, f1, f2);
        }
        function f1(res) {
            if (res != null) {
                $get("Label1").innerHTML = res[0];
                $get("Label2").innerHTML = res[1];
                $get("Label3").innerHTML = res[2];
                var img = document.getElementById("image1");
                img.src = res[3];
            }
            else {
                alert("Details for this Player don't exist in our database");
            }
        }
        function f2() {
            alert("Error in processing.. Please try again!!");
        }

Now let’s try to understand this script. For this we should know what controls are placed in the form. Removing table formatting, the source view of the controls is shown below:

  1. <div>
  2. <asp:ScriptManager ID="ScriptManager1" runat="server">
  3. <Services>
  4. <asp:ServiceReference Path="~/Service.svc" />
  5. </Services>
  6. </asp:ScriptManager>
  7. </div>
  8. </form>
  9. <table>
  10. <tr>
  11. <td>
  12. &nbsp;</td>
  13. <td style="background-color: #99CCFF; font-weight: bold;">
  14. <input id="Text1" type="text" /><input id="Button1" type="button"
  15. value="Submit" onclick="return Button1_onclick()" /></td>
  16. <td>
  17. &nbsp;</td>
  18. </tr>
  19. <tr>
  20. <td>
  21. &nbsp;</td>
  22. <td style="background-color: #99CCFF; font-weight: bold;">
  23. PlayerName:<label id="Label1" ></label></td>
  24. <td>
  25. &nbsp;</td>
  26. </tr>
  27. <tr>
  28. <td>
  29. &nbsp;</td>
  30. <td style="background-color: #99CCFF; font-weight: bold;">
  31. PlayerCountry:<label id="Label2"></label></td>
  32. <td>
  33. &nbsp;</td>
  34. </tr>
  35. <tr>
  36. <td>
  37. &nbsp;</td>
  38. <td style="background-color: #99CCFF; font-weight: bold;">
  39. Play:<label id="Label3"></label></td>
  40. <td>
  41. &nbsp;</td>
  42. </tr>
  43. <tr>
  44. <td>
  45. &nbsp;</td>
  46. <td style="background-color: #99CCFF; font-weight: bold;">
  47. Image:<img alt="" src="" id="image1" /></td>
  48. <td>
  49. &nbsp;</td>
  50. </tr>
  51. </table>

When the button is clicked the code in function Btn_Click() is executed. The WCF service is called in that function. To call a service, a ScriptManager is needed which creates the needed proxy to interact with the service. The Service Reference should be provided in ScriptManager as follows:

  1. <asp:ScriptManager ID="ScriptManager1" runat="server">
  2. <Services>
  3. <asp:ServiceReference Path="~/Service.svc" />
  4. </Services>
  5. </asp:ScriptManager>

 

When the service reference is assigned and the program is compiled, it will create a proxy in JavaScript, through which the function interacts with the service. The following line in Btn_Click function is mainly responsible for providing the result.

  1. Service.GetData($get("Text1").value, f1, f2);

Country.value is the parameter i.e. country name that we are passing to the method. Success and failure are the parameters which represent the functions that are called respectively when the method is executed successfully or failed.

The parameter x passed in the function success(x) is the result obtained from the method GetDetails(). This result is assigned to relevant controls in this function. When the method fails to execute properly, the function failure() is called.

The final result is as shown in the screenshot below:

DOWNLOADSAMPLECODE

Advertisements

How to crate datatable and add primary key to datatable in asp.net


Creating DataTable:

//create inatance of datatable
DataTable dt = new DataTable();
//give datatable name to dt
dt.TableName = “MyTable”;
//add columns to datatable dt
dt.Columns.Add(“ImgPath”, typeof(string));
//creating primary key column
DataColumn[] Key = new DataColumn[1];
DataColumn col = new DataColumn();
//setting datatype to column
col.DataType = System.Type.GetType(“System.String”);
//giving column name
col.ColumnName = “Name”;
//adding column to datatable dt
dt.Columns.Add(col);
Key[0] = col;
// adding other columns to datatable directly
dt.Columns.Add(“Desc”, typeof(string));
dt.Columns.Add(“Price”, typeof(string));
//setting primary key to datatable
dt.PrimaryKey = Key;

Adding Data to Created DataTable:

//creating new data row
DataRow dr = dt.NewRow();
//adding data to the above created datarow
dr[0] = “ImgPath”;
dr[1] = “Name”;
dr[2] = “Desc”;
dr[3] = “123.45”;
//adding datarow to datatable
dt.Rows.Add(dr);

How to call wcf service from wpf client


DataBaseDesign:

First create database with name MySampleDB and create table as follows with name UserDetails

then add data to table as follows:

WCFService Creation:

First go to file newproject–>wcfservicelibrary

Then add required service files as follows

1. interface class

2.Class Implementing InterFace

3.UserDefinedClasses(if any used)

Write following code in Userdefined Class:

Write this code in Interface Class:

Then Write Following Code in Class implementing Interface

After Completion of creating service run the application

now service will hosted check service is hosted of no as follows

After completion of service hosting you can get the following window

To check wether your service is running or not call the service methods in

wcftestclient window as follows

Now your service is Hosted successfully.

Now prepare client as follows

WPFClient:

Open new visualstudio go to file–> new Project–>wpfclient

Design wpfclient as follows

This is the code for above window design

  1. <Window x:Class="WpfClient.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
  4. Title="MainWindow" Height="500" Width="800">
  5.     <Grid>
  6.         <GroupBox Header="Details" Height="361" HorizontalAlignment="Left" Margin="500,27,0,0" Name="groupBox1" VerticalAlignment="Top" Width="266">
  7.             <Grid>
  8.                 <Label Content="EnterID:" Height="28" HorizontalAlignment="Left" Margin="16,17,0,0" Name="label1" VerticalAlignment="Top" FontWeight="Bold" FontSize="16" />
  9.                 <Label Content="UserID:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,122,0,0" Name="label2" VerticalAlignment="Top" />
  10.                 <Label Content="UserName:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,162,0,0" Name="label3" VerticalAlignment="Top" />
  11.                 <Label Content="LastName:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,204,0,0" Name="label4" VerticalAlignment="Top" />
  12.                 <Label Content="Location:" FontSize="16" FontWeight="Bold" Height="28" HorizontalAlignment="Left" Margin="16,244,0,0" Name="label5" VerticalAlignment="Top" />
  13.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="101,22,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
  14.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,167,0,0" Name="textBox2" VerticalAlignment="Top" Width="120" />
  15.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,127,0,0" Name="textBox3" VerticalAlignment="Top" Width="120" />
  16.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,209,0,0" Name="textBox4" VerticalAlignment="Top" Width="120" />
  17.                 <TextBox Height="23" HorizontalAlignment="Left" Margin="118,249,0,0" Name="textBox5" VerticalAlignment="Top" Width="120" />
  18.                 <Button Content="GetSingleRecord" Height="36" HorizontalAlignment="Left" Margin="25,66,0,0" Name="button1" VerticalAlignment="Top" Width="196" Click="button1_Click_1" />
  19.             </Grid>
  20.         </GroupBox>
  21.         <GroupBox Header="AllDetails" Height="361" HorizontalAlignment="Left" Margin="22,27,0,0" Name="groupBox2" VerticalAlignment="Top" Width="453">
  22.             <Grid>
  23.                 <DataGrid AutoGenerateColumns="False" Height="263" HorizontalAlignment="Left" Margin="14,73,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="413" AlternatingRowBackground="#FFDEA5DE" RowBackground="#FFFFBEA5" FontSize="18" FontWeight="Bold">
  24.                     <DataGrid.Columns>
  25.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  26.                             <DataGridTemplateColumn.CellTemplate>
  27.                                 <DataTemplate>
  28.                                     <TextBlock Text="{Binding Path=UserId}"></TextBlock>
  29.                                 </DataTemplate>
  30.                             </DataGridTemplateColumn.CellTemplate>
  31.                         </DataGridTemplateColumn>
  32.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  33.                             <DataGridTemplateColumn.CellTemplate>
  34.                                 <DataTemplate>
  35.                                     <TextBlock Text="{Binding Path=UserName}"></TextBlock>
  36.                                 </DataTemplate>
  37.                             </DataGridTemplateColumn.CellTemplate>
  38.                         </DataGridTemplateColumn>
  39.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  40.                             <DataGridTemplateColumn.CellTemplate>
  41.                                 <DataTemplate>
  42.                                     <TextBlock Text="{Binding Path=LastName}"></TextBlock>
  43.                                 </DataTemplate>
  44.                             </DataGridTemplateColumn.CellTemplate>
  45.                         </DataGridTemplateColumn>
  46.                         <DataGridTemplateColumn Header="UserId" Width="SizeToCells" IsReadOnly="True">
  47.                             <DataGridTemplateColumn.CellTemplate>
  48.                                 <DataTemplate>
  49.                                     <TextBlock Text="{Binding Path=Location}"></TextBlock>
  50.                                 </DataTemplate>
  51.                             </DataGridTemplateColumn.CellTemplate>
  52.                         </DataGridTemplateColumn>
  53.                     </DataGrid.Columns>
  54.                 </DataGrid>
  55.                 <Button Content="GetDataFromDataSet" Height="37" HorizontalAlignment="Left" Margin="14,22,0,0" Name="button2" VerticalAlignment="Top" Width="183" Click="button2_Click_1" />
  56.                 <Button Content="GetDataFromUserDefinedType" Height="39" HorizontalAlignment="Left" Margin="241,20,0,0" Name="button3" VerticalAlignment="Top" Width="186" Click="button3_Click_2" />
  57.             </Grid>
  58.         </GroupBox>
  59.     </Grid>
  60. </Window>

After Completion of designing we need to Create Proxy for service to consume service:

To create Proxy Do the following:

First Copy The Address Of  Service:

Then Add System.ServiceModel  dll file from .net tab of add reference

Then RightClick on your Project select Add ServiceReference:

After Adding this proxy if you want to see things added to servicereference

first select project the click on showhidden files as shown in below diagram

Then Write Following Code In CodeBehind:

Then Satart Calling From Client:

DownloadSampleCode