Monday, March 1, 2010

WCF

WCF Service

-----------------------
Data Contract Basics
-----------------------

Windows Communication Foundation (WCF) uses a serialization engine called the Data Contract Serializer by default to serialize and deserialize data (convert it to and from XML). All .NET Framework primitive types, such as integers and strings, as well as certain types treated as primitives, such as DateTime and XmlElement, can be serialized with no other preparation and are considered as having default data contracts. Many .NET Framework types also have existing data contracts. For a full list of serializable types

This is normally done by applying the DataContractAttribute attribute to the type.

This attribute can be applied to classes, structures, and enumerations.

The DataMemberAttribute attribute must then be applied to each member of the data contract type to indicate that it is a data member, that is, it should be serialized.

DataMemberAttribute can only be applied to fields and properties.


Examples :-

using System;
using System.Runtime.Serialization;

[DataContract]
public class Person
{
// This member is serialized.
[DataMember]
internal string FullName;

// This is serialized even though it is private.
[DataMember]
private int Age;

// This is not serialized because the DataMemberAttribute
// has not been applied.
private string MailingAddress;

// This is not serialized, but the property is.
private string telephoneNumberValue;

[DataMember]
public string TelephoneNumber
{
get { return telephoneNumberValue; }
set { telephoneNumberValue = value; }
}
}


// Example to Create WCF Service

// Interface

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using PjtBDto1;
using System.ComponentModel;

[ServiceContract]
public interface Iuser
{
[OperationContract]
[FaultContract(typeof(ExceptionClass))]
BindingList< BDto1 > GettList(Int32 unicId);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
bool InsertUpdate(BDto1 obj1BDto);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
BindingList< BDto1 > GettList(Int32 unicId);

[OperationContract]
[FaultContract(typeof(ExceptionClass))]
Int32 Del1(BDto1 obj1BDto);

}

//ExceptionFields is an enum containing two members
//“ERROR” and “INCORRECT_OPERATION”.
[DataContract]
public class ExceptionClass
{
[DataMember]
public ExceptionFields errorcode;
[DataMember]
public string message;
[DataMember]
public string details;
}
// Used for holding exception fields
public enum ExceptionFields
{
[EnumMember]
ERROR,
[EnumMember]
INCORRECT_OPERATION
}


// Service class

using System;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.ComponentModel;
using PjtDao;
using PjtBc;
using PjtBDto;

public class Service1 : IService1
{
public BindingList< BDto1 > GetList(Int32 UnicId)
{
using(BC1 ObjBc1=new BC1)
{
return objBc1.GetList(UnicId);
}
return null;
}
}

// Exception Handling in WCF Service Layer

try

{

}

catch(Exception ex)
{
ExceptionClass error=new ExceptionClass();
error.errorcode = ExceptionFields.ERROR;
error.message = "General Exception"
error.details = ex.StackTrace;
throw new FaultException< ExceptionClass > (error);

}

// Service Exceptions in class of Catch block

ActionNotSupportedException
AddressAccessDeniedException
AddressAlreadyInUseException
ChannelTerminatedException
CommunicaitonException
Exception

// Handling same in all catch block
--------
ExceptionClass error=new ExceptionClass();
error.errorcode = ExceptionFields.ERROR;
error.message = "General Exception"
error.details = ex.StackTrace;
throw new FaultException< ExceptionClass > (error);

// In UI
---------

service1.ServiceClient objSerice1=new service1.ServiceClient();
System.ComponentModel.BindingList< BDto1 > objBL = new System.ComponentModel.BindingList< BDto1 >
objBL = objService1.GetList(UnicId);
objService1.close();


---------------------------------------------------------
enable windows authentication on WCF BasicHttpBinding
---------------------------------------------------------

Introduction and Goal

Step 1:- Create WCF project

public class Service1 : IService1
{
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
}

Step 2 :- Ensure authentication mode is windows

Step 3 :- Define the binding in web.config file

system.serviceModel >
.........
.........

Step 4 :- Bind the bindings with service interface

bindingConfiguration="BasicHttpEndpointBinding"
name="BasicHttpEndpoint" contract="WCFWindowsBasicHttpBinding.IService1" >

