Use Extension Methods To Extend Your Applications

1. May 2011 14:09

.NET Framework C# Code Snippets 

What MSDN has to say about Extension Methods

Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

A friend of mine started blogging a months ago and he wrote a blog post showing the usage of Extension Methods. I do some of the search and I found a website called ExtensionMethod.NET with a nice collections of extension methods. You can submit your own extension methods to share with other people among the community. ExtensionMethod is a initiative project started by Fons Sonnemans and Loek van den Ouweland.


Currently rated 4.0 by 1 person API: Shorten URLs / Reverse Long URLs / Get QR Code Image

17. March 2011 16:03

.NET Framework API C# Utils 

If you have long URLs and other and want to create short URLs then API can help. I wrote a wrapper class which can let me create short URLs in jiffy. I was working on API to create my short URLs with a click of a button (that's for my personal use). Therefore, I ended up with a 'short' class to create shor URLs using API. What you need is a login and an apikey, which you can have one for yourself by signing up for a free account. You can find your apikey here after login. The class gives you two ways to make short URL, one with XML and the other with plain TEXT. I haven't write anything for JSON as it was not required at all to me in any ways. I am using plain TEXT for this example. You can read API official documentation for more information.

The below class can be used to create short URLs using API, reverse the short URLs and get the original URL. Also if you are not aware you can have a QR code of your short URL. Read more about QR Code here. If you are using or to shorten your URLs then you can have the QR code image by adding .qrcode in the end of the short URL (See in the code example below)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Net;
using System.IO;

namespace Bitly.API

    public class BitlyData
        #region Properties

        public static string APIKEY { get; set; }
        public static string LoginName { get; set; }

        public static string StatusCode { get; set; }
        public static string StatusDesc { get; set; }
        public static string ShortURL { get; set; }
        public static string LongURL { get; set; }
        public static string HashCode { get; set; }
        public static string GlobalCode { get; set; }
        public static string NewHash { get; set; }


    public class Bitly

        #region Bit.Ly Variables

        private static string URL = "";

        private static string BitResponse = "";


        #region Enums

        public enum Format


        #region Sample Response
        //        <?xml version="1.0" encoding="utf-8"?>
        //    <status_code>200</status_code>
        //    <status_txt>OK</status_txt>
        //    <data>
        //        <url></url>
        //        <hash>ekYLee</hash>
        //        <global_hash>gBH72m</global_hash>
        //        <long_url></long_url>
        //        <new_hash>1</new_hash>
        //    </data>


        public static string ShortURL(string LongURL, Format ReqFormat = Format.TXT)
            string sURL = string.Empty;
            string BitLyURL = URL + BitlyData.LoginName + "&apikey=" + BitlyData.APIKEY + "&longUrl=" + LongURL + "&format=";

            if (ReqFormat == Format.JSON)
                throw new NotImplementedException("This method is not implemented yet!");

            if (ReqFormat == Format.XML)
                BitResponse = new WebClient().DownloadString(BitLyURL + "xml");
                string Response = BitResponse;

                XmlDocument doc = new XmlDocument();
                XmlNodeList XlistResponse = doc.GetElementsByTagName("response");

                foreach (XmlNode XResnode in XlistResponse)
                    XmlElement ResElm = (XmlElement)XResnode;

                    BitlyData.StatusCode = ResElm.GetElementsByTagName("status_code")[0].InnerText;

                    if (BitlyData.StatusCode != "200")
                        BitlyData.StatusDesc = ResElm.GetElementsByTagName("status_txt")[0].InnerText;
                        return BitlyData.StatusDesc;

                if (BitlyData.StatusCode == "200")

                    XmlNodeList XlistData = doc.GetElementsByTagName("data");

                    foreach (XmlNode XDatanode in XlistData)
                        XmlElement DataElm = (XmlElement)XDatanode;

                        BitlyData.ShortURL = DataElm.GetElementsByTagName("url")[0].InnerText;
                        BitlyData.LongURL = DataElm.GetElementsByTagName("long_url")[0].InnerText;
                        BitlyData.HashCode = DataElm.GetElementsByTagName("hash")[0].InnerText;
                        BitlyData.GlobalCode = DataElm.GetElementsByTagName("global_hash")[0].InnerText;
                        BitlyData.NewHash = DataElm.GetElementsByTagName("new_hash")[0].InnerText;

            if (ReqFormat == Format.TXT)
                if (ReqFormat == Format.TXT)
                    BitResponse = new WebClient().DownloadString(BitLyURL + "txt");
                    string Response = BitResponse;

                    BitlyData.ShortURL = Response;

            return sURL = BitlyData.ShortURL;

        public static string ReverseShortURL(string ShortURL)
            HttpWebRequest Webrequest = (HttpWebRequest)HttpWebRequest.Create(ShortURL);
            HttpWebResponse Webresponse = (HttpWebResponse)Webrequest.GetResponse();
            Uri uri = Webresponse.ResponseUri;
            return uri.AbsoluteUri;

        public static string GetQRCodeURL(string ShortURL)
            string QRCodeURL = string.Empty;
            QRCodeURL = ShortURL + ".qrcode";
            return QRCodeURL;

In the above class you can see that the second parameter is accepting TXT by default. So, if you call the method with or without the second parameter it will still work with the default parameter TXT. The enumeration called Format contains all the possible format of all the formats which is accepted by API. The second parameter in the class above should be removed if you plan to use the above code with the lower versions of .NET i.e. 3.x / 2.0

Sample Usage .NET 3.x / 2.0

Bitly.API.BitlyData.LoginName = "LOGIN NAME GOES HERE";
Console.WriteLine("Short URL: "+Bitly.API.Bitly.ShortURL("", Bitly.API.Bitly.Format.TXT));
Console.WriteLine("Reverse URL: "+Bitly.API.Bitly.ReverseShortURL(""));
Console.WriteLine("QRCode Image URL " + Bitly.API.Bitly.GetQRCodeURL(""));

Sample usage .NET 4.0

Bitly.API.BitlyData.LoginName = "LOGIN NAME GOES HERE";
Console.WriteLine("Short URL: "+Bitly.API.Bitly.ShortURL("", Bitly.API.Bitly.Format.TXT));
Console.WriteLine("Reverse URL: "+Bitly.API.Bitly.ReverseShortURL(""));
Console.WriteLine("QRCode Image URL " + Bitly.API.Bitly.GetQRCodeURL(""));

I have tested my code with Console Application, but you can test it with web or Windows form application. Note that the default parameters are only accepted if you are working with .NET 4.0 and not by the lower versions of .NET. If you wish to use the second parameter in .NET 4 then also it will work, but not using it with lower version will give you error.

I hope this class helps someone around the globe!

Currently rated 4.7 by 6 people

Windows 7: Create Jumplists In WPF Application Without Using Windows 7 API Code Pack

26. February 2011 14:24

.NET Framework Windows WPF 

I wrote a blog post on how you can add a custom Jumplist on your Windows form application for Windows 7 platform using the Windows 7 API Code Pack, but that is for Windows Form applications running on Windows 7. 

WPF makes Jumplists more simpler. You need not to add any API reference or any other reference in your project. You can just make the use of Jumplists for better navigation for your users. 

If you are using WPF then, there is a simple way to add Jumplists. I will show how you can have a pre-defined jumplists for your application. The main part of the application in which we have to focus is App.xaml. All work related to jumplist will be done here. For instance use the below code to add calculator to the jumplist.

        <JumpList ShowFrequentCategory="True" ShowRecentCategory="True">
            <JumpTask Title="Calculator"
                      Description="Open Calculator"

You know why there is Title and Description. The ApplicationPath will have the fully qualified name of the application path or just the name of the programs that can be executed with their name. IconResourcePath will have a fully qualified path of the icon. If your application have an icon embedded in the application, then you can just set the application exe path or name else you can have a fully qualified path of the icon file.

To add a new Jumplist, add a new <JumpTask> tag with the above mentioned tags and for every Jumplist item you need to do the same.

 No Rating

Deprecated APIs In .NET 4.0

20. July 2010 11:10

.NET Framework API Visual Studio 

A number of existing APIs are deprecated in .NET Framework 4.0. A complete listing of deprecated APIs in .NET Framework 4.0 can be found here at MSDN:


 No Rating

URL Routing With ASP.NET 4 - Web Forms

26. June 2010 18:38

.NET Framework ASP.NET C# 

URL Routing was first introduced in .NET framework 3.5 SP1 but MVC has built-in and works pretty decently to create SEO friendly URL and prevents URL hacking. ASP.NET 4.0 is now introduced with a new feature called URL routing with web forms. URL routing help developers to create short and friendly URLs which enhance search engine page ranking. There are few other ways to create short friendly URLs like extension or if you have a physical access to IIS you can have installed URL Rewriter extension for IIS 7 to create short friendly URLs. Hey! not everyone has access to IIS!! So if you don't have the access then also you can re-write the URLs using this new feature in ASP.NET 4.0. 

One thing I would like to mention is that when you create a new ASP.NET web application in Visual Studio 2010, it won't show up with a blank page, but instead build a full applicaton with sample pages with a pretty good design. As you see below I haven't design this page..actually this is a default template when you create a new ASP.NET web application. What I have done here is just put a text box to enter contact ID and a button to get the details from the Adventure Works sample database.


This is a pretty simple interface and now we take a look at some internal work of this web application. My primary focus is on having simple URLs for my application for better search engine optimizations. This application has two main pages apart from the about and other pages that added to the project through the template. The Default.aspx is the main page where we have a field which allow the user to enter the contact ID for the person he want to search. The other page which handles the request and show the details of the contact person is called View.aspx. But this is a really tricky part from a user's perspective as a user will never see this page on the browser address bar while navigating a website. Check the View.aspx design code and check the <asp:SqlDatasource> tags and notice the SelectParameter tag. As I am using a select query with a parameter to populate the grid, the SelectParameter tag further uses <asp:RouteParameter> with route name and route key.

<asp:SqlDataSource ID="SqlDataSource1" runat="server" 
        ConnectionString="<%$ ConnectionStrings:AdventureWorksConnectionString %>" 
        SelectCommand="select Title,FirstName,MiddleName,LastName, EmailAddress from Person.Contact where ContactID=@id">
            <asp:RouteParameter Name="id" RouteKey="id" />

OK! Let's start up what we have on the Default.aspx page. This is the default page and a user will see this page first. Write the below code on the button to redirect the request to route handler. Here I have used a Regex expression to validate if the user enters a numeric ID and not any alphanumeric or alphabet. This check is just a workaround, I recommend you to use a better validation technique.

if((Regex.IsMatch(txt_pid.Text.Trim(), @"\d+")) == true)
          new { id = txt_pid.Text });

So does this URL make any sense? Not at this moment but surely it will after if you have registered your routes in the Global.asax file. My Global.asax file has a method called void RegisterRoutes(RouteCollection Route)

void RegisterRoutes(RouteCollection routes)

The method MapPageRoute accepts some parameters. The first parameter - "Person-Details" you see is the name of the Route which can be any thing you like. The second parameter - "Person/{id}" is the URL which we have generated. In short this is the URL which is visible to the user and outside world, what is happening internally only a developer knows!. The third parameter - "~/View.aspx" is the physical file which actually process the request and return it to the second parameter. The second parameter is the route URL and you can name it what you like except the parameter you are passing, just make sure you use the same parameter name everywhere. In the method void RegisterRoutes(RouteCollection Route) you can register number of route handlers in a single go under void Application_Start method in the Global.asax file.

void Application_Start(object sender, EventArgs e){
// Code that runs on application startup

Once you registered the routes in the Global.asax file, you are done. Time to press F5 and see the action. On the default page enter the ID and hit the Get Details button. The page rendered in front of you / user will be having a clean tidy URL.


 Download: (175.58 kb)

Currently rated 5.0 by 1 person