Friday, December 26, 2014

ASP.Net Web api self hosting using windows service

In my previous article, we discussed about web api self hosting using console application. This time, we will use the windows service to perform the self hosting of the web api. So let's start by creating a new windows service project type. We call it as WindowsService_HostAPI. 
In order to perform the self hosting of web api, we need to add references to the self hosting libraries. For this, we use the nuget package manager and install the references.

Next, we select the project in which we need to add the references and the following libraries get added to the project.
Next, we add a new item of the type web api controller class and name it as ValuesController, which inherits from ApiController. Make sure that the suffix of the class is  'Controller'.  This is required for the routing process to handle the incoming request. We remove all the default methods and add a simple method named GetString which returns a string value.

Now we need to configure a hosting server which would host the api. The point here is that this server must get configured in an event, which gets fired when the service is started. So we will use the OnStart event of our service class (which inherits from ServiceBase class). When the service is hosted, this OnStart event will be fired and the hosting configuration will be registered. So our code becomes:

Build the solution. Now the api is ready to be hosted and for this, we only need to install the service and than start it by navigating to the list of installed services.
To host this windows service, go to the service design view, right click and select 
Add Installer

1. Go to the properties of serviceInstaller1 and change the ServiceName property to WebAPISelfHosting. This will be name with which the service will get installed.
2. Go to the properties of serviceProcessInstaller1 and change Account property to LocalSystem.
To install the service, we need to use the installutil.exe from the location:
or you can start the visual studio command prompt (as an administrator) and use the following command to refer to the above location of installutil.exe.
cd  C:\Windows\Microsoft.NET\Framework\v4.0.30319
Execute the following command in the command prompt to install the service.
installutil ...\WindowsService_HostAPI\WindowsService_HostAPI\bin\Debug\WindowsService_HostAPI.exe
I have used only relative path here for the example. Make sure that you use the complete path, from the root. This will install the service on the system.

Go to the list of installed windows services, select the service named WebAPISelfHosting, right click and start the service.

Web api is now hosted and we can create a client to generate request to the api. For this we create an html page which will make an ajax call to the api.

Run the client page and also start the network capture using F12. See the results, web api returns the results.

So this is how we can host the web api using a windows service. Hope you enjoyed reading it. Happy coding...!!!

Sunday, December 21, 2014

ASP.Net Web API self hosting

In this article, we will discuss the concept of self hosting the web api. We will not get into the details of what is a web api or why it should be used. Our main focus in this article will be on hosting process. There are two ways to host a web api:
1.      Self hosting
2.      IIS hosting
As the name suggests itself, self hosting, web api is hosted independent of the main/client application. So the actual web api is hosted either in windows service or console application running on the server. For our case, we will be using the console application to host it. So let's start with it.
Create a new windows application. We will name it as WebAPI_SelfHosting. We need to add the references to the ASP.Net Web API Self host libraries to implement the web api. For this, we will use the nuget package. So go to Tools -> Nuget Package Manager -> Manage NuGet Packages for Solution. Search the library and click Install. 

Select the solution file to which we need to add the library.

Click on 'I Accept' and the references will be added to the project. This will also install the dll's required for the self hosting process which is System.Web.Http.SelfHost.

Next, we will be add a new item in the project, of type, Web API Controller class. We will call it as ProductsController.cs . Here, we have two important points to take care of:
1.  Web api controller must inherit from the ApiController class.
2.  Suffix the name of the class with
 'Controller'  keyword, as the routing process will identify the api controllers, as the ones, which have suffix 'Controller' attached to them. This will help the routing procedure to process the incoming request accordingly.
We also add a Product class with some properties and a method named GetProduct(). This will simply return a Product detailed object. See the code below:

So our basic business logic is ready. Now we need to configure the api, so that it can be hosted. The basic requirement to configure the self hosting, is that we need to make sure that when the hosting application (windows application or windows service) starts, the required configuration is registered for the web api. So we will be writing our code in the Main method in Program.cs file.
We first define the self hosting configuration using the HttpSelfHostConfiguration class. This will include declaring the host url and the routing template for the web api.

Next, we create an instance of the HttpSelfHostServer class and assign to it the configuration, defined above and start the server to listen any HTTP request.

