Wednesday, February 15, 2012

Favor Composition over Inheritance

Even though you “could” solve a problem by inheriting, see if there’s another option that doesn’t require you to inherit and compose your object of other helper object instead.
The above statement sounded so sophisticated when I read it first, that I wanted to put it in my blog. Yet there is something deep in my heart that tells me: don’t through away your years of experience and achievements gained by reusing objects through inheritance.

Original Thought

When 2 classes, let’s say Car and Vehicle implemented as follows:
    public class Vehicle
    {
        public void Drive()
        {
            Debug.WriteLine("Vehicle is driving.");
        }
    }
    public class Car : Vehicle
    {
        public void Drive()
        {
            Debug.WriteLine("Car is driving.");
        }
    }
By default the new implemented Drive method in the Car class hides the implementation in vehicle for any reference of Car type. So the following instances are expected:
    Vehicle v = new Vehicle();
    v.Drive();
    // output : Vehicle is driving.

    Car c = new Car();
    c.Drive();
    // output : Car is driving.

But the next one might cause unexpected situations when the construction occurs in a method far from calling the drive method.
    Vehicle x = new Car();
    x.Drive();
    // output : Vehicle is driving.

The output for the last call (Vehicle x) changes to “Car is driving.” when the Drive method in Vehicle is defined as virtual and in the Car defined as override.
Looks like the problem is solved.
But sometime I have a factory class creating some instances for me and I simply declare my variables and request for an instance:
Vehicle x = Factory.GetBMW();
This means that the place I use the instance might have no knowledge of how the instance is created and might not even know how they are implementing the Drive method.
For me, the ideal situation might be when I have a reference to a class of type Vehicle, I like it to drive as Vehicle. And when I want to have a Car that drives as a Car, I will define my reference as a Car.
Vehicle x = Factory.GetBMW();
Car y = Factory.GetBMW();
x.Drive();
y.Drive();
I can see that my point might not be important for BMW factory and they would rather to create a Car that drives the same way, no matter who is driving it.

Suggested Solution

The Composition over inheritance suggests that Car and vehicle does not inherit from each other. To make sure that they both are sharing functionality, the BMW class needs to implement both interfaces.
Let’s say that the following code is where we like to achieve:
    x.Drive();                  // output : Simply driving.
    (x as ICar).Drive();        // output : Car driving.
    (x as IVehicle).Drive();    // output : Vehicle driving.

To get there I have introduced three interfaces as follows:
    public interface IDrivable
    {
        void Drive();
    }
    public interface IVehicle : IDrivable
    {
        void Drive();
    }
    public interface ICar : IDrivable
    {
        void Drive();
    }

The BMW needs to implement them as it suites. This implementation has nothing to do with the way they are overloaded.
public class BMW : IVehicle, ICar
    {
        void IVehicle.Drive()
        {
            Debug.WriteLine("Vehicle is driving.");
        }
        void ICar.Drive()
        {
            Debug.WriteLine("Car is driving.");
        }
        void IDrivable.Drive()
        {
            Debug.WriteLine("Simply driving.");
        }       
    }


Thursday, November 10, 2011

Convert XmlText to HtmlText

I have been using Xml streams for quite some time. When I use them in an ASP.Net page, using SOAP or Ajax calls, I sometimes want to see what I send and what I recieve from the server. Showing them on the page was always a bit of tweak. This ample code demonstrates a very simple tweek. It provides a label that can show the xml Text (as its content or Text property) on the page, by rendering the simpel characters.
When the control is compiled I can use it as one of the two ways:

<panahyAjax:XmlLabel runat="server" ID="xmlLabel">
<this>
 
<is just="one">sample</is>
</this>
</panahyAjax:XmlLabel>

Or

XmlLabel label = new XmlLabel();
var file = File.OpenText("Sample.xml");
label.Text = file.ReadToEnd();

And the code is as folllows:

public class XmlLabel : Label
{
 public static string ConvertXmlTextToHtmlText(string inputText)
 {
  // Replace all start and end tags.
  string startPattern = @"<([^>]+)>";
  var regEx = new Regex(startPattern);
  string outputText = regEx.Replace(inputText, "&lt;<b>$1&gt;</b>");
  outputText = outputText.Replace(
" ", "&nbsp;");
  outputText = outputText.Replace(
"\r\n", "<br />");
  return outputText;
 }

 protected override void RenderContents(HtmlTextWriter output)
 {
  string xmlText = XmlLabel.ConvertXmlTextToHtmlText(Text);
  output.Write(xmlText);
 }
}

Using RenderControl method to generate Html


This article demonstrates how to generate perfect HTML using the RenderControl method of server controls. The Html code is generated without makeing any server-side state or view state.
/// <summary>
/// This method demonstrates how to show Html output of a Server Control
/// </summary>
private void ShowHtml()
{
  // Create the in-memory objects that will catch the rendered output.
  StringWriter writer = new StringWriter();
  HtmlTextWriter output = new HtmlTextWriter(writer);

  // Render the control to an in-memory string.
  var control = new HyperLink();
  control.NavigateUrl =
@"http:\\asghar.panahy.com";
  control.Text =
"Asghar Panahy";
  control.Target =
"_blank";
  control.ToolTip =
"Demostration";

  control.RenderControl(output);

  // Display the HTML (and encode it properly so that
  // it appears as text in the browser).
  lblHtml.Text = "The HTML for LinkWebControl1 is<br /><blockquote>"
               + Server.HtmlEncode(writer.ToString()) +
"</blockquote>";
}

The output of this codewill be reading what you would ecpect in the Html code behind.
Notice that skipping the Server.HtmlEncode call will put the generated html as a link into the page.

Tuesday, November 8, 2011

Encapsulating an AJAX client control into a custom server control (Part 3)

