Death of silverlight

Silverlight as a plugin is long gone. With Chrome disabling NPAPI by default, the era of plugins, as we knew it, is gone. Now, what do I do with all the skills I’ve developed as a Silverlight developer?

Hmmm… That’s a tough one. Here’s my take on this:

Working as a front-end developer is a continuous process of learning new technologies. Silverlight came out of nowhere and there was a big rush to learn it. Before that there was a bug rush to learn ActionScript (remember those days?). Of course with the introduction of ActionScript 3.0 things changed dramatically as it nearly coincided with the loud bang of Apple releasing its first iPad followed by iPhone which gave Flash a big juicy finger. Whatever happened to the Flash developers anyway?

All that’s way behind in the past. Lets look at the present. Javascript frameworks have become such a big thing in the market now. The capabilities of the first Silverlight app are far surpassed by an AngularJS app. Add NodeJS and the million NPM plugins with funky names to army and that overpowers other front-end technologies in a big way. How did this come to be? Why did Javascript become such a big thing?

I think we need to go back to late 2000s when new phones were being released every other day. First it was iPhone and a tonne of developers started learning Objective C. Then came Android. Then android just went ‘whoooooshh’ and took over the biggest chunk of the mobile market. Windows phone in its ever-losing smartphone race released a few really good phones. Thanks to Nokia! (we still love you). So many platforms.. How would one keep up with everything?

CSS3 to the rescue. With better support for responsive apps and a bunch of really smart people inspired by JQuery started developing re-usable frameworks. Unlike before these were smaller bite-sized frameworks that could be cherry-picked to create an application of your choice.

Problematic sign up process with WP7 dev

I recently purchansed a Nokia Lumia 800 and was very excited with the prospects of developing apps on it. I probably did a dumb thing by not doing some information gathering before I actually purchased the mobile. When I first got the cell, I installed WP7 development tools on my machine. Created my first ‘Hello world’ app and was all excited to run it and things went far far down south from there.

First thing – The WP7 emulator needs the developer key. The error message is quite cryptic. It does not say something like ‘Please enter your developer key as retrieved from AppHub’ but instead gives an error code. Alright, I googled the error and figured out that I need to get the key from AppHub. I set off to sign up on it…

Second thing goes wrong. I realized I need to pay to become a developer. WTF!!! Alright! Im ready to pay. Lets get it done with. I go to the payment details and my country is selected as US which is not my country now, but it was an year ago. I don’t have any more money in my US credit cards so I wanted to change the country, but whatdyaknow…. You can’t. Now how am I supposed to pay?

I go update my windows live account and try again. This time I get an error:

