Code Snippet: Remove Duplicates From ArrayList Apr 30, 2011 C#   CODE SNIPPETS

Two methods to remove Duplicates from ArrayList.

Method 1:

private static ArrayList RemoveDuplicates(ArrayList arrList) 
{ 
        ArrayList list = new ArrayList();
        foreach (string item in arrList) 
        { 
             if (!list.Contains(item)) 
            { 
                list.Add(item); 
            } 
        } 
        return list; 
}

Method 2:

private static string[] RemoveDuplicates(ArrayList arrList)
{
        HashSet<string> Hset = new HashSet<string>((string[])arrList.ToArray(typeof(string)));
        string[] Result = new string[Hset.Count];
        Hset.CopyTo(Result);
        return Result;
}

Note: I found this method on the net and therefore I am sharing it as it is. Use any of the above which suites your requirement.

Blog Analytics: Widget For BlogEngine.NET Powered By Google Analytics Mar 19, 2011 API   ASP.NET   BLOGENGINE.NET

Blog Analytics Logo

Finally, I got to know the way to show Google Analytics stats on my blog space. To know more about using Google Analytics API read their official article on using the API.

I have built a widget with the help of Analytics API to show the Google Analytics stats on my blog. The widget shows three stats at the moment (I don’t want to make the widget look complex). Below is a screenshot for the widget in action on my blog:

Blog Analytics Widget

The above widget shows the stats since I have started blogging. As you can see my blog is not as popular as yours or as popular comparative with other MSFT guys and other popular bloggers. As usual before you can use the widget you need to do some settings for the widget.

Blog Analytics widget settings

