Tuesday, August 4, 2015

WCF Proxy generation - using ChannelFactory


Next in our series about wcf service, we will now discuss how we can generate the wcf proxy using the ChannelFactory class. If you have missed the series, then here are the links for the series:


  1. About the A.B.C. of WCF Service
  2. Types of Contracts in WCF
  3. WCF Proxy generation using 'Add reference'
  4. WCF Proxy generation using 'SvcUtil.exe' 
So let's start with it. As per MSDN, ChannelFactory class is:


A factory that creates channels of different types that are used by clients to send messages to variously configured service endpoints.
This approach has the big advantage that we need not add the Service Reference to our client application, like we did in our very first discussion article. But this approach requires one very important thing, which is sharing of the ServiceContract between the client and service so that the channel can be created, based on the contract (which the service provides), between the client and service. So this makes it very important to use the concept of interfaces which can be shared between the two in a de-coupled manner. So let's start with the discussion.
We will use the same service which we used in our previous discussions. But make sure that we have removed the service reference from the project. Also we remove all the binding and endpoint configuration from the config file. We will be setting these values in our C# code.
But before we start, we move the service interface i.e. IService1 to separate project. The reason, as we discussed above, we need to have the service contract to be available in both client and service itself and adding the reference to the service project does not makes any sense. So, we add a new class type project, move the interface IService1 to this project and add it's reference to both service and client projects. So our project structure changes to:
WCF Proxy using ChannelFactory
Next, we write the code to create binding to be used, the endpoint to be used and create a ChannelFactory<T> instance type, where T is of type IService1. From this channel factory created, we get the channel of type IService1 and use this to invoke the service method  
 static void Main(string[] args)
        {
            BasicHttpBinding _basicHttpBinding = new BasicHttpBinding();
            EndpointAddress _endpoint = new EndpointAddress("http://localhost:9999/Service1.svc");

            ChannelFactory<IService1> _channelFactory = new ChannelFactory<IService1>(_basicHttpBinding, _endpoint);
            IService1 _channel = _channelFactory.CreateChannel();

            //Call the service operation
            Console.WriteLine("Sum is: " + _channel.GetSum(13, 5));

            //Close the channel Factory
            _channelFactory.Close();

            Console.ReadKey();

        }

Run the code and you can see the results.
WCF Proxy using ChannelFactory
Easy...!!! Isn't it. Happy coding...!!!

Saturday, August 1, 2015

Run time error in Global.asax : Line 1: <%@ Application Codebehind="Global.asax.cs"

I was working on a webapi project and created it successfully. It seemed to be all right, until I hosted it in the application. After hosting, browsed the api and got an error of type


Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately. 

Parser Error Message: Could not load type 'Example.WebAPISample' 

Source Error: 



Line 1:  <%@ Application Codebehind="Global.asax.cs" Inherits="Example.WebAPISample" Language="C#" %>


The error was pointing it to be an issue with the Global.asax file. Googled it and found that build action for the project should output the result to "bin" folder rather than "bin/debug" (was something like that).

I checked this option and found that was also fine. So before giving it up, gave a one last try. Cleaned the solution and build it and it worked. For some reason, the solution wasn't getting build properly earlier. But this time it worked and solution got built successfully. Browse the application and this time it worked fine. 

So this was one of the cause of issue with my application. Hope it helps others for whom the other option is not working. Happy coding...!!!

Monday, July 27, 2015

Procedure or function ' ' expects parameter ' ', which was not supplied.

Suppose you have created a stored procedure which takes input a string parameter and returns some data. You think that you have correctly passed the parameter value but still get the following error:

Procedure or function 'GetUserData' expects parameter '@UserName', which was not supplied.

You are confused that the parameter is passed but still error is occurring. But, there is another reason when this can occur. The other issue is that we are passing NULL value in the parameter. In such a case, it is considered as no parameter being passed into it. 

So solution is:
  • Pass the proper value to the parameter OR 
  • Set default value to be NULL for that parameter, in the stored procedure.
Happy SQL'ing...!!!

Saturday, July 25, 2015

WCF Proxy generation – using SvcUtil.exe


Continuing on our series about WCF service, we will now discuss how we can generate the wcf proxy using the SvcUtil.exe command line tool. If you have missed the previous articles, then ypu can read them here:


  1. About the A.B.C. of WCF Service
  2. Types of Contracts in WCF
  3. WCF Proxy generation using 'Add reference'
For this discussion, we will be using the same application we created in our last article, but will remove the reference we added during its discussion, so that we can create the proxy from scratch. So let's start the discussion.
To use the svcutil, we need to use the Visual Studio command prompt and run a command which specifies the svcutil tool to generate a proxy file for us. The command looks like the following format:
svcutil http://service_url /out:proxy_file_name.cs /config: config_file_name.config  /mergeConfig
Here,
  1. service_url : url wcf service is hosted.
  2. proxy_file_name  : Proxy file name which we would like to be generated with.
  3. config_file_name: Name of the config file which will contain the configuration of the service to be consumed by client.