Unable to complete your request
We cannot complete your request now, please try again later.
Message 40001
Hmmm… Alright. Very helpful indeed! Exactly what I was looking for!!! Idiots.
So I googled this error and it looks like I need to email Microsoft and ‘hope’ for an answer. So I did it. I sent a very detailed email.
I reply I got was to update the payment information on Xbox.com! Alright. Microsoft has definitely not thought about a proper distributed DB for their accounts. Ok… Im still going to try to get this thing working… I deal more with broken stuff than proper functional stuff in my line of work. I open my XBox account (which by the way gets created automatically, I guess, when you register your WP7 phone) and look for the country. Hmm… The messed up thing is you can’t bloody change it!!!
Now the solution is to create a new WindowsLive account that is registered in India, then reset my phone to its factory settings and log in using the new credentials… And lose all my previous settings… What bull!
I like WP7 and things… But – “Microsoft… You need to get your act together!! X( “

Error 1001: Service has been marked for deletion

Another of those stupid windows errors!

I was working on this windows service recently. While developing this I code the changes, build the app and run the service installer. (The service installer project is quite cool. I admit). But every now and then when I uninstall the service and try to reinstall it I get this error:

Error 1001: Service has been marked for deletion

I know its marked for deletion. But why is it not deleted yet? I used to restart the system as a solution to this problem. But soon enough I began to see the stupidity behind some of the windows apps. I had the Service Control Manager running to start/stop the service. After uninstalling the service if you happen to open the SCM window, it gets a lock on the service entity and marks it as ‘Disabled’. Now when you try to install the service again Error 1001 pops up.

The solution to this was to just close the SCM and install the service. SCM is one of the core windows utilities. You expect it to behave right?

Mobile emulators

Lately, I’ve been taking a lot of interest into mobile development. I have started developing some Silverlight apps for Windows Phone 7. I plan to upgrade my mobile development skills to include Java, for Android apps, and iOS, for iPhone apps, at some point in the future. (Hopefully that is. For the lazy bum that I am, I am very optimistic in my planning). While I wait to update my skill sets, I need to do something to make my apps available on mobile platforms other than Windows Phone. So creating a mobile version of the web app is the current solution.

I recently developed some test HTML pages and I wanted to test out how it looks on my mobile. To do this test here are my options:

1. Host the site content on some publicly available server (like this… ShishirRao.com 🙂 )

But this is a boring process. I feel sleepy when I open FileZilla. Besides, I’ve messed around with hosted content in all wrong ways before. So I would do my best to prevent doing this with anything other than code ready for production.

2. Host it locally, connect to a LAN connection with WiFi and open the IP:Port of my machine’s Apache/IIS.

This works very well actually. This is my favorite mode of development actually. However I often end up in situations without a WiFi connection. (Like my office where I’m not supposed to be developing mobile apps for my amusement… Or writing this post… {Evil grin})

3. Use a Mobile Emulator on the machine I’m developing stuff on.

This is another good solution. There are several standalone apps and virtual boxes available that emulate mobile browsers for various phones. This is a great way to test my locally hosted app as well as try out the looks of my app on other browsers. (It is very important to see how browsers interpret your HTML. With the advent of HTML 5 and CSS 3.0 and the millions of mobile browsers… ok hundreds… the amount of mismatch in the way a sites are rendered have started to vary greatly) Most importantly, I test out the way it shows up on Safari, Opera and IE. That is for iPhone, Blackberry/Android and Windows Phone.

Here is a link for the windows phone emulator. Nice app it is.

But here’s the best link I’ve found – MOBILE EMULATORS. A neat collection of the emulators available right now.

I almost started making a list of mobile emulators myself, but after seeing the neat job this author has done, I just want to share a link to his page. Hopefully he updates it with new emulators whenever they come around.

Configuring WCF services programmatically for Silverlight

So, like always there was this rather strange problem I came across a couple of days ago. For most normal applications I would be more than happy to just configure my WCF services in the web.config/app.config file. The annoying XML for System.ServiceModel has become quite friendly with me. But the situation now was that I was working on a silverlight application and I had to modify the binding dynamically. Some crazy requirements require my Silverlight application to start using a different service endpoint based on some internal events. The first thing I had to do was shoot out the idea of having the nice friendly config file, delete it off my project and create a code to generate an impromptu binding each time the service is requested.

My normal way of creating a binding configuration is to set all the string and buffer lengths to maximum. (Atleast, the application Im working on requires this). One of the important things that need to be set to max value is the ReaderQuota:

[XML config sample]

So I tried to do this programmatically and guess what?! In Silverlight the XmlDictionaryReaderQuotas object that is required to define the ReaderQuota cannot be instantiated. Now, how the heck am I supposed to create it? Not just that, there is not direct way to set the “ReaderQuota” property of the BasicHttpBinding. The only way to set that property is to use Reflection!

First of all creating a decent configuration file in Silverlight is a pain and on top of that you can even set the values programmaticaly. Were the creators of Silverlight 4.0 drunk when they designed the configuration module?

Anyway, here is how you set up the ReaderQuotas with “MAXIMUM” reader sizes for a WCF binding in Silverlight:

BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.CloseTimeout = new TimeSpan(00, 05, 00);
binding.OpenTimeout = new TimeSpan(00, 05, 00);
binding.ReceiveTimeout = new TimeSpan(00, 05, 00);
binding.SendTimeout = new TimeSpan(00, 05, 00);
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;             

binding.GetType().GetProperty("ReaderQuotas").SetValue(binding, XmlDictionaryReaderQuotas.Max, null);

Hopefully this will help someone out. In fact it was not that tough to Google this solution out, but the implications of this solution just irked me into writing this post.

Failed to load IIS Metabase

Almost everytime I start a new computer I keep having new types of problems with IIS. Though it’s my second favorite server, I really dislike some of it’s cranky behaviors.

The most common of these uncommon IIS problems I’ve has is : Failed to load IIS Metabase.

The solution to this themed out to be quite simple. Run this command in your visual studio command prompt

aspnet_regiis -i

That’s it! Also make sure that each site you’re hosting has the required privileges to IUSR and you are running the required version of .Net

Problem starting Apache/IIS on Windows 7 Port:80

Recently I had severe problems running Apache on Windows 7. There are several reasons why this can happen. I have identified 5. The problem and the solution(s) are presented in this blog post.

You might come across this problem if you’re having trouble starting Apache or IIS. The first thing you should do is to go check your error logs. First thing to do is to go to your system event log. Do Start>[Type “event viewer”]>[Enter]. Select ‘System’ from the left side and check for any logs.

With Apache I was getting a service-related error code: -1

Now I checked the apache error log (C:\xampp\Apache\logs\error.log) and saw that it was ‘not able to bind to port 80’. This means that some other process was using port 80. So, I googled for a command to check the process that’s using port 80. The command was:

netstat -ano

Now if your process id (last column) that’s using port 80 [::]:80 or 0.0.0.0:80 is not 4 (PID), then your solution could be simple:

Solution 1

If your PID is not 4 after the above step, go to Task Manager>Performance>Resource Monitor. Here find the process that was using port 80 and kill it. 🙂

Solution 2

If the process that stole your port 80 was Skype, use this link: http://www.mydigitallife.info/2008/12/03/disable-skype-from-using-opening-and-listening-on-port-80-and-443-on-local-computer/

Solution 3

If PID 4 (The NT kernel process ‘System’) was hogging port 80. Go to your Service Control Manager (Type in ‘Services’ in Start Menu), Find the service named ‘RemoteDesktopManager’ and disable it.

Solution 4

Again if it was PID 4, there could be a problem with the infamous http.sys. To solve this problem, use this link: http://www.cameroncooke.com/2009/01/25/windows-7-uses-port-80-and-makes-it-impossible-to-install-apache-solution/

Solution 5 (This was my problem actually)

If you are running SQL Server Reporting Services, you’d be surprised to know that it steals your port 80. If you have SQL Server (05/08) installed on your system, goto Start > Microsoft Sql Server 20xx > Configuration > Sql Server Configuration Manager. Find the Reporting services and stop it. Also make it ‘Manual’ to be safe.

And Viola! My apache service is running. If it was IIS in your case, you’d have that running too 🙂

If this didn’t help you, comment. If this did help you, comment.

Extending C# Object to make safe type-conversions

In C# one of the most commonly used convert functions is the Convert.To<Type>(object value). Usually when we need to convert an object to a string we just use .ToString() as its to easy to use. But the problem with ToString is that it cannot handle nulls, DbNulls, etc. To handle this, we can very easily extend the methods associated with the C# Object.

To do this all you need to do is create a Static Class, and have Static Functions where the first argument is the type of object that you want to extend. Here’s how its done:

public static class Utils
{
    /// <summary>
    /// Converts an object safely to string or assigns an empty string
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public static string ToStringSafe(this Object obj)
    {
        try
        {
            return Convert.ToString(obj);
        }
        catch
        {
            return null;
        }
    }

    /// <summary>
    /// Converts an object safely to integer or assigns 0
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static int ToInt(this Object obj)
    {
        try
        {
            if (obj.GetType() == typeof(int?)) return ((int?)obj).Value;
            if (obj.GetType() == typeof(DBNull)) return 0;
            return Convert.ToInt32(obj);
        }
        catch
        {
            return 0;
        }
    }

    /// <summary>
    /// Converts an object safely to bool or assigns false
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static bool ToBool(this Object obj)
    {
        try
        {
            if (obj.GetType() == typeof(bool?)) return ((bool?)obj).Value;
            if (obj.GetType() == typeof(DBNull)) return false;
            return Convert.ToBoolean(obj);
        }
        catch
        {
            return false;
        }
    }
}

Once this is done, you can do things like this easily:

NOTE: You CANNOT use this concept to extend instance methods. In the above sample I could not extend the .ToString() method, so I used a new name called ToStringSafe(). The reason is that instance methods have a higher priority than extension methods. Because of this, all the compiler will use the instance method even if there is a matching extension method. (You cannot use override functions here)

Custom event handlers in C# (3.5 style)

Here is a code for custom events in C#. Note the 3.5 style code that involves Lambda expressions and Anonymous types.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    using TestNamespace;

    class Program
    {
        static void Main(string[] args)
        {
            Test t = new Test();

            t.TestStarted += (object sender, Test.TestStartedEventArgs e) =>
                {
                    Console.WriteLine("First event handler");
                    Console.WriteLine(sender.ToString());
                    Console.WriteLine(e.ToString());
                };

            t.TestStarted += (object sender, Test.TestStartedEventArgs e) =>
                {
                    Console.WriteLine("Second event handler @ " + e.StartedTime);
                };

            t.DoTest();

            Console.ReadLine();
        }
    }
}

namespace TestNamespace
{
    class Test
    {
        public delegate void TestStartedHandler(object sender, TestStartedEventArgs e);

        public event TestStartedHandler TestStarted;

        public class TestStartedEventArgs : EventArgs
        {
            public string StartedTime { get; set; }
        }

        public void DoTest()
        {
            if (this.TestStarted != null)
            {
                this.TestStarted(this,
                    new TestStartedEventArgs
                    {
                        StartedTime = DateTime.Now.ToString()
                    });
            }
        }
    }
}