Factory Design Patterns

Hi All,

In this article, we will discuss about Factory design pattern

This is type of creational patterns i.e. it helps us to create objects.
The key feature is to create concrete subclasses

Factory Pattern is defined as “Define an interface for creating an object, but let the subclasses decide which class to instantiate. The Factory method lets a class defer instantiation to subclasses”

Let’s consider the below issue & also we will see how to resolve this issue with design pattern
Lets say I am developing an application to Client, & client’s requirement is I should develop my application in such a way that if I enable config saying SQL my application should connect to SQL DB & if I enable config saying Oracle it should connect to Oracle.

This kind of issue can be resolved with Factory Design Pattern.
So to fix this I have to write all database related methods with respect SQL & Oracle. Also the connection to database should happen on config.

In this we will define Interface as IConnection, this define all the DB related methods

// Base Interface
public interface IConnection
void Display(string conString);

I will have class specific to SQL as shown below & this class has to implement IConnection

// A Connection Class that Implements the IConnection Interface
public class SqlConnect : IConnection
public void IConnection.Display(string conString)
// Method to display data by connecting to SQL Server DB

I will have class specific to Oracle as shown below & this class has to implement IConnection

// A Connection Class that Implements the IConnection Interface
public class OracleConnect : IConnection
public void IConnection.Display(string conString)
// Method to display data by connecting to Oracle Server DB

// The Connection Factory
public class ConnectionFactory
public static IConnection getConnection(string connectionType)
switch (connectionType)

case “Sql”:
return new SqlConnect();
case “Oracle”:
return new OracleConnect();
throw new ApplicationException(string.Format(”ConnectionType ‘{0}’ cannot be created”, connectionType));

Now Lets try with below example
Create a class & add the following code

public interface IConnection
string GetStudentById(int stdId);

public class SQlConnect : IConnection
public SQlConnect()
Console.WriteLine(”SQL Connection Class is Called!!!”);
public string GetStudentById(int stdId)
return “Student name is Mr. Prakash & his ID ” + stdId.ToString() + ” “;


public class OracleConnect : IConnection
public OracleConnect()
Console.WriteLine(”SQL Connection Class is Called!!!”);
public string GetStudentById(int stdId)
return “Student name is Mr. Prakash & his ID ” + stdId.ToString() + ” “;


Let’s create a web page & name the page as “FactoryPattern” and add the following code

public enum ConnectionType
Sql, Oracle

static FactoryPattern()
public static IConnection CreateConnectionObject(ConnectionType TypeOfConnection)
switch (TypeOfConnection)
case ConnectionType.Oracle:
return new OracleConnect();
case ConnectionType.Sql:
return new SQlConnect();
throw new ArgumentException(”Invalid Connection Type!”);

In the page load event add the following code

IConnection connT;

if (ConfigurationManager.AppSettings[”ConnectionType”] == “1″)
connT = FactoryPattern.CreateConnectionObject(FactoryPattern.ConnectionType.Sql);
connT = FactoryPattern.CreateConnectionObject(FactoryPattern.ConnectionType.Oracle);


string str = connT.GetStudentById(1);

/* the above lines of codes clearly states that object return type is defined based on config entry only & in future we need to add another connection type we can still do it with lot minimal changes without affecting the existing changes */

Happy Koooding….. Hope this helps !!!!

Integrate Facebook LIKE button

  1. Open the below link



  1. Specify the url of your site in below text area with other appropriate values

  1. Now click, Get Code button & this would generate code as shown below


  1. Copy the code, click Okay & paste it in your web page, where you want to show LIKE button.



Similar way we generate Open Graph tags. Open Graph tags are <meta> tags that you add to the <head> of your website to describe the entity your page represents, whether it is a band, restaurant, blog, or something else.


An Open Graph tag looks like this:

<meta property="og:tag name" content="tag value"/>


Happy Kooding…. Hope this helps!!!

Google Analytics, Google Web Master Tool, Google Feed burner

Google Analytics, is the one which will help us in see the site traffic details like

  1. From which country we have huge hits
  2. Pages which are viewed the most
  3. And more, see the below pic

Google Web Master Tool: Using this tool we can ask google to crawl our site, doing so this create indexing our site in Google records, which intern increase site traffic. See below screen how to do

  1. First add our site in Google Web Master tool

Look at the options in left menu in below option.

We can create google gadets & submit. These gadgets can be added to iGoogle

Google Feed burner: This is another tool from google related to RSS Feeds

We need to use Google Meta Tag that will increase rankings of site

We need to create Email Account by our brand name, Funky Asian. Using this account we will manage all above thing

