Sunday, 18 March 2012

Difference between proxy and channel factory


Hi friends, 


In this article I will show you what difference between WCF Channel factory and Proxy.
There are 3 basic ways to create a WCF client:
1.      Proxy
2.      WCF Channel Factory
3.      REST services, using the HttpClient or WebClient
Before the difference I will explain you what is WCF channel factory and what is proxy


1.   What is Proxy:
The proxy is a CLR class that exposes a single CLR interface representing the service contract. The proxy provides the same operations as service's contract, but also has additional methods for managing the proxy life cycle and the connection to the service. The proxy completely encapsulates every aspect of the service: its location, its implementation technology and runtime platform, and the communication transport.

The proxy can be generated using Visual Studio by right clicking Reference and clicking on Add Service Reference. This brings up the Add Service Reference dialog box, where you need to supply the base address of the service (or a base address and a MEX URI) and the namespace to contain the proxy. Let Visual Studio generate your proxy. This auto generates code that connects to the service by reading the WSDL. If the service changes for any reason you have to regenerate it. The big advantage of this is that it is easy to set up - VS has a wizard and it's all automatic. The disadvantage is that you're relying on VS to do all the hard work for you, and so you lose cont

Proxy can also be generated by using SvcUtil.exe command-line utility. We need to provide SvcUtil with the HTTP-GET address or the metadata exchange endpoint address and, optionally, with
When we generate (WCF) service proxy class for a service by using svcutil.exe, it creates a proxy that derives from System.ServiceModel.ClientBase<TChannel>. The proxy implements IDisposable and the client code can be wraped inside using statement and guaranteed clean-up in the face of exceptions.



2.   What is Channel Factory :

Use ChannelFactory with a known interface. This relies on you having local interfaces that describe the service (the service contract). The big advantage is that can manage change much more easily - you still have to recompile and fix changes, but now you're not regenerating code, you're referencing the new interfaces. Commonly this is used when you control both server and client as both can be much more easily mocked for unit testing
In order to use ChannelFactory<T> you must be willing to share contract assemblies between the service and the client. If this is okay with you then ChannelFactory<T> can save you some time.
When you share a common service contract dll between the client and the server, you'll be using the ChannelFactory class
When we use channel factory following steps to do
  1. Create a binding
  2. Create a ChannelFactory.
  3. Create a Channel
  4. Send/Receive messages over that channel.


In this example this is done by using ChannelFactory. Once the channel is in place we can send messages back and forth to the service.
using System;
using System.ServiceModel;
using EchoClientConsole.EchoServiceReference;

namespace EchoClientConsole
{
    internal class Program
    {
        private static void Main()
        {
            var channelFactory =
                new ChannelFactory<IEchoService>(
                    "WSHttpBinding_IEchoService" // config endpoint name
                    );

            IEchoService channel = channelFactory.CreateChannel();
            EchoMessage result = channel.Echo(
                new EchoMessage
                    {
                        Text = "Hey "
                    });

            Console.WriteLine("Service responded at {0}: {1}",
                              result.Invoked,
                              result.Text);
            Console.ReadLine();

            ((IClientChannel)channel).Close();
        }
    }
}


3.   Difference between proxy and channel factory


PROXY
Channel Factory
1
Only require URL where the service resides

You must have direct access to the assembly that contains that service contract T for
2
Very Simpler

Not easier
3
Easy to Understand
channels are complex, network-related
4
There is Visual Studio gives you add the reference
When you share a common service contract dll between the client and the server, you'll be using the ChannelFactory class
5
Proxies have several restrictions like:
  1. Properties need to have gets and sets
  2. Contructors can't be exposed
  3. Methods other than the service contract cannot be exposed

If you know that your entities will not change much and the client code is less, then a DLL would work better than a proxy
6
By using SVCutil.exe you will create PRoxy
When you are using DLL that refers Service contract interface then use the channel factory class




Good luck and please, let me know your feedback!
In this way you can learn difference between proxy and channel factory

If you have any query mail me to Sujeet.bhujbal@gmail.com     

Regards
Sujeet Bhujbal


------------------------------------------------------------------------------------------------
 Blog:  www.sujitbhujbal.blogspot.com
Personal Website :- http://sujitbhujbal.wordpress.com/
Contact me on 9822663535
---------------------------------------------------------------------------------

Thursday, 23 February 2012

Choosing binding for WCF service


Choosing binding for WCF service


