Sunday, 21 August 2016

Static and Abstract Confusion

Non static class can have static and non-static Members.

Static class can not have instance members.


Non-Abstract class can not have abstract members.

Abstract class have abstract and non-abstract members.



Wednesday, 17 February 2016

2 calls in WCF

When you get 2 calls from WCF, usually means serialization problems

Tuesday, 8 December 2015

Read Service End points , Method Details in client Side using Reflection

 [HttpPost]
        [AllowAnonymous]
        public JsonResult ListServiceEndPoints()
        {
            ClientSection clientSection = (ClientSection)ConfigurationManager.GetSection("system.serviceModel/client");

            List<WcfServiceEndPointDetails> endPointDetails = new List<WcfServiceEndPointDetails>();

            for(int i = 0; i < clientSection.Endpoints.Count; i++)
            {
                var endPoint = clientSection.Endpoints[i];
                List<EndPointContractOperations> operationDetails = GetContractOperationDetails(endPoint);
                endPointDetails.Add(new WcfServiceEndPointDetails()
                {
                    EndPointName = endPoint.Name,
                    EndPointAddress = endPoint.Address.ToString(),
                    ContractName = endPoint.Contract,
                    ContractOperations = operationDetails
                });
            }
            return Json(new { Success = true, Data = endPointDetails });
        }

        /// <summary>
        /// Get Operations Details
        /// </summary>
        /// <param name="endPoint">endPoint</param>
        /// <returns>EndPoint Contract Operations</returns>
        private List<EndPointContractOperations> GetContractOperationDetails(ChannelEndpointElement endPoint)
        {
            List<EndPointContractOperations> endPointContractOperations = new EditableList<EndPointContractOperations>();

            try
            {
                ContractDescription contractDescription =
                    ContractDescription.GetContract(
                        typeof (IAuthenticationSessionApi));
                foreach (OperationDescription operation in contractDescription.Operations)
                {
                    endPointContractOperations.Add(new EndPointContractOperations()
                    {
                        OperationName = operation.Name,
                        Signature = MethodSignature(operation.SyncMethod),
                        OperationDescription = string.Empty
                    });
                }
            }
                //// Empty Catch -  If any Contract throw error then it will continue to read other Contract Operations
            catch (Exception)
            {
            }

            return endPointContractOperations;
        }

        public static string MethodSignature(MethodInfo mi)
        {
            String[] param = mi.GetParameters()
                .Select(p => String.Format("{0} {1}", p.ParameterType.Name, p.Name))
                .ToArray();


            string signature = String.Format("{0} {1}({2})", mi.ReturnType.Name, mi.Name, String.Join(",", param));

            return signature;
        }

Monday, 20 April 2015

Reflection Examples [C#]

This example shows how to dynamically load assembly, how to create object instance, how to invoke method or how to get and set property value.

Create instance from assembly that is in your project References

The following examples create instances of DateTime class from the System assembly.
[C#]
// create instance of class DateTime
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime));

