Create a Simple WCF Service Client against Pubs Database using EF, LINQ – Part II

This tutorial is in continuation to the creation of simple WCF service – PubsService. Kindly go through the following link to get started with the PART – I.

Create a Simple WCF service against Pubs Database using EF, LINQ  – Part I

NOTE:-
  1. In this tutorial (which is PART – II), we create a small website in ASP.Net 4.0 and we shall use a WebForm (named: PubsServiceTestPage.aspx) as a client to our service (which we created in former tutorial).
  2. We Use the inline model of Webform (not the codebehind model).
  3. We perform the following actions with our client:-
    1. Get all the Authors and display them in the Dropdownlist.
    2. Select a Author and display his corresponding books using a Repeater.
    3. Modify and save the book details back to database.
  4. To test the Client, we need the service to be running in the server, that can be simply manipulated by starting another instance of VS 2010 and running (Ctrl + F5) the PubsService.svc.cs.
Get Started:-
  1. Open VS 2010, File -> New Web Site
  2. Select -> C#,Select -> .net Framework 4.0, Select -> ASP.Net Web Site, Give Name -> PubsServiceClient
  3. Click OK

Now add the reference to the PubsService (which we created in another solution).

  1. Start a new instance of VS 2010. Open samplePubsService Solutions. And then start the WCF service with Ctrl + F5.
  2. A WCF Test Client will be opened. Copy the URL of PubsService.svc (it will be like http://localhost:1460/PubsService.svc).
  3. Now back to the PubsServiceClient Web Site, Right click the Web Site Folder, Select -> Add Service Reference.
  4. In the Add Service Reference Dialog, paste the URL of PubsService.svc in the address location (NOTE: This should be done without closing the other instance of VS 2010, as this literally means the service is running in development server, which is a must).
  5. Click GO. Give namespace name -> PubsServiceReference.
  6. 6. Click OK. A reference to our PubsServiceReference is now added to the web site.

Once you add the service reference, a ServiceModel tag will be added to the web.config file as shown below –

<system.serviceModel>
  <bindings>
   <basicHttpBinding>
    <binding name="BasicHttpBinding_IPubsService" closeTimeout="00:01:00"
     openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00"
     allowCookies="false" bypassProxyOnLocal="false" hostNameComparisonMode="StrongWildcard"
     maxBufferSize="65536" maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
     messageEncoding="Text" textEncoding="utf-8" transferMode="Buffered"
     useDefaultWebProxy="true">
     <readerQuotas maxDepth="32" maxStringContentLength="8192" maxArrayLength="16384"
      maxBytesPerRead="4096" maxNameTableCharCount="16384" />
     <security mode="None">
      <transport clientCredentialType="None" proxyCredentialType="None"
       realm="" />
      <message clientCredentialType="UserName" algorithmSuite="Default" />
     </security>
    </binding>
   </basicHttpBinding>
  </bindings>
        <client>
   <endpoint address="http://localhost:1460/PubsService.svc" binding="basicHttpBinding"
    bindingConfiguration="BasicHttpBinding_IPubsService" contract="PubsServiceReference.IPubsService"
    name="BasicHttpBinding_IPubsService" />
  </client>
    </system.serviceModel>

To code against the Service Reference, we create a webform –

  1. Right Click the Website (PubsServiceClient) Project Folder in the Solution explorer, Select -> Add New Item, Select -> C#.
  2. Select -> WebForm, Give Name -> PubsServiceTestPage.aspx, Uncheck all the checkboxes on the right side bottom.
  3. Click ADD.

Let’s Code against that test page to test our Pubs Service.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            PubsServiceReference.PubsServiceClient client = new PubsServiceReference.PubsServiceClient();

            List<PubsServiceReference.Author> authors = client.GetAllAuthors().ToList();

            ddlAuthors.DataSource = from data in authors
                                    select new
                                    {
                                        Name = data.authorLName + " " + data.authorFName,
                                        Id = data.authorId
                                    };
            ddlAuthors.DataValueField = "Id";
            ddlAuthors.DataTextField = "Name";
            ddlAuthors.DataBind();
            
            ddlAuthors.Items.Insert(0,new ListItem("Select","0"));
        }
        
    }

    protected void btnGetBooks_Click(object sender, EventArgs e)
    {
        if (ddlAuthors.SelectedValue.ToString() != "0")
        {
            PubsServiceReference.PubsServiceClient client = new PubsServiceReference.PubsServiceClient();

            PubsServiceReference.Author authorDetails = client.GetAuthorById(ddlAuthors.SelectedValue.ToString());
            List<PubsServiceReference.bookByAuthor> lstBooks = client.GetBookOfAuthor(authorDetails).ToList();
            rptrBooks.DataSource = lstBooks;
            rptrBooks.DataBind();

            if (lstBooks.Count != 0)
            {
                mvDisplay.ActiveViewIndex = 0;
            }
            else
            {
                NoResultFound("No Books for Selected Author!!!");
            }
        }
        else
        {
            NoResultFound("Sorry! No Results Found");
        }
    }

    private void NoResultFound(string result)
    {
        mvDisplay.ActiveViewIndex = 1;
        lblNoResult.Text = result;
    }

    protected void btnSave_Click(object sender, EventArgs e)
    {
        PubsServiceReference.PubsServiceClient client = new PubsServiceReference.PubsServiceClient();
        List<PubsServiceReference.bookByAuthor> lstbooks = new List<PubsServiceReference.bookByAuthor>();
        
        foreach (RepeaterItem ri in rptrBooks.Items)
        {
            PubsServiceReference.bookByAuthor book = new PubsServiceReference.bookByAuthor();

            book.titleId = ((Literal)ri.FindControl("ltlTitleId")).Text;
            book.title = ((TextBox)ri.FindControl("txtTitle")).Text;
            book.pubdate = Convert.ToDateTime(((TextBox)ri.FindControl("txtPubdate")).Text);
            book.type = ((TextBox)ri.FindControl("txtType")).Text;

            lstbooks.Add(book);
        }

        try
        {
            client.SaveBookDetails(lstbooks.ToArray());
            lblSuccessfulSave.Text = "Successfully Saved";
            mvDisplay.ActiveViewIndex = 2;
        }
        catch(Exception ex)
        {
            lblSuccessfulSave.Text = ex.Message;
        }
        
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        Select Author : 

        <asp:DropDownList ID="ddlAuthors" runat="server">
        </asp:DropDownList>

        <br />

        <asp:Button ID="btnGetBooks" runat="server" Text="Get Books" 
            onclick="btnGetBooks_Click" />

        <br />

        <asp:MultiView ID="mvDisplay" runat="server" ActiveViewIndex="2">
            <asp:View ID="viewActive" runat="server">
            <asp:Repeater ID="rptrBooks" runat="server">
                <ItemTemplate>
                    Book ID : 
                    <asp:Literal ID="ltlTitleId" runat="server" Text='<%#Eval("titleId") %>'></asp:Literal>
                    <br />

                    Book title : 
                    <asp:TextBox ID="txtTitle" runat="server" Text='<%#Eval("title") %>'></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" 
                    ControlToValidate="txtTitle" ErrorMessage="*"></asp:RequiredFieldValidator>
                    <br />

                    Book Type : 
                    <asp:TextBox ID="txtType" runat="server" Text='<%#Eval("type") %>'></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server" 
                    ControlToValidate="txtType" ErrorMessage="*"></asp:RequiredFieldValidator>
                    <br />

                    Book Pub date : 
                    <asp:TextBox ID="txtPubdate" runat="server" Text='<%#Eval("pubdate","{0:MM/dd/yyyy}") %>'></asp:TextBox>
                    <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server" 
                    ControlToValidate="txtPubdate" ErrorMessage="*"></asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="CompareValidator1" runat="server" ControlToValidate="txtPubdate" 
                    Operator="DataTypeCheck" Type="Date" ErrorMessage="Should be a date"></asp:CompareValidator>
                </ItemTemplate>
                <SeparatorTemplate>
                    <hr />
                </SeparatorTemplate>
            </asp:Repeater>

            <br />

                <asp:Button ID="btnSave" runat="server" Text="Save Details" OnClick="btnSave_Click" />                
            </asp:View>
                
            <asp:View ID="viewInActive" runat="server">
                <asp:Label ID="lblNoResult" runat="server"></asp:Label>
            </asp:View>

            <asp:View ID="viewDefault" runat="server">
            <asp:Label ID="lblSuccessfulSave" runat="server"></asp:Label>
            </asp:View>
        </asp:MultiView>

    </div>
    </form>
</body>
</html>
OUTPUT:-

Disclaimer:

All coding and suggestions made in the above discussion is strictly in point of view of the author. It is neither mentioned any where nor even concluded that this is the only possible way to go with, as there will be always a chance for a new approach in achieving the same requirement (in context of programming). The above mentioned code is strictly written and explained for the sake of new comers to C# and ASP.NET world.

You may also like...

One Pingback/Trackback

  • Goran Tesic

    Hello Rami,

    Fist of all I want to thank you for writing this sample. It was very helpful for me because based on your article I’ve created my WCF service and WPF application that uses it.

    I have a question, if you can answer. I want to ask you about how to host this WCF service?

    I created my WCF service and it’s hosted inside VS2010 by ASP.NET Development Server. It contains web.config file that looks like this:

    As you can see it works with entity framework.

    I also have WPF client application that uses WCF service and all works fine inside VS2010 on the same machine. The app.config file of client WPF application looks as follows:

    How can I use IIS 7.0 to host my WCF service or any other type of host? I want to use WPF client application on some another machine? What should I do in that case?

    Thank you in advance.

    Regards,

    Goran Tesic

  • RamiVemula

    Hi Goran,

    Its very easy to host a WCF application in IIS. Or else you can even you can create a host according to your wish.

    Try the below link – http://msdn.microsoft.com/en-us/netframework/wcf-screencasts

    Those got of all kinds of possibilities with WCF hosting.

    In case you ran into troubles ping me back. I can always help you.

    But because of my tight schedule if i dont reply you in couple of days, then dont feel bad.

    Thanks/Regards,
    Rami.

  • Chandradev

    Hi
    Your article is very nice.

    I have created some WCF file and consume in asp.net project. It is working fine on local server. If i have to host on remote service,then i have to host like general asp.net project or is there some special process to do before hosting on remote server ?

  • Muhammad Ishfaq

    Hi Rami Vemula

    Bundles of thanks for your full and complete example and it is easy to understand.

    Regards
    Muhammad Ishfaq

  • Leon

    Than you for such a nice sample.

    I just have one question.
    Is it possible to cache the data that returned from the database?
    So, if data is not changed service will return cashed data.If data are changed it should be cached again.

    Thanks,

    Leon.

  • RamiVemula

    @Leon – Yes, you do have a cache mechanism. you can use Cache Object in C# and set expiry time on it. http://msdn.microsoft.com/en-us/library/6hbbsfk6(v=vs.100)

  • Benny Blanco

    Excellent work !!! I have been searching for a WCF service with LINQ and EF and this one is way the best. Keep up the good work and many developers in the world I am sure will take your sample as a reference to do more elaborated stuff.

    Thanks very much for your work !!!

  • K L P Naidu

    Hi Rami Vemula,

    Thanks for giving Clear example to easily understand.

  • Pingback: Web Service Coding « Lloyd's Project()

  • anilkumar

    Very good article thank you very much………………
    can you provide MVC sample page like the above Example…….
    iam very new for MVC

  • Zak Ahmad

    Excellent work,This is best article on Wcf with entity framework/linq .Thanks..!!