Tuesday, December 30, 2014

The Last Alive Architect!

Have you ever met an Software Architect (or even worked with such a person) who thinks, he/she is the last alive Software Architect on the planet?
  • If your answer is Yes, then you will easily relate to this post :)
  • If its No, then I would have to say its definitely worth an experience - After all, life is not only about happiness :P
This rare species is facing extinction, but some of them have managed to survive.  Because they are so rare, finding them is almost like finding a needle in a hay stack!

Since they are so rare, how do you know when you have found one such person?

Here are some of the symptoms that people from this species exhibit:
  • They stopped reading about the latest in software development since 1981
  • They think all open source frameworks are crappy
  • They think the code written by them is the best possible in the world.
    • But in reality their code is a lot crappier than anything that you have seen before.
  • They would build everything from scratch.  Its their habit to reinvent the wheel.
    • For e.g. building a buggy ORM all by themselves (and of course being proud of it :P)
  • They think all code they write is bug free.  Since all their code is bug free, Unit Testing is such a big waste of time.
  • They can "talk static methods, they can walk static methods and the can laugh static methods, because static methods are the way to go!"
    • If you don't know the context around the dialog do see this clip
  • If given an opportunity, they would like to build a new programming language which runs on an Operating System built all by themselves.
As you can see, its definitely worth an experience meeting a person from this species.  My question to my readers is, whether you have ever met someone like this before?  If yes, do share any other symptoms that people of this species exhibit!

As a closing remark, here is an important disclaimer:

Disclaimer: The views expressed in this post are strictly personal and any resemblance to any real person is purely incidental and not intentional.

Sunday, November 30, 2014

How to show realtime translucent background frost/blur effect similar to iOS UIToolbar

In our app "Monster Math - Best Arithmetic Game. Ever" we wanted to show a parental gate screen, when people click on the "Upgrade" or "Restore" button.  The parental gate screen should have a realtime translucent background frosted glass/blur effect, similar to how its shown in the UIToolbar.

So essentially what I wanted was something like this.

The actual view with a carousel, Upgrade and Restore buttons on it

The parental gate with a translucent background frost effect similar to iOS UIToolbar
I searched around, to see if I can find an inbuilt API in iOS that can help us do this.  But unfortunately there is nothing exposed by Apple that helps us do it.  That said, Apple did show a simple trick that can give us the desired effect very easily.

How do they do it!

This can be done in 3 simple steps
  • Convert the underlying UIView to an UIImage
  • Frost/Blur the UIImage
  • Set this new frosted/blurred UIImage as background of your new view
NOTE: The explanation of how to do these steps can be found in this SO Answer.


Convert the underlining UIView to an UIImage


This can be done by creating a new category of UIView and adding the following method to that category


Frost/Blur the UIImage


To frost/blur the UIImage that we created in the previous step we can use the Apples Image Effect category.  The code for ImageEffects category looks as follows

Using this ImageEffects category we can frost/blur any UIImage as follows


Set this new frosted/blurred UIImage as background of your new view


This is by far the simplest step of all.  All that needs to be done here is to set the newly created UIImage as the background of your new view.  Our game is developed with Cocos2d and we could do this using the following lines of code

The end result is very satisfying.  It looks great on the devices as well!

Thats all folks! I hope you like this realtime frosted glass/blurred effect as much as I do.

Friday, October 31, 2014

How to get Apple Cover Flow effect in an iOS app

Recently, for our flagship app Monster Math, I was on a hunt to find a control that gives me the Apple Cover Flow like effect.  After evaluating a few options I ended up using the awesome iCarousel control.

Its extremely customisable, lightweight, has numerous hooks and many many predefined effects, its simply awesome!  In this post, we will see how easy it is to get the iCarousel integrated into our app.

How Do They Do It!

To get this control up and running follow these simple steps

Installation

The installation is stock standard, you can install it via Cocoapods.  Use the following line in your pod file

and then run

Usage
  • There are two protocols that need to be implemented for the iCarousel to work correctly.  iCarouselDataSource and iCarouselDelegate
  • The iCarouselDataSource protocol has two mandatory methods to be implemented 
    • (NSInteger)numberOfItemsInCarousel: This method returns the number of items in the carousel 
    • (UIView *)carousel:viewForItemAtIndex:reusingView: This method returns the view that needs to be shown in the carousel.
  • The iCarouselDelegate protocol has no mandatory methods but its good to implement the following method
    • (CGFloat)carousel:valueForOption:withDefault: This method can return values for different options which alter the display and behaviour of the carousel.
Thats about all the methods we will need to implement to get the cool Apple Cover Flow effect.  Lets jump into the code to see the details of implementation


In this snippet we are just initialising the iCarousel and setting the type of carousel to iCarouselTypeCoverFlow2, this type's behaviour closely mimics the App Cover Flow effect.

Next up are the protocol methods that we described earlier.

This snippet implements the two mandatory methods of iCarouselDataSource protocol.  For the view we are showing a simple image from our assets.  And we have total 4 items in our carousel.

The last and final method just customises two options of the iCarousel.  It basically wraps the view so that we get an infinite view sort of a feeling and adjusts the spacing between the views a bit.

With all the pieces in place lets fire it off and see how it looks!

An Infinite Cover Flow Effect

An Infinite Cover Flow Effect

Pretty impressive for such little code, won't you agree?  

That's all folks, until we meet again, Guten Tag!

Monday, September 29, 2014

How to map Fluently mapped NHibernate Entities To Stored Procedures ResultSet

In one of our .NET/NHibernate project, we wanted to move a time and resource consuming NHibernate generated query to a Stored Procedure.  Nothing else should change, the stored procedure should return the same result set as the query.

