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...!!!

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.

Suppose we have a separate layer of our entity framework project. Then we are trying to use its reference in another project, from where we have not access the database and bang, the error occurs.

The specified named connection is either not found in the configuration, not intended to be used with the EntityClient provider, or not valid.

Solution, make sure you add the connection string of the database, in the project where the database project is referred to and it should work. Even if you have added the connection string in the main project, try checking the syntax of the connection string. These are the 2 possible reasons for this issue. Hope it helps...!!!

Wednesday, July 15, 2015

Types of Contracts in WCF


In this discussion, we will discuss about the types of Contracts in WCF. But before we start, role of Contracts can be summarized as:

Contracts in WCF make it possible for a service to be created and exchange data between the service and the client application. 

Following types of Contracts are available in WCF:

1. ServiceContract: This is the basic contract type which makes it possible to expose a service to the client applications. This is basically a class level attribute. Any class which needs to be exposed as a service to client, has to be decorated with this attribute on it's definition. For example, a class which provides different operations on an entity of type Employee, as a service to client, will have this attribute added on its definition.

[ServiceContract]
public class Employee
{
    // Your service Methods
}

An important point, this attribute can be added on an interface as well.


2. OperationContract: Once we create a class which will provide services to client, we will add the methods which should be available to client for calling. This is done through the use of the OperationContract attribute. Once this attribute is added, this operation becomes available for client to access. If this contract is not added, client cannot access the method, even if it is a public method.

For example, in above class, if we need to make any method callable by client, we need to add the OperationContract attribute.

[ServiceContract]
public class Employee
{
    [OperationContract]
    public void GetData()
    {
    }
 
    // Not accessible by client as the OperationContract attribute is missing.
    public void DeleteData(Int32 Id )
    {
    }
}

3. DataContract: Now we have the Service class and it's methods. It's turn to configure the data the we would like to be exchanged between  the client and the server. This could be of type Int32, String etc. Exchange of this type of data types is fine. But if we need to pass data of any complex/POCO object, we need to use the DataContract attribute on that object.

For example, if we need to use EmployePOCO type as input parameter or return type of any function in our above service, we need to mark this class with DataContract attribute.

[DataContract]
public class EmployeePOCO
{
    // Class methods and properties go here.
}

4. MemberContract: Normally we use the DataContract to exchange message between the client and server. Sometimes we may need to send the data in either SOAP message header or body. This is done through the use of the MemberContract attribute.

This attribute along with 2 more attributes MessageHeader and MessageBodyMember, allows us to define how the data is being sent through the SOAP message. MessageHeader allows data to be passed in SOAP header and MessageBodyMember allows to send the data through the SOAP body.

For example, we may need to send sensitive data into SOAP header. For this, we use the MessageContract on the complex type and MessageHeader on the property which needs to be sent through the SOAP header.

[MessageContract]
public class UserData
{
  [MessageHeader]
  public string Password
   {
       get;
       set;
   }
   [MessageBodyMember]
   public string UserName
   {
       get;
       set;
   }
}


5. FaultContract: By default the exceptions that occur in a service are not sent to the client. If we throw exception of the type FaultException, it sends the actual exception details to the client. But this is not a good practice that client should never know about the actual technical issue. But it is also important to send the information to client about what has happened in service.

This is where FaultContract helps us. We create a custom class say ExceptionData with properties which specify a custom ErrorMessage and ErrorCode. Then we apply the FaultContract<T> attribute where T is of type ExceptionData, to our method for which we need to pass the custom error message.

[DataContract]
public class ExceptionData
{
  [DataMember]
  public string ErrorMessage
   {
       get;
       set;
   }
   [DataMember]
   public string ErrorCode
   {
       get;
       set;
   }
}

Apply the FaultContract on the method as:

[ServiceContract]
public class Employee
{
    [OperationContract]
    [FaultContract(typeof(ExceptionData))]
    public void GetData()
    {
    }
}