Step 5 :- Ensure that anonymous access is disabled

In IIS uncheck Enable anonymous access (Authentication Methods)

Step 6:- Host your WCF service on IIS

We need to host our service in the IIS. So make the directory as an IIS application so that your service can be hosted. Now if you try to browse the service i.e. the SVC file you will see that it pops up the authentication authorization security dialog box. So this service cannot be executed with windows authentication.

Step 7 :- Consume the WCF service

add an ASP.NET webapplication and do a add webreference. You will be popped up with a dialog box as shown below. Click on add reference so that a proxy is generated for the WCF service.

Step 8:- Create the WCF client

Server1 obj=new Service1();
obj.Credentials = System.Net.CredentialCache.DefaultCredentials;
Response.Write(obj.GetData(1,true));

----------------------------------------------------
Form Authentication
----------------------------------------------------

1.
propertyName1="value1"

propertyName2="value2"

...

propertyNameN="valueN"

/ >


2.
cookieless :-
This attribute specifies under what conditions the authentication ticket is stored in a cookie versus being embedded in the URL. Allowable values are: UseCookies; UseUri; AutoDetect; and UseDeviceProfile (the default). Step 2 examines this setting in more detail.
defaultUrl
Indicates the URL that users are redirected to after signing in from the login page if there is no RedirectUrl value specified in the querystring. The default value is default.aspx.

------------------------
Steps for WCF Security
------------------------

There are FOUR core security features that WCF addresses:-

Confidentiality:- This feature ensures that the information does not go in 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 sends 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.

--------------------------------------------------------------
advantages and disadvantages of transport VS message security
--------------------------------------------------------------

transport security :-
-------------------
When there are no intermediate systems in between this is the best methodology.
If it’s an intranet type of solution this is most recommended methodology.

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 lot of interoperability support and communicating clients do not need to understand WS security as it’s built in the protocol itself.

disadvantages :-
As it’s a protocol implemented security so it works only point to point.
As security is dependent on protocol it has limited security support and is bounded to the protocol security limitations.

message security :-
----------------
When there are intermediate systems like one more WCF service through which message is routed then message security is the way to go.

advantages :-
Provides end to end security as it’s not dependent on protocol. Any intermediate hop in network does not affect the application. Supports wide set of security options as it is not dependent on protocol. We can also implement custom security.

disadvantages :-
Needs application refactoring to implement security.
As every message is encrypted and signed there are performance issues.
Does not support interoperability with old ASMX webservices/

----------------------------------------------------------------------
What is the difference between BasicHttpBinding and WsHttpBinding ?
----------------------------------------------------------------------

Security support

BasicHttpBinding
This supports the old ASMX style i.e WS-BasicProfile 1.1.

WsHttpBinding
This exposes web services using WS-* specifications.

Compatibility

BasicHttpBinding :
This is aimed for clients who do not have .Net 3.0 installed and it supports wider ranges of client. Many of clients like Windows 2000 still do not run .NET 3.0. So older version of .NET can consume this service.

WsHttpBinding :
As its built using WS-* specifications it does not support wider ranges of client and it cannot be consumed by older .NET version less than 3 version.

Soap version

BasicHttpBinding :
SOAP 1.1

WsHttpBinding :
SOAP 1.2 and WS-Addressing specification.

Reliable messaging

BasicHttpBinding
Not supported. In other words if a client fires two or three calls you really do not know they will return back in the same order.

WsHttpBinding
Supported as it supports WS-* specifications.

Default security options

BasicHttpBinding
By default there is not security provided for messages when the client calls happen. In other words data is sent as plain text.

WsHttpBinding
As WsHttBinding supports WS-* it has WS-Security enabled by default. So the data is not sent in plain text.

Security options

BasicHttpBinding:
None
Windows – default authentication.
Basic
Certificate

WsHttpBinding:
None
Transport.
Message.
Transport with message credentials.

By default ‘BasicHttpBinding’ sends data in plain text while ‘WsHttpBinding’ sends in encrypted and secured manner.

By Default security is not enabled on ‘BasicHttpBinding’ for interoperability purpose