Showing posts with label Ajax. Show all posts
Showing posts with label Ajax. Show all posts

Saturday, March 21, 2020

How to write an HTTP Handler to feed an AUTOCOMPLETE JQUERYUI widget

In this tutorial we'll learn how to write an HTTP Handler to feed an AUTOCOMPLETE JQUERYUI widget 
This JQueryUI Autocomplete will be showing as follows :



Step by step How to write an HTTP Handler to feed an AUTOCOMPLETE JQUERYUI widget



First, we create a new ASPNET HTTP HANDLER, in Visual Studio, as follows:

using System.Web.Script.Serialization;
namespace WEBAPI_AJAX

    public class EmployeeHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            string t = context.Request.QueryString["term"];

            Func<string, bool> pred = (w) => { if (w.StartsWith(t)) return true; else return false; };

            List<string> l = new List<string>()  { "albert","andrew","asterix","ddddd","eeeeee","fffffff","gggggggg","hhhhhh","iiiiii"};

            l = l.Where(pred).ToList();
            //context.Response.ContentType = "text/plain";
            context.Response.Write(new JavaScriptSerializer().Serialize(l));
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}





Then, we create the HTML file :

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery UI Autocomplete - Default functionality</title>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <link rel="stylesheet" href="/resources/demos/style.css">
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <link href="../Content/bootstrap.min.css" rel="stylesheet" />
    <script>
        $(()=>{
       
            $("#tags").autocomplete({
                source:  'http://localhost:58776/HANDLER1.ASHX'
            });
        });
    </script>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="jumbotron">
                <div class="form-group">
                    <label for="tags" class="control-label col-md-2">Tags: </label>
                    <div class="col-md-10">
                        <input class="form-control" id="tags">
                    </div>
                </div>
            </div>
        </div>
    </div>

</body>
</html>




That's all.... 
In this tutorial we've seen how to write an HTTP Handler to feed an AUTOCOMPLETE JQUERYUI widget. 
Happy programming.....
      By Carmel Shvartzman
כתב: כרמל שוורצמן











Wednesday, August 21, 2019

MVC Ajax WebGrid with Sorting and Paging

In this Step by step MVC Ajax WebGrid with Sorting and Paging in 10 Minutes 
   we see how to build an Ajax enabled WebGrid using an jQueryUI Theme  in 10 minutes, following this simple steps :

1) Use MVC scaffolding and build your Model and Views
2) Select a jQueryUI Theme & download it
3) In the "Index" View, replace the Table with a WebGrid and enable Ajax


All the code in this tutorial , can be downloaded from the following GitHub repository:
https://github.com/CarmelSoftware/MVC_WebGrid

This is how this sortable paged Ajax WebGrid is shown in the Ripple Mobile Emulator , Nexus Galaxy settings:


MVC Ajax WebGrid with Sorting and Paging


MVC Ajax WebGrid with Sorting and Paging in 10 Minutes


The whole process of creating an Ajax WebGrid with a jQueryUI Theme , is as following:

1) Use MVC scaffolding and build your Model and Views:

First build your MVC project using EDM & Controller scaffolding.


2) Select a jQueryUI Theme & download it

Browse to http://jqueryui.com/themeroller/  , select your Theme, and download it.
After you unzip the folder, you'll see several files in it.
You do not need all of them. Just copy the following 2 files and folder to your MVC project:
MVC Ajax WebGrid with Sorting and Paging1



Paste the files inside your MVC project as follows:

MVC Ajax WebGrid with Sorting and Paging2


As you can see, the ONLY files that we'll use from the jQueryUI theme are the following:

1) JS folder :
     "jquery-X.X.X.min.js" (here get the latest version of jQuery)
     "jquery-ui.min.js"

2) CSS folder :
     "jquery-ui.css"


Add the following references to the _Layout file:

MVC Ajax WebGrid with Sorting and Paging3

There is no need of referencing the "images" folder.
Also, you get the latest version of jQuery framework : at this moment, that version is 2.1.4


