3 March 2014

WCF Fundamentals


 Endpoint:
         WCF Service is a program that exposes a collection of Endpoints. Each Endpoint is a portal for communicating with the outside world. All the WCF communications are take place through end point. End point consists of three components.

Address:

      Basically URL specifies where this WCF service is hosted .Client will use this URL to connect to the service.

Example: http://localhost:8090/MyService/SimpleCalculator.svc

Binding:

       Binding will describes how client will communicate with service. There are different protocols available for the WCF to communicate to the Client. You can mention the protocol type based on your requirements.

Bindings have following properties:

  • Transport -Defines the base protocol to be used like HTTP, Named Pipes, TCP, and MSMQ are some type of protocols.
  • Encoding (Optional) - Three types of encoding are available-Text, Binary, or Message Transmission Optimization Mechanism (MTOM). MTOM is an interoperable message format that allows the effective transmission of attachments or large messages (greater than 64K).
  • Protocol(Optional) - Defines information to be used in the binding such as Security, transaction or reliable messaging capability
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
Contract:

      It specifies what operations are to be exposed to client. Each operation has certain data exchange pattern such as one-way, duplex and request reply. It also specifies which end point will expose what operations

Below figure describes the functions of End points:


Example:

      Endpoints will be mentioned in the Web.Config file on the created service.
        <system.serviceModel>
          <services>
      <service name="MathService" behaviorConfiguration="MathServiceBehavior">
      <endpoint address="http://localhost:8090/MyService/MathService.svc"             contract="IMathService" binding="wsHttpBinding"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MathServiceBehavior">
          <serviceMetadata httpGetEnabled="True"/>
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>








Diversities between WCF and Web services


   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.

   Few diversities between Web services and WCF 

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
[Web Service] attribute has to be added to the class
[ServiceContract] attribute has to be added to the class
Model
[Web Method] 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

Windows Communication Foundation (WCF)

   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 combination of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication. It will take .svc as extension 

     Below figures shows the different technology combined to form WCF.   


   Advantages:
  •    WCF is interoperable with other services when compared to .net Remoting, where the client and service have to be in .net
  •    It provides better reliability and security in compared to web services
  •    We can implement security by changing configuration settings without changing the code
  •    It is integrated with logging mechanism, so small changes in configuration setting will provide the required functionality


2 March 2014

Source Code-Interfaces


Implementation of interfaces:


using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace InterfaceApplication
{

   public interface ITransactions
   {
      // interface members
      void showTransaction();
      double getAmount();
   }
   public class Transaction : ITransactions
   {
      private string tCode;
      private string date;
      private double amount;
      public Transaction()
      {
         tCode = " ";
         date = " ";
         amount = 0.0;
      }
      public Transaction(string c, string d, double a)
      {
         tCode = c;
         date = d;
         amount = a;
      }
      public double getAmount()
      {
         return amount;
      }
      public void showTransaction()
      {
         Console.WriteLine("Transaction: {0}", tCode);
         Console.WriteLine("Date: {0}", date);
         Console.WriteLine("Amount: {0}", getAmount());

      }

   }
   class Tester
   {
      static void Main(string[] args)
      {
         Transaction t1 = new Transaction("001", "8/10/2012", 78900.00);
         Transaction t2 = new Transaction("002", "9/10/2012", 451900.00);
         t1.showTransaction();
         t2.showTransaction();
         Console.ReadKey();
      }
   }
}

Interfaces

       Interface is defined as a syntactical contract that all the classes inheriting the interface should follow. The interface defines the 'what' part of the syntactical contract and the deriving classes define the 'how' part of the syntactical contract.
     Interfaces define properties, methods and events, which are the members of the interface. Interfaces contain only the declaration of the members. It is the responsibility of the deriving class to define the members. It often helps in providing a standard structure that the deriving classes would follow. It supports multiple inheritances
    Abstract classes to some extent serve the same purpose, however, they are mostly used when only few methods are to be declared by the base class and the deriving class implements the functionality.

Declaring Interfaces:

Interfaces are declared using the interface keyword. It is similar to class declaration. Interface statements are public by default. Following is an example of an interface declaration: 
Public interface ITransactions
{
   // interface members
   Void showTransaction ();
   Double get Amount ();
}

Source Code -Abstract Classes with Example



Example for Abstract Classes:

using System;
 
namespace abstractSample
{
      //Creating an Abstract Class
      abstract class absClass
      {
            //A Non abstract method
            public int AddTwoNumbers(int Num1, int Num2)
            {
                return Num1 + Num2;
            }
 
            //An abstract method, to be
            //overridden in derived class
            public abstract int MultiplyTwoNumbers(int Num1, int Num2);
      }
 
      //A Child Class of absClass
      class absDerived:absClass
      {
            [STAThread]
            static void Main(string[] args)
            {
               //You can create an
               //instance of the derived class
 
               absDerived calculate = new absDerived();
               int added = calculate.AddTwoNumbers(10,20);
               int multiplied = calculate.MultiplyTwoNumbers(10,20);
               Console.WriteLine("Added : {0}, 
                       Multiplied : {1}", added, multiplied);
            }
 
            //using override keyword,
            //implementing the abstract method
            //MultiplyTwoNumbers
            public override int MultiplyTwoNumbers(int Num1, int Num2)
            {
                return Num1 * Num2;
            }
      }
}

Abstract Classes

         An abstract class cannot be instantiated. The purpose of an abstract class is to provide a common definition of a base class that multiple derived classes can share. For example, a class library may define an abstract class that is used as a parameter to many of its functions, and require programmers using that library to provide their own implementation of the class by creating a derived class. Abstract classes may also define abstract methods. This is accomplished by adding the keyword abstract before the return type of the method

       The abstract keyword enables you to create classes and class members that are incomplete and must be implemented in a derived class.

Syntax:

public abstract class A
{
    public abstract void DoWork(int i);
}

      If a virtual method is declared abstract, it is still virtual to any class inheriting from the abstract class. A class inheriting an abstract method cannot access the original implementation of the method.


Implementation:

// compile with: /target:library 
public class D
{
  public virtual void DoWork(int i)
  { // Original implementation. }
}
public abstract class E : D
{
    public abstract override void DoWork(int i);
}
public class F : E
{
    public override void DoWork(int i)
    { // New implementation.}
}

Source Code

Important rules applied to abstract classes:
  •     An abstract class cannot be a sealed class.
Example: Abstract  sealed class absClass {}
  •     Declaration of abstract methods is only allowed in abstract classes.
  •     An abstract method cannot be private
Example: Private abstract int MultiplyTwoNumbers();
  •     The access modifier of the abstract method should be same in both the abstract class and its derived class. If you declare an abstract method as protected, it should be protected in its derived class. Otherwise, the compiler will raise an error.
  •     An abstract method cannot have the modifier virtual. Because an abstract method is implicitly virtual.
Example: public abstract virtual int MultiplyTwoNumbers();
  •      An abstract member cannot be static.
Example:public abstract static int MultiplyTwoNumbers();