You should be aware by now that this widgets uses Google Analytics API, and I hope you all have Analytics account. The Username and Password will be the same as your Analytics account (and without @xyz.com). From Date and To Date specifies the date range which then populate the stats from Analytics service for the specified date range. I have provided an option that allows you to always use the To Date as the current date, you can do that by checkingAlways use Current Date (checking this will override To Date value). If you wish to show the stats ONLY for the current day then check Use From and To Date as Current Date (change the widget title from what you have to Today's Hit or whatever you wish!). I have settings as shown in the screenshot above for my blog and I am showing all my stats since I have started blogging.Last three options will allow you to toggle between the three statistics options you want to show on the widget or not.

Download: BlogAnalytics - Widget.zip (107.28 kb)

Windows Live Theme For BlogEngine.NET Mar 17, 2011 BLOGENGINE.NET

Windows live theme for blog engine

I have now been using BlogEngine for 2 years now and I was kinda fed up with the standard theme I have been since starting which I have modified a bit to look more prettier. I am not saying it’s bad but it’s too much now, I should do a makeover of my blog. Now the BlogEngine community is not as big and vast as that of the most popular blogging engine Wordpress and therefore it is hard to get beautiful themes for BlogEngine.

This time I made my mind and sat down to create a new theme for my blog from scratch (LOL!!) but with the help of some good looking Wordpress theme. So I began my search and what I got is the one I have been looking for in the past when I started blogging. I found a Wordpress theme which resembles Windows Live default blue skin. It looks good to me so I download and start changing the looks for my blog. I don’t know if I have messed up, but I like it and so my blog is up with a new Windows Live theme. There are few other customizations that I have done with the theme that works for my blog like after every post you see a Google Ads (let me know if they are annoying, which I feel they are not), logos of the sites having a reference of my blog and some other internal stuff (simple HTML and server-side work). This is the case with me, for you there are no hiccups, just copy and paste the Windows Live theme folder inside Themes folder and you are done.

This theme is based on the standard theme template for BlogEngine. If you have any suggestions to make the theme look more beautiful in some way or the other (as I am not a designer) please do share with me and all of us in the community.

Download: WindowsLive.zip (70.33 kb)

UPDATE: There is a slight change in the style.css file. The image above is broken when a blog is viewed in a large display.

it is now been fixed. Please download the latest style sheet from the link below.

style.css (13.91 kb)

Windows Live Theme For BlogEngine.NET Mar 17, 2011 .NET FRAMEWORK   API   C#   UTILS

Bit.ly logo

If you have long URLs and other and want to create short URLs then Bit.ly API can help. I wrote a wrapper class which can let me create short URLs in jiffy. I was working on Bit.ly 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 short URLs using Bit.ly 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 Bit.ly API official documentation for more information.

The below class can be used to create short URLs using Bit.ly 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 Bit.ly or Goo.gl 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; }
 
        #endregion
    }
 
    public class Bitly
    {
 
        #region Bit.Ly Variables
 
        private static string URL = "http://api.bit.ly/v3/shorten?login=";
 
        private static string BitResponse = "";
 
        #endregion
 
        #region Enums
 
        public enum Format
        {
            XML,
            JSON,
            TXT
        }
 
        #endregion
 
        #region Sample Response
        //        <?xml version="1.0" encoding="utf-8"?>
        //<response>
        //    <status_code>200</status_code>
        //    <status_txt>OK</status_txt>
        //    <data>
        //        <url>http://bit.ly/ekYLee</url>
        //        <hash>ekYLee</hash>
        //        <global_hash>gBH72m</global_hash>
        //        <long_url>http://midnightprogrammer.net/post/Windows-7-Development-Working-With-Task-Dialog-Class.aspx</long_url>
        //        <new_hash>1</new_hash>
        //    </data>
        //</response>
 
        #endregion
 
        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();
                doc.LoadXml(Response);
                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 Bit.ly 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";
Bitly.API.BitlyData.APIKEY = "API KEY GOES HERE";
Console.WriteLine("Short URL: "+Bitly.API.Bitly.ShortURL("http://midnightprogrammer.net/post/9-Promises-Should-Be-Taken-Before-Choosing-IT-Profession.aspx", Bitly.API.Bitly.Format.TXT));
Console.WriteLine("Reverse URL: "+Bitly.API.Bitly.ReverseShortURL("http://bit.ly/eZ1kdb"));
Console.WriteLine("QRCode Image URL " + Bitly.API.Bitly.GetQRCodeURL("http://bit.ly/eZ1kdb"));

Sample usage .NET 4.0

Bitly.API.BitlyData.LoginName = "LOGIN NAME GOES HERE";
Bitly.API.BitlyData.APIKEY = "API KEY GOES HERE";
Console.WriteLine("Short URL: "+Bitly.API.Bitly.ShortURL("http://midnightprogrammer.net/post/9-Promises-Should-Be-Taken-Before-Choosing-IT-Profession.aspx", Bitly.API.Bitly.Format.TXT));
Console.WriteLine("Reverse URL: "+Bitly.API.Bitly.ReverseShortURL("http://bit.ly/eZ1kdb"));
Console.WriteLine("QRCode Image URL " + Bitly.API.Bitly.GetQRCodeURL("http://bit.ly/eZ1kdb"));

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.

Upload Files In RAZOR With jQuery Uploadify Plugin Mar 16, 2011 ASP.NET   JQUERY   MVC

A Few months back I wrote a post on how to use jQuery plugin Uploadify to upload single/multiple files without postback in ASP.NET. The program works similarly to simple file upload sites in its ease of use. Now a few days back I was working on a demo project which is on MVC 3 Razor and I use the same plugin without any problems. But the files that are being uploaded are uploaded to the root folder instead of the folder I specified to upload the files. After a lot of head scratching, I was unable to find the actual problem as why the file was not being uploaded to the folder of my choice. The answer was hidden in the normal file upload code that I saw in a forum posted by a user. So I gave it a try and it WORKED!! I was about to blog about the usage of uploadify plugin, but before that one of my blog reader asked me a question about uploading the files in Razor, though it was a bit different but this way it is pretty.

How do I do it?

Using the uploadify plugin in MVC 3 is the same as used with web forms, the only difference is that on the server-side we are going to use Controller and not a ASP.NET handler. Client side script is the same and there are only changes in script and folder parameter. Set the multi parameter to true if you wish to upload multiple files.


The script tag specifies the method in the Home Controller which handles the file upload. The Upload method in the Home Controller:

public string Upload(HttpPostedFileBase fileData)
{
      var fileName = this.Server.MapPath("~/uploads/" + System.IO.Path.GetFileName(fileData.FileName));
      fileData.SaveAs(fileName);
      return "ok";
}

Now you can use the uploadify plugin with MVC 3 Razor and upload files in a more effective and efficient way and that too with no postback.

Download: FileUploader.zip (572.92 kb)