If we hover over the name of this class, we can see its description as:
Implementation of an System.Web.Http.HttpServer which listens directly to HTTP
which is very much self explanatory i.e. it creates a type of hosting server, like we have the IIS server for hosting our applications.
Now run the application and our web api is hosted and ready to be used by a client application. For this, we create an html page in an mvc application and make an ajax GET request to the method we created above. There is no difference in how we make the ajax request to web api. It remains the same as we would have done in our normal application.

Run the application. Also start the network capturing in browser to see the results.

See the response body contains the results returned by the api, as a json. Although the api is being hosted in a windows application, still it s being referred to as a self hosted web api. You may face the following issue, when you start the web api application:
{"HTTP could not register URL http://+:8080/. Your process does not have access rights to this namespace (see for details)."}

This something related to the permissions. Without going much into depth of the issue, just restart the Visual Studio as an administrator and start the application and it will be fine. So this is we do the self hosting of a web api.

Saturday, December 13, 2014

Friend Assembly using C#

Internal access modifier in C#

An internal modifier allows access to the elements of an assembly, within the same assembly only. This means if we have one class library type project with two classes, Class1 and Class2, any internal classes in then it will be accessible only within this class library project. When we add a reference of it's DLL to any other project, the internal classes of this library will not be accessible in that project.

By default, class is internal in nature.

So, using an internal access modifier is like telling our children not to talk with strangers. We tell our assembly not to share the internal classes with the stranger assemblies.

Access internal members outside the assembly

That was the basics of the internal modifier. But suppose we have created a product based library. Now we need to provide access to one of our internal member classes to some of our customers and not all of them. The very first thing that will occur to us is to make the class public. But this will expose the class to all the customers, that they do not even require. Moreover, it creates a security vulnerability. This is where friend assemblies are useful. We will simply tell our assembly or DLL that this class is your friend and you can share your internal members with it. To do this, we just need to add the following line of code to our namespace.
[assembly: InternalsVisibleToAttribute("Name_of_Assembly")]

And that's it. We are done. Build the assembly and we can now access the internal class members as well.

Adding this attribute instructs our assembly to share the details with stranger assemblies. It's like telling our children name of the people with whom they can talk.

Access internal members of the class outside the assembly: Example

For this, we will create a new project solution and add two project types, one class library named ClassLibrary and the other a console application named Consumer. In the class library, we add two classes, one internal named InternalClass and the other public named PublicClass.

Next, we build this project and add its reference to the Consumer project. Then we try to access these two classes in the console application. We will be able to access the public class but not the internal class.

Now in order to access the internal class in the console application, we add the InternalsVisibleTo attribute, with the name of the assembly in which we would like to access the internal members. In our case, it is named Consumer. See the code below.

Build the code and we can now easily access the internal members. In this way, we can add as many assembly names as we need.

So this is all we had to do to allow access to internal classes. We can add multiple attributes, with the names of the assemblies with which we would like to share these internal classes. But the condition here is that we need to add this attribute at the namespace level. I hope you enjoyed reading it!

Saturday, December 6, 2014

checked & unchecked keywords in C#

In this article, we will discuss about the checked and unchecked keywords. Let's start with their definitions first. As per MSDN checked means,
The checked keyword is used to explicitly enable overflow checking for integral-type arithmetic operations and conversions.
and unchecked means,
The unchecked keyword is used to suppress overflow-checking for integral-type arithmetic operations and conversions.
Here, overflow checking means that when the value of any integral-type exceeds its range, it does not raises any exception, instead will give unexpected results. Let's discuss with an example of integers.
We know that range on an integer is 2147483647. Let's see what happens when we try to add more to it, say add 50 to itSee the code below:

It gives the compile time error :
Error 3 The operation overflows at compile time in checked mode ...\checked\Program.cs 23 29 checked.
So, at-least directly we cannot do this. Also, in most of our cases, we work with values from database. So we fetch them, store in variables and then perform any operations on it. In such a case, there will be no compile time or run time error, instead will be unexpected results. Let's check see what happens:

As we discussed, an unexpected result. The unexpected result is generated in a pattern. The add operation adds a given number up-to maximum possible value of its range. After that it resets itself to its minimum value of its range and then starts adding again. In our case, we were adding 50 to 2147483647. So let's see how it works.
§  It starts adding 1 at a time. By first addition of 1, it resets itself to minimum value of -2147483648. Now further 49 is to be added.
§  Then it re-starts from its minimum value of its range, which is -2147483648 and starts adding them one by one.
-2147483648 + 49 = -2147483599
We can handle this overflow of the value using the checked keyword. It will not give correct result but at-least it will give you exception of the type System.OverflowException and you can easily identify the issue. So apply the checked keyword, wrap the code in try-catch block and perform the alternate operation in catch block. Let's change the code accordingly now:

So you can now at-least handle such kind of situation, instead of giving incorrect results to the user.
Now, earlier in our discussion, we discussed that directly we cannot add more value to the maximum value of integer. What if we need to do this. This where we can use the unchecked keyword. Just use the same code with the unchecked keyword and it will compile and will even run to give the results. See the code below:

So to summarize the discussion:
§  If we are directly trying to add something to maximum value of integer, we will get compile time error.
§  To avoid the above compile time error, we can use the unchecked keyword.
§  Using the unchecked keyword or indirectly adding more values to a maximum value of its range, results in unexpected results, generated in a pattern.
§  To handle the overflow value, we can use the checked keyword, apply try-catch block and handle the operation in catch block.
§  These keywords  can be applied as blocks of code or directly on the variables(like in our discussion above). See the code below:

So this about the use of checked-unchecked keywords. Hope you enjoyed reading it...!!!

Friday, December 5, 2014

Dynamic query using LINQ

In this article, we will try to understand how we can create a dynamic query in LINQ. In order to do this, we first need to understand the concept of expression trees.
What is Expression tree?

As per MSDN : Expression trees represent code in a tree-like data structure, where each node is an expression, for example, a method call or a binary operation such as x < y
In simple language, an expression tree is a tree data structure, which can be used to represent some executable piece of code, in the form of nodes of this tree. This code is then converted into actual executable code. This kind of property allows you to generate the dynamic linq query. So let's start with the code :
We have the following linq query which returns data of a Customer, based on the CustomerId.
_dbEntities.Customers.Where(cust => cust.CustomerId == 10).FirstOrDefault();
We will now convert this query into dynamic query, by creating an expression tree for it. First, we need to add the namespace System.Linq.Expressions. This class contains various static methods, which we will use to generate the query. These methods include Parameter, Constant, Property etc. We will be using these methods to generate the query, in multiple steps. So let's start
Step 1 : We need to first generate the input parameter which is represented by code on the left of the lamda operator i.e. cust =>. For this, we use the Expression.Parameter method, which will be passed 2 parameters Type and String name. Here
§  Type is the type of entity we are using i.e. Customer entity.
§  String is the any name we use to represent an input to the parameter, which in our case is cust. So our code will be :
ParameterExpression pe = Expression.Parameter(Customer, "cust");
Step 2: Next, we need to use the CustomerId property to make the comparison with a value which is represented by cust.CustomerId in our initial query. So we need to get that property first and we use the Expression.Property method for it. So our code will be:
var _prpToUse = Expression.Property(pe, "CustomerId");
Step 3: Now we need to compare our CustomerId with some value say 10 in our case. So we generate our expression for this using the Expression.Constant method as :
var _cnstToUse = Expression.Constant(10);
Step 4: Next we need to combine the above two expressions, to generate expression cust.CustomerId == 10. For this purpose, we will use the Expression.Equal method. So our code becomes:
var qry = Expression.Equal(_prpToUse, _cnstToUse);
Step 5: Now, we have the expression of the form cust => cust.CustomerId == 10 and need to combine it with the Where extension method, to complete the query. So our following code will pass the above expression to tit, using the MethodCallExpression method.
MethodCallExpression whereExpression = Expression.Call(
new Type[] { lst.ElementType },
Expression.Lambda<Func<Customer,bool>>(qry, new ParameterExpression[] { pe }));
Step 6: Finally, we need to execute the query it using CreateQuery method in the provider on which we need to execute the query.
Here, lstData is the list of customers which we have from the database. Execute the code and see the results. It will be the same that we had at the start of the article.
In all the above steps, except step 6, we have created expressions of code that are combined to create an Expression tree, as a whole, which is nothing but the query that we executed at the start of the article.
Below is the generic implementation of the code that we created

So this was about the use of Expression trees to generate the dynamic linq query. Hope you enjoyed reading it.