Skip to main content

WCF Basic

WCF
- windows communication foundation (.net 3.0)
- communication framework
- enables us to expose CLR type services and consume exisitng services as CLR types
- Different communication technologies in the world - webservices (asmx), web services enhancements(wse), messaging (msmq), .net enterprise services (ES), .net remoting
- used for building service oriented applications
- eg: websevice for weather - consumes zip code and outputs forecast
- wcf service is based on contract ( implemented  as an interface decorated with the attribute [ServiceContractAttribute] )
[ServiceContract]
public interface IWeatherForecastService
{
    [OperationContract]
    public WeatherForecast GetForeCast(int zipCode);
}
- Address : where the service will be found [ServiceContract]
public interface IWeatherForecastService
{
    [OperationContract]
    public WeatherForecast GetForeCast(int zipCode);
}
ABC od WCF
- Address: where the service will be found scheme://domaon[:port]/path (e.g.: http://localhost:8080/MyWCFService ). 
- Binding :Protocols used by specific endpoint(http, tcp, msmq)
- Contract : Expresses what the service does (can have an app with multiple channels)
- Endpoint : combination of ABC
- Consumer of sevice creates a proxy. This Proxy is what the consumer uses to communicate with the host and basically is an empty type that exposes all operations in a service contract, and hides serialization/sending over wire details. A single proxy, uses a single endpoint.
- WeatherForecast type is a class we wrote and it represents a business object that conveniently holds all data related to the forecast. When sending this object to a consumer it will be serialized.
Conclusion: We have a host and client who agree upon a contract.  Our host exposes one or more EndPoints which are a combination of Address, Binding and Contract. On the other side our client uses a Proxy (this proxy is tied to a specified EndPoint thus also tied to a particular Contract). The actual communication related details are abstracted in Channels and Behaviors.
Ask these to yourself
   -  First, think of the contract (What am I trying to do?!)
   -  Secondly, think of where you will host it, and what technology you will use to host it.  
   -  Finally think of the other parts like authentication.
1. Create a 'WCF Service Application'
2. Add a new WCF Service file (.svc). [name.svc and Iname.cs will be created]
3. Add this in .cs file
namespace HelloWorldService
{
    [ServiceContract]
    public interface IHelloWorld
    {
        [OperationContract]
        string sayHello(string name);
    }
}
4. Add this in .svc file
namespace HelloWorldService
{
   public class HelloWorld : IHelloWorld
    {
        public string sayHello(string name)
        {
            return "Hello " + name;
        }
    }
}
5. We just can run the application and use the default bindings
6. To test the method we can also run WCF Test Client (in C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE) and pass value to the method. We can see the output in 2 formats - XML, formated

The request:
http://schemas.xmlsoap.org/soap/envelope/
">
 
            xmlns="http://schemas.microsoft.com/ws/2005/05/addressing/none">                 http://tempuri.org/IHelloWorld/sayHello>
 

 
    http://tempuri.org/
">
      Jeroen
   
 
The response:http://schemas.xmlsoap.org/soap/envelope/
">
 
 
    http://tempuri.org/
">
      Hello Jeroen
   
 

WCF CLIENT - will consume this service
client can be created
- by using metadata exposed by the EndPoint to generate proxies on the fly
- by pre-distribute the metadata as a definition of the interface, or a dll that contains the IHelloWorld interface.
1. Create a console app and add a refernce to our WCF service (add service refernce : address : http://localhost:5558/HelloWorld.svc
2. write
static void Main(string[] args)
{
    // Create a new HelloWorldClient object
    HelloWorldReference.HelloWorldClient client = new HelloWorldReference.HelloWorldClient();
    // Write the response from the sayHello method
    Console.WriteLine(client.sayHello("Jeroen"));
    // Close the WCF connection
    client.Close();
    Console.Read();
}



Types of Contracts / Services:
1. Service Contract : all operations that client can perform
2. Data Contract : defines data types that are passed in and out of service. [DataContract] and [DataMember] attributes are used
3. Fault Contract : describes the error raised by the service . [FaultContract(<>)] attribute is used
4. Message Contracts: direct control over SOAP message structure. This is useful in inter-operability cases and when there is an existing message format you have to comply with. [MessageContract], [MessageHeader], [MessageBodyMember] attributes are used



Example of Data Service:
- Microsoft implementation of OData, which is an open-format specification for accessing data
- Microsoft Visual Studio .NET facilitates creating a WCF data service by using an ADO.NET Entity Framework data model.
- WCF Data Services is designed to provide access to your data (xml, database,


A solution has a web application and a 'WCF Data Service'  file (exposed URI you can call from the internet)

Comments

Popular posts from this blog

Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)

While accessing the active directory (AD) and authorization manager (AZMAN) , If you get “   Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098)  “ message check the    account that is being used to get the LDAP query from AD .  ERROR DETAILS Exception Details:  System.Runtime.InteropServices.COMException: Insufficient access rights to perform the operation. (Exception from HRESULT: 0x80072098) Source Error: Line 154:    'Session("FullName") = System.Security.Principal.WindowsIdentity.GetCurrent.Name.ToString() Line 155: Line 156:    If Not User.IsInRole("Role1") Then Line 157:          Response.Redirect("./Login.aspx") Line 158:    End If  Stack Trace : .... SOLVE IT Steps to do check the app pool rights: Click on the website name that you are having problem with in IIS  In the right panel you will see 'Basic Settings'. Click It. Select the specific pool option and enter the name of the ac

Sql Server database Read_Only / Read_Write

The ALTER DATABASE command allows a database administrator to modify SQL Server databases and their files and filegroups. This includes permitting the changing of database configuration options. Why Read Only ? When you need to ensure that the data is a database is not modified by any users or automated processes, it is useful to set the database into a read-only mode. Once read-only, the data can be read normally but any attempts to create, updated or delete table rows is disallowed. This makes the read-only mode ideal when preparing for data migration, performing data integrity checking or when the data is only required for historical reporting purposes. Make Database Read Only USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_ONLY  WITH  NO_WAIT GO Make Database Read/Write USE  [master] GO ALTER DATABASE  [TESTDB]  SET  READ_WRITE  WITH  NO_WAIT GO In case you get the following error message make the database single user: Msg 5070, Level 16, Stat

Do's and Don't SQL

Do's: Writing comments whenever something is not very obvious, as it won’t impact the performance.  (--) for single line  (/*…*/) to mark a section Use proper indentation Use Upper Case for all SQL keywords. SELECT, UPDATE, INSERT, WHERE, INNER JOIN, AND, OR, LIKE. Use BEGIN... END block for multiple statements in conditional code  Use Declare and Set in beginning of Stored procedure Create objects in same database where its relevant table exists otherwise it will reduce network performance. Use PRIMARY key in WHERE condition of UPDATE or DELETE statements as this will avoid error possibilities. If User table references Employee table than the column name used in reference should be UserID where User is table name and ID primary column of User table and UserID is reference column of Employee table. Use select column name instead of select * Use CTE (Common Table Expression); its scope is limited to the next statement in SQL query, instead of temporary tables and der