Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Thursday, July 31, 2014

How to generate strongly typed C# client for ASP.NET Web API

Recently, I was looking out for ways to consume the ASP.NET Web API via strongly typed C# client (i.e. a client similar to C# Web Service Client).

Initially I thought, Microsoft would have a utility to generate the client but, I was wrong, they don't have any such utility.  Why would they not provide such a utility is beyond me, I really don't understand why would they not expose such a utility, it would have benefited everyone who wants to consume Web API using strongly typed classes.

None the less, After a bit of googling, I found this awesome open-source project which does exactly what I needed.

The detailed instruction on how to use it can be found here.  In summary you need to do the following steps to generate the strongly typed C# client for ASP.NET Web API


How do they do it!

Setting up the Server
  • Install the NuGet package "WebApiProxy" into the project that hosts the Web API.  This package will host a proxy endpoint for your service.  This proxy endpoint can be used as the JavaScript client to invoke the Web API via JavaScript.  The endpoint will be hosted at URL "/api/proxies"
  • Once you have this installed in your Web API, if you browse the URL "/api/proxies" you should see a JavaScript client already generated!
  • This package also exposes the metadata necessary to automatically generate the C# client.
Creating the client
  • Create a Client project which will be used to invoke the Web API via C#.
  • Install the NuGet package "WebApiProxy.CSharp" into this project.  This package seamlessly integrates the proxy generation build task with the project build step.  
  • Every time you rebuild the project it will try and generate the C# client for the desired Web API.
  • The configuration required to generate the C# client is placed in a file called "WebApiProxy.config"
  • This is the simplest XML file I have ever seen.  It only expects you to provide the 
    • endpoint - The location of the Web API where it will be hosted.
    • namespace - The namespace in which the C# client will be generated.
  • That's about all the setup that is needed to generate the strongly typed C# client for a given Web API
Example
  • Imagine you have an EmployeeController on the Service side. 
  • We can invoke this Web API via our generated client as follows
  • As you can see its very straightforward and intuitive to invoke the Web API with strongly typed C# client.
Further Reading
  •  I went ahead and modified the source code to generate not just the Async method but also the Sync version of the Web API.  
  • This is done so that anyone who wants to invoke the Web API in a Sync manner does not have to deal with the Async behaviour.
  • The above code for Sync invocation can be reduced to the following
  • Updated source can be found here
  • TIP: In case if you are trying to modify the source to suite your needs, make sure that you kill the MSBuild process before you rebuild the Task and the Client.
Thats all folks!  

Sunday, November 6, 2011

Making operator precidence more explicit with NHibernate Linq Provider

Recently, while writing one of the NHibernate queries, using the NHibernate LINQ provider we faced a very interesting problem.

The issue was the NHibernate LINQ provider was not adding appropriate parenthesis to make the operator precedence more explicit.

The query was simple enough, we wanted to get a list of records based on certain condition. Let's say, for the sake of this post, consider that there is an employees table with ID, Name and Salary columns. The DDL to create the employees tables on SQLServer looks like
NHibernate class against which this table is mapped is called Employee. The Employee class and its mapping file looks like
As you can see there is nothing fancy about the table or the mapping.

Let's talk a bit about the query we want to fire against the employees table.  We want to get list of employees whose name equals "Git" OR whose salary is between 1000 and 10000.

The SQL that would do the job for us would look like:

Again nothing remotely fancy about the SQL.

Let's try and write the same query using, NHibernate LINQ provider and lets look at the generated SQL.  The NHibernate LINQ query to get similar results would look like:
The where condition is the exact replica of the SQL where condition that we had seen earlier.  Only difference this time around is, we are using the LINQ syntax.

So far so good, the problem starts when we look at the SQL that is generated. The simplified version of the SQL generated from the above LINQ query looks like

I have removed all the named parameters that NHibernate adds, but essentially the query looks like the one shown above.

Whats wrong with the query? 

Notice that there are no parenthesis to enforce the operator precedence!  Because of this, it might get confusing to identify the order in which the operators will be process.

Consider a case when you have a complex query with many conditions and if proper parenthisis are not applied then it could get confusing.

I tried various permution and combination to force the NHibernate LINQ provider to spitout the parenthesis correctly, however I was not successful in doing so.