3) In the "Index" View, replace the Table with a WebGrid and enable Ajax

Then go to the "Index" view, and comment the Table that was scaffolded there.
Add the following markup to replace it:

<link href="~/Content/index.css" rel="stylesheet" />

@{ var grid = new WebGrid(Model, new[] { "Title", "DatePosted", "MainPicture" }, rowsPerPage: 3, ajaxUpdateContainerId: "gridDIV"); }


<div id="gridDIV">
@grid.GetHtml(tableStyle:"webgrid-table",headerStyle:"webgrid-header",

    columns: new[] {

        grid.Column("ID",format:(item) =>  item.GetSelectLink(item.BlogID.ToString()) ) ,
        grid.Column("Title",format:@<a href='/Blog/Comments/@item.BlogID'><b>@item.Title</b></a>),
        grid.Column("DatePosted","DatePosted", (item) => String.Format("{0:dd/MM/yyyy}", item.DatePosted != null ? item.DatePosted : DateTime.Now )),
        grid.Column("Picture",format:(item) =>
        { return new MvcHtmlString("<a href='/Blog/Comments/" + item.BlogID +
            "'><img src='/Images/"+item.MainPicture+"' style='width:100px;height:100px;'></img></a>");
        }),
  
        grid.Column(
            format:@<div class="ActionsTH">
            @Html.ActionLink("Edit", "Edit", new { id=item.BlogID })
            @Html.ActionLink("Details", "Details", new { id=item.BlogID })
            @Html.ActionLink("Delete", "Delete", new { id=item.BlogID })
        </div>)
    })
</div>

This code enable Ajax on the Grid, which comes already with Sorting and Paging functionality.
Of course, customize this code with your Model's properties.

As you can see, we also reference a "~/Content/index.css" file:
Inside this file, i added background style found in the "images" folder, such as "images/ui-bg_fine-grain" corresponding to the Theme "Pepper-Grinder" .
If you select another Theme, replace the backgrounds accordingly.
Create this CSS file in the Content folder , and paste this style in it:


body {
    background: #f7f3de url("images/ui-bg_fine-grain_15_f7f3de_60x60.png") 50% 50% repeat;
}

.webgrid-table {
    font: italic 11px Verdana;
    width: 100%;
    display: grid;
    border-collapse: separate;
    border: solid 1px #98BF21;
    background: #f8f7f6 url("images/ui-bg_fine-grain_10_f8f7f6_60x60.png") 50% 50% repeat;
    padding: 5px 5px 5px 5px;
    text-align: center;
}

.webgrid-header th {
    width: 150px;    
    background: #eceadf url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFFFFF !important;
    font: 900 14px Verdana !important;
    padding: 5px 5px 5px 5px;
    text-align: center;
}

.ActionsTH {
    width: 50px;
    background: #eceadf url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFFFFF !important;
    font: 900 14px Verdana !important;
    padding: 5px 5px 5px 5px;
    text-align: center;
    width: 180px;
}

.webgrid-footer, .webgrid-footer a {
    background-color: #c67f1c;
    color: #FFF;
    font: 900 14px Verdana;
    padding: 3px 3px 3px 3px;
}

.webgrid-alternating-row {
    background-color: #e5d773;
    padding: 5px 5px 5px 5px;
}

.title-column {
    font: 900 13px Verdana;
    text-align: center;
}

.webgrid-img {
    width: 150px;
    height: 150px;
}

.webgrid-table a {
    text-decoration: none;
    color: #808080;
}


Important:
If you do not see the Ajax working (), it is because the jQuery scripts are lacking.
Just cut the jQuery.js file from the _Layout file to the <head> tag :
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
</head>


THE END

To use a Mobile devices Emulator, take a look at this short tutorial on installing the FREE Ripple Emulator.


That's all. Our WebGrid will be displayed this way:
MVC Ajax WebGrid with Sorting and Paging4

MVC Ajax WebGrid with Sorting and Paging5

MVC Ajax WebGrid with Sorting and Paging6





      by Carmel Schvartzman


כתב: כרמל שוורצמן



