Showing posts with label WCF. Show all posts
Showing posts with label WCF. Show all posts

Wednesday, September 30, 2015

Self Hosting Code in WCF

class Program
    {
        static void Main(string[] args)
        {
       
            Type srvcinfo=typeof(Greet);
            //Create a URI to serve as the base address
            // Address as well binding
            Uri uri=new Uri("https://localhost:8086/Myservice");

 //Create ServiceHost         
            ServiceHost host=new ServiceHost(srvcinfo,uri);

 //Add a service endpoint  

            host.AddServiceEndpoint(typeof(IGreet), new WSHttpBinding(), "ws");

//Start the Service    

            host.Open();
            Console.WriteLine("Hosted the service");
            Console.Read();


        }
    }

Monday, July 6, 2015

WebApi Part1



WEBAPI ,
Is an HTTP service
Is designed for broader reach (different client , browsers, tablets,phones etc)
It uses HTTp as a protocol and not transport protocols
Lets see how we create one

Create New Projects->web ->WebAPi
You can see the structure is similar to your Web MVC Projects
Go to ->controllers->values controller
You can see the GET,POST,PUT,DELETE methods
Now run the solutions
You will end up in default home page .
See the WebApiConfig File

      config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }}
You see the url is similar to MVC but you don’t see the action here instead you see the api/controllers . actions are your GET,PUT,POST ,DELETE methods

Run the solutions navigate to api/Values

http://localhost:54725/api/Values

It will either return Json Doc or XML doc 


<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>


You can also use fiddler to see results in different formats
Here is how I created new WEBApi .
Create a model class “team”

public class Team
    {
        [Key]
        public int TeamID { get; set; }
        [Required]
        public string TeamName { get; set; }
        public string CoachName { get; set; }
    }

Then create a controller with Entity framework scaffolding
You will see the controller has all the HTTp methods
Run the solution
Initially you will not get any results since its empty
Now either youu can make use of fiddler or what I have use is RestClient
Addon in firefox

Set method:post
content-type:application/json
body : {
"TeamName":"Team1","CoachName":"Tom"
}
Hit send you can see the result.
You can view in xml format also 


·  Status Code: 201 Created
·  Cache-Control: no-cache
·  Content-Length: 206
·  Content-Type: application/xml; charset=utf-8

1.  <Team xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/WebApplication1.Models">
2.    <CoachName>Tom</CoachName>
3.    <TeamID>1</TeamID>
4.    <TeamName>Team1</TeamName>
5.  </Team>



Friday, January 30, 2015

Learning WCF



I was used to create web service but then I was once working on a migration application project where I was supposed to convert all web services to WCF services. I was new to it. I still am. But will little hands on experience. Let me share how I learned creating and consuming WCF services
Ok before that. my manager asked me a simple questions . “Supreet, what do you know about message binding, contracts, and endpoints? without which you cannot proceed with it.
I said “I don’t know technical definitions. What I know is you should know:
Where the service located is
How can we communicate or consume the service,
And what the parameters the service seeks are.”
Now that suffices completely. You can now map it with technical jargons.

I thought of simple webpage with functionality of doing mathematical calculation to learn WCF
I created new Projects from Visual studio 2013 of type WCF be application
 

Now I created a class (svc file )which was supposed to be an interface and define the methods to be implemented later . called IMathService.svc
[ServiceContract]
    public interface IMathService
    {
        [OperationContract]
        Int32 Sum(Int32 a, Int32 b);

        [OperationContract]
        Int32 difference(Int32 a, Int32 b);

        [OperationContract]
        Int32 Product(Int32 a, Int32 b);

       
    }
}

Now I declared a class which can actually implement the interface class for maths operation


public class MathService : IMathService
    {
      public  Int32 Sum(Int32 a, Int32 b)
    {
        return a+b;
    }

     
      public  Int32 difference(Int32 a, Int32 b)
{
        return a-b;
}

     
       public Int32 Product(Int32 a, Int32 b)
{
    return a * b;
}
    }
}

Now my service is ready to use.
Let see how we can consume this service. To do that, I created a Simple User Interface which holds UI controls to do maths calculation and display result.
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      num1  <asp:TextBox ID="txt1Num1" runat="server"></asp:TextBox>
       
      num2  <asp:TextBox ID="txtNum2" runat="server"></asp:TextBox>

        <asp:DropDownList ID="DropDownList1" runat="server">
            <asp:ListItem>Add</asp:ListItem>
            <asp:ListItem>sub</asp:ListItem>
            <asp:ListItem>product</asp:ListItem>
        </asp:DropDownList>
     result   <asp:TextBox ID="txtResult" runat="server"></asp:TextBox>
        <asp:Button ID="btnDisplay" runat="server" Text="Display" OnClick="btnDisplay_Click" />
    </div>
       
    </form>
</body>
</html>
Now the most important thing is to add the web reference to consume it
Now on the button click event I implemented the corresponding functionality
using MathApp.ServiceReference1;

namespace MathApp
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        MathServiceClient client = new MathServiceClient();
        protected void Page_Load(object sender, EventArgs e)
        {
    

        }

        protected void btnDisplay_Click(object sender, EventArgs e)
        {
            if(DropDownList1.SelectedItem.Text=="Add")
            {
                var res = client.Sum(Int32.Parse(txt1Num1.Text), Int32.Parse(txtNum2.Text));
                txtResult.Text=res.ToString();
            }
            else if (DropDownList1.SelectedItem.Text == "sub")
            {
                var res = client.difference(Int32.Parse(txt1Num1.Text), Int32.Parse(txtNum2.Text));
                txtResult.Text = res.ToString();
            }
           else
            {
                var res = client.Product(Int32.Parse(txt1Num1.Text), Int32.Parse(txtNum2.Text));
                txtResult.Text = res.ToString();
            }
        }
    }
}
That’s it. You are now ready to test the WCF service. Run the solution
So that’s how I tried to make it very simple to learn how to Create WCF services.
By the way the technically endpoint, binding and contract details are available in the web.config as below
   <endpoint address="http://localhost:18647/MathService.svc" binding="basicHttpBinding"
        bindingConfiguration="BasicHttpBinding_IMathService" contract="ServiceReference1.IMathService"
        name="BasicHttpBinding_IMathService" />
Will post more on advanced way of creating WCF service