Thursday, October 31, 2013

how to add wcf service to asp net mvc project

how to add wcf service to asp net mvc project


1) Create a New Project Select ASP.NET MVC 4 APPLICATION
2) Add New Item -> select WCF Service
         name it as "wcfservice1"

     Service Interface:

    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        String DoWork();
    }

     Service Class:

  [AspNetCompatibilityRequirements(RequirementsMode= AspNetCompatibilityRequirementsMode.Allowed)]

    public class Service1 : IService1
    {
        public String DoWork()
        {
            return "HELLO WCF SERVICE";
        }
    }

3) just right click on wcfService.svc run it, U will get medata data.

  http://localhost:port/wcfservice.svc

4)  How to Consume WCF Service in ASP.NET MVC 4


5)  Add Service Reference 

right click on Reference folder -> Add Service Reference.,

enter WCF Service URL i.e got in Step 3)

It will generate WCF Service Proxy class through which service methods can be called.

6) Add Controller Class Name it as Default 2

7) Create WCF Service Client in Default2 controller class

      Service1Client client = new Service1Client();

8)  Add following code in Index Action Method

      public ViewResult Index(){
            ViewBag.WCFDATA = client.DoWork();
            return View("~/Views/Default2/Index.cshtml",(object)client.DoWork());
  }

9) Add View to Index Method(right click on Index Method click on Add View)

Add following code to this View

<h3>
How to consume WCF Service in ASP.NET MVC @ViewBag.WCFDATA
    </h3>
<b>Using Model Class<</b>
@Model


10) Just run the Controller
  http://localhost:port/Default2


OUTPUT


Index

How to consume WCF Service in ASP.NET MVC HELLO WCF SERVICE

Using Model Class< HELLO WCF SERVICE      

Wednesday, October 30, 2013

WCF vs. ASP.NET Web API

WCF vs. ASP.NET Web API


1. WCF is a One stop development for SOAP Services and REST services.
2.ASP.NET WEB API  is a lightweight 
3.WCF supports many transports where as WEb API supports http only.
4.WCF Rest Service methods decorated with WebGet or WebInvoke
   where as Web API the class is derived from APIController,

5. WCF has many decorated attributes WEB API simplified version of WCF 
6. URI path differs in WCF and WEB API
    WEb API uses MVC URL routing technique
7. Web API as a Service Layer may not be optimum solution from a performance standpoint. because there is an HTTP overhead,
   In this case TCP or Named Pipes could be better choice. 
so WCF outshine WEB API.

8.ASP.NET WEB API is well suited for communication across the firewall.

How to Consume Web API in JQUERY ajax

How to Consume Web API in JQUERY ajax


1) Create a HTML Page/ASPX Page etc.,

2) Add following input elements and 4 buttons for POST,DELETE,PUT,GET

3) Div Element to display all results   


        <b>Id:</b><input type="text" value="" id="txtId" /><br />
        <b>cusomer Name:</b><input type="text" value="" id="txtName" /><br />
        <b>Date Joined:</b><input type="date" value="" id="doj" /><br />
        <b>EmailID:</b><input type="email" value="" id="txtEmail" /><br />
        <b>Mobile:</b><input type="text" value="" id="txtMobile" /><br />
       
        <input type="button" value="POST" onclick="javascript: CustomerWebApi('POST')" />&nbsp;&nbsp;
        <input type="button" value="PUT" onclick="javascript: CustomerWebApi('PUT')" />&nbsp;&nbsp;
        <input type="button" value="DELETE" onclick="javascript: CustomerWebApi('DELETE')" />&nbsp;&nbsp;
        <input type="button" value="GET" onclick="javascript: CustomerWebApi('GET')" />&nbsp;&nbsp;
        <br />
        <div id="cusomersTbl"></div>

4) Add JQUERY Ajax function to do CRUD operations on Web API


        <script type="text/javascript">
            function CustomerWebApi(verb) {
                var customerJson = getmyjson(verb);
                alert(customerJson+getUrl(verb));
                var rquest=$.ajax({
                    type: verb,
                    url: getUrl(verb),
                    async: true,
                    data: getmyjson(verb),
                    dataType:"json"
                });

                rquest.done(function(customer)
                {
                    alert(customer);
                    DisplayData(customer);
                });

                rquest.fail(function (jqXHR, textStatus) {
                    alert(textStatus+jqXHR.statusCode);
                });
            }

            function getUrl(verb) {
                var URL="http://localhost:42340/api/customer";
                if (verb == "DELETE" || verb == "PUT") URL = URL + "/" + document.getElementById("txtId").value;
                return URL;
            }

            function getmyjson(verb) {
                var jsonCustomer="";
                if (verb == "POST" || verb == "PUT") {

                    var isoDate = new Date($("#doj").val()).toISOString();
                    var customer = {
                        custId: $("#txtId").val(),
                        Name: $("#txtName").val(),
                        DOJ:isoDate,
                        szEmailID:$("#txtEmail").val(),
                        Mobile:$("#txtMobile").val()
                    }
                    return customer;
                }
                else if (verb == "GET" || verb == "DELETE");

                return jsonCustomer;
            }

            function DisplayData(customers) {
                var divE = document.getElementById("cusomersTbl");
                for (i = 0; i < customers.length; i++) {
                    divE.innerHTML += customers[i].custId + " " + customers[i].Name + "<br/>";
                }

            }

        </script>