There are different types of bindings supported by WCF. Now question is which binding is suitable for your service.Following is list of frequently used bindings in WCF:
*   BasicHttpBinding: If clients can be non-WCF. This exposes service to the outside world as if it was an ASMX (webservice). You cannot take advantages of modern WS* protocol on this binding. This is unsecure binding by default.
*   NetMsmqBinding: If client is WCF application and requires offline or disconnected interaction choose NetMsmqBinding which uses MSMQ for transporting the messages.
*   NetTcpBinding: If client requires connected communication and no problem on communicating between firewalls as it requires port to open for communication across firewalls. This is WCF to WCF communication.This is secure and optimized binding that is suitable for on machine communications between WCF applications.
*   NetNamedPipeBinding (IPC Binding): It is similar to TCP protocol but if requirement is to communicate on same machine then you can consider it.
*   WSHttpBinding: If you want a secure and interoperable binding that is suitable for non-duplex service contracts.
*   WSDualHttpBinding (WS dual binding): It is similar to WS binding but it can also support duplex communication from service to client.It it nothing more than two WsHttpBinding bindins wired up against each other to support callbacks.
Important:
*       Select a binding that has security enabled. By default, all bindings, except the BasicHttpBinding binding, have security enabled. If you do not select a secure binding, or if you disable security, be sure your network exchanges are protected in some other manner, such as being in a secured data center or on an isolated network.
*       Do not use duplex contracts with bindings that do not support security, or that have security disabled, unless the network exchange is secured by some other means.
Binding Features
This is matrix of high level features of bindings. This is excerpt from MSDN.
Binding
Interoperability
Mode of Security (Default)
Session (Default)
Transactions
Duplex
BasicHttpBinding
Basic Profile 1.1
(None), Transport, Message, Mixed
None, (None)
(None)
n/a
WSHttpBinding
WS
None, Transport, (Message), Mixed
(None), Transport, Reliable Session
(None), Yes
n/a
WS2007HttpBinding
WS-Security, WS-Trust, WS-SecureConversation, WS-SecurityPolicy
None, Transport, (Message), Mixed
(None), Transport, Reliable Session
(None), Yes
n/a
WSDualHttpBinding
WS
None, (Message)
(Reliable Session)
(None), Yes
Yes
WSFederationHttpBinding
WS-Federation
None, (Message), Mixed
(None), Reliable Session
(None), Yes
No
WS2007FederationHttpBinding
WS-Federation
None, (Message), Mixed
(None), Reliable Session
(None), Yes
No
NetTcpBinding
.NET
None, (Transport), Message,
Mixed
Reliable Session, (Transport)
(None), Yes
Yes
NetNamedPipeBinding
.NET
None,
(Transport)
None, (Transport)
(None), Yes
Yes
NetMsmqBinding
.NET
None, Message, (Transport), Both
(None)
(None), Yes
No
NetPeerTcpBinding
Peer
None, Message, (Transport), Mixed
(None)
(None)
Yes
MsmqIntegrationBinding
MSMQ
None, (Transport)
(None)
(None), Yes
n/a


If you have any doubt please reply to this post else mail me on sujeet.bhujbal@gmail.com


Regards
Sujeet 

Monday, 13 February 2012

How to search a value in entire database

Question: How to search a value in entire database

Answer:
We created on Stored Procedure SearchAllTables
The output of this stored procedure contains two columns:

- 1) The table name and column name in which the search string was found
- 2) The actual content/value of the column (Only the first 3630 characters are displayed)


Create this procedure in the required database and here is how you run it:


Here is the complete stored procedure code:

CREATE PROC SearchAllTables
(
               @SearchStr nvarchar(100)
)
AS
BEGIN
               
               CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
               SET NOCOUNT ON
               DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
               SET  @TableName = ''
               SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
               WHILE @TableName IS NOT NULL
               BEGIN
                               SET @ColumnName = ''
                               SET @TableName = 
                               (
                                      SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
                                          FROM       INFORMATION_SCHEMA.TABLES
                                       WHERE                     TABLE_TYPE = 'BASE TABLE'
                     AND          QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
                     AND          OBJECTPROPERTY(
                                OBJECT_ID(
                                 QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                                        ), 'IsMSShipped'
                                 ) = 0
                               )
                               WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
                               BEGIN
                                              SET @ColumnName =
                                              (
                                                             SELECT MIN(QUOTENAME(COLUMN_NAME))
                                                             FROM       INFORMATION_SCHEMA.COLUMNS
                                     WHERE     TABLE_SCHEMA          = PARSENAME(@TableName, 2)
           AND          TABLE_NAME              = PARSENAME(@TableName, 1)
             AND          DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar')
                AND          QUOTENAME(COLUMN_NAME) > @ColumnName
                                              )
               
                                              IF @ColumnName IS NOT NULL
                                              BEGIN
                                                             INSERT INTO #Results
                                                             EXEC
                                                             (
            'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) 
                 FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
                                                             )
                                              END
                               END          
               END
               SELECT ColumnName, ColumnValue FROM #Results
END


How to execute

EXEC SearchAllTables ‘Sujeet’
GO



If you have any doubt please reply to this post else mail me on sujeet.bhujbal@gmail.com

Regards
Sujeet 

Friday, 20 January 2012

Per Call Instance in WCF with example


Per Call Instance

In WCF there are 3 types of instancing we can do
  1. Per Call
  2. per Session
  3. Single



Per Call

When we don configuration in WCF service as per call, every call method new service instances are created

In the below example I have created on service for percall

Below example shows the details.


