Saturday, December 5, 2009

Singleton Design Pattern

Singleton design pattern
Design patterns are useful to implement a functionality of known problem. Singleton pattern is a object creational pattern which helps when you want only and only one instance of your class

You don’t allow the consumer of your class to create the instance but return a instance to the calling class by a static property and private\protected constructor
Here is a sample implementation
Class SingletonPattern
{
Private SingletonPattern _instance ;

Private SingletonPattern(){}

Public static SingletonPattern getInstance()
{
        If(_instance==null)
       {
            _instance =new SingletonPattern();
        }
return _instance;
}
}

Key considerations in singleton patterns:

Thread safety: when multiple threads are trying to get the only instance it may behave inconsistently so you must consider locking the object e.g.

LOCK(_instance)
{
      if(_instance==null)
      {
       _instance =new SingletonPattern();
       }
       return _instance;
}
Lazy initialization: when you initialize the instance as late as it requires called as lazy initialization. To ensure thread safety we can initialize the instance while declaring it in the class but that comes with a cost of object creation as soon as the class instantiate. Above given example is a lazy initialization where we initialized it in getInstance function. Another way to do is as follows
Class SingletonPattern
{
              Private SingletonPattern _instance= new SingletonPattern() ;
              Private SingletonPattern(){}
              Public static SingletonPattern getInstance()
              {
                            return _instance;
              }
}
Private Vs Protected constructor: singleton pattern doesn’t suggest to create a public constructor so which access modifier should we use protected or private.
Well all that depends on the functionality required but if you want to inherit your singleton class you must have to provide a protected constructor

Difference in static class implementation and Singleton pattern:
  • Static class doesn’t represent the instances but represents a global variable while singleton is only possible instance of a class
  • Static classes can’t be passed as objects in a function call
  • Singleton classes can implement interfaces while static classes can’t
  • Initialization may be lazy or during the class load in singleton but static simply initialized when class loads in the memory

 Singleton pattern mostly used in scenarios when object initialization is heavy and program can’t afford to do so every time for almost similar operation



Wednesday, September 30, 2009

Creating a Tag Cloud using C#

Introduction:
A tag cloud is a visual depiction of user-generated tags used typically to describe the content of web sites, which is basically a feature of web 2.0 sites. Tags are usually single words and are typically listed alphabetically, and the importance of a tag is shown with font size or color. Thus both finding a tag by alphabet and by popularity is possible. The tags are usually hyperlinks that lead to a collection of items that are associated with a tag.
A tag cloud is a set of related tags with corresponding weights. Typical tag clouds have between 30 and 150 tags. The weights are represented using font sizes or other visual clues.


Types of Tag Cloud:

There are three types of tag cloud representation in WEB 2.0 as described below:
1) In the first type, size represents the number of times that tag has been applied to a single item. This approach is being used to display metadata about an item.
2) In the second type, size represents the number of items to which a tag has been applied,
This represents the popularity of a particular tag.
3) In the third type, tags are used as categorization method for content items. Tags are represented in a cloud where larger tags represent the quantity of content items in that category.
In this document, second type tag cloud is being created, where tag size is the token for the popularity of a particular tag. Tag’s size shows that how many times that particular tag is being used for tagging.

Tag Cloud Implementation:
In this approach, Tags information is stored in Tag.xml file which will provide necessary data to create tag cloud .This information can be stored in database or file system as per requirement.
Tags.xml is used to store following information:-
Tag-Id Attribute depicts uniqueness of the tag, so that no repetitive tags should be displayed in the user control.
Tag-Count Attribute defines the size of the tag that will be displayed in the user control. This count defines the uses of that particular tag. Every time an existing tag is used for tagging, Count increases by one.
The tag size is shown using a simple logic. What the user controls does is that it displays top 100 most popular tags. The tags in the xml file are sorted in descending order as per their count and then the top 100 are picked. The size of those top 100 tags is then defined by the formula:
(Tag count/max. count) x 30 pixel
Thus the most popular tag will be having the size of 30 pixel and later tags will have size with respect to most popular tag.
The below shown xml file displays all the necessary information to create a tag cloud.
Tags.xml
<tags>
<tag id="1" count="34">india</tag>
<tag id="2" count="33">chandigarh</tag>
<tag id="3" count="33">symonds</tag>
<tag id="4" count="34">adobe</tag>
<tag id="5" count="71">infosys</tag>
<tag id="6" count="36">microsoft</tag>
<tag id="7" count="156">Amir Khan</tag>
<tag id="8" count="38">tata motors</tag>
<tag id="9" count="39">bse</tag>
<tag id="12" count="40">suzene</tag>
<tag id="13" count="39">bhatinda</tag>
<tag id="14" count="23">ABB</tag>
<tag id="15" count="50">BHEL</tag>
<tag id="16" count="11">Reliance natural</tag>
<tag id="17" count="23">Asia electronics</tag>
<tag id="18" count="56">jaypee hydro</tag>
<tag id="19" count="30">bank of india</tag>
<tag id="20" count="58">HDFC</tag>
<tag id="21" count="10">Asp.Net</tag>
<tag id="22" count="78">Atlanta</tag>
<tag id="23" count="20">tiger</tag>
<tag id="25" count="47">EMEA</tag>
<tag id="26" count="50">wedding</tag>
<tag id="27" count="11">ONGC</tag>
</tags>
Create a New Visual studio C# project name Forum3.UserControls.In this project directory ,create a New folder name xml and place tags.xml file there, now a tag cloud can be created as a User Control.
By Using C# Code:
Create a User Control name UCTagCloud in Visual studio 2005.
It consists two files:-
• UCTagCloud.ascx
• UCTagCloud.ascx.cs