Finally, I decided to switch to the QueryOver API provided by NHibernate.  QueryOver API is a Fluent wrapper over the NHibernate Criteria API.  Using the QueryOver API the above code would look like

As you can see the nothing much has changed.  The only changes are, .Query() call has been changed to .QueryOver() and instead of .ToList() we have to call .List().

Let's look at the generated SQL Query:
As you can see, it correctly adds the parenthesis to make the operator precedence more explicit!

Sunday, October 2, 2011

Strongly Typed Session Using MVC3 and Spring.NET - Part - 3

This is the last post in the series of posts to show How we can achieve Strongly Typed Session using MVC3 and Spring.NET.  In previous two posts (first and second) we saw what were the benefits of strongly typed session and how we could enable the session scope using Spring.NET 1.3.1.

The question that we had left unanswered in the previous post was:  

What is "session" scope supposed to do with Strongly typed sessions?

Well the session scope is the key, in this post we will see how it enables us to create a strongly typed session.

The session scope enables us, to register objects with scope=session.  Spring.NET will create one instance per user Session for objects that are configured with scope=session.  This means effectively we can use such an object to hold information that would otherwise be saved in the HTTP Session.  Since, these objects are configured in Spring.NET, they can be injected as dependencies in any other class. 

Where would we want to inject such a class?

MVC Controllers are a good place to do so.

Why? 

Because, controllers are the class that would do some business processing and then would want to set some information in the HTTP Session.

For e.g. Lets consider this scenario, we have a AuthenticationController which has a Login action.  This method takes in the username and password as argument.  This method calls the AuthenticationService to find whether the username and password combination is valid.  If the username and password are valid, AuthenticationController wants to set the username in the session so that it could be used by other pages to show user information on the page.

In our case we do not want to use the HTTP Session.  Hence, our AuthenticationController will put the username in some object, let's call it UserContext, which has been configured in Spring.NET with scope="session".

But wait,

What if two users are trying to login at the same time?  Will one thread overwrite the username saved in the UserContext by the other thread?

As the UserContext object is configured with scope="session", Spring.NET is smart enough to understand that, two requests are coming  to AuthenticationController are coming from two different user sessions, it injects two different instances of UserContext in the AutheticationController for two different user sessions.  Hence, one thread will *not* overwrite the username set in the UserContext by the other thread. 

So far so good.

What happens when, user who had logged in earlier (i.e. UserContext has the UserName property set), sends another request to the server?  How do we ensure that correct UserContext instance is injected in the Controller so that previously set UserName could be retrieved?  

Again, Spring.NET is smart enough to understand that, for the given user session an instance of UserContext was already created, Spring.NET will find the correct UserContext instance associated with the user session and injects it in other Controllers/objects that need it.  This effectively eleminates the direct use of HTTP Session for us.  We can be sure that, whatever information we set in UserContext will be specific for a given User Session and correct UserContext instance will be injected in the controller whenever we need it.

I know, at first it all looks very confusing, but lets look at the code to make things clear.

These are the steps required to configure the UserContext and AuthenticationController
  • Register the UserContext in Spring.NET configuration file with scope="session"
  • Write the implementation for the UserContext
  • Register the AuthenticationController in Spring.NET configuration flie with singleton="false".  Add to this the dependency of UserContext.
  • Write implementation of Login Action to set the UserName Property in the UserContext.  Write another action method let's call it UserInfo which will retrieve the UserName Property from the UserContext object and display it on the UI
  • Write the RazorIndex view to show the UserName from the ViewBag 
  • Test that the setup is working with two different browser windows trying to Login and access the UserInfo at the same time.  We should see correct user names being displayed based on where the request is coming from
Lets look at individual steps in detail

Register the UserContext in Spring.NET configuration file with scope="session"

Update the web.xml and add the configuration for UserContext as follows
Notice that we have registered the UserContext object with scope="session". Spring.NET will understand that the UserContext object is registered with singleton but in session scope i.e. One UserContext object per user session.

Write the implementation for the UserContext 

The UserContext class would be simple enough.
Register the AuthenticationController in Spring.NET configuration flie with singleton="false".  Add to this the dependency of UserContext

Update the web.xml to add the configuration for AuthenticationController as follows. 
Write implementation of Login Action to set the UserName Property in the UserContext