After this, return the FaultException of the type ExceptionData from the method :

[ServiceContract]
public class Employee
{
    [OperationContract]
    public void GetData()
    {
      try
          {
          }
     catch
         {
               ExceptionData exceptionData = new ExceptionData();
               exceptionData.ErrorMessage = "Incorrect parameter passed";
               exceptionData.ErrorCode  = "500";
               throw new FaultException<ExceptionData>(exceptionData);
         }
    }
}

So this was about the concept of Contracts in WCF. Hope you enjoyed reading it. Happy Coding...!!!

Sunday, July 12, 2015

0x800a139e - JavaScript runtime error: SignalR: Error loading hubs.

This was an error that i faced while Error faced while trying to implement Persistent Connection in asp.net signalR application.

0x800a139e - JavaScript runtime error: SignalR: Error loading hubs. Ensure your hubs reference is correct, e.g. <script src='/signalr/js'></script>

The issue in this case was, I was trying to implement the Persistent Connection based hub and had the reference of the dynamically generated proxy file. But in case of persistent hub, we do not need this proxy file.

So solution was, remove the reference and it should work.




Saturday, July 11, 2015

RESTful API using WCF Services



In this article, we will discuss about the concept how we can use WCF services to create a REST based service. We will not go into the details about what is REST architecture style. As per it's type, our service will be of nature, where each method will act as a resource on the internet. So in order to create a REST based service, we will create a new ASP.Net project and add a WCF service project into it. Let's call it RESTService.

Next, we remove any default methods. We add a sample class named POCOClass with 2 properties of Name and Id. Next we add a method in the service, which returns a list of the type POCOClass.

Next, in order to make this service a RESTful type, we need to do some code changes. These include:
  1. Add WebGet attribute or WebInvoke attribute to the methods to allow them to be used with HTTP verbs like GET, PUT, POST etc.
  2. Add a Uri template to these methods, which is nothing but a url which will identify the methods as a unique resource on the internet.
  3. Change the binding to be used as webHttpBinding type.
So let's start by adding the WebGet attribute on the method. To use these attributes, we need to add reference to System.ServiceModel.Web.

Add the WebGet attribute on the implementation of the service method.

Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Net;
using System.ServiceModel.Web;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Web.Http;

namespace SampleApplication
{
    public class RESTService : IRESTService
    {
        [WebGet]
        List<POCOClass> IRESTService.GetListData()
        {
            var _lstPOCOClass = new List<POCOClass>();

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 1,
                Name = "User 1"
            });

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 2,
                Name = "User 2"
            });

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 3,
                Name = "User 3"
            }); 

            return _lstPOCOClass;
        }
    }
}

Next, in order to make it as a resource on the web, we use the UriTemplate parameter to the WebGet attribute above. We also add a parameter named ResponseFormat, to make it return a JSON type.
Code:
 [WebGet(UriTemplate = "/GetListData", ResponseFormat = WebMessageFormat.Json)]
        List<POCOClass> IRESTService.GetListData()
        {
            var _lstPOCOClass = new List<POCOClass>();

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 1,
                Name = "User 1"
            });

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 2,
                Name = "User 2"
            });

            _lstPOCOClass.Add(new POCOClass
            {
                Id = 3,
                Name = "User 3"
            }); 

            return _lstPOCOClass;
        }
Now we need to add settings for making it use webHttpBinding.
First,  we need change the endpoint behavior to use the webHttpBinding. This is to be done inside
system.serviceModel => behaviors => endpointBehaviors => behavior
and change the endpoint to use the webHttpBinding. This is to be done in:
system.serviceModel => services => service => endpoint
The complete settings will look like:
<configuration>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>

      <endpointBehaviors>
        <behavior name="web">
          <webHttp/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <services>
      <service name="SampleApplication.RESTService">
        <endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
                  contract="SampleApplication.IRESTService" >
        </endpoint>
      </service>
    </services>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>