The motivation behind this move was to use some native techniques to tune/optimize the query for example compute some intermediate result set and put into a temporary table etc.

Now that the requirements are clear lets dive into the problem a bit more.  We were using Fluent NHibernate to map our entities and the problematic query was generated using NHibernate's criteria API using one of the Fluently mapped NHibernate Entity.  This object was a pretty big object with numerous associations to other NHibernate Entities.

I (being a lazy developer) was in no mood to map the result set of Stored Procedure all over again in an hbm.xml file.  Basically I was trying to do as little as possible to get the job done :).  What I had in mind was to directly map the result set of Stored Procedure to already mapped Fluent NHibernate Entities.

DISCLAIMER: Before I say anything else, let me make it very clear that its was not NHibernate that was generating an un-optimized query, our schema is a legacy schema and the query itself was pretty complex to begin with.  In all likelihood its a problem caused by us not using NHibernate correctly.

OK enough of context setting, let jump into code.

How Do They Do It!

Lets assume that we have two NHibernate entities called Department and Employee.  Department has a one-to-many relationship with Employee (i.e. A Department can have many Employees).  The mapping files of Employee and Department are stock standard, but just for sake of completeness showing them here

Now lets say we have a method that queries the departments by Name.  We want to move this query to a Stored Procedure.  The method and the generated query (for reference)


To move this NHibernate generated query to a Stored Procedure we need to do the following steps

  • Create a Stored Procedure that returns the exact same result set as the NHibernate generated query

  • Configure the stored procedure as a Named Query in hbm.xml file.  

  • Invoke the named query via NHibernate
That's about all the changes we need to map the result set of Stored Procedure to the Fluently mapped NHibernate entities.  As shown above all the lazy loading and other relationships work as before!

These simple steps got us what we wanted without some painful mapping jugglery.  As always, NHibernate just does not cease to amaze!

Thanks all folks!

Shameless Plug: we will be launching the best ever arithmetic app called "Math Monsters" very soon on the AppStore.  Checkout the details on our Website and like us on Facebook!

Sunday, August 31, 2014

How to add NOLOCK hint to EntityFramework Queries

We were using EntityFramework (don't ask me why, but yea thats a reality) in one of our projects as the ORM tool.  In one of the obscene query generated by EntityFramework, we wanted to make sure that it does not acquire any locks on any tables involved.

Obviously, we should be running such a query using the ReadUncommitted transaction isolation level.  However, in certain cases that is really not an option.  In such a situation we need to add the NOLOCK hint explicitly to the generated query.  This post is about adding the NOLOCK hint to any query generated by EntityFramework.

How Do They Do It!

The solution that I found was pretty elegant and nicely abstracted in one class.  The solution described in this post is taken from this SO post.  Here are the steps involved in getting the job done.
  • Create subclass of DbCommandInterceptor
  • Override two methods in this derived class ScalarExecuting and ReaderExecuting
  • These methods will be called by EntityFramework just before executing the generated query.
  • In these methods we get an opportunity to update the entity framework generated query and add the NOLOCK hint if required.
Heres the code that will get the job done.
Basically all we are doing here is, looking for a pattern which matches table names in the entity framework generated query and replacing all the table names with <TableName> WITH (NOLOCK) hint.  Thats all that is needed really!
The thread static variable ApplyNoLock is kind of a switch that, controls whether the NOLOCK hint is to be applied or not.

The Interceptor can be added during the application start as follows
Thats all folks, its really a simple and elegant way to add the NOLOCK hint to any query generated by EntityFramework!

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!  

Monday, June 30, 2014

How to run Entity Framework Migrations using MSBuild and Migrate.exe

Recently, one of out client moved to Entity Framework.  Along with that, they also decided to use the Entity Framework Migrations.

On a DEV machine, Entity Framework Migrations can be executed very easily using the the Update-Database command in Package Manager Console.

Naturally, we do have a Continuous Integration (CI) server that builds and integrates the checked-in code.  We needed to run the migrations on the CI server as well.  For building our project we were using MSBuild.  I wanted to integrate Entity Framework Migrations with MSBuild so that the migrations can be executed outside the Visual Studio and on the CI server as well.

Looked like a no brainier task to me, I hoped that there will be an MSBuild task that would run the Entity Framework Migrations and my job would be done!  But to my surprise, Entity Framework Migrations is not fully thought through, it does not come with any task for MSBuild which can be executed out of the box.

Turns out that there is a Migrate.exe that could be used to execute the migrations.  This could then be invoked from MSBuild to get the job done.  So how do they do it, how to run Entity Framework Migrations using MSBuild and Migrate.exe

How do they do it!
  • Migrate.exe can be found under the tools directory of the Entity Framework package that comes along with NuGet.
  • We could create a simple task that can invoke migrate.exe using the Exec MSBuild task. 
  • However, simply running the above task will not get your the desired results.  When you run this task you might end up getting some weird exception.  I got the following exception
  • Turns out that to successfully run Migrate.exe, it needs to be copied to the directory where the DLL holding all the Entity Framework Migrations is located.
  • I don't understand why such a restriction is necessary.  Why could they not use the StartUpDirectory parameter or some other parameter to accept the full directory path of the DLL that has the migrations.  May be when someone wrote the code for Migrate.exe, he/she found it convenient to run it this way!
  • Anyways, so the fix to this problem was simple, first copy the Migrate.exe to the folder where the DLL is located and then run the Migrate.exe
  • Updated target code looks as follows.
As you can see, its not very straightforward to get the Entity Framework Migrations integrated with MSBuild, but with some hacks, we can get it working! 

Have some Fun!