AuthenticationController will have a Login Action and UserInfo Action.  Login Action will set the UserName in the UserContext.  For demonstration purpose we will append the SessionId to the UserName.  This will show us that, when we request the login action method from two different browser windows we will see different user name on the UI.
Write the RazorIndex view to show the UserName from the ViewBag

The RazorIndex.cshtml will simply show the UserName from the ViewBag if its not null. Else it will show no user logged in yet message.
Test that the setup is working with two different browser windows trying to login and access the UserInfo at the same time

Enough theory, lets see the setup in action.  As they say,

Real test is in the real world!

Let's try and browse the URL Authentication/UserInfo from FireFox and Internet Explorer and see what happens

User not logged in - FireFox

User not logged in -IE
As the UserName is not set in UserContext we see no user name set message.

Now in IE, lets browse the URL Authentication/Login and see what happens.
User Successfully Logged in.  UserName and SessionID shown - IE
As we can see, the page redirect to the Authentication/UserInfo User name with session id is shown.

Lets reload the Authentication/UserInfo the page on FireFox.  Remember that, we have not yet visited the Login page on FireFox, but we have visited the Login page on IE.
Even after user is logged in on IE, he/she is not logged in on FireFox
Yep even though we have set the UserName in the user session started from IE, it does not effect the UserContext reference in the User Session started from FireFox.

Now lets visit the Authentication/Login URL in FireFox as well to see what happens.


Now user is logged in even in FireFox





As you can see it redirects to Authentication/UserInfo with UserName set.  Notice that the session id in FireFox window is different from the session id in IE.
Notice that the Http SessionId are different in two images

This effectively proves that UserContext reference plugged in by Spring.NET when request comes from IE is different from the one that gets plugged in when request comes in from FireFox i.e. We have successfully injected different UserContext reference per User Session. UserContext object can now be used to hold any information that would have be placed in HTTP Session. This effectively eliminates the use of HTTP Session and gets us a strongly typed object which can be used as a replacement to the HTTP Session.

That's it! we have successfully achieved Strongly Typed Session in an MVC3 application using Spring.NET.

Tuesday, September 27, 2011

Strongly Typed Session Using MVC3 And Spring.NET - Part - 2

In my previous post, we saw why its a good idea to have strongly typed HTTP Session. In this post we will do the real thing (well at least first part of the real thing).

Using Sping.NET we can control the objects lifecycle. By default the Objects configured in Spring.NET are Singleton for the entire application (singleton for scope="application"). Singleton for the entire application means, Spring.NET will create only one instance of the given object for the life-cycle of the application.  Service classes, DAO classes etc are a good fit for Singleton Pattern.

However, there are other Object Scopes that can be configured in Spring.NET.  These Scope's tell Spring.NET that, A given object is singleton but in a given scope.

One of the interesting scope is session.  Session scope is only available if we use a web-aware Spring IApplicationContext implementation.  For such objects, Spring.NET would create one instance per HTTP Session.  In this post we will see how we could take advante of the session scope, to create Strongly typed session in an MVC3 application.


Enough blabber.  Let see how exactly its done.

How do they do it!

As we had seen in one of the previous post to Integrate Spring.NET with MVC3 application, we had used the Spring.Context.Support.MvcContextHandler.  This class instantiates Spring.Context.Support.MvcApplicationContext, which in turn initializes the spring application context.

Support for session scope is porivded by spring.web.dll.  Unfortunately, as of Spring.NET 1.3.1, spring.web.mvc.dll does not depend on spring.web.dll, which effectively means, MvcApplicationContext is unaware of the session scope.

Hence, using just the MvcApplicationContext there is no way we can eable the session scope for a certain objects.  Its a bug you can find more details here.  But where there is will, there is a way!  There is obviously a way around this problem.

Here are the steps to enable full session scope support for any object in Spring.NET 1.3.1
  • Update the web.config to use a custom WebContextHandler
  • Register the spring WebSupportModule in web.config under the <httpModule> section for IIS6 and under the <modules> section for IIS7+
  • Implement the custom WebcontextHandler.  Override the property DefaultApplicationContextType.  This property informs Spring.NET about the class type of ApplicationContext that Spring.NET should instantiate.  This will be again a custom class that extends from Spring.Context.Support.MvcApplicationContext.
  • Implement the custom class that inherits from Spring.Context.Support.MvcApplicationContext.  This class will basically override two methods
    • CreateXmlObjectDefinitionReader to return the instance of WebObjectDefinitionReader
    • CreateObjectFactory to return the instance of WebObjectFactory