Monday, October 26, 2015

MVC Ajax WebGrid with Administrator Buttons

This article is about an MVC Ajax WebGrid with Administrator Buttons and Sorting and Paging . 
  Here we see how to build an Ajax enabled WebGrid , which in case of an User Administrator will display management buttons (Edit - Delete) , and otherwise will not.

In case of an Administrator, the WebGrid will be displayed like this:

MVC Ajax WebGrid with Administrator Buttons





In case of a common User, the WebGrid will be displayed this way:
MVC Ajax WebGrid with Administrator Buttons



All the code in this tutorial , can be downloaded from the following GitHub repository:
https://github.com/CarmelSoftware/MVC_WebGrid_Admin

This is how this Administrator's Ajax WebGrid is shown in a Mobile Emulator :

MVC Ajax WebGrid with Administrator Buttons

In the case of a common User:

MVC Ajax WebGrid with Administrator Buttons



MVC Ajax WebGrid with Administrator Buttons


The whole code for creating this Ajax WebGrid with Management functionality , can be obtained from the following GitHub rep:
https://github.com/CarmelSoftware/MVC_WebGrid_Admin


Add the following markup  to the "Index" view:

@model IEnumerable<MyGrid_BL.Blog>

@{
    ViewBag.Title =  "Ajax WebGrid with Administrator Role Check";
    WebGrid grid = new WebGrid(Model, new[] { "Title", "Text", "DatePosted", "MainPicture", "Blogger" },
        rowsPerPage:2,ajaxUpdateContainerId:"GridDiv");

    IEnumerable<WebGridColumn> oColumns = new[] {

        grid.Column("ID",format:(item) =>  item.GetSelectLink(item.BlogID.ToString()) ) ,
        grid.Column("Title",format:@<a href='/Blog/Details/@item.BlogID'><b>@item.Title</b></a>),
        grid.Column("DatePosted","DatePosted", (item) => String.Format("{0:dd/MM/yyyy}", item.DatePosted != null ? item.DatePosted : DateTime.Now )),
        grid.Column("Picture",format:(item) =>
        { return new MvcHtmlString("<a href='/Blog/Details/" + item.BlogID +
            "'><img src='/Images/"+item.MainPicture+"' style='width:100px;height:100px;'></img></a>");
        })
    };

    if (User.IsInRole("Admin"))
    {
        oColumns = oColumns.Concat(new[] {grid.Column(
            format:@<div class="ActionsTH">
            @Html.ActionLink("Edit", "Edit", new { id=item.BlogID })<br />
            @Html.ActionLink("Details", "Details", new { id=item.BlogID })<br />
            @Html.ActionLink("Delete", "Delete", new { id=item.BlogID })
        </div>) });
    }
    
}

<h2>@ViewData["Title"]</h2>

<div id="GridDiv">
    @grid.GetHtml(tableStyle:"webgrid-tableStyle",headerStyle:"webgrid-headerStyle",footerStyle:"webgrid-footerStyle",alternatingRowStyle:"webgrid-alternatingRowStyle",columns: oColumns) </div>
<p style="text-align:center;">
     
    <input type="button"   value="Create New" onclick="javascript:location='/Blog/Create'" class="btn btn-default"/>
</p>



This code enable the Management Buttons on the Grid, only in case of a Power User such as an Administrator.

The code to set some User to the "Admin" Role, must be added to the "Acount" Controller, at the Register Action, and is as follows:

