Factory Pattern

Published 11/10/2005 by Henry in C# | Patterns
Tags: ,

The challenge:
We got a lot of classes derived from one baseclass. Like a TableRow with controls in it.
Every control got another control in the third row, like:

  • A Textbox
  • A DropdownListBox 
  • A RadioButtonList
  • Multiple Textboxes and a Dropdownlist (Date)
  • Etc.

In our client (A Webb App) we do not want to be bothered with which control we have to instantiate. We want to instantiate and get the right kind of object returned.
For this kind of scenario we can use the Factory Pattern.

A Factory Pattern returns an instance of one of the several classes depending upon the parameters passed to the shared/non-shared factory method. Typically, all these classes are inherited from a common parent class.
Each of them has common methods. But each of them has their own optimization task operation on data. For simplicity I decided to give an example that is more simple than the real life implementation I described above.
I will use a very simple example.

We got an abstract Employee class (must be inherited), which will act as our base class.
The Employee class has two properties:

  • Name (string)
  • Salary (double)

We derive from the Employee class two classes:

  • Developer
  • Manager

Because we do not want the hassle to instantiate another class everytime we want to create a developer instance, or a Manager instance and because there will be more Employee derived objects in the future (Secretary, Architect, etc.), we create a Factory class that does the job for us.
We call it the EmployeeFactory. 


 Here is the code for the Employee class, with the derived classes:

   1:  using System;
   2:  namespace FactoryExample
   3:  {
   4:      public abstract class Employee
   5:      {
   6:          #region Private Members
   7:          private string m_Name = string.Empty;
   8:          private double m_Salary = 0;
   9:          #endregion
  10:          #region Public Properties
  11:          public string Name
  12:          {
  13:              get { return m_Name; }
  14:              set { m_Name = value; }
  15:          }
  16:          public double Salary
  17:          {
  18:              get { return m_Salary; }
  19:              set { m_Salary = value; }
  20:          }
  21:          #endregion
  22:      }
  24:      public class Developer:  Employee
  25:      {
  26:          public Developer()
  27:          {
  28:              Name = "John Refactorer";
  29:              Salary = 2000;
  30:          }
  31:      }
  33:      public class Manager: Employee
  34:      {
  35:          public Manager()
  36:          {
  37:              Name = "Peter PeopleManager";
  38:              Salary = 5000;
  39:          }
  40:      }
  41:  }

Next we have the Factory:

   1:  using System;
   2:  namespace FactoryExample
   3:  {
   4:      public class EmployeeFactory
   5:      {
   6:          public Employee CreateEmployee(int employeeKind)
   7:          {
   8:              Employee EmployeeObject;
   9:              switch (employeeKind)
  10:              {
  11:                  case 0:
  12:                      EmployeeObject = new Developer();
  13:                      break;
  14:                  case 1:
  15:                      EmployeeObject = new Manager();
  16:                      break;
  17:                  default:
  18:                      EmployeeObject = new Developer();
  19:                      break;
  20:              }
  21:              return EmployeeObject;
  22:          }
  23:      }
  24:  }

And last but not least the console app that calls the factory to instantiate the Developer and manager objects.

   1:  using System.Collections;
   2:  using System.Text;
   3:  namespace FactoryExample
   4:  {
   5:      class Program
   6:      {
   7:          static void Main(string[] args)
   8:          {
   9:              EmployeeFactory EmpFactory = new EmployeeFactory();
  10:              Employee emp;
  11:              for (int i = 0; i < 2; i++)
  12:              {
  13:                  emp = EmpFactory.CreateEmployee(i);
  14:                  Console.WriteLine("{0} - ({1}) Name: {2} Salary: {3}",
  15:                                      i,
  16:                                      emp.GetType().Name,
  17:                                      emp.Name,
  18:                                      emp.Salary);
  19:                  emp = null;
  20:              }
  21:              Console.Read();
  22:          }
  23:      }
  24:  }

When we run this code the output in the console looks like this:


I hope you get the idea, I have some real use for this pattern in the situaton described at the beginning of this post.

Henry Cordes
My thoughts exactly...

Load document in iframe dynamically

Published 11/3/2005 by Henry in ASP.NET | C#
Tags: ,

Supose you need to show an xml, html or aspx document inside an ASP.NET page. So you actually want to embed another page or document inside the original page. You want to load a document in an iframe dynamically from the server-side.
What you really need is an iFrame server control. However an iFrame is an html control and it's properties are not directly available at the server side (in the codebehind). So we need a way to access the 'src' property of the iFrame directly. Inside the iFrame's tag in the html of the aspx page we set the 'runat' attribute with the 'server' value.

   1:  <iframe id ="MyIframe" runat ="server"> 
   2:  </iframe> 

In the aspx.cs (codebehind) file we declare a System.Web.UI.HtmlGenericControl and name it (the name does not have to be the same as in the html page, but I think it is good practice to do so).

   1:  protected System.Web.UI.HtmlControls.HtmlGenericControl MyIframe;

We create a method we can call in order to load a document in our iFrame by using the FindControl method of the System.Web.UI.Page and typecast it This way we can acces all properties of the HtmlControl through the Attributes property. The "MyIframe" referred in Find Control is the ID as declared in the ASPX Page.

   1:  private void LoadDocumentInIFrame(string url)
   2:  { 
   3:      HtmlControl MyIframe = (HtmlControl)this.FindControl("MyIframe"); 
   4:      MyIframe.Attributes["width"] = "100%"; 
   5:      MyIframe.Attributes["height"] = "400px"; 
   6:      MyIframe.Attributes["src"] = url; 
   7:  }
  10:  // Example that calls the method
  11:  LoadDocumentInIFrame("http://www.google.com")

