Wednesday, 11 November 2015

Different types of WCF Contracts

WCF contract specify the service and its operations. WCF has five types of contracts: service contract, operation contract, data contract, message contract and fault contract.


  1. Service Contract

    A service contract defines the operations which are exposed by the service to the outside world. A service contract is the interface of the WCF service and it tells the outside world what the service can do. It may have service-level settings, such as the name of the service and namespace for the service.

    [ServiceContract]

    interface IMyContract

    {

     [OperationContract]

     string MyMethod();

    }



    class MyService : IMyContract

    {

     public string MyMethod()

     {

     return "Hello World";

     }

    }
  2. Operation Contract

    An operation contract is defined within a service contract. It defines the parameters and return type of an operation. An operation contract can also defines operation-level settings, like as the transaction flow of the op-eration, the directions of the operation (one-way, two-way, or both ways), and fault contract of the operation.
[ServiceContract]

 interface IMyContract

 {

 [FaultContract(typeof(MyFaultContract))]

 [OperationContract]

 string MyMethod();

 }
  1. Data Contract

    A data contract defines the data type of the information that will be exchange be-tween the client and the service. A data contract can be used by an operation contract as a parameter or return type, or it can be used by a message contract to define elements.

[DataContract]

class Person

{

 [DataMember]

 public string ID;

 [DataMember]

 public string Name;

}



[ServiceContract]

interface IMyContract

{

 [OperationContract]

 Person GetPerson(int ID);

}

  1. Message Contract

    When an operation contract required to pass a message as a parameter or return value as a message, the type of this message will be defined as message contract. A message contract defines the elements of the message (like as Message Header, Message Body), as well as the message-related settings, such as the level of message security.
    Message contracts give you complete control over the content of the SOAP header, as well as the structure of the SOAP body.

[ServiceContract]

public interface IRentalService

{

 [OperationContract]

 double CalPrice(PriceCalculate request);

}



[MessageContract]

public class PriceCalculate

{

 [MessageHeader]

 public MyHeader SoapHeader { get; set; }

 [MessageBodyMember]

 public PriceCal PriceCalculation { get; set; }

}



[DataContract]

public class MyHeader

{

 [DataMember]

 public string UserID { get; set; }

}



[DataContract]

public class PriceCal

{

 [DataMember]

 public DateTime PickupDateTime { get; set; }

 [DataMember]

 public DateTime ReturnDateTime { get; set; }

 [DataMember]

 public string PickupLocation { get; set; }

 [DataMember]

 public string ReturnLocation { get; set; }

 }

Fault Contract

A fault contract defines errors raised by the service, and how the service handles and propagates errors to its clients. An operation contract can have zero or more fault contracts associated with it.[ServiceContract]

interface IMyContract

{

 [FaultContract(typeof(MyFaultContract1))]

 [FaultContract(typeof(MyFaultContract2))]

 [OperationContract]

 string MyMethod();



 [OperationContract]

 string MyShow();

 }

Security features that WCF

There are four core security features that WCF addresses:
  • Confidentiality: This feature ensures that information does not go in to the wrong hands when it travels from the sender to the receiver.
  • Integrity: This feature ensures that the receiver of the message gets the same information that the sender sent without any data tampering.
  • Authentication: This feature verifies who the sender is and who the receiver is.
  • Authorization: This feature verifies whether the user is authorized to perform the action they are requesting from the application.

What is transport level and message level security?

When we talk about WCF security, there are two aspects. The first is the data and the second is the medium on which the data travels, i.e., the protocol. WCF has the ability to apply security at the transport level (i.e., protocol level) and also at message level (i.e., data).
Figure: Transport and Message level security
Transport level security happens at the channel level. Transport level security is the easiest to implement as it happens at the communication level. WCF uses transport protocols like TCP, HTTP, MSMQ, etc., and each of these protocols have their own security mechanisms. One of the common implementations of transport level security is HTTPS. HTTPS is implemented over HTTP protocols with SSL providing the security mechanism. No coding change is required, it’s more about using the existing security mechanism provided by the protocol.
Message level security is implemented with message data itself. Due to this, it is independent of the protocol. One of the common ways of implementing message level security is by encrypting data using some standard encryption algorithm.