Now Copy the following code in UCTagCloud.ascx
<%@ Control Language="C#" AutoEventWireup="true" Inherits="Forum3.UserControls.UCTagCloud, Forum3.UserControls, Version=1.0.0.0, Culture=neutral, PublicKeyToken=18c318ff50f694f2" %>
<table id="TABLE1" runat="server" style="width: 100%">
<tr>
<td style="width: 100%">
</td>
</tr>
</table>

And copy the following code in UCTagCloud.ascx.cs.
public partial class UCTagCloud : System.Web.UI.UserControl
{
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
int mincount;
ds = new DataSet();
//Get Tags.xml Data into Dataset
ds.ReadXml(Server.MapPath("./xml/Tags.xml"));
//Sort the tags data on Its Count
ds.Tables["Tag"].DefaultView.Sort = "count desc";
DataTable dt = ds.Tables["Tag"].DefaultView.ToTable();
//Get Row count of Table
int rowCount = dt.Rows.Count;
//Get Max value of count in existing Data
int maxcount = Convert.ToInt32(dt.Rows[0]["count"].ToString());
if (rowCount > 100)
{
//If More then 100 tags are available
//Get the Value of 100 th Tag as Minimum value of Count from sorted data
mincount = Convert.ToInt32(dt.Rows[100]["count"].ToString());
}
else
{
//If less then 100 tags are available
//Get the Value of last Tag as Minimum value of Count from sorted data
mincount = Convert.ToInt32(dt.Rows[rowCount-1]["count"].ToString());
}
//Select tags data from data table which have count value more or equal then minimum count to display in tag cloud
DataRow[] drc = dt.Select("count>=" + mincount, "tag_Text");
dt = ds.Tables["Tag"].DefaultView.ToTable();
//For each tag to diplay
foreach (DataRow dr in drc)
{
HtmlAnchor a = new HtmlAnchor();
//Assign URL as a hyperlink to each tag
//User will be traversed to this link when click on particular tag
a.HRef = "http://********:999/search.aspx?q=" + dr["tag_Text"].ToString();// xnod.InnerText;
//Assign inner text to Display as a Tag
a.InnerText = dr["tag_Text"].ToString();
//Assign Text to Display as a Tag
a.Title = dr["tag_Text"].ToString();
//Calculate size(weightage) of each tag based on its count and maximum count value
double normalWeight = (Convert.ToDouble(dr["count"].ToString()) / maxcount) * 30;
//Assign Font size to Each Tag according to its weightage
a.Style.Add(HtmlTextWriterStyle.FontSize, normalWeight.ToString());
//Add tags in a Htmltable to display
this.TABLE1.Rows[0].Cells[0].Controls.Add(a);
this.TABLE1.Rows[0].Cells[0].Controls.Add(new LiteralControl(" "));
}
}
}
}

Results will be displayed as in picture

Please note that the size of some tags is too small (the tag is not popular), there is possibility that it will be difficult to read. To rectify this we need to implement the “tooltip” on all the tags as shown in the picture above.
However it depends upon the developer choice whether he/she wants to implement this functionality or not.




Thursday, August 27, 2009

Generics VS Object Types

Can I call ONLY those methods supported on System.Object type , if I use generic?? : yes because when you want to do operation on generic (data) type it can only identify it as a object base class (because everything in .net is inherited from Object) and hence you can only call methods which can be called on Object.


if you want to make your generic more specific you can use constraints by which you can only use that particular generic for the constraint define and hence can call any method that is supported by constraint let say you define a generic class list where T: IComparable. So here compiler allow only IComparable type to use the generic class and since you know all types that can use the class will be of Icomparable so you can call function defined in Icomparable like T.CompareTo(obj)

Cannot use the + operator or the > operator. (Why ???? ): because if i assume that my generics can be used by any type then it will be difficult for compiler to call + operator on some "Person" type or for that matter any type which can't support addition, The reason is that the less-than or + operator in C# only works with certain types. Hence will be error on runtime

See how constraints helps to overcome this issue better explanation on this article of MSDN Magazine

