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

Monday, September 16, 2013

How to Use Session Object in asp.net mvc 4


How to Use Session Object in asp.net mvc 4
CRUD OPERATIONS on LIST Object IN ASP.NET MVC 4


2)  Create a Equivalent class for this Profile Table  in Model folder


public          class Profile
{
   public int ID{get;set;}
  public String Name{get;set;}
  public String Mobile{get;set;}
  public String EmailID{get;set;}
    public DateTime? doj{get;set;}
}

3) Add a controller 

               right click on Controller Folder->Click on Add Controller name it as ProfileController  Select  template as 

4) Create  a  List of Profile object
   List<Profile> profiles = new  List<Profile>()
   {  
new Profile{Name="Pete",Mobile="2023034004",EmailID="pete@yahoo.com",doj=new DateTime(2013,12,12)},

new Profile{Name="Hans",Mobile="4073035005",EmailID="hans@gmail.com",doj=new DateTime(2000,1,22)},

};
5) Index method -> add View
     select Model class as Profile, Scaffolding as List

add following code in Index Method.


        public ActionResult Index()
        {
           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>();
                     
            }
            else 
                              Session["Profiles"]=profiles;
                            

            return View(profiles);
        }


5) In Create method

              add View   select Model class as Profile, Scaffolding as Create

   2 Create methods will be created 
               1. Create will allow user to input data
                2. To Post user entered data to server

        public ActionResult Create()
        {
              //right click on this method Click on "Add View"
              //Select Model class as Profile
              //Scaffolding as Create

                 return View();
        } 

6) in Create(FormCollection) method 


Change  from Create(FormCollection) to Create(Profile p) and then
add following code.

   //This method is called whenever user posts the data
        [HttpPost]
        public ActionResult Create(Profile p)//FormCollection collection)
        {
            try
            {


           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>();
                     
            }
                 profiles.add(p);
                 Session["Profiles"]=profiles;
                 
                return RedirectToAction("Index");

            }
            catch
            {
                return View();
            }
        }

7. Add Edit View

        right click on Edit Method View Select Model class as Profile, Scaffolding as Edit


        public ViewResult Edit(int id)
        {

           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>();
                     
            }
           Profile profile = profiles.find(id);
            return View(profile);
        }


//Once user updates the record clicks on Save button, the information will be saved to database and then return to Index Page, which again queries all records from the database.

        //
        // POST: /Profile/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, Profile p)
        {
            try
            {
                // TODO: Add update logic here

           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>();
                     
            }
           Profile profile = profiles.find(id);
           profile.Name = p.Name;
            profile.Mobile = p.Mobile;
           profile.EmailID = p.EMailID;
           profile.doj = p.doj;
          
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }



7. Add Details View

        right click on Details Method View Select Model class as Profile, Scaffolding as Details


        public ActionResult Details(int id)
        {
           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>();
                     
            }
           Profile profile = profiles.find(id);

            return View(profile);

        }





8. Add Delete View

        right click on Delete Method View Select Model class as Profile, Scaffolding as Delete

           2 Delete Methods will be displayed
                        1. Delete method displays record details 
                         2.Second Delete method Posts delete record details


        public ActionResult Delete(int id)
        {

           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>();
                     
            }
           Profile profile = profiles.find(id);

            return View(profile);
        }



//Change FormCollection to Profile object


        [HttpPost]
        public ActionResult Delete(int id, Profile p)//FormCollection collection
        {
            try
            {
           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>();
                     
            }
           Profile profile = profiles.find(id);
           profiles.Remove(profile);
          
Session["Profiles"]=profiles;
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }


Here is the complete code of ProfileController


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcApplication2.Models;

namespace MvcApplication2.Controllers
{
    public class ProfileController : Controller
    {


         List<Profile> profiles = new  List<Profile>()
   {  
new Profile{Name="Pete",Mobile="2023034004",EmailID="pete@yahoo.com",doj=new DateTime(2013,12,12), ID=101},

new Profile{Name="Hans",Mobile="4073035005",EmailID="hans@gmail.com",doj=new DateTime(2000,1,22), ID=102}
   };

        //
        // GET: /Profile/

        public ActionResult Index()
        {
           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>;
                     
            }
            else 
                              Session["Profiles"]=profiles;
                            

            return View(profiles);
        }

         public ActionResult Create()
        {
              //right click on this method Click on "Add View"
              //Select Model class as Profile
              //Scaffolding as Create

                 return View();
        } 


         [HttpPost]
        public ActionResult Create(Profile p)//FormCollection collection)
        {
            try
            {
           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>;
                     
            }
            p.ID = GetNextProfileID();
                 profiles.Add(p);
                 Session["Profiles"]=profiles;
                 
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

         private int GetNextProfileID()
         {
             if (Session["Profiles"] != null)
             {
                 profiles = Session["Profiles"] as List<Profile>;

             }

             return (from p in profiles
                     select p.ID).Max() + 1;
         }
        public ViewResult Edit(int id)
        {

           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>;
                     
            }

           Profile profile = profiles.SingleOrDefault(p => p.ID == id);
            return View(profile);
        }

        [HttpPost]
        public ActionResult Edit(int id, Profile p)
        {
            try
            {
                // TODO: Add update logic here

           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>;
                     
            }
           Profile profile = profiles.SingleOrDefault(pp => pp.ID == id);
           profile.Name = p.Name;
            profile.Mobile = p.Mobile;
           profile.EmailID = p.EmailID;
           profile.doj = p.doj;
          
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

         public ActionResult Details(int id)
        {
           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>;
                     
            }
           Profile profile = profiles.SingleOrDefault(p => p.ID == id);

            return View(profile);

        }

         public ActionResult Delete(int id)
        {

           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>;
                     
            }
           Profile profile = profiles.SingleOrDefault(p => p.ID == id);

            return View(profile);
        }

        [HttpPost]
        public ActionResult Delete(int id, Profile p)//FormCollection collection
        {
            try
            {
           if(Session["Profiles"] != null)
           {
                         profiles =Session["Profiles"] as List<Profile>;
                     
            }
           Profile profile = profiles.SingleOrDefault(pp => pp.ID == id);
           profiles.Remove(profile);
          
Session["Profiles"]=profiles;
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}