Blogs, Facebook, Twitter, Google, Yahoo, Hotmail etc.

If by change user is tying our brandname, then our funky site detail information will show which will help to increase traffic

Blogger & Word Press are free site where we can create blog & post our blogs.

We will find more similar site for this.

Calling Web Service from Javascript


Now we will discuss how to call web service from javascript.

This example demonstrates of

1. Calling web service method from javascript after page loads completely (async) &

2. This method returns XML string &

3. Displays XML node content div &

4. Between if there is any delay from web service, we need to show loading image or loading text.

Lets get into details

  • Add new Item, select webservice from template & name it as “ServiceOne.asmx”
    • Add  [System.Web.Script.Services.ScriptService] attribute to ServiceOnce class
    • Add below method to ServiceOne class
    • [WebMethod]publicstring GetResponse(string callerName){string txt = string.Empty;txt = “<bookstore><book>”;txt = txt + “<title>Everyday Italian</title>”;txt = txt + “<author>Giada De Laurentiis</author>”;txt = txt + “<year>2005</year>”;txt = txt + “</book></bookstore>”;if (callerName == string.Empty)thrownewException(“Web Service Exception: invalid argument”);Thread.Sleep(5000); // To get response delay, forced to sleepreturnstring.Format(txt.ToString());}  
  • Add Script Manager and add Service reference to default.aspx as shown below

<asp:ScriptManagerID=”ScriptManager1″runat=”server”> <Services><asp:ServiceReferencePath=’~/ServiceOne.asmx’/></Services></asp:ScriptManager>

  • Now lets add DIV, which will show loading text if there is any delay response from Web Service & when there is response from web service it will  display XML NODE content


  • Now Lets the javascript function code which will call web method & the response from web method can be Success/Completed response, TimeOut response & Error response. Below sendRequest function is called in BodyLoad event, & first statement shows loading text in div until we get response from Web Service

This function pass static string value to web method & response will be either completed, timeout or error. So we define respective function names in web method calls.

ServiceOne is web service

GetResponse is web method defined in ServiceOne service class

function SendRequest() {document.getElementById(“lblResponse”).innerHTML = “Please wait loading……. “;ServiceOne.GetResponse(

“TESTING TO BE ……..”, OnComplete, OnError, OnTimeOut);}

  • On Success/Complete reponse we need to parse XML string & read the Title XML node from XML string & display in lblResponse DIV as shown below

function OnComplete(arg) {//alert(arg);

if (window.DOMParser) {parser = new DOMParser();xmlDoc = parser.parseFromString(arg,


else// Internet Explorer


xmlDoc = new ActiveXObject(“Microsoft.XMLDOM”);xmlDoc.async = “false”;xmlDoc.loadXML(arg);


x = xmlDoc.getElementsByTagName(“title”)[0];y = x.childNodes[0];

txt = y.nodeValue;

document.getElementById(“lblResponse”).innerHTML = txt;}

  • Whenever there is ErrorReponse then below function will be called

function OnTimeOut(arg) {alert(“timeOut has occured”);}

  • Whenever there is TimeOut response below function will be called

function OnError(arg) {alert(“error has occured: “ + arg._message);}

  • Finally call sendRequest JS function in body load event as shown below

<bodyonload=”return SendRequest();”>

  • Now lets execute this & checkout the output

HTTP Error 500.19 – Internal Server Error

The requested page cannot be accessed because the related configuration data for the page is invalid

  1. Go to “C:\Windows\System32\inetsrv\config”. [Note: you need to have admin rights to modify applicationHost.config file]
  2. Now open applicationHost.config
  3. Look for “modules” or “handlers” based on error message
  4. Change the overrideModeDefault attribute from “Deny” to “Allow”. In my case it is with handlers. So I modified it accordingly.

<section name=”handlers” overrideModeDefault=”Allow” />

Alphanumeric Regular Expression in java script

We will validate text box data to be alphanumeric data onblur event. On blur we Validate_Alphanumeric js event will be called

<asp:TextBox ID=”txt” runat=”server” onblur=”javascript:Validate_AlphaNumeric(this.id);” MaxLength=”100″></asp:TextBox>

function Validate_AlphaNumeric(id) {
var regEx = /^([a-zA-Z0-9_-]+)$/;
var strValue = document.getElementById(id).value;
if (regEx.test(strValue)) {
alert(“ Value is alphanumeric”);
else {
alert(“ Value is not an alphanumeric”);


 regular expression string should be in between / & /
^         start of string
a-zA-Z0-9_-  a or b or c or … z or 0 or 1 or … 9 or _ or –
$         end of string

Happy Koooding! Hope this helps

using HTTPContext Object

In this article we will see what is HTTPContext object & how to make use of it.
The HttpContext object in the System.Web namespace encapsulates all of the information related to request & response of aspx page at an instance.
HttpContext object will be constructed newly for each & every request made by client, apart from Request & Response information it will contain Server, Session, Cache, User & etc.
Now let’s dig into code, & see how to find a control using HTTPContext Object

// HttpContext.Current.Request.Form gives all control names that are part of current
// request, this will give hidden field controls that are being used by asp.net engine

foreach (string ctrlName in HttpContext.Current.Request.Form)
// locate the control that you want to find
if (ctrlName.ToString() == “txtname”)
// will allow to get page object
Page page = HttpContext.Current.Handler as Page;

// now find control with page object & type cast
TextBox txt = (TextBox)page.FindControl(ctrlName);

// check if control object not null & assign the value
if(txt != null)
txt.Text = “Finally found the control”;

Ok this looks ok but you must be wondering why do I need to write this length of code to assign value.
Let’s look at the below scenario


The static property Current on the HttpContext class can be useful whenever the flow of control leaves the code in your Page.
Using this property you can reach out and magically grab the current Request, Response, Session, and Application objects (and more)
for the request you are servicing.

Take the following code as an example.

private void Page_Load(object sender, System.EventArgs e)
DemoClass dClass = new DemoClass();


class DemoClass
public void DemoMethod()
HttpContext.Current.Response.Write(”Demo Method Class”);

This provides the ability to grab the context for the current request from any code inside the same
application domain is powerful.

Happy Kooding… Hope this helps!

Modal Popup in PageLoad using AjaxTool Kit

In this article we will evaluate ASP.NET ModalPopUp ajax extender control.
Using this control we will show ModalPopUp in pageload & this popup should be shown to user only once during the session i.e. popup should not be shown when page is refreshed and should not be shown after returning back to this page before session expires.

Let’s dig into this article by following below steps:
1. As we all know the primary control to be used whenever we use .NET Ajax control. Yes you have guessed it right it’s not other than ScriptManager control. Add this to the form
<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

2. Next we need ModalPopUp extender control
<asp:ModalPopupExtender runat=”server” ID=”myExtender” BackgroundCssClass=”myModalPopupbackGrnd”
PopupControlID=”myPopup” TargetControlID=”myhiddencontrol”>

myExtender: Modalpopup control ID
myModalPopupbackGrnd:  background CSS name for entire page
myPopup: Name of panel which will be shown as PopUp
myhiddencontrol: Modalpopup extender expects target control ID. Based on
this control event extenders are executed. For example if we want popup to shown upon click event these we need to give button control ID. But in our case we want to show popup on page load we will give label ID
3. Now let’s add the panel which will be shown as popup
<asp:Panel ID=”myPopup” runat=”server” CssClass=”myModalPopup” Style=”display: none;”>
<asp:Panel ID=”dragHandler” runat=”server”>
<div style=”padding: 3px;”>
This is a demo popup extender
<div style=”width: 500px; text-align: right;”>
<asp:Button ID=”btnOK” runat=”server” Text=”Thanks!” />
In panel we will place our content which is to be shown in popup.
dragHandler: panel to show header & by selecting this we can move popup.
btnOK: button ok upon clicking we will hide popup
4. To make our popup to be drag we need to add DragHandler & provide the DragHandler ID with the Panel ID which is inside PopUp panel
<asp:DragPanelExtender ID=”drgPnlExt” runat=”server” TargetControlID=”myPopup” DragHandleID=”dragHandler” />

5. To hide popup when OK button is clicked, we will write a JS function inside head tag, which will do this for us
function HideMyPopup() {
return false;

6. Place the below code in Style tag inside head tag
background-color: #dedede;
filter: alpha(opacity=50);
opacity: 0.7;

min-width: 200px;
min-height: 150px;
background: white;
7. Let’s get into server side code, to bind JS function with button click event need to use below code
btnOK.Attributes.Add(”onclick”, “return HideMyPopup();”);

8. To show popup only on page load of the page, we need to use below code in PageLoad event
if (Session.IsNewSession)
9. Now execute and see it. Popup extender shows up for first time only & will not show when you refresh.

Happy Kooding… Hope this helps!

JQuery Carousel Control in ASP.NET

In this article we will explore how to build Carousel control. To start with first we will build Static HTML carousel control & then we will integrate with our .NET Repeater control to show data & work similar to Static HTML content.
It is expected you have basic knowledge on what is JQuery.

Below are steps to be followed to build Carousel control
1. Open new web site & start scratching default.aspx as mentioned below
2. Download below JQuery java script files from http://jquery.com site
a. jquery-latest.pack.js
b. jcarousellite_1.0.1.js
3. Add above JS script reference in default.aspx under head tags as shown below
<script type=”text/javascript” src=” jquery-latest.pack.js”></script>
<script type=”text/javascript” src=” jcarousellite_1.0.1.js”></script>

4. Now we will add a div, which will contain Unordered list tag & image tags. This div should be assigned with some class name. In our instance we are using class name as “anyClass” & image should be assigned with proper image source path

<div class=”anyClass”>
<li><img src=” sample-logo.png” alt=”” width=”100″ height=”100″ ></li>
<li><img src=” sample-logo.png” alt=”” width=”100″ height=”100″ ></li>
<li><img src=” sample-logo.png” alt=”” width=”100″ height=”100″ ></li>
<li><img src=” sample-logo.png” alt=”” width=”100″ height=”100″ ></li>

5. Now for navigation of images, we need 2 buttons for forward & backward navigation.
<button class=”prev”><<</button>
<button class=”next”>>></button>

6. In the head section, add JS script tag & add the following code.
<script type=”text/javascript”>
$(function() {
btnNext: “.next”,
btnPrev: “.prev”


/*  Comment : div class name & following  and name in this line of code should match $(”.anyClass”).jCarouselLite( */

7. Now run the page & see the output.
8. So far so good, till now we have seen static HTML works fine.  Let’s say we have image list which comes from DB source or any other source & you want to bind it to grid view or any list control. But when you use these control you would not be able to add UnOrdered list <ul> and the HTML as same as above static. If you have similar HTML, JQuery carousel will not work properly. I mean you need to have <div>, followed by <ol> then followed by <li> & finally <img> tag.
9. So to get out of this & generate similar stuff, we need to Repeater control instead of GridView, DataGrid and DataList
10. First lets add Repeater control to webpage, inside our DIV & css class should be “anyClass”

<div class=”anyClass”>
<asp:Repeater ID=”myRepeater” runat=”server”>
<td><img src=”<%# DataBinder.Eval(Container.DataItem, “ImageURL”)%>” alt=”” width=”100″ height=”100″ />



11. To bind this repeater with source, we will generate static list as following

var list = (new[] { new { ImageURL = “images/sample-logo.png”, Text = “The Sun” } }).ToList();
list.Add(new { ImageURL = “images/sample-logo.png”, Text = “New York” });
list.Add(new { ImageURL = “images/sample-logo.png”, Text = “Office Meeting” });
list.Add(new { ImageURL = “images/sample-logo.png”, Text = “A Beach” });
list.Add(new { ImageURL = “images/sample-logo.png”, Text = “Global Technology” });
list.Add(new { ImageURL = “images/sample-logo.png”, Text = “My Global Technology” });
list.Add(new { ImageURL = “images/sample-logo.png”, Text = “Our Global Technology” });

Hope above code is simple enough to understand, is yes then let’s move on

12. Finally add this list to our repeater control

myRepeater.DataSource = list;

13. Now run the application & have a look at the output.
Happy Kooding… Hope this helps!

Read RSS FEED data (blogspot.com)

Hi All,

In this article we will see how to read RSS Feed data & show it on our web site.
To start with on we need to know from where we are going read RSS feed data. In this example, we will read RSS feed data from blogger.com site, where recent posts are available.
Let’s say there is a blog spot as http://xxxxxx.blogspot.com then RSS feed data would be available at http://xxxxx.blogspot.com/rss.xml. So this is the source data for us to work with.
Now start with code part:

1. First lets add DataGrid to our web page, with one template column as shown below

<asp:DataGrid runat=”server” ID=”myPosts” AutoGenerateColumns=”False”>
<asp:TemplateColumn HeaderText=”My Posts”>
<a href=”<%# DataBinder.Eval(Container.DataItem, “link”)%>”>
<%# DataBinder.Eval(Container.DataItem, “title”) %>
2. In our page load, lets declare XMLTextReader object with & this will take RSS FEED URL. In this example I am using my blogspot url
XmlTextReader reader = new XmlTextReader(”http://bgsuryablog.blogspot.com/rss.xml“);
3. We will declare Dataset
DataSet ds = new DataSet();

4. To read XML data & read into DS lets use below code

5. As we have dataset object filled up with RSS feed data. Lets assign Dataset to datagrid as below
myPosts.DataSource = ds;

6. Dataset object would contain properties in the form of Link & Title, which we have used in our .aspx code i.e. step1

7. Now execute the code & see the output

Happy Kooding… Hope this helps!