This way we can load a document in an iframe dynamically from server-side.
With the FindControl() we can get a reference to the HtmlGenericControl object and access the properties of it. As you will understand this is not limited only to the iFrame, but can be used for more 'HTML' controls.

Henry Cordes
My thoughts exactly...


.NET Framework version...

Published 10/19/2005 by Henry in ASP.NET

I started working on a new project, the project runs on version 1.0 of the .NET Framework, on my development machine version 1.1 of the .NET Framework also is installed. Now the project gives exeptions becasue IIS runs it on the 1.1 Framework.

This is why I had to solve the following problem:
How do you tell one Web application to use the new version and the others to use the previous version?

The simple answer is to use the ASP.NET IIS Registration Tool, which is included with each version of the .NET Framework and usually is located at <WinDir>Microsoft.NETFramework<version>aspnet_regiis.exe.

In the case of an .aspx page, IIS loads the ASP.NET ISAPI extension (aspnet_isapi.dll) and passes it the request. The ASP.NET ISAPI extension then passes the request to the ASP.NET worker process, aspnet_wp.exe. Each version of the .NET Framework installs its own version of aspnet_isapi.dll and aspnet_wp.exe, how does IIS know which one to invoke for any particular .aspx page? You can find the answer in the IIS management console, located under the Administrative Tools section of the Control Panel.

To determine which version of ASP.NET is being used, open the IIS management console, right-click on the virtual directory or Web site, and select Properties. On the Directory or Home Directory tab, click on the Configuration button.
As shown in Figure 1, you should be on the Mappings tab, which displays a list of file extensions and the path to the corresponding CGI executable or ISAPI extension. The key here is to see which version of the ASP.NET ISAPI extension is being invoked for .aspx pages. For version 1.0 it should be <WinDir>Microsoft.NETFrameworkv1.0.3705aspnet_isapi.dll; for version 1.1 it should be <WinDir>Microsoft.NETFrameworkv1.1.4322 aspnet_isapi.dll.

ASP.NET Version 1.1
Version 1.1.4322

It now is possible to change this by selecting al extensions that use the .NET framework and click "Edit" to re- map the executable path for all the ASP.NET extensions to <WinDir>Microsoft.NETFrameworkv1.1.4322aspnet_isapi.dll., but what if you need to do this more often or have many websites to cover?
Using the IIS Registration Tool is straightforward. It has several options that let you install and uninstall not only the extension mappings but also the JavaScript files that perform client-side validation. You can do this for a virtual directory, an entire Web site, or all ASP.NET applications on the machine. Using the previous example, you can force the NewVersion Web application to use ASP.NET 1.1, by using this syntax:

aspnet_regiis -s W3SVC/1/ROOT/NewVersion

Watch out for a couple of possible pitfalls here. One thing to remember is your command prompt must be in the <WinDir>Microsoft.NETFrameworkv1.1.4322 directory; otherwise, there's no telling which version will be executed. The other thing to remember is the path to the virtual directory might not always begin with W3SVC/1/.
determine the path for the Web site you're working with. It is possible to do this by going to the Web site's Properties dialog and on the Web Site tab clicking the Properties button in the logging section. You should see the Log File Name at the bottom of the General Properties tab. This is the path you should use, minus the actual filename itself.

Logdirectory IIS

Another handy option for this tool is to view all the applications that are mapped to ASP.NET and which version they are mapped to. This is also another way to find the path name for the Web site. For this option, use this syntax:

aspnet_regiis -lk

This syntax will display something like this:

W3SVC/ 1.1.4322.0
W3SVC/1/ROOT/ 1.1.4322.0
W3SVC/1/ROOT/OldVersion/ 1.0.3705.288
W3SVC/1/ROOT/NewVersion/ 1.1.4322.0

Henry Cordes
My thoughts exactly...


Published 10/12/2005 by hendaman

Your Four minutes of fame...
Yesterday I went to MIND, the (M)icrosoft (IN)ternal up(D)ate.
An event my employer sponsors every year to give an update about the alliance with Microsoft and talk about Microsoft related issues. Also this evening is used to network with fellow employees, enjoy a nice meal and it is possible to attend breakout sessions.
The following sessions could be attended yesterday:

  • Business Intelligence in combination with SQL-Server
  • .NET Development
  • Microsoft Business Solutions
  • Infrastructure and Security

    I attended the .NET Development session where Microsoft's Lex Oskamp (a speaker I always enjoy) showed us the Visual Studio Tools For Office. This was interesting.
    But what I really would like to share is a new initiative called FourHour.net. This is a website where a community will be started along the lines of Channel9.
    Here is what they say themselves:

    "We want to show the real people behind the innovative IT-Solutions build with the .NET products. Bring fame to those who are normally behind the scenes. What keeps them awake at night? What are they proud off? Do they have a life besides IT? We know you are out there, so don’t be shy when we pay you a visit… "

    So they give developers a change to show off cool projects or stuff you do in your own time. I hope this will take off, so remember this and pay them a visit: www.fourhour.net. The site and initiative is brand new, so give them the time to built their content. In the future everybody can join and offer their "sexy shit", to quote the speaker.

    Henry Cordes
    My thoughts exactly...

  • ASP.NET 2.0 update

    Published 9/27/2005 by Henry in ASP.NET

    Through this link you can find a lot of information about ASP.NET 2.0:


    Henry Cordes
    My thoughts exactly...