http://msdn.microsoft.com/en-us/magazine/cc164081.aspx

Ref: http://social.msdn.microsoft.com/Forums/en-US/Vsexpressvcs/thread/c74f0b06-31b4-438a-b0be-8fbed288b1e9

Wednesday, March 18, 2009

Writing RSS Feeds in .net

This article will cover following topics

• About RSS feeds
• Various ways to generate RSS Feed
o Using HTTP handlers and Cache mechanism.
o Building an HTTP Handler
• RSS Library
• RSS XML Format
• Advantages
• Limitation and support
 About RSS Feeds:
RSS stands for really simple syndication. It’s one of the medium to deliver information to users’ offline directly in their mailbox/ offline RSS reader application on subscription. It mostly consist the frequently updated data in a website such as blog entries, web feeds, news & alerts, audio & video links etc. RSS feeds are updated on defined frequency depends on the new contents available on the site. It might be hourly, weekly, monthly etc. The users subscribe to the feed on which they like to get timely updates or to aggregate feeds from many sources to one application


An RSS document includes full text or summary based on content plus it’s related metadata such as date of publishing, author, web links etc. it can aggregated using an RSS reader application sometimes called aggregator also. A user provides a link to RSS document and thereafter RSS reader application checks for timely update on each feed subscribed. The RSS icon ("
 ") is very much popular among many web2.0 based websites.

RSS formats are specified using XML, a generic specification for the creation of data formats

Various ways to generate RSS Feed:
RSS Feeds can be generated in following three ways.

• Using HTTP handlers and Cache mechanism.
• Using a scheduler (Window services).
• Using default RSS provided by the MOSS Lists.

1.1 HTTP handlers and Cache mechanism:
1.1.1 When user clicks on the RSS icon attached to the web page/data list, the client browser or RSS reader requests an RSS document from the site.
1.1.2 IIS checks the .rss file extension and invokes .NET library to process it. It will be configured in IIS. The details steps are discussed later in the document
1.1.3 Based on information in the Web.Config file, .NET knows to invoke RSS library class (HTTP handler) to process the request.
1.1.4 RSS library class checks for a cached copy of the RSS document. If it exists, RSS library sends the document back to the browser and terminates. If the response has not been cached (or if it expired), then RSS library continues.
1.1.5 RSS library merges information from the datatable/list/xml with item data from the appropriate list to build the RSS document.
1.1.6 RSS library caches the RSS document and sends it back to the browser.

1.2 Building an HTTP Handler

Whenever a page request comes to IIS it checks the extension of the page requested which is in the Web server configuration that which file to serve on that particular request, since IIS initially handles the request.

An HTTP handler can be configured so that the browser request can ask for a file that doesn't physically exist under the Web site. For example, you won't find a file under the Web root called "example.rss." Instead, IIS sends all requests for .rss files to the .net assembly which is directed from the web configuration file, and .net assembly writes the response from memory.

An http handler be configured in the following way


• Open ISS, Click start, run and enter inetmgr
• Click on configuration button on home directory tab, Application configuration dialog popup
• click on add button in mapping tab, Add/edit application extension mapping dialog open up
• Select the path of the DLL in executable text box and set the extension to .rss
• Close all the dialog boxes and now IIS is ready to serve any request that comes from .rss extension
To configure handler to a file extension through .NET, add a section to the Web.Config file in the root folder of Web application. Here's an example that shows how to associat RSS library with rss file requests .

The httpHandlers "add" tag tells .NET to send all rss file requests (verb="*" path="*.rss") to the RssHandler class in the RSS library assembly (type="Forum3.RSS library.RssHandler, RSS library").




Fig: Sample Web.Config

An HTTP handler is nothing more than a simple class library with at least one class that implements the IHttpHandler interface. The interface has just two members
• ProcessRequest method
• IsReusable property.
IsReusable tells .NET whether or not instances of your class can be safely pooled and reused. RssHandler returns true because it doesn't maintain any state that would interfere with its reusability.

The ProcessRequest method is where all the fun stuff happens. The .NET worker process passes you a reference to the request's HTTP context, which gives you access to the Request and Response objects as well as the other standard elements of the context.

2. RSS Library:

RSS library (RSS library) is .net class file which defines all the methods related to fetch/search and cache the resulted output to RSS format. it can be use any data source to find the result as databases/ xml/MOSS list etc. RSS profile contains all the settings related to the particular RSS that has to served like connection setting, Web link to RSS, title of feed etc.

FIG: Format of well defined RSS
3. RSS Format:

RSS format contain the data according to RSS 2.0 specification.
Here each item depicts a new feed in the document with its metadata. The properties of an RSS feed is classified under channel node. It can title of RSS feed, short description, web link, publish date etc.
Channel node contains many item nodes which translate into specific information available for the user in RSS feed. Each item node contains similar properties like title, description, web link, date of publish etc



References: www.msdn.microsoft.com