That's it!  We have now successfully enabled the session scope for Spring.NET 1.3.1.  Let look at the actual code.

Step - 1 - Update the web.config to use a custom WebContextHandler

Update the web.config configSection to look like

The class aspnetwebFormsWithMvc3App.Context.MvcWebContextHandler is our custom class where we will override the property DefaultApplicationContextType.

Step - 2 - Register the spring WebSupportModule in web.config under the <httpModule> section for IIS6 and under the <modules> section for IIS7+ 

Adding the spring module for IIS6 and IIS7

Step - 3 - Implement the custom WebcontextHandler

Lets look at the custom WebcontextHadler class aspnetwebFormsWithMvc3App.Context.MvcWebContextHandler

As you can see this class is pretty simple, it just overrides the property DefaultApplicationContextType to return the class type of custom WebApplicationContext.

Step - 4 - Implement the custom class that inherits from Spring.Context.Support.MvcApplicationContext

This is the class where the real work is done.
That's it! We have successfully enabled the session scope in MVC3 application using Spring.NET.

Question is: What is all this supposed to do with Strongly typed sessions?

In the next and the final post in this series, we will see how we can take advantage of session scoped objects to create the Strongly Typed Session in an MVC3 application using Spring.NET. 

Wednesday, September 21, 2011

Strongly typed Session with MVC3 and Spring.NET - Part - 1

In every Web project I have worked so far, always there is a need to store some or the other information in HTTP Session.

I am very finicky about putting things in the HTTP Session.  IMHO HTTP Session should be kept as light as possible.  There should be a very very strong and compelling reason to put a certain value in the HTTP Session.  Having said that, I do agree that there are times when we want to put certain information in the HTTP Session like user name, user id, etc.

With me so far?  Till now we understand that, we do not like to put things in HTTP Session, however, we understand that there is a definite need to put certain things in HTTP Session for the app to work correctly.

Question is, Is there an alternate to putting things in HTTP Session?

In this series of three posts we will try to answer this question.  We will try to use MVC3 and Spring.NET to eliminate the need of putting stuff in HTTP Session.

But wait a minute, let's first answer this question,

Why is putting things in HTTP Session is such a bad idea?  

Lets start by looking at the code that will put UserName into the HTTP Session.
Does it remind you of code that you have seen in one of your applicatoin? It certainly reminds me of code that is used all over the place in one of the projects that I had worked.

I totally hate to see code like this.  Why whats wrong with such code?

Session is used like a Hash Table:

In our example, key of the hash table would be UserName and value will be Git Shah.  Imagine while putting/retrieving values to/from the HTTP Session, if incorrect keys are used, results could be catastrophic.  Even a small typo like one shown in the example below would yield incorrect results
Ofcourse there are ways to get around this problem. Simplest of them is to use a Static Class that holds all the keys as constants.

However, you can still not gaurentee that every programmer on your team will always always use constant keys from the static class.  Believe me, because of human error or some other unexplainable reason, someone would use hardcoded inline key to put value in the Session and rest of the team will curse him/her for eternity! 

Session values are not strongly typed:

We have inserted a string value Git Shah in the HTTP Session against the key UserName but when we want to retrieve the value from the session we will have to typecast to its correct type.  In our example to retrieve the value of UserName key in HTTP Session code would look like
I have a name for code like that, I call it A Time Bomb!

Its just a matter of time before which you start getting a class cast exception.

Dude, whats in my Session? Where are these values used?

Can we say for sure what all values are stored in our session?  

Another important question to answer is, Can we say for sure, from what all places in the code are these values accessed?

These are a very important questions.  Answers to these questions are absolutely vital for the health of your application.

In one of the projects that I had worked, we were extremely confused for a very long period of time.  The question that was bothering us was, who was setting a specific value in the session and in what condition?

Consider an example

