Saturday, July 18, 2015

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