[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                try
                {
                    if (!Roles.RoleExists("Admin"))
                    {
                        Roles.CreateRole("Admin");
                    }
                    WebSecurity.CreateUserAndAccount(model.UserName, model.Password);

                    string sAdmins = ConfigurationManager.AppSettings["Admins"];
                    string[] oAdmins = sAdmins.Split(';');

                    WebSecurity.Login(model.UserName, model.Password);

                    foreach (string sAdmin in oAdmins)
                    {
                        if (string.Compare(model.UserName, sAdmin) == 0
                                                &&
                            !Roles.IsUserInRole("Admin"))
                        {
                            Roles.AddUserToRole(model.UserName, "Admin");
                        }
                    }



                    return RedirectToAction("Index", "Home");
                }
                catch (MembershipCreateUserException e)
                {
                    ModelState.AddModelError("", ErrorCodeToString(e.StatusCode));
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

And these are the AppSettings to the Web.config file:


<appSettings>
    <add key="Admins" value="sa;sa1;sa2;sa3"/>
  </appSettings>

As you can see, we also reference a "~/Content/WebGrid.css" file:


body {
    background: #f7f3de url("images/ui-bg_fine-grain_15_f7f3de_60x60.png") 50% 50% repeat;
}

.webgrid-tableStyle {
    font: italic 11px Verdana;
    width: 100%;
    display: grid;
    border-collapse: separate;
    border: solid 1px #98BF21;
    background: #f8f7f6 url("images/ui-bg_fine-grain_10_f8f7f6_60x60.png") 50% 50% repeat;
    padding: 5px 5px 5px 5px;
    text-align: center;
    border-radius:10px;
}

.webgrid-headerStyle th {
    width: 250px;    
    background: #c67f1c url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFFFFF !important;
    font: 900 14px Verdana !important;
    padding: 5px 5px 5px 5px;
    text-align: center;
    height:50px;
}

.ActionsTH {    
    background: #eceadf url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFFFFF !important;
    font: 900 14px Verdana !important;
    padding: 5px 5px 5px 5px;
    text-align: center;
    width: 180px;
}

.webgrid-footerStyle, .webgrid-footerStyle a {
    background:#c67f1c url("images/ui-bg_fine-grain_10_eceadf_60x60.png") 50% 50% repeat;
    color: #FFF;
    font: 900 14px Verdana;
    padding: 3px 3px 3px 3px;
    height:50px;
}

.webgrid-alternatingRowStyle {
    background: #f8f7f6 url("images/ui-bg_fine-grain_10_f8f7f6_60x60.png") 50% 50% repeat;
    padding: 5px 5px 5px 5px;
}

.title-column {
    font: 900 13px Verdana;
    text-align: center;
}

.webgrid-img {
    width: 150px;
    height: 150px;
}

.webgrid-tableStyle a {
    text-decoration: none;
    color: #808080;
}
select {
      width: 200px;
    }


Important:
If you do not see the Ajax working  , it can be because some jQuery scripts are missing.
Just cut the jQuery.js file from the _Layout file to the <head> tag :
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/jqueryui")
</head>



To install a Mobile Emulator, take a look at this tutorial on installing the FREE Ripple Emulator.


That's all. Our Administrator WebGrid will be displayed this way:

MVC Ajax WebGrid with Administrator Buttons

MVC Ajax WebGrid with Administrator Buttons






      by Carmel Schvartzman


כתב: כרמל שוורצמן


Tuesday, June 9, 2015

jQueryMobile Toggle and Reflow Tables For Android and BlackBerry

Here we see Step by step How to create jQueryMobile Toggle and Reflow Tables For Android and BlackBerry
In this post we build in 20 minutes a jQuery Mobile App , with a toggle Table , where you can hide or display its columns,  for use on all kind of Mobile devices : iPad, iPhone, Nexus , BlackBerry, Nokia,  Acer ,
The data displayed on this table will be loaded in Json format via Ajax.
This Mobile App will look like this:
jQueryMobile Toggle and Reflow Tables For Android and BlackBerry

jQueryMobile Toggle and Reflow Tables For Android and BlackBerry    1


How to create jQueryMobile Toggle and Reflow Tables For Android and BlackBerry



For this post of jQuery Mobile , we'll need the  jQuery and jQueryMobile Frameworks, so  enter http://jquerymobile.com/ and jQuery web site , and get the latest versions of the files via CDN  . We  will also use a Mobile Emulator, so please refer to this short tutorial on Ripple Emulator setup.
Also, this basic   "First jQueryMobile App" Tutorial explains the installation of both the frameworks and the emulator in detail.
After you got the references, add them to the Head of the HTML5 file:
jQueryMobile Toggle and Reflow Tables For Android and BlackBerry   2



First, we'll add a Header with a NavBar , using the data-role="page" and the data-role="header" with a "fixed" attribute to fix it as the user scrolls the screen :
jQueryMobile Toggle and Reflow Tables For Android and BlackBerry    3


Now we create a "main" div with our table: we use the data-role=table and the data-mode=columntoggle, which allows the user to display/hide the columns. If you don't use "columntoggle", the table will be displayed as "Reflow" mode, meaning that ALL columns are displayed, and in small screens, all data is grouped in chunks corresponding to each row.
Then you define a data-priority directive from 1 (most important field) to 6 (less important column).
If you do not define a data-priority for a column, it will be always displayed:

jQueryMobile Toggle and Reflow Tables For Android and BlackBerry    4



We also define a button for calling the function that loads the table data.

Finally, we write the markup for a Footer with a Navbar as follows:
jQueryMobile Toggle and Reflow Tables For Android and BlackBerry   5



The script which loads the data includes a call to the jQuery  $.ajax method, to the URL where a text file contains JSON data for the table.
The HTTP request uses a GET method and, this is really important, we tell the server that we are expecting data in JSON format, meaning that the request's "Accept" header will include "application / json".
We add two callback functions : error and success.
In case of success, we perform a $.each() loop over the JSON data, which is built on key/value pairs, where the Key is the "id" field, and the Value is the Customer object.
For each customer, we append to the Table a Row with a Cell (<td>) per column:
jQueryMobile Toggle and Reflow Tables For Android and BlackBerry   6



Very important too, we REFRESH the Table after adding the Row, so that the Toggle functionality will include the appended rows.


We customized this Mobile using the following style in a CSS3 file:
jQueryMobile Toggle and Reflow Tables For Android and BlackBerry   7





And this is how the jQuery Mobile Toggle Table looks like:

Toggle and Reflow Tables For Android and BlackBerry

Reflow Tables For Android and BlackBerry

Android and BlackBerry

jQueryMobile Toggle and Reflow Tables For Android

jQueryMobile Toggle and Reflow Tables

jQueryMobile Toggle and Reflow







Hoping this post was helpful for you...
Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן



Thursday, June 4, 2015

jQueryMobile using Ajax to load Json data to a Table

Here we review Step by step jQueryMobile using  Ajax  to load Json data to a Table For Android and BlackBerry
In this article we create in 20 minutes a jQuery Mobile App to load Json data to a toggle Table , where you can hide or display its columns,  via Ajax calls . This App is for use on all kind of Mobile devices : Nexus , iPad, iPhone, BlackBerry, Nokia,  Acer ,  ...
The data will be loaded in Json format via Ajax, in order to be displayed on this table .
This jQuery Mobile App looks like this:
jQueryMobile using  Ajax  to load Json data to a Table

jQueryMobile using  Ajax  to load Json data to a Table   1




jQueryMobile using  Ajax  to load Json data to a Table For Android and BlackBerry



For this article on jQuery Mobile , we'll be using the  jQuery and jQueryMobile Frameworks, so  browse to http://jquerymobile.com/ and jQuery , and obtain the latest versions of the frameworks via CDN  . If you want to use a Mobile Emulator, please refer to the following short tutorial on the Ripple Emulator.

After you got the files , add them to the Head of the HTML5 file:
jQueryMobile using  Ajax  to load Json data to a Table    2



First, add a Header with a NavBar , by making use of the data-role="page" and the data-role="header" , adding also a "fixed" attribute to fix the header in its place when the user scrolls the screen :
jQueryMobile using  Ajax  to load Json data to a Table    3


Create a "main" div element containing our table.  Use the data-role=table and the data-mode=columntoggle directives, which allow to display/hide the columns. However , if you don't write "columntoggle", the table will be shown in "Reflow" mode, then ALL columns will be displayed, and all the data will be grouped in chunks per row.
Inside the table,  define to each field a data-priority directive from 1 (most priority field) to 6 (less important column).
Notice that if you do not set a data-priority for a field, it will always be displayed:

jQueryMobile using  Ajax  to load Json data to a Table   4






We also write a button to call the function that brings the table data.

Finally, we code the markup for making a Footer with a Navbar :
jQueryMobile using  Ajax  to load Json data to a Table    5



The javascript which brings the data includes using the jQuery  $.ajax function, sending requests to the URL where is stored a file containing JSON data .
This HTTP GET request  tells the server that the data is expected in JSON format, so that the request's "Accept" header will include "application / json".

In case of successful performance, we do an $.each() loop on the received JSON data in the response, which includes key/value pairs, where the Key is the "id"  , and the Value is the Customer  JSON object.
Then, for each customer, we add to the tbody of the Table a Row with a Cell per column:

jQueryMobile using  Ajax  to load Json data to a Table    6


Is imperative that you REFRESH the Table after adding the Rows, therefore the table's Toggle functionality will work on the new rows.

We added also some style to this Mobile using the following  CSS3 file:
jQueryMobile using  Ajax  to load Json data to a Table  7


All the code can be downloaded from the following GitHub repository:


This is how the jQuery Mobile Toggle Table looks :
jQueryMobile using  Ajax  to load Json data

Json
load Json

to load Json

  Ajax  to load Json

using  Ajax  to load Json



We hope that this article was helpful for you...
Happy programming.....

      by Carmel Schvartzman


כתב: כרמל שוורצמן


Wednesday, November 19, 2014

How to expose a WCF Service through many endpoints and multiple bindings

  
In this post we'll explore how to expose one single WCF Service through many  endpoints and multiple bindings. We'll have only one C# WCF code, and we'll make it implement several interfaces in order to expose several endpoints with many different bindings. Technically, we'll create several WCF services via creating several interfaces, but the C# class implementing them will be running the SAME CODE. We'll enable that unique C# class code to handle both Soap and HTTP requests, proceeding from backends calls, from jQuery Ajax calls, and from standard HTTP web calls. Some calls will be made programmatically in C# from some Application Back-End . Other, REST calls, will proceed from Ajax or from regular web calls. But ALL requests will be handled by the SAME C# service class.

How to expose a WCF Service through many endpoints and multiple bindings


Another interesting feature of this exercise will be, we are not creating a WCF Application, but adding a WCF Web Service to an existing MVC application.
The schema of our WCF app will be as follows : one unique C# Class, which implements two Interfaces as Services Contracts, finally exposed through three Endpoints:
How to expose a WCF Service through many endpoints and multiple bindings



One of the Endpoints will handle Soap calls, one HTTP web calls, and another one Ajax HTTP web calls. The first one will use an basicHttpBinding, and the former two, an webHttpBinding.

The WCF service we are building will handle HTTP requests based on the REST (REpresentational State Transfer) architecture, designed by Dr. Fielding at 2000. Our WCF sample will receive HTTP requests depending what it intends to do:

1) CREATE an item :     HTTP "POST" request
2) RETRIEVE  an item : HTTP "GET" request
3) RETRIEVE  ALL items : HTTP "GET" request