Here is the Output



Tuesday, October 29, 2013

How to Consume WEB API in Java Script

How to Consume WEB API in Java Script


1) Create a HTML Page/ASPX Page etc.,

2) Add following input elements and 4 buttons for POST,DELETE,PUT,GET

3) Div Element to display all results   


        <b>Id:</b><input type="text" value="" id="txtId" /><br />
        <b>cusomer Name:</b><input type="text" value="" id="txtName" /><br />
        <b>Date Joined:</b><input type="date" value="" id="doj" /><br />
        <b>EmailID:</b><input type="email" value="" id="txtEmail" /><br />
        <b>Mobile:</b><input type="text" value="" id="txtMobile" /><br />
       
        <input type="button" value="POST" onclick="javascript: CustomerWebApi('POST')" />&nbsp;&nbsp;
        <input type="button" value="PUT" onclick="javascript: CustomerWebApi('PUT')" />&nbsp;&nbsp;
        <input type="button" value="DELETE" onclick="javascript: CustomerWebApi('DELETE')" />&nbsp;&nbsp;
        <input type="button" value="GET" onclick="javascript: CustomerWebApi('GET')" />&nbsp;&nbsp;
        <br />
        <div id="cusomersTbl"></div>

4) Add Javascript Ajax function to do CRUD operations on Web API


Here JSON object  has/required 5 elements. custID,Name,DOJ,szEmailID,Mobile


    <script type="text/javascript">
       
        function CustomerWebApi(verb) {
            var url = "http://localhost:42340/api/customer";
            var jsonCustomer = "";
            
            if (verb == "DELETE" || verb == "PUT") {

                url = url + "/" + document.getElementById("txtId").value;
            }
            if (verb == "POST" || verb == "PUT") {

               jsonCustomer = "";

               jsonCustomer += "\"custId\"" + ":"+document.getElementById("txtId").value + ",";
                jsonCustomer += "\"Name\"" + ":\"" + document.getElementById("txtName").value + "\",";

                var isoDate = new Date(document.getElementById("doj").value).toISOString();
                jsonCustomer += "\"DOJ\"" + ":\"" + isoDate + "\",";

                jsonCustomer += "\"szEmailID\"" + ":\"" + document.getElementById("txtEmail").value + "\",";

                jsonCustomer += "\"Mobile\"" + ":\"" + document.getElementById("txtMobile").value+"\"";
                //jsonCustomer = JSON.stringify(jsonCustomer);

                jsonCustomer = "{" + jsonCustomer + "}";
            }
            if (verb == "GET") jsonCustomer = "";

 alert(jsonCustomer+url+verb);

            var xmlHttp = new XMLHttpRequest();
            xmlHttp.open(verb, url, false);
            xmlHttp.setRequestHeader("Content-type", "application/json");
            xmlHttp.send(jsonCustomer);
            //alert(xmlHttp.status);
            //alert(xmlHttp.responseText); alert(xmlHttp.statusText);

            if (verb == "GET") {
                var customers = eval('(' + xmlHttp.responseText + ')');
                DisplayData(customers);
            }
          
        }

        function DisplayData(customers)
        {
            var divE = document.getElementById("cusomersTbl");
            for (i = 0; i < customers.length; i++) {
                divE.innerHTML += customers[i].custId + " " + customers[i].Name + "<br/>";
            }

        }
    </script>


Press on GET gets all records from the database
Press POST button adds a record to the database 
Press PUT modifies specific record User must specify CustID
Press DELETE deletes record from the Database User must specify custID

How to create Web API using code first Entity Framework 5.0

How to create Web API using code first Entity Framework 5.0

1) Create ASP.NET MVC 4 application

2) Select Web API Project template

3) Create a Customer class

         public class Customer
    {
        [Key]
        public int custId { get; set; }
        public String Name { get; set; }
        public DateTime DOJ { get; set; }
        public String szEmailID { get; set; }
        public string Mobile { get; set; }
    }
     

4) Create CustomerModel class which is Derived from DBContext

 public class CustomerModel:DbContext
    {
        public CustomerModel() : base("CustDB") { }

        protected override void OnModelCreating(DbModelBuilder mb)
        {
           // mb.Entity<Customer>().ToTable("Customers");
        }


        public DbSet<Customer> customers { get; set; }
    }

   CustDB is a Connection String Specified in Web.config
 <add name="CustDB"
providerName="System.Data.SqlClient" 
connectionString="Server=C4968397007;Trusted_connection=yes;database=mydb;"/>

5) Build the Project


6) Create a Controller Class Select "API controller with read/write operations using Entity Frame "
      Name it as "CustomerController"
      In this 
        select DataContext as CustomerModel
                  Model Class as Customer

7)  That;s it

8) Just run the Web API class in Browser

    http://localhost:port/api/Customer


U will get Empty JSON/XML data.



How to Insert,UPDATE,DELETE on Web API 

pls see below articles