Advantages:
  • Does not need any extra coding as protocol inherent security is used.
  • Performance is better as we can use hardware accelerators to enhance performance.
  • There is a lot of interoperability support and communicating clients do not need to understand WS security as it’s built in the protocol itself.


Implement transport security?

Step 1: Create a simple service using a WCF project

The first step is to create a simple WCF project. So click on New Project and select WCF Service project. By default, a WCF project creates a default function GetData(). We will be using the same function for this sample.
public class Service1 : IService1
{
    public string GetData(int value)
    {
        return string.Format("You entered: {0}", value);
    }
    public CompositeType GetDataUsingDataContract(CompositeType composite)
    {
        if (composite.BoolValue)
        {
            composite.StringValue += "Suffix";
        }
        return composite;
    }
}

Step 2: Enable transport level security in the web.config file of the service

The next step is to enable transport security in WsHttp binding. This is done using the Security XML tag as shown in the below code snippet.
<bindings>
    <wsHttpBinding>
        <binding name="TransportSecurity">
            <security mode="Transport">
                <transport clientCredentialType="None"/>
            </security>
        </binding>
    </wsHttpBinding>
</bindings>

Step 3: Tie up the binding and specify HTTPS configuration

We need to now tie up the bindings with the end points. So use the bindingConfiguration tag to specify the binding name. We also need to specify the address where the service is hosted. Please note the HTTS in the address tag.
Change mexHttpBinding to mexHttpsBinding in the second end point.
<service name="WCFWSHttps.Service1" behaviorConfiguration="WCFWSHttps.Service1Behavior">
<!-- Service Endpoints -->
<endpoint address="https://localhost/WCFWSHttps/Service1.svc" 
  binding="wsHttpBinding" bindingConfiguration="TransportSecurity" 
  contract="WCFWSHttps.IService1"/>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
In serviceMetadata, we also need to change httpGetEnabled to httpsGetEnabled.
<serviceBehaviors>
........
.........
<serviceMetadata httpsGetEnabled="true"/>
.........
.........
</serviceBehaviors>

Step 4: Make the web application HTTPS enabled

Now that we are done with the WCF service project creation and the necessary configuration changes are done, it’s time to compile the WCF service project and host it in an IIS application with HTTPS enabled.
We will be using ‘makecert.exe’ which is a free tool given by Microsoft to enable HTTPS for testing purposes. MakeCert (Makecert.exe) is a command-line tool that creates an X.509 certificate that is signed by a system test root key or by another specified key. The certificate binds a certificate name to the public part of the key pair. The certificate is saved to a file, a system certificate store, or both.
You can get it from C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin or you can also get it from the Windows SDK.
You can type the below through your DOS prompt on “C:\Program Files\Microsoft Visual Studio 8\Common7\Tools\Bin”. Please note “compaq-jzp37md0” is the server name so you need to replace it with your PC name.
makecert -r -pe -n "CN= compaq-jzp37md0 " -b 01/01/2000 
  -e 01/01/2050 -eku 1.3.6.1.5.5.7.3.1 -ss my -sr localMachine -sky exchange 
  -sp "Microsoft RSA SChannel Cryptographic Provider" -sy 12
If you run the same through your command prompt, you should get a succeeded message as shown below:
Now it’s time to assign this certificate to your IIS website. So go to IIS properties, click on the Directory Security tab, and you should see the Server Certificate tab.
Click on the Server Certificate tab and you will then be walked through an IIS certificate wizard. Click ‘Assign an existing certificate’ from the wizard.
You can see a list of certificates. The “compaq-jzp37md0” certificate is the one which we just created using ‘makecert.exe’.
Now try to test the site without ‘https’ and you will get an error as shown below….That means your certificate is working.
Do not forget to enable IIS anonymous access.

Step 5: Consume the service in a web application

It’s time to consume the service application in ASP.NET web. So click on Add Service Reference and specify your service URL. You will be shown a warning box as in the below figure. When we used makecert.exe, we did not specify the host name as the service URL. So just let it go.

Step 6: Suppress the HTTPS errors

makecert.exe’ creates test certificates. In other words, it’s not signed by CA. So we need to suppress those errors in our ASP.NET client consumer. So we create a function called IgnoreCertificateErrorHandler which returns true even if there are errors. This function is attached as a callback toServicePointManager.ServerCertificateValidationCallback.
In the same code, you can also see the service consuming code which calls the GetData function.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WebApplicationConsumer.ServiceReference1;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