</configuration>
That's it. We are done with the settings and now we simply need to test it. To do this, we will browse the service to get the url.

Next, we use the Google chrome extension app called Postman to test the service. Add the service url and select GET as the HTTP verb.

Click the Send button and see the results.

Next, let's try to POST some data to it. So we add another method which receives data of the type POCOClass from the HttpBody. We also add the WebInvoke attribute and the UriTemplate for it.
 [WebInvoke(UriTemplate="/PostUserData", RequestFormat=WebMessageFormat.Json)]
        void IRESTService.PostUserData([FromBody] POCOClass userData)
        {

        }

Now again, we use our POSTMan app to POST the data to the same url, but with method name as per defined in the uri template.


Click Send and see the results. We are getting the results on the server.

Easy, isn't it. So create the REST services as per the requirements. No need to use the SOAP based WCF service, making it lighter.

Function breakpoints in Visual Studio

Previously we discussed the concept of Hit Count breakpoints and Conditional breakpoints.  We will now discuss the concept of Function breakpoints. This functionality allows us to set the name of any function as the condition for the breakpoint to hit.
Let's start by creating 2 different functions SetString() and GetString() and call them as SetString() first and then GetString(). 

To set the breakpoints for this type, go to Debug -> Windows -> Breakpoints to open the Breakpoints windowSelect the option New -> Break at Function option from the window.

This open ups a new window and we specify the name of the GetString() function as the function condition for the breakpoint to be hit.

Hover the breakpoint and we can see its details.

Run the application and breakpoint will get hit only when the execution of the Getstring() function starts.

Easy and helpful, isn't it. Happy coding...!!!

Sunday, July 5, 2015

Hit Count breakpoints in Visual studio

Previously in our discussion, we discussed about the concept of Conditional breakpoints. In this article, we will discuss about the Hit Condition breakpoints.

Consider a case where you have a for loop with iteration of thousands of records. You know that your records at around 500th location is corrupted and you need to debug that value. Will you sit and keep pressing F5 until the record number 500 is reached ? This is where you can use the concept of Hit Condition breakpoints. This is achieved by setting Hit Count condition on the breakpoint i.e. hit the breakpoint when it has iterated 499 times.

Let's create  a sample application to understand this.  Add a for loop with iteration of 1000 records and add a condition to hit the breakpoint when the 500th record is being iterated.
To add the condition, right click on the breakpoint and select the 'Hit Count' condition. This will open up a window where we can define a condition to hit the breakpoint only when it meets the criteria set for its execution.







Here we have 4 different conditions and these are self explanatory in their details. So we select the condition 'break when the hit count is equal to' and set its value to be 500.

Hover to the breakpoint and see the details:


Run the application and see the value of variable 'i', when the breakpoint is hit.



So here when the value of i becomes 499 (starting from 0), it is iterating the 500th record and the breakpoint gets hit. So set the break point and enjoy the debugging...!!!

Saturday, July 4, 2015

Conditional Breakpoints in Visual Studio

This is just a simple trick which many of you might have been using. It's a small but very powerful tip, especially helpful when you are debugging large code base. This is the concept of Breakpoint Conditions.
As the name itself suggests, it is setting the breakpoints which are hit, only when certain condition is met. It's easy to implement as well. Create a new application and set a normal breakpoint.



So this will be hit every-time the Page_Load executes. This could be very annoying when you are debugging for a bug and this keeps on hitting this breakpoint. So let's make it conditional. Simply put your mouse on the breakpoint, right click and select 'Condition'.




This will open up a window where we can define a condition to hit the breakpoint only when the condition is met. Even you get the intellisense help for it.



See how the color of the breakpoint changes with a plus sign on it. Also, hover over it and you can see the details.




Now let's run the application. First time, no breakpoint is hit. Press the button for postback and see the breakpoint gets executed.




Even you can set this condition to be on your variables or properties etc.  So happy debugging now...!!!