The previous article was a step forward but it is still far from reusing as a server side control. What we will do in this part will make us possible to have a custom textbox control that makes al it takes to have this client-side functionality and we will be able to drag the ASP.NET control into our page.
To start with, we need a new server-side control library project that will compile as a dll and contains the server side code and embeds the client-side script. This project will have two files in it: the PassTextBox.cs which deals with the server-side TextBox and inherits from TextBox and implements the IScriptControl which makes it possible to embed the script code.
Notice in the code that the class needs to register the script with the ScriptManager which is accessible through its static method GetCurrent(Page). This is done in OnPreRender method.
In the previous article we had the css class names inside the javascript. In this example we will assign them through the controls properties. The GetScriptDescriptor method allows us to prototype our class where we define these properties.

namespace Panahy.Ajax
{
 
public class PassTextBox : TextBox, IScriptControl
  {
private ScriptManager sMgr;
public string WeakCssClass;
public string MediumCssClass;
public string StrongCssClass;
protected virtual IEnumerable<ScriptDescriptor> GetScriptDescriptors()
{
 
ScriptControlDescriptor descriptor =
   
new ScriptControlDescriptor("Panahy.Ajax.PassTextBox", this.ClientID);

  descriptor.AddProperty(
"weakCssClass", this.WeakCssClass);
  descriptor.AddProperty(
"mediumCssClass", this.MediumCssClass);
  descriptor.AddProperty(
"strongCssClass", this.StrongCssClass);
  return new ScriptDescriptor[] { descriptor };
}

protected virtual IEnumerable<ScriptReference> GetScriptReferences()
{
 
ScriptReference reference = new ScriptReference();

  reference.Assembly =
"Panahy.Ajax";
  reference.Name =
"Panahy.Ajax.PassTextBox.js";
 
return new ScriptReference[] { reference };
}

protected override void OnPreRender(EventArgs e)
{
 
if (!this.DesignMode)
  {
   
//test for the existence of a ScriptManager
   
sMgr = ScriptManager.GetCurrent(Page);

   
if (sMgr == null)
      
throw new HttpException("A ScriptManager control must exist on the page.");
    sMgr.RegisterScriptControl(this);
  }
 
base.OnPreRender(e);
}

protected override void Render(HtmlTextWriter writer)
{
 
if (!this.DesignMode)
    sMgr.RegisterScriptDescriptors(
this);
  base.Render(writer);
}

IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
{
 
return GetScriptReferences();
}

IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
{
 
return GetScriptDescriptors();
}
}
}
The javascript file remains as before.
Now we can reuse the control in any project that refers to the dll.

<%@ Register Assembly="Panahy.Ajax" Namespace="Panahy.Ajax" TagPrefix="panahyAjax" %>

<panahyAjax:PassTextBox ID="textbox1" runat="server" width="200"
   
TextMode="Password" WeakCssClass="weak" MediumCssClass="medium"
    StrongCssClass
="strong"></panahyAjax:PassTextBox>



Although this sample can be handy to use as a template for other server controls, the introduced functionality could be done by creating an AJAX Behavior for client controls, which is the topic for the next article.

Implementing Custom Classes for Microsoft AJAX Library (Part 2)

The previous article is demonstrates the use of custom class but it makes some assumption which is not best practice for developping pages.
In this article I will try to make this one step forward by taking the class names (that were hard coded in the javascript) out of the script and assign them in the page. I will also provide a initialization to assign the same functionality to any page element.
We start with the construction and pass the element that is using the class:

Panahy.Ajax.PassTextBox = function(element) {
    Panahy.Ajax.PassTextBox.initializeBase(
this, [element]);

    // initialize internal variables
   
this._weakCssClass = null;
    this._mediumCssClass = null;
    this._strongCssClass = null;
}
Next, I call the passwordStrengthClass method in a new event handler called _onKeyup which I will apply the css class to the element using get_element():

//define key press event
_onKeyup : function(e) {
    //get password text
    var pass = this.get_element().value;
    var strength = this.returnPasswordStrength(pass);
    switch (strength) {
      case "Weak":
         this.get_element().className = this._weakCssClass;
         break;
      case "Medium":
         this.get_element().className = this._mediumCssClass;
         break;
      case "Strong":
         this.get_element().className = this._strongCssClass;
         break;
    }
},
Now, I need to tell the AJAX Library to assign the _onKeyup method to keyup event of the element. To do this, I create a delegate and add the handler as follows:

//initialize the UI control
initialize: function() {
   Panahy.Ajax.PassTextBox.callBaseMethod(
this, 'initialize');

  
this._onKeyupHandler = Function.createDelegate(this, this._onKeyup);
   $addHandlers(
this.get_element(), {'keyup' : this._onKeyup}, this);
},
By doing this, I have to remove the reference when cleaning up the things in the dispose method:

dispose: function() {
    $clearHandlers(
this.get_element());
    Panahy.Ajax.PassTextBox.callBaseMethod(
this, 'dispose');
},
It is almost done, except the definition of the get and set properties which can be done like this:

//define properties
get_weakCssClass: function() {
   return this._weakCssClass;
},
set_weakCssClass: function(value) {
   this._weakCssClass = value;
},
I need to do this for all three properties.
Now, I can use this in my page after referencing it in the ScriptManager.

<script language="javascript" type="text/javascript">
  var app = Sys.Application;
  app.add_init(appInit);

  function appInit(sender, args) {
    $create(Panahy.Ajax.PassTextBox,
        { weakCssClass:
'weak', mediumCssClass: 'medium', strongCssClass: 'strong' },
        
null, null, $get('MainContent_TextBoxPassword'));
}
</script>

In this way, I don't need to set anything on the textbox.
This is still not perfect, In the next article I will demonstrate how to put this in a custom ASP.NET Control.