Hello World


Friday, December 21, 2007

JSON (JavaScript Object Notation)

Introduction to JSON

JSON is a lightweight data-interchange format. It is particularly useful because it can be 'decoded' easily by web page JavaScript into object form.
AJAX-based web pages use XmlHttpRequest to receive data from a server in response to a user action. While the returned data is normally in XML format, it can also be returned in JSON string format and processed more easily in JavaScript.
Many applications may store information in XML format. However they may want to send data to a client using JSON.
To achieve this, they must convert their XML data into JSON format.
JSON Site: JSON

How to convert XML to JSON in ASP.NET C#
ASP.NET Podcast on JSON

Thursday, December 20, 2007

.NET Framework 3.0

When speaking to developers about WinFX one question that repeatedly comes up is, “WinFX sounds great, but what happens to .NET?” .NET Framework has become one of the most successful developer platforms in the world.
The .NET Framework has always been at the core of WinFX, but the WinFX brand didn’t convey this. The WinFX brand helped us introduce the incredible innovations in terms of Windows Presentation Foundation (WPF), Windows Communication Foundation (WCF), Windows Workflow Foundation (WF) and the newly christened Windows CardSpace (WCS) formerly known under the codename “InfoCard.” The brand also created an unnatural discontinuity between previous versions of our framework and the current version.
With this in mind we have decided to rename WinFX to the .NET Framework 3.0. .NET Framework 3.0 aptly identifies the technology for exactly what it is – the next version of our developer framework.
The change is in name only and will not affect the technologies being delivered as part of the product. The .NET Framework 3.0 is still comprised of the existing .NET Framework 2.0 components, including ASP.NET, WinForms, ADO.NET, additional base class libraries and the CLR, as well as new developer-focused innovative technologies in WPF, WCF, WF and WCS.

The .NET Framework 3.0 will still ship with Windows Vista, and will be available down-level for Windows XP and Windows Server 2003 as planned. This change doesn’t affect in any way the ship schedules of either Windows Vista or the .NET Framework 3.0 itself.

C# 3.0: An Introduction




.NET 3.5

With the release of .NET 3.5 is Language Integrated Query (LINQ).
LINQ essentially is the composition of many standard query operators that allow you to work with data in a more intuitive way regardless of the data source.

You can query in-memory collections, Relational Data and XML.

For an introduction to LINQ goto : .NET 3.5 LINQ

Wednesday, December 19, 2007

XSLT - Simple HTML Table

In this example we will convert a simple XML file to HTML























The HTML output
The goal is to generate the HTML output shown below using the XML document as the source of the information.



















XSLT will help us to do this.
Add this line to your XML file.

Here's the people.xsl (XSL) file that produces the HTML.
Every XSL file needs to specify the XSL namespace so that the parser knows which version of XSLT to use.























Here's a break down of the XSL file.
The namespace prefix xsl: is used in the rest of the XSL file to identify XSL processing statements. If a statement isn't prefixed with xsl:, then it's simply copied to the output without being processed. This is the way to add HTML statements to the output. When we are working with XSLT, the context for a query is the node in the source XML document currently being processed. So in the template xsl:template match="/", we are in the context of the root of the XML document. This isn't the PEOPLE element, it's the whole document, above the PEOPLE element.
When you're debugging XSL, the first question you should ask is, "What context is being processed?".

The backslashes are not part of the syntax.
<\xsl:template match="/"\>