[C#]
// create instance of DateTime, use constructor with parameters (year, month, day)
DateTime dateTime = (DateTime)Activator.CreateInstance(typeof(DateTime),
                                                       new object[] { 2008, 7, 4 });

Create instance from dynamically loaded assembly

All the following examples try to access to sample class Calculator from Test.dll assembly. The calculator class can be defined like this.
[C#]
namespace Test
{
    public class Calculator
    {
        public Calculator() { ... }
        private double _number;
        public double Number { get { ... } set { ... } }
        public void Clear() { ... }
        private void DoClear() { ... }
        public double Add(double number) { ... }
        public static double Pi { ... }
        public static double GetPi() { ... }
    }
}

Examples of using reflection to load the Test.dll assembly, to create instance of the Calculator class and to access its members (public/private, instance/static).
[C#]
// dynamically load assembly from file Test.dll
Assembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");

[C#]
// get type of class Calculator from just loaded assembly
Type calcType = testAssembly.GetType("Test.Calculator");

[C#]
// create instance of class Calculator
object calcInstance = Activator.CreateInstance(calcType);

[C#]
// get info about property: public double Number
PropertyInfo numberPropertyInfo = calcType.GetProperty("Number");

[C#]
// get value of property: public double Number
double value = (double)numberPropertyInfo.GetValue(calcInstance, null);

[C#]
// set value of property: public double Number
numberPropertyInfo.SetValue(calcInstance, 10.0, null);

[C#]
// get info about static property: public static double Pi
PropertyInfo piPropertyInfo = calcType.GetProperty("Pi");

[C#]
// get value of static property: public static double Pi
double piValue = (double)piPropertyInfo.GetValue(null, null);

[C#]
// invoke public instance method: public void Clear()
calcType.InvokeMember("Clear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, calcInstance, null);

[C#]
// invoke private instance method: private void DoClear()
calcType.InvokeMember("DoClear",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic,
    null, calcInstance, null);

[C#]
// invoke public instance method: public double Add(double number)
double value = (double)calcType.InvokeMember("Add",
    BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,
    null, calcInstance, new object[] { 20.0 });

[C#]
// invoke public static method: public static double GetPi()
double piValue = (double)calcType.InvokeMember("GetPi",
    BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public,
    null, null, null);

[C#]
// get value of private field: private double _number
double value = (double)calcType.InvokeMember("_number",
    BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,
    null, calcInstance, null);

Sunday, 19 April 2015

select n th row of table using jquery

  1. $(document).ready(function(){  
  2.   
  3.    //select the second row of table and change font color to red  
  4.    $('table tbody tr:nth-child(2)').css('color','red');  
  5.   
  6. });  

Sunday, 12 April 2015

Unmanaged Resource



Unmanaged -  The most common types of unmanaged resource are objects that wrap operating system resources, such as files, windows, network connections, or database connections. 

Saturday, 21 March 2015

Objects and Types in Javascript

4 types of Object
Intrinsic objects   - Date ,String .number,.....
Host Objects - Window ,document
Creating Objects -  var obj =new Object();
Activex Object

The type of all objects created with a custom constructor is object. There are only six types in JavaScript:objectfunctionstringnumberboolean, and undefined.

Sunday, 11 January 2015

REST in REST-ful

The Web is made up of many resources and a resource can be any item of interest, for example, an online book store may define book as a resource and clients may access that resource with this URL : http://www.myEbookStore.com/Books.

As a result of accessing the above URL is that the representation of the resource is returned (e.g., books.html) which results in a state change of the client. Now the end users browser is displaying more than just the home page of the online book store, a more informative and detailed state than the previous.
Thus, the client application transfers state with each resource representation. Isn't this same as browsing a website over the INTERNET ???
WWW is like a REST system and many of such services are being used in our day to day activities like purchasing something from Amazon.com, using Facebook, and even using GMail. So you are using REST, and you didn't even know it.

REST stands for Representational State Transfer. REST is not a standard but an architecture. However REST does make use of certain standards like http, URL, XML , html etc.

Consider the case of myEbookStore.com which enables its customers to :
1. get list of books
2. get detailed information about a book
3. purchase books on-line
 
image

Get List of Books :
--------------------------
http://www.myEbooksStore.com/books

Note that "how" the web service generates the books list is completely transparent to the client. All that the client knows is, if he/she submits the above URL then a document containing the list of books is returned which is obviously displayed in the browser. Since the implementation is transparent to clients, myEbooksStore.com owner is free to modify the underlying implementation of this resource without impacting clients.So we can consider REST as a loosely coupled architecture.

Here's the document that the client receives:

    <?xml version="1.0"?>
    <p:Books xmlns="http://www.myEbooksStore.com" xmlns:link="http://www.w3.org/1999/xlink">
          <Book id="0120" xlink:href="http://www.myEbooksStore.com/books/0120"/>
          <Book id="0121" xlink:href="http://www.myEbooksStore.com/books/0121"/>
          <Book id="0122" xlink:href="http://www.myEbooksStore.com/books/0122"/>
          <Book id="0123" xlink:href="http://www.myEbooksStore.com/books/0123"/>
    </p:Book>

Note that the books list has links to get detailed information about each book. This is a key feature of REST. The client transfers from one state to the next by examining and choosing from among the alternative URLs in the response document. This is something like zooming the view on Google Maps. If you want to see the map of a location in Pune, the satellite will first zoom onto India, then Maharashtra and then Pune. At first level we get a list of countries from which we select India , then list of states in India from which Maharashtra is selected and then finally we get a list of districts in Maharashtra from which Pune is selected. We can see how data is refined gradually by taking decisions at each level. Lets get back to our BookStore example.

Get Detailed Information about a Book
------------------------------------------------------
The web service makes available a URL to each book resource.For example, here's how a client requests book 0122:

http://www.myEbooksStore.com/books/0122

Here's the document that the client receives:

    <?xml version="1.0"?>
    <p:Book xmlns="http://www.myEbooksStore.com"  xmlns:link="http://www.w3.org/1999/xlink">
          <Book-ID>0122</Book-ID>
          <Name>JSON explored</Name>
          <Description>This book explains JSON</Description>
          <Versions xlink:href="http://www.myEbooksStore.com/books/0122/versions"/>
          <UnitCost currency="USD">9.20</UnitCost>
          <Quantity>10</Quantity>
    </p:Book>

Again observe how this data is linked to still more detailed data - the versions for this book may be found by traversing the versions hyperlink. Each response document allows the client to drill down to get more detailed information. Thats the whole idea of REST, Representational State Transfer.

In-short lets summarize some important points related to REST/Web Services :

  1. Client-Server model, where the client pulls representations.
  2. Stateless, meaning state of the data provider is not important. So each request from client to server should contain all the information necessary to understand the request. For example searching google.com for the word "computer" is sent to google server as http://www.google.com/#hl=en&output=search&q=computer ... so the required information is sent from client to server irrespective of the state of the server... that's true because before searching, we never worry about the state of google's server.
  3. Common interface. For example : All google search queries are accessed with a generic interface (e.g., HTTP GET, POST, PUT, DELETE) and there is no static page for all searches. Imagine having a static page like : http://www.google.com/computer.html for search results of "computer" keyword... a bad idea.
  4. Interconnected representations - the representations of any resource are interconnected using URLs, thereby enabling a client to progress from one state to another.
  5. Cache to improve network efficiency. Hence once a website is loaded all the external javascripts needed by the site will be cached.
  6. Categorizing the resources according to the requirement of a particular resource. Clients can just receive a representation of the resource, or even modify the resource. For the former, make those resources accessible using an HTTP GET. For the later, make those resources accessible using HTTP POST, PUT, and/or DELETE.
  7. Underlying implementation of REST needs to be independent of the URL or type of REST service (GET, PUT, POST, DELETE). This means a website can be built using either JSP or ASP, without impacting the service being provided to the client. Also data can be represented in JSON format or as XML format or any other structured format.

Note :  APIs built using REST or conforming to REST design/architecture are said to be RESTful.

WCF and ASP.NET Web API

WCF is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments. (ASP.NET Web APIis a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. This topic presents some guidance to help you decide which technology will best meet your needs.

Choosing which technology to use


The following table describes the major features of each technology.
WCF
ASP.NET Web API
Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them.
HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.
Enables building services that support multiple encodings (Text, MTOM, and Binary) of the same message type and allows switching between them.
Enables building Web APIs that support wide variety of media types including XML, JSON etc.
Supports building services with WS-* standards like Reliable Messaging, Transactions, Message Security.
Uses basic protocol and formats such as HTTP, WebSockets, SSL, JQuery, JSON, and XML. There is no support for higher level protocols such as Reliable Messaging or Transactions.
Supports Request-Reply, One Way, and Duplex message exchange patterns.
HTTP is request/response but additional patterns can be supported through SignalRand WebSockets integration.
WCF SOAP services can be described in WSDL allowing automated tools to generate client proxies even for services with complex schemas.
There is a variety of ways to describe a Web API ranging from auto-generated HTML help page describing snippets to structured metadata for OData integrated APIs.
Ships with the .NET framework.
Ships with .NET framework but is open-source and is also available out-of-band as independent download.
Use WCF to create reliable, secure web services that accessible over a variety of transports. Use ASP.NET Web API to create HTTP-based services that are accessible from a wide variety of clients. Use ASP.NET Web API if you are creating and designing new REST-style services. Although WCF provides some support for writing REST-style services, the support for REST in ASP.NET Web API is more complete and all future REST feature improvements will be made in ASP.NET Web API. If you have an existing WCF service and you want to expose additional REST endpoints, use WCF and the WebHttpBinding.

http://msdn.microsoft.com/en-us/library/jj823172%28v=vs.110%29.aspx

Web Service

  1. It is based on SOAP and return data in XML form.
  2. It support only HTTP protocol.
  3. It is not open source but can be consumed by any client that understands xml.
  4. It can be hosted only on IIS.

WCF

  1. It is also based on SOAP and return data in XML form.
  2. It is the evolution of the web service(ASMX) and support various protocols like TCP, HTTP, HTTPS, Named Pipes, MSMQ.
  3. The main issue with WCF is, its tedious and extensive configuration.
  4. It is not open source but can be consumed by any client that understands xml.
  5. It can be hosted with in the applicaion or on IIS or using window service.

WCF Rest

  1. To use WCF as WCF Rest service you have to enable webHttpBindings.
  2. It support HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively.
  3. To enable other HTTP verbs you have to do some configuration in IIS to accept request of that particular verb on .svc files
  4. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified
  5. It support XML, JSON and ATOM data format.

Web API

  1. This is the new framework for building HTTP services with easy and simple way.
  2. Web API is open source an ideal platform for building REST-ful services over the .NET Framework.
  3. Unlike WCF Rest service, it use the full featues of HTTP (like URIs, request/response headers, caching, versioning, various content formats)
  4. It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, unit testing that makes it more simple and robust.
  5. It can be hosted with in the application or on IIS.
  6. It is light weight architecture and good for devices which have limited bandwidth like smart phones.
  7. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML or whatever format you want to add as a MediaTypeFormatter.

To whom choose between WCF or WEB API

  1. Choose WCF when you want to create a service that should support special scenarios such as one way messaging, message queues, duplex communication etc.
  2. Choose WCF when you want to create a service that can use fast transport channels when available, such as TCP, Named Pipes, or maybe even UDP (in WCF 4.5), and you also want to support HTTP when all other transport channels are unavailable.
  3. Choose Web API when you want to create a resource-oriented services over HTTP that can use the full features of HTTP (like URIs, request/response headers, caching, versioning, various content formats).
  4. Choose Web API when you want to expose your service to a broad range of clients including browsers, mobiles, iphone and tablets.

Saturday, 3 January 2015

delete duplicate record in SQL server

create table empp(id int identity ,name varchar(30))
insert into empp values('bhanu')

select * from empp

-- for selecting duplicate record
select name ,count(*)  cnt from empp e group by e.name having count(*) >1

-- for selecting non-duplicate record
select name ,count(*)  cnt from empp e group by e.name having count(*) =1


--with having
delete from empp  where id  in (select max(id) from empp  group by name having count(*)>1)
--without having

delete from empp  where id not in (select max(id) from empp  group by name)

DELETE FROM emp WHERE ID NOT IN (SELECT MIN(ID) FROM emp GROUP BY FName)

delete from tableName where UniqueColumn NOT IN (select MIN(UniqueColumn) from tableName GROUP BY DuplicateRecoedColumn/DeletedDuplicateColumn)

Saturday, 6 December 2014

iis 7.5 handler "extensionlessurlhandler-integrated-4.0" has a bad module "managedpipelinehandler" in its module list

First Repair .NET Framework

and configure your iis using

http://www.sitefinity.com/documentation/documentationarticles/installation-and-administration-guide/install-sitefinity/configuring-the-iis-to-host-sitefinity-projects

Tuesday, 18 November 2014

Send model data from view to controller using ajax call

 $("#btnSubmit").click(function () {
            var tommy = {
                FromDate: $("#FromDate").val(),
                ToDate: $("#ToDate").val()
            };

            $.ajax({
                url: "@Url.Action("SearchVehicle", "Default")",
               type: "POST",
               contentType: "application/json",
               data: JSON.stringify({ vehicleSearchParameter: tommy }),
               success: function (response) {
                   response ? alert("It worked!") : alert("It didn't work.");
               }
           });
        })

vehicleSearchParameter is a class  file model
tommy  is javascript object

public ActionResult SearchVehicle(VehicleSearchParameter vehicleSearchParameter, string Command)
        {
}

Friday, 29 August 2014

Binding Dropdown using EF in MVC

Model Code:

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

namespace RAVDEVMVC.Models
{
    public class Vehicles
    {
        public  SelectList VehicleList { get; set; }
    }
}

Controller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using RAVDEVMVC.Models;

namespace RAVDEVMVC.Controllers
{
    public class HomeController : Controller
    {
     
        public ActionResult Index()
        {
            RAVEntities RE = new RAVEntities();
            IList<vehicle> objVehicleList = (from data in RE.vehicles
                                             select data).ToList();
            vehicle objvehicle = new vehicle();
            objvehicle.Vehicle1 = "Select";
            objVehicleList.Insert(0, objvehicle);
            SelectList objmodeldata = new SelectList(objVehicleList,"","Vehicle1",0);

            Vehicles objVehicleModel = new Vehicles();
            objVehicleModel.VehicleList = objmodeldata;
            return View(objVehicleModel);
        }
    }
}

View Code
@model RAVDEVMVC.Models.Vehicles

@Html.DropDownList("ddlVehicle",Model.VehicleList)
         

Autocomplete TextBox in MVC

RAVEntities  is a Entity Model

Controller Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using AutoComplete.Models;

namespace AutoComplete.Controllers
{
    public class AutoCompleteController : Controller
    {
        //
        // GET: /AutoComplete/

        public ActionResult Index()
        {
            return View();
        }

        public JsonResult getData(string term) {
            var result = new List<KeyValuePair<string, string>>();
            RAVEntities re=new RAVEntities();
            IList<vehicle> objVehicleList= (from data in re.vehicles
                               select data).ToList();
            foreach (var item in objVehicleList)
            {
                result.Add(new KeyValuePair<string, string>(item.Vehicle1, item.Vehicle1.ToString()));
            }
            var result3 = result.Where(s => s.Value.ToLower().Contains(term.ToLower())).Select(w => w).ToList();
            return this.Json(result3, JsonRequestBehavior.AllowGet);
        }

    }
}

View Code

@{
    ViewBag.Title = "Index";
    Layout = null;
}
@Styles.Render("~/Content/themes/base/css")
@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryui")

<script type="text/javascript">
    $(document).ready(function () {
        $("#Country").autocomplete({
            source: function (request, response) {
                $.ajax({
                    url: "/AutoComplete/getData",
                    type: "POST",
                    dataType: "json",
                    data: { term: request.term },
                    success: function (data) {
                        response($.map(data, function (item) {
                            return { label: item.Key, value: item.Value };
                        }))

                    }
                })
            },
            messages: {
                noResults: "", results: ""
            }
        });
    })
</script>
@Html.TextBox("Country")
<input id="tags" type="text" />

Wednesday, 30 April 2014

procedure with in ,out ,in out parameter in pl/sql

create or replace procedure test211(idd   IN number,
                                    names varchar2,
                                    NAME2 OUT VARCHAR,
                                    X     IN NUMBER,
                                    Y     IN OUT NUMBER) is
begin
  insert into test21 values (idd, names);
  SELECT NAMES INTO NAME2 FROM TEST21 T WHERE T.IDD = IDD;
  IF X = 1 THEN
    Y := 1;
  ELSE
    Y := 2;
  END IF;
end;



DECLARE IDD NUMBER;
 NAMES VARCHAR2(55);
  NAME2 VARCHAR2(20);
   X NUMBER;
    Y NUMBER;
BEGIN
IDD := 81;
 NAMES := 'BHANU';
 X := 1;
  Y := 0;
   test211(IDD, NAMES, NAME2, X, Y);

END;

Friday, 25 April 2014

Order by and RowNUM in ORACLE

SELECT ROWNUM SLNO, QRY.* FROM (SELECT TRADE_PK,TRADE_ID, TRADE_NAME,SELFLAG
  FROM (SELECT DISTINCT TMT.TRADE_MST_PK TRADE_PK,
                        TMT.TRADE_CODE TRADE_ID,
                        TMT.TRADE_NAME TRADE_NAME,
                        '1' SELFLAG
          FROM TRADE_MST_TBL TMT
         WHERE TMT.TRADE_MST_PK IN (222, 226 , 227, 224, 225)
       
         UNION
         SELECT DISTINCT TMT.TRADE_MST_PK TRADE_PK,
                        TMT.TRADE_CODE TRADE_ID,
                        TMT.TRADE_NAME TRADE_NAME,
                        '' SELFLAG
          FROM TRADE_MST_TBL TMT
         WHERE TMT.TRADE_MST_PK NOT IN (222, 226 , 227, 224, 225))
         ORDER BY SELFLAG ASC)QRY

Wednesday, 12 February 2014

to convert a currency in comma seprated values

function digits (ExcessAmt) {
                             return ExcessAmt.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
                                }

Call this function ,pass number and collect in any variable

Saturday, 4 January 2014

WCF example

Introduction: 

Here I will explain what WCF (windows communication foundation) is, uses of windows communication foundation and how to create and use windows communication foundation in c#.

What is WCF (windows communication foundation) Service?

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.
Advantages of WCF
     1)    WCF is interoperable with other services when compared to .Net Remoting where the client and service have to be .Net.

     2)    WCF services provide better reliability and security in compared to ASMX web services.

     3)    In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.

     4)    WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service; following table provides detailed difference between them.

Features
Web Service
WCF
Hosting
It can be hosted in IIS
It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming
[WebService] attribute has to be added to the class
[ServiceContract] attribute has to be added to the class
Model
[WebMethod] attribute represents the method exposed to client
[OperationContract] attribute represents the method exposed to client
Operation
One-way, Request- Response are the different operations supported in web service
One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML
System.Xml.serialization name space is used for serialization
System.Runtime.Serialization namespace is used for serialization
Encoding
XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom
XML 1.0, MTOM, Binary, Custom
Transports
Can be accessed through HTTP, TCP, Custom
Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols
Security
Security, Reliable messaging, Transactions

A WCF Service is composed of three components parts viz,

1) Service Class - A WCF service class implements some service as a set of methods.

2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.

3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:

Address: The endpoints specify an Address that defines where the endpoint is hosted. It’s basically url.

Ex:http://localhost/WCFServiceSample/Service.svc

Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. Various components of the WCF are depicted in the figure below.
  • "A" stands for Address: Where is the service?
  • "B" stands for Binding: How can we talk to the service?
  • "C" stands for Contract: What can the service do for us?
Different bindings supported by WCF

Binding
Description
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions
WSDualHttpBinding
Web services with duplex contract and transaction support
WSFederationHttpBinding
Web services with federated security. Supports transactions
MsmqIntegrationBinding
Communication directly with MSMQ applications. Supports transactions
NetMsmqBinding
Communication between WCF applications by using queuing. Supports transactions
NetNamedPipeBinding
Communication between WCF applications on same computer. Supports duplex contracts and transactions
NetPeerTcpBinding
Communication between computers across peer-to-peer services. Supports duplex contracts
NetTcpBinding
Communication between WCF applications across computers. Supports duplex contracts and transactions
BasicHttpBinding
Basic Web service communication. No security by default
WSHttpBinding
Web services with WS-* support. Supports transactions

Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.

Different contracts in WCF

Service Contract

Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

Data Contract

Data contract describes the custom data type which is exposed to the client. This defines the data types, which are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are returning or passing parameter to the method.

Message Contract

Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Fault Contract

Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.

Overall Endpoints will be mentioned in the web.config file for WCF service like this

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="http://localhost:8090/MyFirstWcfService/SampleService.svc"binding="wsHttpBinding" contract="IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>


Creating simple application using WCF

First open Visual Studio and click file --> Select New --> Website Under that select WCF Service and give name for WCF Service and click OK 



Once you created application you will get default class files including Service.cs and IService.cs



Here IService.cs is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.

Now open IService.cs write the following code

[ServiceContract]
public interface IService
{
[OperationContract]
string SampleMethod(string Name);
}

After that open Service.cs class file and write the following code 

public class Service : IService
{
public string SampleMethod(string Name)
{
return "First WCF Sample Program " + Name;
}
}


Here we are using basicHttpBinding for that our web.config file system.serviceModel code should be like this and I hope no need to write any code because this code already exists in your web.config file insystem.serviceModel

<system.serviceModel>
<services>
<service name="Service" behaviorConfiguration="ServiceBehavior">
<!-- Service Endpoints -->
<endpoint address="" binding="wsHttpBinding" contract="IService">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>

Our WCF service ready to use with basicHttpBinding. Now we can call this WCF Service method console applications

After completion of WCF service creation publish or deploy your WCF Service in your system. If you don’t’ have idea on deploy check this post publish or deploy website

After completion of deploy webservice now we can see how to use WCF Service in our console application

Calling WCF Service using Console Application

To call WCF service we have many ways like using console app, windows app and web app but here I am going for console application.

Create new console app from visual studio select project type as console application gives some name as you like.



After Creation Console application now we need to add WCF reference to our console application for that right click on your windows application and select Add Service Reference


Now one wizard will open in that give your WCF service link and click Go after add your service click OK button.


After completion of adding WCF Service write the following code in Program.cs class file Main method

static void Main(string[] args)
{
ServiceReference1.ServiceClient objService = new ServiceClient();
Console.WriteLine("Please Enter your Name");
string Message = objService.SampleMethod(Console.ReadLine());
Console.WriteLine(Message);
Console.ReadLine();
}
After that open your app.config file and check your endpoint connection for WCF Service reference that should be like this

<endpoint address=" http://localhost/WCFServiceSample/Service.svc"
binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"
contract="ServiceReference1.IService" name="WSHttpBinding_IService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>