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)

Starting Prism in Silverlight

So I got my hands onto Prism and I found it extremely intriguing. I created a bunch of applications on that and its been a fun learning experience. Though its very interesting, the scarcity of reference material on Internet forced me to create a tutorial here.

There will be a couple of posts on this following this one. I’ll update the links to them later on.


The following code is rough and can be ignored completely
xmlns:Regions=”clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation”

Problems with user controls while publishing ASP.net web apps

I recently had a major issue while publishing a web app that consisted of a lot of User Controls. Every time I opened a page that contained a user control I got the following error:

The base class includes the field ‘TestUserControl1’, but its type (TestUserControl) is not compatible with the type of control (ASP.TestUserControl_ascx).

I noticed that my code was running perfectly fine when I was running it through Visual Studio, but as soon as I published this error would show up on the published website. After cursing and swearing for a while, I tried to publish it with no extended publish options. And viola the error was gone. Intrigued by this I tried to recreate the error and noticed that the ‘updatable’ option while publishing was the cause of the problem.

So the fix: Uncheck the “Allow this precompiled site to be updatable” and publish the site again.

However, the reason behind this error can be many. So I would suggest you google a bit. There are many forums with annoying amounts of discussion on this. I read several posts on this and spent about an hour googling when I came across this article on Microsoft Support web site which may also be helpful:

http://support.microsoft.com/kb/919284

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()
                    });
            }
        }
    }
}

Displaying 'Window-Style' error messages in Silverlight

To display ‘window-style’ (I mean something like a Javascript alert page that has a message and a ‘close’ button) error message in a silverlight form you have two options – An easy but not-so-cool one and a not-so-easy but a cool one.

First solution is to display a regular javascript alert message using Silverlight’s DOM support. This is as simple as follows:

System.Windows.Browser.HtmlPage.Window.Alert("Hello World");

The second solution is to use the Silverlight popup control. The advantage of this is that you can display anything you want. If you were to show a message box with some formatting, you could do that with the popup control. A problem you might have with a popup control is the amount of XAML that you need to write each time you have to display a popup. My suggestion for this is to create a Template for a popup and display a user control (The user control contains a textblock with a message or any other content that you want) in the popup. This way all your popups have the same ‘look-and-feel’.

Here is a tutorial by Jesse Liberty a.k.a the ‘Silverlight Geek’ on using Silverlight Popup controls.

Tutorial on Silverlight Popup by Jesse Liberty

Grid paging in Silverlight

A common companion of all grids is the pager. In Silverlight, we need to go about in a somewhat round about way to get this working. I found a nice article by Malcom Sheridan that does this. His approach to do this is to have a grid and a horizontally aligned stack panel under the grid. He generates buttons on-the-fly which display the grid pages.

Tutorial on paging by Malcom Sheridan (.NET Curry)

I will try to come up with a working sample of Malcom’s code for your reference soon. (Currently im off on a Texan holiday)

Simple Ad Slider in JQuery

A couple of days ago I was asked if there is a way to achieve flash like ad slider in JQuery without much of Javascripting. The immediate answer is “Yes”. JQuery is extremely fun and is very powerful. In this short post, I’ll explain the small amount of Javascript required to create an Ad Slider. We’ll only be using Basic HTML, CSS and JQuery. You can download JQuery from http://docs.jquery.com/Downloading_jQuery. Additional documentation can be found at http://docs.jquery.com/Main_Page.

http://www.cakeeditonline.info/samples/2010/02/adslider/

I have provided the code for this below. To get a detailed understanding, just go through those few comments in the code.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

    <style type="text/css">
    #AdOuterWrapper /* Outer static wrapper the Ads are displayed in */
    {
        border:1px solid #000000;
        margin:25px;
        position:relative;
        text-align:left;
        overflow:hidden; /* Remove/Comment this line to see how this is working */
    }
    #AdMoveFrame /* Expandable, Moveable frame that contains a horizontal array of ads */
    {
        position:absolute;
        text-align:left;
    }
    #AdButtonFrame
    {
        position:relative;
        z-index:9999;
    }
    #AdPrev, #AdNext /* General button style */
    {
        width:25px;
        height:25px;
        background:#ffffff;
        margin:10px;
    }
    #AdPrev:hover, #AdNext:hover /* General button hover style */
    {
        background:#999999;
        cursor:pointer;
    }
    #AdPrev /* Button left */
    {
        float:left;

    }
    #AdNext /* Button right */
    {
        float:right;
    }
    .AdFrame /* An individual Ad frame */
    {
        float:left;
        overflow:hidden;
    }
    </style>
    <script type="text/javascript" language="javascript" src="jquery.min.js"></script>
    <script type="text/javascript" language="javascript">

        var _AdHeight = 300;     // Set the height of your ad
        var _AdWidth = 300;     // Set the width of your ad

        var _AdNum = 0;
        var _AdCurPos = 0;
        $(function ()
        {
            // Position the ads
            $(".AdFrame").each(function ()
            {
                $(this).css('width', _AdWidth).css('height', _AdHeight);
                _AdNum++;
            });
            $("#AdOuterWrapper").css('width', _AdWidth).css('height', _AdHeight);
            $("#AdMoveFrame").css('width', parseInt(_AdNum * _AdWidth) + 1);
            __AdButtonControl ();

            $("#AdNext").click(function () // Move left
            {
                _AdCurPos -= _AdWidth;
                $('#AdMoveFrame').animate({ left : _AdCurPos }, 500, 'linear');
                __AdButtonControl ();
            });
            $("#AdPrev").click(function () // Move right
            {
                _AdCurPos += _AdWidth;
                $('#AdMoveFrame').animate({ left : _AdCurPos }, 500, 'linear');
                __AdButtonControl ();
            });
        });
        function __AdButtonControl () // Checks the current position and hides the corresponding button
        {
            if (_AdCurPos == 0) $("#AdPrev").css('display', 'none'); else $("#AdPrev").css('display', 'block');
            if (_AdCurPos == (1 - _AdNum) * _AdWidth) $("#AdNext").css('display', 'none'); else $("#AdNext").css('display', 'block');
        }
    </script>
</head>
<body>
    <center>

    <!-- This is the outer div -->
    <div id="AdOuterWrapper">
    <div id="AdMoveFrame">

        <!-- Replace the contents of each of this DIV with you AD -->
        <!-- To change the Width and Height, set it in the JS above. Remove the style attribute for the divs and the h1 tags -->
        <div class="AdFrame" style="background-color:#c0ffee">

            <!-- Your ad content goes here -->
            <h1>One</h1>

        </div>
        <div class="AdFrame" style="background-color:#FF0000">

            <h1>Two</h1>

        </div>
        <div class="AdFrame" style="background-color:#00FF00">

            <h1>Three</h1>

        </div>
        <div class="AdFrame" style="background-color:#0000FF">

            <h1>Four</h1>

        </div>
    </div>
    <div id="AdButtonFrame">
        <a id="AdPrev">&lt;</a>
        <a id="AdNext">&gt;</a>
    </div>
    </div>

    <br>

</body>
</html>