Here we replace the values with our actual values. So the url becomes:
svcutil http://localhost:13490/Service1.svc?wsdl /out:SampleServiceClient.cs /config:App.config /mergeConfig
Before we run the command, we need to consider following points:
  • Run the Visual Studio command prompt in admin mode or else you may face issue with permission in generating files.
  • Use of mergeConfig :  This specifies that we want the configuration of the wcf service to get merged into our clients' config file.  For this option to work properly, make sure that you specify the config file name (in the /config: option) same as that of the clients' config file. In our case, it was App.config in client application, so we specify it to be app.config.
  • When we run the command prompt, it will generate the proxy file in the current directory or location and not in our project location. To avoid this, we change the directory to point to our project location, and then run the command.
  • We could also have specified the path of the directory where we would like the output files to get generated, using the /directory option. For more options, refer to  MSDN.If we do not want to config files to merge, we can specify any other name in the /config: option. When this file gets generated, we can copy the configuration to out clients' config file.
So here, we have changed the directory to our project location and the proxy files will be generated in the current directory i.e. project folders. We have also specified the merge option so that the required configuration is merged in client config file. So let's run the command and see the results.

Include the newly generated proxy file in the project. Now, rest of the things remain the same. The way we call the service from the client remains the same.

class Program
{
    static void Main(string[] args)
   {
         Service1Client _svcClient = new Service1Client();
         Console.Write("Sum is: " + _svcClient.GetSum(1, 2));
         Console.ReadKey();
    }
}
Run the code and see the results.

Works like charm. Happy coding...!!!

Wednesday, July 22, 2015

WCF Proxy generation - Add Reference to website


In our previous discussions, we discussed what about A.B.C. of WCF services and types of contracts in WCF. Continuing on the same lines, we will now discuss how we can generate the wcf proxy by adding the service reference in our project. If you have missed the series, then here are the links for the series:
  1. About the A.B.C. of WCF Service
  2. Types of Contracts in WCF
In this article, we will discuss about the concept of how we can generate the proxy for a service to use it in a client application. 
So let's start by adding a new application of Console type.

Next, we add another project to the solution, of type WCF Service Application.

We remove the default methods generated and add a simple method GetSum, to return sum of two numbers. So our interface implementation will be:

 
namespace TestService
{
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        Int32 GetSum(Int32 a, Int32 b);
    }
}
and our service implementation will be like:


namespace TestService
{
    public class Service1 : IService1
    {
        Int32 IService1.GetSum(int a, int b)
        {
            return a + b;
        }
    }
}

 
Next, in order to use this service in our client application, we will right click on project and select the option 'Add Service Reference'.

This will open up a window, where we can add the url of the service, where it is currently hosted. In case of current application, click on 'Discover' and it will automatically get the current service in the solution. You can expand the service and see the methods available. In case of any issues in your service, it will not be able to locate any service.

Provide a namespace and click Ok. This will add the service reference in the client project. To use the service, add the ServiceClient namespace on the project and the service can be accessed by the name as Service1Client. Use this service client instance to access the service methodsIn our case, it is GetSum method.

Run the code and see the results.

Easy to use, isn't it. Happy coding...!!!

Sunday, July 19, 2015

HTTP could not register URL 'http://+:12433/Service1/'. Your process does not have access rights to this namespace

While hosting the WCF service in a console application, you may face an issue like the following:

HTTP could not register URL http://+:12433/Service1/. Your process does not have access rights to this namespace (see http://go.microsoft.com/fwlink/?LinkId=70353 for details).

The issue is basically related to permissions to run the application. Restart the Visual Studio in Administrator mode and the issue is resolved. Happy coding..!!!

Saturday, July 18, 2015

ABC of Windows Communication Foundation

Windows Communication Foundation or WCF was introduced by Microsoft way back in its framework 3.0, with the code name Indigo. But what is WCF and why it was introduced. Let's discuss briefly about it and how it can be created.

For creating distributed applications, we already had the concept of web services, .Net Remoting and MSMQ etc. Which one to be used, depended on the requirement. But, as an implementation, all of them were separate techniques/technologies for use. So Microsoft created a uniform framework which provided all these technologies under a single umbrella called WCF. 




The basic requirements how WCF works is defined by it's three attributes also know as (ABC of WCF). These ABC are defined as:
  • A stands for Address
  • B stands for Binding
  • C stands for Contracts
These three things are what make the WCF a powerful framework.To understand about these, we will try to understand it with a simple real life example. Suppose it's your friend's birthday and you have to attend his party. But before that, you have to plan or you must know some important things for joining the party:

  • Where is the party venue ?
  • How you will be going to the party alone or with other friends ?
  • What will be the gift you will be giving to your friend ?
This is what WCF requires you to know:

  • Where is the party i.e. Where is the WCF service hosted i.e. Address
  • How will you go to the party i.e. How will you communicate with the service i.e. Binding
  • What will be the gift you will be giving i.e. What is the data shared between the client and service i.e. Contracts

So Address is, the service url, which can be of the forms like:
  1. http://localhost:8021/TestService.svc
  2. net.tcp://localhost/TestService.svc
  3. net.msmq://localhost/TestService.svc
So Binding is how the communication will take place with the service. This through the use of different protocols like Http, TCP and msmq etc. These protocols are supported through the use of different bindings like:
  1. BasiHttpBinding
  2. NetTcpBinding
  3. WSHttpBinding
  4. WSDualHttpBinding
  5. WSFederationHttpBinding
  6. NetNamedPipeBinding
  7. NetMsmqBinding
  8. NetPeerTcpBinding
And, Contracts are, what kind of data can be exchanged between the client and service. Contracts can be of following types:

  1. ServiceContract
  2. OperationContract
  3. DataContract
  4. MessageContract
  5. FaultContract

So this was about the ABC of WCF services. Hope you enjoyed reading it. Happy coding...!!!