Fixing WebView QueryString bug!

Few weeks ago I came across the most annoying bug I have ever seen in Android where WebView URL mechanism is broken when we pass query string.

Fortunately an Android project member did provide a workaround for the issue, until it is fixed in Jelly bean update. However the work around given is in Java so, I have coverted the code to C# for developer targeting Xamarin tools.

Hope it helps you.

Get the code from Gist here: https://gist.github.com/prashantvc/5013207

Where.FirstOrDefault vs FirstOrDefault

Use of 1. Where(predicate).FirstOrDefault vs. 2. FirstOrDefault(predicate) came up quite a lot during the recent code reviews. While both yields same result most of the team members preferred using option 2.

I thought FirstOrDefault would execute faster than Where.FirstOrDefault, because the LINQ doesn’t need to filter the collection before it calls the FirstOrDefault, and I was wrong!

The chaining behaviour of Linq to objects makes sure that collections iterated lazily, so both Where(predicate).FirstOrDefault and FirstOrDefault(predicate) methods won’t go further if the first item is hit.

Consider this code snippet,

var items = new[] { 1, 2, 3, 4, 5, 2 };
Func<int, bool> predicate = delegate(int i)
    {
        Console.WriteLine(i);
        return i == 2;
    };

//Prints: 1 2
items.Where(predicate).FirstOrDefault();

//Prints: 1 2    
items.FirstOrDefault(predicate);

I expected the items.Where(predicate).FirstOrDefault() would print all the items in the sequence, but it did not, it returned after printing 1 2. So, in the end it doesn’t matter what method you use the result and execution will be same and any performance difference are highly insignificant.

Monotouch: UIView to Image

I wrote this code snippet quite a while ago to make it easy to print a UIView from a iOS device. Hope it helps you too.

public static class Extensions
{
    public static UIImage ToImage (this UIView view)
    {
        RectangleF canvasRect = view.Bounds;
        UIGraphics.BeginImageContextWithOptions (canvasRect.Size, false, 0.0f);

        CGContext ctx = UIGraphics.GetCurrentContext ();
        ctx.FillRect (canvasRect);
        view.Layer.RenderInContext (ctx);

        UIImage newImage = UIGraphics.GetImageFromCurrentImageContext ();
        UIGraphics.EndImageContext ();
        NSData imgData = newImage.AsPNG ();

        return UIImage.LoadFromData (imgData);
    }
}

Geek out: Automate FB birthday comments

It’s my birthday today and lot my friends and family members took time to wish me on the Facebook. It is common courtesy to thank them for the wishes, but typing out comment to huge list of wishes is such a pain.

Over the year as a developer I learned one thing, “If you have to do a task more than three times, you should automate it”, after reading over fifty wishes I found it tiring to reply them one by one. My first thought was to write small piece of javascript/C# to comment using Facebook’s Graph API, and again its hard task to create whole oauth implementation and JSON parsing. I was looking something simple, a script not more than ten lines.

Then I found this wonderful command line tool called fbcmd, it actually lets you interact with facebook right from your terminal/command prompt. If you are running OSX/linux, the installation and setup is pretty straight forward, you can do it without even touching the mouse.

After you set up we are interested in three commands

  1. fbcmd mywall, this commands lets me get the steam of messages posted on the my wall by friends, and set the context to execute next command
  2. fbcmd like <id>, like a message posted on the wall for a given id.
  3. fbcmd comment <id> <text>, comment on a post like “thank you”.

Now we know what are the command we should be using, it’s time to write a tiny shell script to comment and like wishes posted by friends.

fbcmd mywall <n>
for i in {1..<n>}
do
fbcmd like $i
fbcmd comment $i "Thank you"
done

and there you are, we just automated the act of expressing the gratitude :P

Thank you all for the birthday wishes.

PS: If you hate to type, you can download shell script here https://www.dropbox.com/s/md5o3pgr11yetem/FBLike.sh