UserName key is populated in the LoginController.Login method. Lets look at another place where UserName is used.
AccoutController.UpdateUser updates the value of the UserName key in the HTTP Session to the new value passed as argument and AccountController.GetUserDetails method fetches the value of the UserName key from the HTTP Session and sets the ViewBag.UserName property.

As you can see in our simplistic example UserName key of the HTTP Session is used at three places.  In real life, it would be used in many more places than this.  The code that accesses the UserName key from the HTTP Session would be littered all over the place!

How will we find the exact places where UserName key is populated/fetched into/from the HTTP Session?

There is no easy way to find the exact places where UserName key of the HTTP Session is used.  We can extract a constant for the UserName and then search for its usages, but still this is not a full proof way, as I mentioned earlier, there are many fools out there who will not bother to use the constant and use an Hardcoded string key instead.

These are few of the problems that are a big concern to me.  Question to be answered is,
  • How can we avoid such code?  
  • How can we achieve an alternate option that will discourage people from writing such code?
Before we dig deeper into the solution, lets first focus on some of the design goals that this new solution should have.
  • Things that we put into and fetch from the session should be strongly typed objects.  There should not be any cast of any sort.  This will avoid Time Bomb like code.
  • Session should not be used as a Hash Table.  Whatever we put into the session should become a property of the session which can be accessed from anywhere in the code.  Moreover, because it becomes a property of the HTTP Session, we would get all sorts of intelli-sense on it.  There is no chance of any typo in this case.  For e.g. the existing code
Should no longer be required instead we should have code that looks like
  • At any point in time, it should be easy enough to find the exact places where a certain property of HTTP Session is used. In some ways this point is related to the previous point. If we are able to convert Keys of session into strongly typed Properties then we can just search for the usages of those properties and we know exactly where those properties were used!
Enough goals to start with.  Question is, Can these goals be implemented in real life? 

Well, the good news is, these goals are definitely implementable.  In fact its not too difficult to implement these goals when we use Spring.NET with MVC3. 


What is the bad news?  You will have to wait for my next posts to see how exactly we could implement these goals :)

Stay tuned folks in the next couple of posts we are going to have some fun with HTTP Session Management!

Saturday, June 11, 2011

Visual Studio 2010 Fixing "The referenced project XX does not exist" Error

Recently one of my friend was facing a weird issue while building our application. The application was developed in C#. We were using MSBuild as the build tool.

What was the issue?

The issue was simple, she was not able to compile the application.

The issue was special in many ways because, all of us (i.e. her team members) were able to compile the project just fine. Even the continuous integration service - Jenkins (formally Hudson), was able to compile the application. We were not able to compile the application only on her machine. The build failed with the error

The project "AB.dosomeprojects.Services.FillImporter.Service.csproj" referred the project "abcdefgh.dosomeprojects.Common.csproj" which was in the path "..\..\..\abcdefgh.dosomeprojects\abcdefgh.dosomeprojects.Common". The path was relative to the Service project directory.

The directory structure was correct, Common project was correctly reffered from the Service project, but still we were not able to build the app on her machine.

Initially, we thought that there must me some local changes on her machine because of which, she was not able to run the build on her machine.  Build was not passing neither with Visual Studio 2010 nor with MSBuild and that too only on her machine.

We looked for any local changes on her machine, but unfortunately her machine was clean.  There were no local changes.  We were simply clueless!  Why does the project build fine on other developers machine while it does not build on her machine?

After some intense Googling, we found an interesting hidden treasure shipped silently by Microsoft Visual Studio 2010.  I call such issues as hidden treasure because, I can hardly believe my ears when I hear/read about such an issue.

I am sure it will come as an surprise to you as well.  The issue is:

The Real Problem:

Visual Studio 2010 fails to build the project when the following conditions are met:
  1. Solution with multiple projects exists, where there exists dependency relationships among them
  2. The sum of the following two path length is exactly added up to 259 characters (= MAX_PATH – 1) 
    1. The path of a referencing project’s directory.
    2. The relative path to a referenced project from the current directory (= a referencing project’s directory).
Hmm, cryptic information lets decrypt it.

Condition 1: We have solution with multiple projects where there exists dependency relationships among them