namespace PerCall
{
   [
ServiceContract(Namespace=" http://sujitbhujbal.blogspot.com")]
   //Created PerCall Interface
   
public interface IPerCall   {
      [
OperationContract]
      
int IncrementCounter();
   }

   //PerCall session created
   [
ServiceBehavior(InstanceContextMode=InstanceContextMode.PerCall)]
   
public class CounterServicePerCall: IPerCall   {
      
private int m_counter;
      
int ICounterServicePerCall.IncrementCounter()
      {
         m_counter++;
         
MessageBox.Show(String.Format("Incrementing PerCall counter to {0}.\r\nSession Id: {1}", m_counter, OperationContext.Current.SessionId));
         
return m_counter;
      }
    }
}

In the above example i created one service that creates PerCall instance and on the every instacne Counter is incremented

Below screen shot shows the different settings and Per call instances




When we click on PerCall button below screenshots shows the details what happen in PerCall
When again we press perCall session counter remains the same







Above screenshots and example shows that when we use per call instance in WCF every time call is created and counter remains same.

When should we use per call mode?

Per call

When you want a stateless services

When your WCF functions are called in a per call

References

MSDN link for WCF instances
 http://msdn.microsoft.com/en-us/library/ms733040.aspx

Wednesday, 4 January 2012

Migrating ASP.NET Web Services to WCF

Hi friends,

Again new WCF article

We are currently migrating a small web services built on top of ASP.NET in .NET 2.0 (commonly referred to as ASMX Web Services) over to the Windows Communication Foundation (WCF) platform available in .NET 3.0.
The reason behind this is we want speed which WCF provides.
The primary reason we want to do that is because we would like to take advantage of the binary message serialization support available in WCF to speed
up communication between the services and their clients. This same technique was possible in earlier versions of the .NET Framework thanks to a technology called Remoting, which is now superseded by WCF. In both cases it requires that both the client and server run on .NET in order to work. But I digress.

Since the ASMX model has been for a long time the primary Microsoft technology for building web services on the .NET platform, I saw Microsoft has made nice setting in app.config of WCF migration path to bring all those web services to the new world of WCF.


The quick way
If you built your ASMX web services with code separation (that is, all programming logic resided in a separate code-behind file instead of being embedded in the ASMX file) it is possible to get an ASMX web service up and running in WCF pretty quickly by going through a few easy steps:
  • Your WCF web service class no longer inherits from
    the  System.Web.Services.WebService class so remove it.
  • Change the System.Web.Services.WebService attribute on the web service class to the System.ServiceModel.ServiceContract attribute.
  • Change the System.Web.Services.WebMethod attribute on each web service method to the System.ServiceModel.OperationContract attribute.
  • Substitute the .ASMX file with a new .SVC file with the following header:




Here is a summary of the changes you’ll have to make to your ASMX web service:
Where the change applies
ASMX
WCF
Web service class inheritance
WebService
-
Web service class attribute
WebServiceAttribute
ServiceContractAttribute
Web service method attribute
WebMethodAttribute
OperationContractAttribute
Data class attribute
XmlRootAttribute
DataContractAttribute
Data class field attribute
XmlElementAttribute
DataMemberAttribute
HTTP endpoint resource
.ASMX
.SVC


As a side note, if you are using .NET 3.5 SP1 the porting process gets a little easier
  • WCF services are not bound to the HTTP protocol as ASMX web services are. This means you can host them in any process you like, whether it be a Windows Service or a console application. In other words using Microsoft IIS is no longer a requirement, although it is a valid possibility in many situations.
  • Even if WCF services are executed by the ASP.NET worker process when hosted in IIS, they do not participate in the ASP.NET HTTP Pipeline. This means that you have no longer access to the ASP.NET infrastructure services such as HttpContext, HttpSessionState, HttpApplicationState, ASP.NET Authorization and Impersonation in your WCF services.

So what if your ASMX web services are making extensive use of the ASP.NET session store or employ the ASP.NET security model? Is it a show-stopper?
Luckily enough, no. There is a solution to keep all that ASP.NET goodness working in WCF. It is called ASP.NET Compatibility Mode.



Backwards compatibility
Running WCF services with the ASP.NET Compatibility Mode enabled will integrate them in the ASP.NET HTTP Pipeline, which of course means all ASP.NET infrastructure will be back in place and available from WCF at runtime.
You can enable this mighty mode from WCF by following these steps:

  • Decorate your web service class with the System.ServiceModel.Activation.AspNetCompatibilityRequirements attribute as following:
[AspNetCompatibilityRequirements(
    RequirementsMode = AspNetCompatibilityRequirementsMode.Required)]
public class MyService : IMyService
{
    // Service implementation
}
  • Add the following setting to the application configuration file:
<system.serviceModel>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" />
</system.serviceModel>
Remember that this will effectively tie the WCF runtime to the HTTP protocol, just like with ASMX web services, which means it becomes prohibited to add any non-HTTP endpoints for your WCF services.


Good luck and please, let me know your feedback!

Regards,
Sujeet Bhujbal