We'll want to create an WCF Web Service with CRUD functionality, which fetches and persists all data proceeding from a RESTful Web Service, based on a Model as follows:


Step 1 - Add a WCF Service to your application



Step 2 - Write the C# code for the WCF Service


[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class BlogService : IBlogService,IBlogService1
    {
        public string GetBlogs()
        {
            Models.BlogEntities ctx = new Models.BlogEntities();
            ctx.Configuration.ProxyCreationEnabled = false;
            List<Blog> data = ctx.Blogs.ToList();

            return new JavaScriptSerializer().Serialize(data);
        }

        public string GetBlog(string Id)
        {
            Models.BlogEntities ctx = new Models.BlogEntities();
            ctx.Configuration.ProxyCreationEnabled = false;
            int id = Convert.ToInt32(Id);
            Blog data = ctx.Blogs.Where(b => b.BlogID == id).FirstOrDefault();

            return new JavaScriptSerializer().Serialize(data);
        }

        public string CreatePost(Blog post)
        {
            Blog responsePost = post;
            return new JavaScriptSerializer().Serialize(responsePost);
        }
    }

Why do we create first the service implementation and after that the interfaces? Because we know exactly what our class is supposed to do, but only later we'll decide how many Service Contracts we'll need.

Step 3 - Create the C# interfaces as Service Contracts

In this example, we create two Service Contracts through two Interfaces: the first one look this way:



[ServiceContract]
    public interface IBlogService
    {
        [OperationContract]
        [WebGet]
        string GetBlogs();
        [OperationContract]
        [WebGet]
        string GetBlog(string Id);
        [WebInvoke(Method = "POST")]
        [OperationContract]
        string CreatePost(Blog post);
    }

The second one is similar but has the Operation Contracts names changed:


[ServiceContract]
    public interface IBlogService1
    {
        [OperationContract(Name = "GetBlogsSoapREST")]
        [WebGet]
        string GetBlogs();
        [OperationContract(Name = "GetBlogSoapREST")]
        [WebGet(UriTemplate="GetBlog1/{id}")]
        string GetBlog(string Id);
        [WebInvoke(Method = "POST")]
        [OperationContract(Name = "CreatePostSoapREST")]
        string CreatePost(Blog post);
    }

Then, we make our Service Class to implement the Interfaces:




Step 4 - Declare the WCF Service & its Endpoints

At the web.config, declare the service with its service behavior:



This service behavior states that the service metadata can be fetched , using the declaration:

<serviceBehaviors >
        <behavior  name="MultipleInterfacesAndEndpointsSvc" >
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>

Also we want that , at this development stage of our application, the errors could be view by us:
includeExceptionDetailInFaults="true"

Now we create three Endpoints:


 <service name="WCF_RESTful.BlogService" 
               behaviorConfiguration="MultipleInterfacesAndEndpointsSvc" >
       <endpoint 
         address="RESTfulAjax" 
         behaviorConfiguration="RESTfulAjaxBehavior"  
         binding="webHttpBinding" 
         contract="WCF_RESTful.IBlogService" />
        <endpoint 
          address="RESTfulNoAjax" 
          behaviorConfiguration="RESTfulNoAjaxBehavior"
          binding="webHttpBinding" 
          contract="WCF_RESTful.IBlogService1" />
        <endpoint 
          address="SoapEndpoint"  
          binding="basicHttpBinding" 
          contract="WCF_RESTful.IBlogService1" />
      </service>

The first two are for REST calls, that's why we use webHttpBinding. Each one exposes a different Service Contract (interface).
The last is for Soap calls, and therefore uses basicHttpBinding.
Now , to handle regular HTTP REST calls, we need to bind a "webHttp" behavior to the Endpoint:



 <behavior  name="RESTfulNoAjaxBehavior" >
          <webHttp />
        </behavior>

And to handle Ajax web calls, we declare another behavior using "enableWebScript", which also includes the "webHttp" directive:

Step 5 - Routing

Finally, reroute the path since we are inside an MVC application:

routes.IgnoreRoute("BlogService.svc/{*pathInfo}");


Build & run, and let's call our WCF from :
1) Soap request: we create a service reference in some MVC application, and discover our WCF with its methods:

The WSDL schema appears as this:



Now, just build the back end client Proxy and use the service.

2) Web HTTP REST request: XML response : 


And for getting just one record :



As you see, the response is given in XML format. Notice that we needed to call an "GetBlog1" method: that's because we defined an UriTemplate at the Operation Contract , and because of the format "GetBlog1/{id}" we don't need to specify the "GetBlog1?id=4" argument: 


3) Ajax REST HTTP request: Json response : 



Here, the response is Json. And to get only one record:




That's all!! 
In this tutorial we've learn How to expose a WCF Service through many endpoints and multiple bindings.  

Happy programming.....
      By Carmel Shvartzman
כתב: כרמל שוורצמן