namespace WebApplicationConsumer
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            ServicePointManager.ServerCertificateValidationCallback = 
               new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler); 
            Service1Client obj = new Service1Client();
            Response.Write(obj.GetData(12));
        }
        public static bool IgnoreCertificateErrorHandler(object sender, 
          X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
        {
            return true;
        }
    }
}

Step 7: Enjoy success

Now to the easiest step, compile your ASP.NET client and enjoy success.

Monday, 9 November 2015

IQS

v  Wcf
Ø  Security in wcf
Ø  Difference between datacontract and message contract
Ø  Multiple endpoint in wcf

A) Configure the multiple end points here. 
  1. Add as many end points as you want in service tag.
  2. Make sure none of the end points is having same address. Else you will get run time error.
  3. Advisable is to use relative address. So for that add base address using Host tag.
So configuration file with multiple end points can look like, 

image8.gif

Explanation 

1. There are two end points getting exposed. 
2. Relative address is being used to expose the end points. 
3. Two end points are having their respective names as firstBinding and secondBinding. 

Ø  Overloading in wcf
Ø  In WCF, can data contract classes inherit from one another?
A) Yes, but you need to decorate the base class with the [KnownTypeAttribute] constructing it with the derived class's type. For instance:

[DataContract]
[KnownType(typeof(B))]
public class A
{
   [DataMember]
   public string Value { get; set; }
}

[DataContract]
public class B : A
{
   [DataMember]
   public string OtherValue { get; set; }
}

Ø  Faultcontract use
Ø  Interfaces in wcf

Ø  How to create proxy how many files are created
A) When we create a proxy 2 files created
1) serviceproxy.cs
2) output.config
 Generate Proxy by using SvcUtil.exe Tool
Let’s generate proxy by using third option i.e. SvcUtil.exe Tool by following step by step approach.
  • Add a Client Project to solution named as “ClientApp3″ that is basically a Console Application.
SvcUtil Tool
  • Our WCF Service must be running, so let’s run our service.
WCF Service Running
  • Open Visual Studio Command Prompt and generate proxy using svcutil.exe tool as follows:
svcutil http://localhost:4321/StudentService /out:StudentServiceProxy.cs
SvcUtil Command It will generate a new class “StudentServiceProxy.cs”.
  • Add newly created proxy class to our client application “ClientApp3″.
  • Call WCF Service using proxy class as:
class Program
{
        static void Main(string[] args)
        {
                   StudentServiceClient myclient;
                   myclient = new StudentServiceClient();
                   int studentId = 1;
                   Console.WriteLine(“Calling StudentService with StudentId = 1…..”);
                   Console.WriteLine(“Student Name = {0}”, myclient.GetStudentInfo(studentId));
                   Console.ReadLine();
         }
}
When we run the application, it will call StudentService method getStudentInfo and generate the same output as we received in other options.


Ø  Use of message contract
Ø  Bindings in wcf
Ø  How to provide security in wcf service
Ø  Difference between wcf and webservice
Ø  Exception handling in wcf
Ø  How to host wcf service
Ø  What is msmq
v  Sql
Ø  Getting top  records without using top keyword
Ø  Cross join
Ø  Inner join
Ø  Left outer join
Ø  Cursor
Ø  View
Ø  Index
Ø  Indexes having drawback for this what is the alternative way to get the records
Ø  I have 1000 lines in sp how to optimize performance
Ø  Get the data from two tables
Ø  I have 10 records in table, 5 records in other table if use select statement what is the result
Ø Delete Duplicate records in sql
v  C#
Ø  Sealed
Ø  Interface
Ø  Oops
Ø  Constructor purpose brief discussion
Ø  Exception handling
Ø  Polymorphism and overloading and overriding
Ø  Databoung controls
Ø  I have 5 methods in  base class, how will I access only 4methds in derived class

v  Asp.net
Ø  Pagelife cycle
Ø  When you enter url in browser what action to be done
Ø  Masterpage,user control which one to be load first
Ø  Ajax controls, validations
Ø  Webmethods in Jquery
Ø  Validations in Jquery
Ø  State management technics used
Ø  If disabled in cookies what happen?
Ø  Session in asp.net