Before processing can begin, the part of the XML document with the information to be copied to the output must be selected with a XPath expression. The selected section of the document is called a node and is normally selected with the match operator. If the entire document is to be selected, match the root node using match="/". Another approach is to match the document element (the element that includes the entire document). In our example, the document element can be selected using match="PEOPLE". (If you use this alternative approach, don't include PEOPLE in the 'for-each' selection below.)

The backslashes are not part of the syntax.
<\xsl:for-each select="PEOPLE/PERSON"\>


The expression xsl:for-each finds all 'PERSON' elements in the 'PEOPLE' element context using the XPath expression 'PEOPLE/PERSON'. If the selected node contains all elements in the root, all of the 'PEOPLE' elements will be selected. Since we want to include all 'PERSON' elements in our output document, we have used this expression.
The 'for-each' expression is a loop that processes the same instructions for these elements.


The backslashes are not part of the syntax.
<\xsl:value-of select="NAME"/\>

<\xsl:value-of select="ADDRESS" /\>
<\xsl:value-of select="TEL" /\> etc...

When the xsl:for-each expression has selected a 'PERSON' element, the xsl:value-of expression extracts and copies to the output file the value stored in the selected element. In this case, the value stored in the 'NAME' element is copied to the output. This call is made for each value you are extracting.


This will produce the html required that can then be displayed in the clients browser.

Tuesday, December 18, 2007

AJAX .Net Wrapper

Asynchronous JavaScript and XML (AJAX)


Ajax: A New Approach to Web Applications


Download the Ajax DLL from:
Ajax.NET
Add the Ajax.dll reference to your application.
Add the using Ajax; namespace to your page.
Add the httpHandler to your web.config.







Sample Code to try.

Ajax can return custom classes. All that is required is that the class be marked with the Serializable attribute. Given the following class:

[Serializable()]
public class User
{
private int _userId;
private string _firstName;
private string _lastName;
public int userId{ get { return _userId; } }
public string FirstName{ get { return _firstName; } }
public string LastName{ get { return _lastName; } }

public User(int _userId, string _firstName, string _lastName)
{
this._userId = _userId;
this._firstName = _firstName;
this._lastName = _lastName;
}
public User(){}

[AjaxMethod()]
public static User GetUser(int userId)
{
// The userId would normally be a value to use in a DB call.
return new User(userId,"Elvis", "Costello");
}

We would register the GetUser proxy via a call to the RegisterTypeForAjax
private void Page_Load(object sender, EventArgs e)
{
Ajax.Utility.RegisterTypeForAjax(typeof(User), this.Page);
}

Allowing us to asynchronously call the GetUser in client-side code with code such as:

















The value returned in the response is actually an object which exposes the same properties as a server-side object (FirstName, LastName and UserId).

Remote Desktop

mstsc.exe

Make your Site OffLine in IIS

Add the following file app_offline.htm in the physical directory of your internet site and when the url for the site is requested the app_offline.htm file will be loaded instead of your default page.

HTM Contents can be any thing you want.

Sample contents.
This application is currently offline. To enable the application, remove the app_offline.htm file from the application root directory.

REGISTERING ASPNET with IIS

aspnet_regiis /i

RESTARTING IIS

iisreset [PC NAME] /RESTART

Searching a Combo Box on the client side.

Using the available data in the Combo perform a Search for a close match.

ddlAllUsers is an ASP.NET Combo box populated with user data.
searchTextBox is a html input control.
" input id="searchTextBox" onkeyup="searchSel()"

The following Javascript snippet shows what occurs on the KeyUp event.
The method searchSel() searches the Users combo with the txtSearch input, converts it to lower case and "if(output[i].text.toLowerCase().indexOf(input) == 0)" then it selects the closest match in the users combo box.
The indexOf() method returns the position of the first occurrence of a specified string value in a string.











Very useful if you need to locate a entry in the combo without going bind scrolling down the list.

Thursday, December 13, 2007

Wednesday, December 12, 2007

Facade Design Pattern

Provide a unified interface to a set of interfaces in a subsystem.
Façade defines a higher-level interface that makes the subsystem easier to use. With a Facade you can take a complex subsystem and make it easier to use by implementing a Facade class that provides a more reasonable interface. Its similar to wrapping but it is designed around simpler access to complex systems while still leaving the sub-system functions exposed if needed. A sort of delegation of tasks to a single object.

Example: Below is a image of a Complex set of tasks that relate to a HomeTheater system. These are all the tasks you would need to do separately in order to use you appliances.




















However a Facade can simplify the operations down to a few small function calls.
For example: The Facade class treats the home theatre components as a subsystem, and calls on the subsystem to implement its watchMovie() method.
The Client i.e.: The Remote Control invokes calls to methods in the Facade, not on the subsystem. So we just invoke the watchMovie() method and it communicates with the lights, DVD player, projector, amplifier, screen and pop-corn maker for us.




















Remember Facades don't necessarily encapsulate subsystem classes because you should still have access to the lower level function(s), they merely provide a simplified interface to their functionality.

A Facade Pattern allows us to de-couple the client implementation from the subsystem.
So if you buy a bigger and better HomeTheater system and you coded your Client to the Facade rather than the subsystem then nothing should change.
Here's a code snippet from Head First that demonstrates the Facade in Action.

Cut and Paste it into a Console Project and step through it to better see how it works.


namespace Martins.Facade.Pattern
{
class HomeTheaterTestDrive
{
static void Main(string[] args)
{
Amplifier amp = new Amplifier("Top-O-Line Amplifier");
Tuner tuner = new Tuner("Top-O-Line AM/FM Tuner", amp);
DvdPlayer dvd = new DvdPlayer("Top-O-Line DVD Player", amp);
CdPlayer cd = new CdPlayer("Top-O-Line CD Player", amp);
Projector projector = new Projector("Top-O-Line Projector", dvd);
TheaterLights lights = new TheaterLights("Theater Ceiling Lights");
Screen screen = new Screen("Theater Screen");
PopcornPopper popper = new PopcornPopper("Popcorn Popper");

// Facade Class
HomeTheaterFacade homeTheater =
new HomeTheaterFacade(amp, tuner, dvd, cd,
projector, screen, lights, popper);



//The WatchMovie() method wraps alot of functions.
homeTheater.WatchMovie("Raiders of the Lost Ark");
homeTheater.EndMovie();
}
}
#region Facade
public class HomeTheaterFacade
{
private Amplifier amp;
private Tuner tuner;
private DvdPlayer dvd;
private CdPlayer cd;
private Projector projector;
private TheaterLights lights;
private Screen screen;
private PopcornPopper popper;
public HomeTheaterFacade(Amplifier amp,
Tuner tuner,
DvdPlayer dvd,
CdPlayer cd,
Projector projector,
Screen screen,
TheaterLights lights,
PopcornPopper popper)
{
this.amp = amp;
this.tuner = tuner;
this.dvd = dvd;
this.cd = cd;
this.projector = projector;
this.screen = screen;
this.lights = lights;
this.popper = popper;
}
public void WatchMovie(string movie)
{
Console.WriteLine("Get ready to watch a movie...");
popper.On();
popper.Pop();
lights.Dim(10);
screen.Down();
projector.On();
projector.WideScreenMode();
amp.On();
amp.SetDvd(dvd);
amp.SetSurroundSound();
amp.SetVolume(5);
dvd.On();
dvd.Play(movie);
}
public void EndMovie()
{
Console.WriteLine("\nShutting movie theater down...");
popper.Off();
lights.On();
screen.Up();
projector.Off();
amp.Off();
dvd.Stop();
dvd.Eject();
dvd.Off();
}
public void ListenToCd(string cdTitle)
{
Console.WriteLine("Get ready for an audiopile experence...");
lights.On();
amp.On();
amp.SetVolume(5);
amp.SetCd(cd);
amp.SetStereoSound();
cd.On();
cd.Play(cdTitle);
}
public void EndCd()
{
Console.WriteLine("Shutting down CD...");
amp.Off();
amp.SetCd(cd);
cd.Eject();
cd.Off();
}
public void ListenToRadio(double frequency)
{
Console.WriteLine("Tuning in the airwaves...");
tuner.On();
tuner.SetFrequency(frequency);
amp.On();
amp.SetVolume(5);
amp.SetTuner(tuner);
}
public void EndRadio()
{
Console.WriteLine("Shutting down the tuner...");
tuner.Off();
amp.Off();
}
}
#endregion
#region Subsystem Components
public class Tuner
{
string description;
Amplifier amplifier;
double frequency;
public Tuner(string description, Amplifier amplifier)
{
this.description = description;
this.amplifier = amplifier;
}
public void On()
{
Console.WriteLine(description + " on");
}
public void Off()
{
Console.WriteLine(description + " off");
}
public void SetFrequency(double frequency)
{
Console.WriteLine(description + " setting frequency to " + frequency);
this.frequency = frequency;
}
public void SetAm()
{
Console.WriteLine(description + " setting AM mode");
}
public void SetFm()
{
Console.WriteLine(description + " setting FM mode");
}
public override string ToString()
{
return description;
}
}
public class Amplifier
{
string description;
Tuner tuner;
DvdPlayer dvd;
CdPlayer cd;
public Amplifier(string description)
{
this.description = description;
}
public void On()
{
Console.WriteLine(description + " on");
}
public void Off()
{
Console.WriteLine(description + " off");
}
public void SetStereoSound()
{
Console.WriteLine(description + " stereo mode on");
}
public void SetSurroundSound()
{
Console.WriteLine(description + " surround sound on (5 speakers, 1 subwoofer)");
}
public void SetVolume(int level)
{
Console.WriteLine(description + " setting volume to " + level);
}
public void SetTuner(Tuner tuner)
{
Console.WriteLine(description + " setting tuner to " + dvd);
this.tuner = tuner;
}
public void SetDvd(DvdPlayer dvd)
{
Console.WriteLine(description + " setting DVD player to " + dvd);
this.dvd = dvd;
}
public void SetCd(CdPlayer cd)
{
Console.WriteLine(description + " setting CD player to " + cd);
this.cd = cd;
}
public override string ToString()
{
return description;
}
}
public class TheaterLights
{
string description;
public TheaterLights(string description)
{
this.description = description;
}
public void On()
{
Console.WriteLine(description + " on");
}
public void Off()
{
Console.WriteLine(description + " off");
}
public void Dim(int level)
{
Console.WriteLine(description + " dimming to " + level + "%");
}
public override string ToString()
{
return description;
}
}
public class Screen
{
string description;
public Screen(string description)
{
this.description = description;
}
public void Up()
{
Console.WriteLine(description + " going up");
}
public void Down()
{
Console.WriteLine(description + " going down");
}
public override string ToString()
{
return description;
}
}
public class Projector
{
string description;
DvdPlayer dvdPlayer;
public Projector(string description, DvdPlayer dvdPlayer)
{
this.description = description;
this.dvdPlayer = dvdPlayer;
}
public void On()
{
Console.WriteLine(description + " on");
}
public void Off()
{
Console.WriteLine(description + " off");
}
public void WideScreenMode()
{
Console.WriteLine(description + " in widescreen mode (16x9 aspect ratio)");
}
public void TvMode()
{
Console.WriteLine(description + " in tv mode (4x3 aspect ratio)");
}
public override string ToString()
{
return description;
}
}
public class PopcornPopper
{
string description;
public PopcornPopper(string description)
{
this.description = description;
}
public void On()
{
Console.WriteLine(description + " on");
}
public void Off()
{
Console.WriteLine(description + " off");
}
public void Pop()
{
Console.WriteLine(description + " popping popcorn!");
}
public override string ToString()
{
return description;
}
}
public class DvdPlayer
{
string description;
int currentTrack;
Amplifier amplifier;
string movie;
public DvdPlayer(string description, Amplifier amplifier)
{
this.description = description;
this.amplifier = amplifier;
}
public void On()
{
Console.WriteLine(description + " on");
}
public void Off()
{
Console.WriteLine(description + " off");
}
public void Eject()
{
movie = null;
Console.WriteLine(description + " eject");
}
public void Play(string movie)
{
this.movie = movie;
currentTrack = 0;
Console.WriteLine(description + " playing \"" + movie + "\"");
}
public void Play(int track)
{
if (movie == null)
{
Console.WriteLine(description + " can't play track " + track + " no dvd inserted");
}
else
{
currentTrack = track;
Console.WriteLine(description + " playing track " + currentTrack + " of \"" + movie + "\"");
}
}
public void Stop()
{
currentTrack = 0;
Console.WriteLine(description + " stopped \"" + movie + "\"");
}
public void Pause()
{
Console.WriteLine(description + " paused \"" + movie + "\"");
}
public void SetTwoChannelAudio()
{
Console.WriteLine(description + " set two channel audio");
}
public void SetSurroundAudio()
{
Console.WriteLine(description + " set surround audio");
}
public override string ToString()
{
return description;
}
}
public class CdPlayer
{
string description;
int currentTrack;
Amplifier amplifier;
string title;
public CdPlayer(string description, Amplifier amplifier)
{
this.description = description;
this.amplifier = amplifier;
}
public void On()
{
Console.WriteLine(description + " on");
}
public void Off()
{
Console.WriteLine(description + " off");
}
public void Eject()
{
title = null;
Console.WriteLine(description + " eject");
}
public void Play(string title)
{
this.title = title;
currentTrack = 0;
Console.WriteLine(description + " playing \"" + title + "\"");
}
public void Play(int track)
{
if (title == null)
{
Console.WriteLine(description + " can't play track " + currentTrack +
", no cd inserted");
}
else
{
currentTrack = track;
Console.WriteLine(description + " playing track " + currentTrack);
}
}
public void Stop()
{
currentTrack = 0;
Console.WriteLine(description + " stopped");
}
public void Pause()
{
Console.WriteLine(description + " paused \"" + title + "\"");
}
public override string ToString()
{
return description;
}
}
#endregion
}

Tuesday, December 11, 2007

Decorator Design Pattern

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality.

The following is a sample of the Decorator Design Pattern in action taken from the Head First Series.

Example:
In this example the Beverage is a closed Object so we can't change it.
So by creating the CondimentDecorator abstract class that inherits from Beverage we can add or override certain behaviour of Beverage.
Whip is a CondimentDecorator but it is also Beverage. As we add CondimentDecorator types around Beverage the cost of the Beverage is accumulating.
We are extending the behaviour.
Every time we create a new CondimentDecorator object and pass the Beverage reference to the constructor we are extending behaviour to Beverage.

Code Snippet...

namespace Martins.Decorator.Pattern
{
class StarbuzzCoffee
{
static void Main(string[] args)
{
//Decorate Espresso with Mocha and Whip
Beverage beverage2 = new Espresso();
beverage2 = new Mocha(beverage2);
beverage2 = new Whip(beverage2);

//Decorate HouseBlend with Soy, Mocha and Whip
Beverage beverage3 = new HouseBlend();
beverage3 = new Soy(beverage3);
beverage3 = new Mocha(beverage3);
beverage3 = new Whip(beverage3);
}
}
public abstract class Beverage
{
string description = "Unknown Beverage";
public virtual string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public abstract double Cost
{
get;
}
}
public class Espresso : Beverage
{
public Espresso()
{
Description = "Espresso";
}
public override double Cost
{
get
{
return 1.99;
}
}
}
public class HouseBlend : Beverage
{
public HouseBlend()
{
Description = "House Blend Coffee";
}
public override double Cost
{
get
{
return .89;
}
}
}
public abstract class CondimentDecorator : Beverage
{
}
public class Whip : CondimentDecorator
{
Beverage beverage;
public Whip(Beverage beverage)
{
this.beverage = beverage;
}
public override string Description
{
get
{
return beverage.Description + ", Whip";
}
set
{
this.Description = value;
}
}
public override double Cost
{
get
{
return .10 + beverage.Cost;
}
}
}
public class Mocha : CondimentDecorator
{
Beverage beverage;
public Mocha(Beverage beverage)
{
this.beverage = beverage;
}
public override string Description
{
get
{
return beverage.Description + ", Mocha";
}
}
public override double Cost
{
get
{
return .20 + beverage.Cost;
}
}
}
public class Soy : CondimentDecorator
{
Beverage beverage;
public Soy(Beverage beverage)
{
this.beverage = beverage;
}
public override string Description
{
get
{
return beverage.Description + ", Soy";
}
}
public override double Cost
{
get
{
return .15 + beverage.Cost;
}
}
}
}







Adapter Design Pattern

Convert the interface of a class into another interface clients expect.

Imagine travelling anywhere in the world and be able to plug in your appliances to the power point of the local hotel without any problems with the plug connection.

Doesn't happen right. You need an Adapter.
Adapters are a small plug with two different interfaces, one for our appliance and the other for the local power outlet.
The Adapter allows us to use the Hair dryer that we bought in Australia and dry our hair in England for example, simply because we adapted to the interface.

Same goes with Software adapters, they take one interface and convert it to something that the receiving interface expects.

Some refer to Adapters as Wrappers.

Example:
How to make sure the HairDryer Turns on when we plug into Hotels Socket.
The code demonstrates the Adapter pattern which maps the interface of one class onto another so that they can work together.
The Key is the HairDryerAdapter
If we have any more appliances we just implement a new Adapter
Inheriting from the IEnglandHotelsocket interface.

namespace Martins.Adapter.Pattern
{
class WorkingHairDryer
{
static void Main(string[] args)
{
//Create a HairDryer object
HairDryer dryer= new HairDryer();
//Create a HairDryerAdapter
//and pass in the HairDryer reference
//and return a IEnglandHotelsocket reference

IEnglandHotelsocket dryerAdapter = new HairDryerAdapter(dryer);

//The dryer reference is our Hair Dryer
//The IEnglandHotelsocket is the Hotel power outlet.
//The HairDryerAdapter is the Adapter that connects the two.

//Use the IEnglandHotelsocket interface to call the
//correct Power method for the type
dryerAdapter.GiveMePower();
}
}
public interface IEnglandHotelsocket
{
void GiveMePower();
}
public interface IAustralianAppliance
{
void PowerOn();
}
public class HairDryer: IAustralianAppliance
{
public void PowerOn()
{
Console.WriteLine("BZZZZZZZZZZZ");
}
}
public class HairDryerAdapter : IEnglandHotelsocket
{
IAustralianAppliance dryer;

public HairDryerAdapter(IAustralianAppliance dryer)
{
this. dryer = dryer;
}
public void GiveMePower()
{
dryer.PowerOn();
}
}
}

Command Design Pattern

Encapsulate a request as an object.
What does that mean?

Example
The code demonstrates the Command pattern, which stores requests as objects allowing clients to execute or playback the requests.
All Commands implement the same interface, so they can be handled polymorphically. Typically their interface includes methods such as Do and Undo (or Execute and Undo).
In this case we invoke a method called Execute that could perform any number of tasks.

There are three players in the Command Design Pattern.

The Receiver: As the name suggests is the eventual recipient of the command.
The Command: The Object that encapsulates the request.
The Invoker: You could say the broker of the command. It’s the Invokers job to make sure the command is stored and processed when required.

The Invoker does not store requests it stores Command Objects that encapsulate requests.

Below in the example is the Receiver Object. I has a method named Action. The Action method call in the Receiver object is Vendor specific. It could be any method call that needs to be invoked, i.e.: DataBase.Update(....) etc..

Also we have the Command class, it can have any number of methods that perform a variety of functions. By adding this layer of Abstraction we don't tie our Receivers to the actual true function calls. We keep everything de-coupled.
This allows for new commands to be added by implementing the abstract Command class and setting the invoker.SetCommand(command (Reference to Abstract Command)) with it.

In the following sample we Create a Command object, pass in to the constructor the receiver (Reference) of the command and then store all that in the Invoker.
When we need the the Receiver.Action() method to be invoked we do it via the invoker.ExecuteCommand().

The invoker.ExecuteCommand polymorphically calls Command.Execute which calls the true Receiver.Action function.

namespace Martins.Command.Pattern
{
//MainApp startup
//Command Design Pattern.
class MainApp
{
//Entry point into console application.
static void Main()
{
//Create receiver, command, and invoker
Receiver receiver = new Receiver();
Command command = new ConcreteCommand(receiver);
Invoker invoker = new Invoker();

//Set and execute command
invoker.SetCommand(command);
invoker.ExecuteCommand();
}
}
//Command
abstract class Command
{
protected Receiver receiver;

//Constructor
public Command(Receiver receiver)
{
this.receiver = receiver;
}
public abstract void Execute();
}
//ConcreteCommand
class ConcreteCommand : Command
{
//Constructor
public ConcreteCommand(Receiver receiver) :
base(receiver)
{
}
public override void Execute()
{
receiver.Action();
}
}
//Receiver
class Receiver
{
public void Action()
{
Console.WriteLine("Called Receiver.Action()");
}
}
//Invoker
class Invoker
{
private Command command;
public void SetCommand(Command command)
{
this.command = command;
}
public void ExecuteCommand()
{
command.Execute();
}
}
}

Monday, December 10, 2007

Observer Design Patterns

Tell Me if something happens will you!
The Observer Pattern is basically our typical Publisher/Subscriber model.
Except in this case it’s referred to as Subject (Publisher) and the Observer (Subscriber).

The whole idea around the Observer Pattern is you the Client wish to be notified when something you subscribed for occurs.
This could be a Button Click Event. The Button (Publisher) notifies those who (Subscribed) for the click notification so then you can do something about it.

Example:
The code demonstrates the Observer pattern in which registered objects are notified of and updated with a state change.

namespace Martins.Observer.Pattern
{
//MainApp startup class
//Observer Design Pattern.
class MainApp
{
//Entry point
static void Main()
{
//Configure Observer pattern
ConcreteSubject s = new ConcreteSubject();

s.Attach(new ConcreteObserver(s,"X"));
s.Attach(new ConcreteObserver(s,"Y"));
s.Attach(new ConcreteObserver(s,"Z"));

//Change subject and notify observers
s.SubjectState = "ABC";
s.Notify();
}
}
//Subject
abstract class Subject
{
private ArrayList observers = new ArrayList();
public void Attach(Observer observer)
{
observers.Add(observer);
}
public void Detach(Observer observer)
{
observers.Remove(observer);
}
public void Notify()
{
foreach (Observer o in observers)
{
o.Update();
}
}
}
//ConcreteSubject
class ConcreteSubject : Subject
{
private string subjectState;
//Property
public string SubjectState
{
get{ return subjectState; }
set{ subjectState = value; }
}
}
//Observer
abstract class Observer
{
public abstract void Update();
}
//ConcreteObserver
class ConcreteObserver : Observer
{
private string name;
private string observerState;
private ConcreteSubject subject;

//Constructor
public ConcreteObserver(
ConcreteSubject subject, string name)
{
this.subject = subject;
this.name = name;
}
public override void Update()
{
observerState = subject.SubjectState;
Console.WriteLine("Observer {0}'s new state is {1}",
name, observerState);
}
//Property
public ConcreteSubject Subject
{
get { return subject; }
set { subject = value; }
}
}
}

AbstractFactory Design Pattern

Abstract Factories allow clients to create related objects while keeping themselves de-coupled from the implementation classes.
By using Abstract Interfaces the concrete implemented classes are encapsulated (Hidden) in this abstraction layer from the client.

Example:
The following is an example on how the Abstract Factory is used to create a family of related objects.

Basically we are a Factory to create Planets, Intelligent Life and some sort of Food.
The client never gets exposed to the Concrete Products. i.e.: Humans or Cows etc.
This is the way it should be. Imagine if the Food type Cow goes extinct, the client would need to get into the code that creates Cows and modify it to create a new type of Food. But by using the Abstract method the Factory can supply a new Food type and leave Cows alone.
The Client always refers to the Food SuperType and the Factory will sort out the Concrete object to return.

The client works directly with the Abstract Factory and the Factory will create Products based on the Factory type.

Have ago and Play God.

namespace Martins.Abstract.Factory.WorldCreator
{
//AbstractFactory
abstract class PlanetsFactory
{
//Factory Methods
public abstract InteligentLife CreateInteligentLife();
public abstract Food CreateFood();
}
//ConcreteFactory implements PlanetsFactory
class EarthFactory : PlanetsFactory
{
public override InteligentLife CreateInteligentLife()
{
return new Human();
}
public override Food CreateFood()
{
return new Cow();
}
}
//ConcreteFactory implements PlanetsFactory
class MarsFactory : PlanetsFactory
{
public override InteligentLife CreateInteligentLife()
{
return new Martian();
}
public override Food CreateFood()
{
return new GreenSlime();
}
}

//AbstractProductA
abstract class Food
{
}
//AbstractProductB
abstract class InteligentLife
{
public abstract void Eat(Food h);
}
//ConcreteProductA1
class Cow : Food
{
}
//ConcreteProductB1
class Human : InteligentLife
{
public override void Eat(Food h)
{
//Humans Eat Cows
Console.WriteLine(this.GetType().Name + "s eat " + h.GetType().Name + "s");
}
}
//ConcreteProductA1
class GreenSlime : Food
{
}
//ConcreteProductB1
class Martian : InteligentLife
{
public override void Eat(Food h)
{
//Martian's Eat Slime
Console.WriteLine(this.GetType().Name + "s eat " + h.GetType().Name + "s");
}
}

//The Client works with Abstract Super Types
//Polymorphism kicks in to resolve the concrete implemented instance.

//Client
class PlanetEarth
{
private Food food;
private InteligentLife life;
public PlanetEarth(PlanetsFactory factory)
{
life = factory.CreateInteligentLife();
food = factory.CreateFood();
}
public void WhatsToEat()
{
life.Eat(food);
}
}

//The Client works with Abstract Super Types
//Polymorphism kicks in to resolve the concrete implemented instance.

//Client
class PlanetMars
{
private Food food;
private InteligentLife life;
public PlanetMars(PlanetsFactory factory)
{
life = factory.CreateInteligentLife();
food = factory.CreateFood();
}
public void WhatsToEat()
{
life.Eat(food);
}
}

//Test application that uses both Factories to create Earth and Mars

class MainApp
{
public static void Main()
{

//Create Earth and let the Earth factory create the InteligentLife and Food Products.
PlanetsFactory world1 = new EarthFactory();
PlanetEarth planet1 = new PlanetEarth(world1);
planet1.WhatsToEat();

//Create Mars and let the Mars factory create the InteligentLife and Food Products.
PlanetsFactory world2 = new MarsFactory();
PlanetMars planet2 = new PlanetMars(world2);
planet2.WhatsToEat();

Console.WriteLine("\r\nPlanets Factory Rest for 7 days");
}
}
}

Camtasia

Screen capture and recording tools for people like you.
People everywhere are using TechSmith products to capture content from their screen in ways that help them communicate more clearly, create engaging presentations for diverse audiences, and analyze product usability and customer experience.

Mail Relay Test - Check Email Privacy

Email relay testing.
Read About HELO

Wildcard Mappings

Tip/Trick: Integrating ASP.NET Security with Classic ASP and Non-ASP.NET URLs
Wildcard Mappings

AJAX Abstraction Patterns

  • AJAX Level I : Raw Javascript

  • AJAX Level II : Microsoft AJAX client library

  • AJAX Level III : ASP.NET 2.0 AJAX server controls

  • Ajax Design Patterns

    Montastic

    The free website monitoring service that doesn't suck.
    Montastic

    Determistic Finalization with IDisposable

    Finalization, how it works?
    Heap exhaustion/shutting down an application triggers a Garbage Collection. Class that manage external resources like DB connection, file handler should implement Finalization to improve the system performance – proactively release the (external) resource once finished use.
    However, objects that require finalization complicate the collection process. An object with a finalizer is not immediately released. How is works? GC checks metadata of every object type in the scan. If the object implements the Finalize() method, GC doesn't destroy it. Instead it is marked as reachable and it moved from it's orginal graph to another object graph- a special queue called finalized queue, which establishes a reference to the object, preventing its collection. GC proceeds. Meanwhile, a seperate background thread iterates all objects in the finalized queue, calling Finalize() on each and removes the finalized object from the finalization queue.
    There is a fair standard pattern on implementing Finalize, such like define it as proteced+virtual; calling parent's Finalize at the end of your call... In fact c# comes with a code template destructor (~{MyClassName}), compiler expands it to full size Finalize() method at compiling.
    Only after finalization can the object be removed from memory during the *next* GC pass. As a side effect of surviving one collection pass, the object is promoted into a higher generation, further delaying its eventual collection-
    Non-Determistic Finalization meaning Garbage collection time is unpreditable. The application should not rely on GC to clean up expensive resources, which hurts scalability and performance.
    Determistic Finalization
    To free up used resources, client should proactively release used resource, such like DB connection when it is no longer used, instead of relies on GC.
    -The Open()/Close() Pattern
    Use object pool to manage objects without really destroy an object. Many .Net framwork classes use this pattern, E.g. file, stream (I/O, memory, network), DB connection, communication port etc.

    -IDisposable Pattern
    Classes that require finalization should implement the IDisposable interface in order to allow client to provide a determistic finalisatoin - short-circuit GC finalization and avoid the garbaged object (which uses external resource, say) promoted to G1.
    There are two ways that classes that implement IDisposable have their objects being cleaned up.
    1) Client code explicitly calls Dispose.
    Your implementation in Dispose has the _chance_ to explicitly clean-up unmanaged resource as well as managed resource (by GC). By now your unmanaged resource is already freed up, there is no point to put the object in finalize queue to delays its release (G1), you should supress this by calling GC.SuppressFinalize(this);

    2) Destructor Finalize method calls Dispose. This is a fallback plan if client fails to clean up.
    In this case the Dispose method can only clean up unmanaged resource. Because during finalization, GC may have already removed the object for which Dispose is called (in following code example, the timer object). In this case, Dispose calls to clean this object, it will fail on null referencing.

    Continuous Integration

    Q1: What is Continuous Integration?
    The practice of continuous integration represents a fundamental shift in the process of building software. It takes integration, commonly an infrequent and painful exercise, and makes it a simple, core part of a developer's daily activities. Integrating continuously makes integration a part of the natural rhythm of coding, an integral part of the test-code-refactor cycle. Continuous integration is about progressing steadily forward by taking small steps.

    Integration should happen continuously, and continuously is more often than you might think. The frequency of integration will vary from project to project, from developer to developer, and from modification to modification. However, as a goal and a good rule of thumb, developers should integrate their changes once every few hours and at least once per day.

    Learning how to integrate so frequently requires practice and discipline. Fundamentally, an integration can occur at any point when the code compiles and all the unit tests are passing. The challenge is learning how to write software so that you never stray too far from this point. If you are testing at the right level of granularity and are refactoring regularly, then you should never be more than a few minutes away from this point. This means that you are almost always in a position where you can launch a new integration.

    Deciding when to integrate is all about controlling risk. When making modifications in a high traffic area of the code base or when conducting broad refactorings like class renaming or package reorganisation, there is an elevated risk of impacting other developers or of having merge conflicts when committing. The longer that developers go without integrating, the greater the likelihood of conflicts and the larger the effort required to resolve those conflicts. As the effort of integration increases exponentially in proportion to the time between integrations, best practices dictate that when making high-risk changes a developer should start from a clean workspace, focus only on required modifications, proceed with the smallest logical steps, and then commit at the earliest opportunity.

    A successful integration is a measure of progress. It provides feedback that the new code runs correctly in the integration environment and successfully interoperates with the rest of the code base. Code sitting unintegrated in a developer's workspace simply does not exist. It is not part of the code base, it cannot be accessed by other developers or tested by the customer. Only when it has been successfully integrated is the benefit of the new code realised.

    ANTS Profiler

    ANTS Profiler will drill down to the slowest lines of code and the slowest methods, helping you identify bottlenecks.
    ANTS Profiler

    Microsoft Baseline Security Analyzer

    Improve your security management process by using MBSA to detect common security misconfigurations and missing security updates on your computer systems.
    Microsoft Baseline Security Analyzer

    FitNesse & CruiseControl.NET

    How to integrate FitNesse acceptance tests into your CC.Net. (CruiseControl.NET)
    FitNesse & CruiseControl.NET

    CruiseControl

    CruiseControl is a framework for a continuous build process.
    CruiseControl.NET

    Selenium

    Automated Web Testing with Selenium Driven by .Net.
    Selenium

    Fitnesse

    Fitnesse is Acceptance testing framework.
    Fitnesse
    FitNesse is a software development collaboration tool.
    Great software requires collaboration and communication. FitNesse is a tool for enhancing collaboration in software development.
    FitNesse enables customers, testers, and programmers to learn what their software should do, and to automatically compare that to what it actually does do.
    It compares customers' expectations to actual results.
    FitNesse is a software testing tool.
    Collaboratively define AcceptanceTests -- web pages containing simple tables of inputs and expected outputs.
    FitNesse is a wiki.
    You can easily create and edit pages.
    FitNesse is a web server.
    It requires no configuration or setup.
    Just run it and then direct your browser to the machine where it is running (see DownloadingAndInstallingFitNesse).
    How Fitnesse Works
    Fit works by reading tables in HTML files, produced with a tool like Microsoft Word.
    Each table is interpreted by a "fixture" that programmers write.
    The fixture checks the examples in the table by running the actual program.

    NAnt

    NAnt is a free .NET build tool.
    NAnt

    NUint

    NUnit is a unit-testing framework for all .Net languages.
    NUnit

    Network Load Balancing on Windows Server 2003 and IIS 6.0

    Network Load Balancing and IIS 6.0 to help ensure that your Web sites are reliable, scalable and efficient.

    Software Solutions to Load Balancing.

    Windows NLB (Network Load Balancing) for 2003.
    NLB's employ a "broadcast" approach similar to how layer 2 (OSI Model) hubs work..
    When servers are part of an NLB cluster, they are participating in the sharing of a virtual IP.
    When requests are made to that virtual IP all servers receive the request.
    Responses occur from the only one member in the cluster; all others are dropped (aka-ignored).















    All PC's are setup with IIS and the business web applications but only one IIS instance is used to handle the request via the NLB service.

    NLB is configured using the Network Load Balancer User Interface or the Command Line tool (WLBS.exe).

    Web Application Stress Tool

    The Microsoft WAS web stress tool is designed to realistically simulate multiple browsers requesting pages from a web site.
    Web Application Stress Tool

    Biztalk and SOA

    Biztalk is a useful product to integrate systems together.
    Biztalk SOA Explained




    What is boxing?

    Boxing Explained

    XmlIgnoreAttribute Class

    Instructs the Serialize method of the XmlSerializer not to serialize the public field or public read/write property value. Goto: Jun Meng's blog for an example.

    4GuysFromRolla.com Headlines