Fixing async search suggestions exception

I absolutely love the fact that how we developer can seamlessly integrate our apps with Windows 8. The WinRT framework enforces us to use asynchronous in almost every aspects of the programming, which really helps to develop very responsive apps.

Lately I have experienced frustrating moment when implementing the asynchronous search suggestion in my app. I was trying to get the search suggestion from REST API, but I was never able get it right. My code was pretty straight forward to populate suggestions

image

I kept getting this very uninformative exception message every time I tried to append query suggestions.

An unhandled exception of type ‘System.InvalidOperationException’ occurred in mscorlib.dll
Additional information: A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)

I did not had any clue on how to resolve this, even msdn documentations did not include any help on this. Well after spending about 30 minutes I found the solution that was quite simple. We just have to signal the app that we finished getting the suggestions, and this can be done using SearchPaneSuggestionsRequestDeferral class, it’s not something complex to implement but proper documentation would have saved few minutes for the new Windows 8 devs like me. Now here I present the working code.

image

Interview and Gamma Function

Update: One of my friends showed me a very popular blog post on how not to write factorial function in general http://chaosinmotion.com/blog/?p=622

Lately I had an opportunity to interview with the Aditi Technology, though I had to wait for almost three hours before I get to meet the panel, it’s been great experience.  People at Aditi were incredibly friendly and kind, I and bunch other guys who have come for interview been served hot Samosas the McVeggies, seriously.

Eventually when I got my chance to face the interview panel, it was in kind of living room setup on their office where they had big flat TV and a Nintendo hooked it! (I was bit surprised to see the Nintendo in 100% Microsoft technology focused company as they claim on their web site :P )

There were very few question on logical, reasoning and conceptual, but I was so bad at answering these questions I was already prepared for the failure. May be it’s because I tried to answer the questions in more like white board approach solve the proble, where as their expectation was to write down the code!

Surprisingly enough, I was through the first round.

There was no much difference in round two, I was asked few questions about the interfaces and inheritance. But, one question really made go mad about myself, I was asked to write method to calculate the Factorial. The first thing popped in my mind was Gamma function (we will come back to it later), the equations is not so easy to remember, so I wrote method with ‘for loop’ to calculating the factorial, and the interviewer looked all uninterested and asked me to write without using the loops.

When did finish writing the LINQ version of factorial calculation, the interviewer was told me like “I was expecting you to use the inbuilt features of C#”, and my reply was “There are no inbuilt feature in C# to calculate the factorial!”, and he told me to that was expecting me to write the function using recursion! Which never popped in mind.

May be the problem is, from past few year I was kind of stopped considering the recursion as an option when solving mathematical problems, reason 1. when there is a very large number involved, odds are high that recursion fills the stack and your presented with stackoverflow exception reason 2. from my past experience if recursion is used in the algorithm or code, it is not very efficient code/algorithm, usually recursion is a case of brute-force (so is the for-loop) that takes lot of computational power.

If our daily used calculators ever used recursion or loop techniques to calculate the factorial like trivial problems either they would take long time or you may sense the burning smell coming out of calculator.

So, now we will go back to the Gamma function a better way of calculating factorial, the wolfram defines the gamma function as “The (complete) gamma function Gamma(n) is defined to be an extension of the factorial to complex and real number arguments”,  Gamma(n)=(n-1)!, that means gamma(4) is equals to 6. There is no gamma function defined in the Math class of dotnet framework, but we can easily create one, here’s the simplified version gamma function that we can use to translate:

\Gamma(z) \approx \sqrt{\frac{2 \pi}{z} } \left( \frac{1}{e} \left( z + \frac{1}{12z- \frac{1}{10z}} \right) \right)^{z},

after we translate to C# we get:

image

[click on image to get the source from github]

certainly there are few boundary conditions are missing, but you get my point. There could be other other better way of doing it, but I find it better.