Yes, we do have the solution with multiple projects in it and one project depends on the other.  In our case the AB.dosomeprojects.Services.FillImporter.Service.csproj depends on the abcdefgh.dosomeprojects.Common.csproj project.  Hence, condition 1 is met.

Condition 2: The sum of the following two path length is exactly added up to 259 characters (= MAX_PATH – 1)

This one is tricky.  Which path sum are we talking about?

Condition 2.1: The path of a referencing project’s directory.

The path of the referencing project's directory, in our case the path of the AB.dosomeprojects.Services.FillImporter.Service.csproj on the file system, which was, "E:\projects\ABC\SVN\dosomeprojectsweb\trunk\AB.dosomeprojects.Services\AB.dosomeprojects.Services.FillImporter\AB.dosomeprojects.Services.FillImporter.Service" has total length of 158 chars.

Condition 2.2: The relative path to a referenced project from the current directory (= a referencing project’s directory).

The relative path of the referenced project from the current directory, in our case its the relative path of abcdefgh.dosomeprojects.Common.csproj, which is, "..\..\..\abcdefgh.dosomeprojects\abcdefgh.dosomeprojects.Common\abcdefgh.dosomeprojects.Common.csproj" has total length of 101 chars.

The sum total of these two path lengths: 158 + 101 = 259!


Wow! condition 2 is also met.

As I said, we have uncovered an hidden treasure of Visual Studio 2010.  Its unable to build the project when the path length of referencing project + path length of relative path to a referenced project = 259!

If the sum total is one less or one greater than 259 it all works fine! On other developers machine the total path length was less than or greater than 259 but was never equal to 259 and because of this reason we were all able to build the project but she was not able to build the project on her machine! Weird isn't?

This issue occurs due to a bug in the Path.GetFullPath in .NET Framework library.  This is a known issue in Visual Studio 2010.

The Fix:

The workaround is pretty straight forward, rename one of the folders a bit longer or a bit shorter and make sure that, the sum of the two path length is NOT equal to 259 chars.

For more information on the issue visit the offical Microsoft Knowledge base article here http://support.microsoft.com/kb/2516078

Now you know, we are having so much fun with .Net (sarcasm intended)!

Thursday, September 30, 2010

Dont be in love with one language, be in love with the concepts

If you are like me, who does programming for living, if you are very passionate about one language and would never ever think of switching to any other language?

Then this blog post if for you. 

During my early years as programmer, I was very passionate about Java and only Java (does not mean that, I am any less passionate about Java today).  I wanted to do programming only in Java.  I thought I can do anything and everything in Java (which is true even today).

I was very apprehensive to do programming in any other language.

Then due to a project requirement I had to work on C++.  Because of that, I started appreciating Java even more.

How elegantly it does memory allocation and garbage collection etc.  I started appreciating the high productivity I could get using Java.


After that, I got an opportunity to work on Ruby on Rails.  I started admiring all the dynamic feature of Ruby language.  Started appreciating closures in Ruby and learned how a few lines of code can be expressed in just on single line.  Started admiring how simple, a modern web framework could be. 

Then came along .Net.  In .Net we had used a dependency injection framework called Castle.  I had used Spring framework from the Java world in the past, because of this I could apply same concepts in Castle framework.  This meant, I was productive from Day 1.  Effectively no learning curve involved!

I realized that as time passed, C# and Java have converged to each other.  Both these languages have learned from each other and implemented some very good features.

Then, I started working on Grails.  I was amazed to see that, Grails and Ruby on Rails are almost 90% similar.  They are so similar to each other in concepts and implementation that, I find the only difference is the syntax!

Again, was able to apply the concepts, that I had learned while doing the Ruby on Rails project in Grails.  End result productive from Day 1.


After all these years, I have learned one thing and that is, all these languages be it Java, Ruby, Groovy, C# etc. be it anything, they implement same concepts over and over and over again.

Now I feel, If someone is a good programmer it actually does not matter which language they use to achieve a given task.

Language and Framework are just tools to achieve a particular task. 

In the olden days car manufactures used old tools to manufacture cars and now as the tools and technologies improve they use better tools and manufacture wonderful cars!

Applying similar analogy we just have to keep updating the tools that we use so that we can create good efficient software.

That's why I keep saying to programmers, don't be in love with one language, be in love with the concepts!
Have some Fun!