GSharper

Friday 30 March 2007

Substrings with regular expression

Hi,

since I always forget this one, I'll post it here.

I'm tired of always using native c# code to perform substring selects on string values. This produces lots of code. I've replaced it with regular expressions

Let's suppose we have the following string value

string expr = "This is a test message where I want to extract the value test out of [test]";

We can use this code:

string value=
Regex.Match(expr ,@"(?<=\[).*(?=\])").Value;

value will be test !!

Labels:

Conditional dispatcher to Command Pattern

Some time ago, a customer asked me for a solution for the following problem:

They had to send messages to certain people. These messages where kept in a database table. The messages contained variables which had to be filled in by the person who sends the message. For example:

I will be [NumberInput] minutes late.

You need to make a delivery to address [AddressList].

Please call telephone number [TelephoneList].

When the operator selects the first message, a textbox is shown where he has to input a delay.

When the second message is selected, a combobox will be shown containing addresses.

When the third message is selected, a listbox will be shown containing telephone numbers.

So I created a little application which retrieved the messages from the database in a Combobox. When selecting one of the messages, the following code runs

Label lblTitle;
if (messageSelector.SelectedItem.ToString().IndexOf("NumberInput") != -1)
{
Label lblTitle
= new Label();
lblTitle.Text
= "Input Number"
messagePanel.Controls.Clear();
TextBox txtNumberInput
= new TextBox();
txtNumberInput.Name
= "NumberInput"
messagePanel.Controls.Add(lblTitle);
txtNumberInput.Width
= 120;
txtNumberInput.Location
= new Point(100, 0);
messagePanel.Controls.Add(txtNumberInput);
}
else if (messageSelector.SelectedItem.ToString().IndexOf("AddressList") != -1)
{
Label lblTitle
= new Label();
lblTitle.Text
= "Choose Address"
messagePanel.Controls.Clear();
ComboBox cmbAdressList
= new ComboBox();
cmbAdressList.Name
= "AddressList"
// Get addresses from the database.
GetAddresses(cmbAdressList);
messagePanel.Controls.Add(lblTitle);
cmbAdressList.Width
= 120;
cmbAdressList.Location
= new Point(100, 0);
messagePanel.Controls.Add(cmbAdressList);
}
else if (messageSelector.SelectedItem.ToString().IndexOf("TelephoneList") != -1)
{
Label lblTitle
= new Label();
lblTitle.Text
= "Choose Telephone"
messagePanel.Controls.Clear();
ListBox lstTelephoneList
= new ListBox();
lstTelephoneList.Name
= "TelephoneList"
// Get telephone numbers from the database.
GetTelephoneNumbers(lstTelephoneList);
messagePanel.Controls.Add(lblTitle);
lstTelephoneList.Width
= 120;
lstTelephoneList.Location
= new Point(100, 0);
messagePanel.Controls.Add(lstTelephoneList);
}

This is definitely a violation of the open-closed principle. And duplicate code? A lot of it.

But the customer wanted a quick solution and they said no other messages will be added with different controls. One week later, a new message was added :)


Please call telephone number [TelephoneInput].


This message resulted in a special textbox GsmNumberTextBox which did some extra validations using regular expressions.


So, I could add another conditional statement but I was sure that there would be additional messages in the future. So time to change some stuff.


I read an article, "Replace conditional dispatcher with command pattern".


First I would do the refactor step "Extract Method":


if (messageSelector.SelectedItem.ToString().IndexOf("NumberInput") != -1)
{
ShowNumberInput();
}
else if (...)

private Label ShowNumberInput()
{
Label lblTitle;
lblTitle
= new Label();
lblTitle.Text
= "Input Number"
messagePanel.Controls.Clear();
TextBox txtNumberInput
= new TextBox();
txtNumberInput.Name
= "NumberInput"
messagePanel.Controls.Add(lblTitle);
txtNumberInput.Width
= 120;
txtNumberInput.Location
= new Point(100, 0);
messagePanel.Controls.Add(txtNumberInput);
return lblTitle;
}

I do the same for the other conditional steps.

The next refactor step is "Extract class":



class NumberInputTextBox
{
TextBox _txtNumberInput;

public NumberInputTextBox()
{
_txtNumberInput
= new TextBox();
}

public Control CreateNumberInput()
{
Control control
= new UserControl();
control.Width
= 276;
Label lblTitle;
lblTitle
= new Label();
lblTitle.Text
= "Input Number"
_txtNumberInput.Name
= "NumberInput"
control.Controls.Add(lblTitle);
_txtNumberInput.Width
= 120;
_txtNumberInput.Location
= new Point(100, 0);
control.Controls.Add(_txtNumberInput);
return control;
}

public string Text
{
get { return _txtNumberInput.Text; }
set { _txtNumberInput.Text = value;}
}
}

I create a NumberInputTextBox and move all the code from the ShowNumberInput method to a public class method CreateNumberInput. The Text property has to be exposed so I create a public property. In the CreateNumberInput method I create some sort of placeholder named control which I decorate with the necessary controls.


I do the same for the other conditional steps. So now we have three classes.


Now I change the conditional steps to call the new classes and I also remove the call to the old ShowNumberInput method.



if (messageSelector.SelectedItem.ToString().IndexOf("NumberInput") != -1)
{
messagePanel.Controls.Clear();

NumberInputTextBox numberInputTextBox
=
new NumberInputTextBox();

messagePanel.Controls.Add
(numberInputTextBox.CreateNumberInput());
}
else if (...)

I apply the step "Extract Interface" on the classes. I have to decide a common command execution method name. Now we have :



  • CreateNumberInput
  • CreateAddressListBoxCombo
  • CreateTelephoneListBox

Let's change these names to CreateParameterControl and create the interface:



public interface IHandler
{
Control CreateParameterControl();
}

Let the parameter classes implement IHandler. Now every class' Create... method is renamed to CreateParameterControl.

The next step is to change the calls in the conditional statements to the new CreateParameterControl method.


if (messageSelector.SelectedItem.ToString().IndexOf("NumberInput") != -1)
{
messagePanel.Controls.Clear();

NumberInputTextBox numberInputTextBox
= new
NumberInputTextBox();

messagePanel.Controls.Add(numberInputTextBox.CreateParameterControl());
}


Now we have a couple of different solutions to go further with the refactoring:



  • Create a Command map and fill it with key value pairs being the name of the parameter to create and the resulting parameter class.
  • Create a Factory which uses reflection (see my article Reflection instances ) to let a config file decide which parameter requires which control.

First let's see how the the Command map solution works:


First of all we create a map. I'll use a generic dictionary for it like this:



IDictionary<string,Control> _paramCreationMap;
During initialization we fill the map:


private void CreateHandlerMap()
{
_paramCreationMap
= new Dictionary<string,Control>();
_paramCreationMap.Add(
"NumberInput", new NumberInputTextBox().CreateParameterControl());
_paramCreationMap.Add(
"AddressList", new AddressListComboBox().CreateParameterControl());
_paramCreationMap.Add(
"TelephoneList", new TelephoneListBox().CreateParameterControl());
}

the previous conditional dispatcher, can now be completely removed and replaced with this code:


// Get the param string out of the selectedItem using reflection
string paramName = Regex.Match(messageSelector.SelectedItem.ToString(), @"(?<=\[).*(?=\])").Value;
messagePanel.Controls.Clear();
Control paramControl
= _paramCreationMap[paramName];
messagePanel.Controls.Add(paramControl);

So no more conditional if...then...else...else if... or switch case statements.


Now, lets look at the second solution:


The result I'm trying to achieve is to get rid of the filling of a map with instances. Because when a new control is created, the instance has to be added to the map which I don't particularly like.


Then, a friend of mine showed me the beauty of reflection. I created my reflection based factory like this:



public static class ParameterFactory
{
public static Control CreateParameter(string paramName)
{
string assemblyName =
ConfigurationManager.AppSettings[
"ParameterControlsProject"];

string typeToLoad =
ConfigurationManager.AppSettings[paramName];

ObjectHandle objectHandle
=
Activator.CreateInstance(assemblyName,typeToLoad);

IHandler parameter
= (IHandler)objectHandle.Unwrap();
Control control
= parameter.CreateParameterControl();
control.Name
= typeToLoad;

return control;
}
}

The factory gets called like this:



// Get the param string out of the selectedItem using reflection
string paramName =
Regex.Match(messageSelector.SelectedItem.ToString(),
@"(?<=\[).*(?=\])").Value;

messagePanel.Controls.Clear();

Control paramControl
= ParameterFactory.CreateParameter(paramName);

messagePanel.Controls.Add(paramControl);

In the config file, in the AppSettings section we declare some key-value pairs which specify, which paramName corresponds with which type to load:




<appSettings>
<add key="ParameterControlsProject" value ="ParameterControls"></add>
<add key="NumberInput" value ="ParameterControls.NumberInputTextBox"></add>
<add key="AddressList" value ="ParameterControls.AddressListComboBox"></add>
<add key="TelephoneList" value ="ParameterControls.TelephoneListBox"></add>
</appSettings>


The key corresponds with paramName. ParameterControlsProject resembles the project where the actual control classes reside. Maybe we can change this to get the name from the calling assembly or something. I'll have to try this out.


That's it,


Greetz, G

Labels: , ,

Wednesday 28 March 2007

Refactoring to Null Object

On my holiday, I was reading the book refactoring to patterns and I came to a topic called "Introducing Null Object".

It seemed to be extremely promising for some duplicate code I wrote some time ago. Let me explain what the problem is.

I had written code to do some actions on a logfile. Like writing, reading and more similar actions.

The log class looked like this:

public class Log
{


StreamWriter textWriter;

public Log()
{
}

 

public void Write(string logMessage)
{
      textWriter = new StreamWriter(@"<path>\log.txt");
      textWriter.WriteLine(logMessage);
}

 

public string Read()
{
      return "Some log entries";
}

 

public void DoSomeLogAction()
{}

 

public void DoSomeOtherLogAction()
{}


}

Then I created the following service LogService:

public class LogService
{


Log _log;

public LogService(){}

 

public LogService(Log log)
{
      _log = log;
}


public void WriteToLog(string logMessage)
{
        if (_log != null)
       {
                this._log.Write(logMessage);
       }
       else
      {
              DoSomethingElse();
      }
}

public string ReadFromLog()
{
       string result="";

       if (_log != null)
      {
            result = _log.Read();
      }
      else
     {
            DoSomethingElse();
     }
     return result;

public void SomeLogAction()
{
      if (_log != null)
      {
            _log.DoSomeLogAction();
      }
      else
     {
            DoSomethingElse();
     }
}

 

public void SomeOtherLogAction()
{
      if (_log != null)
     {
           _log.DoSomeOtherLogAction();
     }
     else
    {
           DoSomethingElse();
    }
}

 

private void DoSomethingElse()
{}


}

We can see that there's a lot of duplicate code in it. Because of the possibility that logging is not enabled, we repeatedly have to test against the null value. If we don't do this, at some point in time we will definitely going to receive some exceptions.

Isn't it possible to reduce the duplicate code? Yes it is. By using refactoring to Null Object. This is what we have to do.

First of all we extract an interface from the Log Class. Like this:

public interface ILog
{
      void Write(string logMessage);
      string Read();
      void DoSomeLogAction();
      void DoSomeOtherLogAction();
}

 We let Log implement this interface.

Then we create a new class NullLog and let it also implement the ILog interface. But, the difference with the Log class is that NullLog takes care of the actions when a null value is passed to the service. Like this:

public class NullLog : ILog
{
      public NullLog()
     {}

      public void Write(string logMessage)
      {
            DoSomethingElse();
      }

      public string Read()
      {
            string result=""
            DoSomethingElse();
            return result;
      }

      public void DoSomeLogAction()
      {
            DoSomethingElse();
      }

      public void DoSomeOtherLogAction()
      {
            DoSomethingElse();
      }

      private void DoSomethingElse()
      {}

}

It's also common to let the methods do nothing at all.

Now comes the fun part. Change the LogService class to remove redundant code. Like this:

public class LogService
{


Log _log;

public LogService(){}

 

public LogService() : this(new NullLog()){}

public LogService(Log log)
{
      _log = log;
}


public void WriteToLog(string logMessage)
{
        if (_log != null)
       {
                this._log.Write(logMessage);
       }
       else
      {
              DoSomethingElse();
      }
}

public string ReadFromLog()
{
       string result="";

       if (_log != null)
      {
            result = _log.Read();
      }
      else
     {
            DoSomethingElse();
     }
     return result;

public void SomeLogAction()
{
      if (_log != null)
      {
            _log.DoSomeLogAction();
      }
      else
     {
            DoSomethingElse();
     }
}

 

public void SomeOtherLogAction()
{
      if (_log != null)
     {
           _log.DoSomeOtherLogAction();
     }
     else
    {
           DoSomethingElse();
    }
}

 

private void DoSomethingElse()
{}

}

First of all we changed the default constructor to pass an instance of the NullLog class to the overloaded constructor. So whenever the Service is instantiated without a Log object, everything will be delegated to the NullLog object.

Because of this change, all the null testing is redundant and can be removed.

Finally the private method DoSomethingElse is no longer necessary and can be safely removed.

The new ServiceLog class now looks like this:

public class LogService
{
      private ILog _log;

      public LogService() : this(new NullLog()){}

      public LogService(ILog log)
      {
            _log = log;
      }

      public void WriteToLog(string logMessage)
      {
            _log.Write(logMessage);
      }

      public string ReadFromLog()
      {
            return _log.Read();
      }

      public void SomeLogAction()
      {
            _log.DoSomeLogAction();
      }

      public void SomeOtherLogAction()
      {
            _log.DoSomeOtherLogAction();
      }

}

This looks a lot better doesn't it.

Comments are always welcome.

Greetz,

G

Labels: ,

Sunday 25 March 2007

Refactoring to patterns by Joshua Kerievsky

Hi,

I've just got back from a holiday. One week holiday means read, read, read.

So I bought and read the book "Refactoring to patterns" and this is my conclusion:

I found it not particularly easy. But it is really great. I read stuff I already did but could be improved enormously. One thing I have to say is that reading "Refactoring: Improving the Design of Existing Code" from Martin Fowler is a must before reading this one. There are a lot of pointers to Fowler's book.

Greetz,

G

Labels: ,

Thursday 15 March 2007

Create Sequence/Trigger in Oracle

Use the following script

DROP SEQUENCE SEQNAME;

CREATE SEQUENCE SEQNAME
START WITH 1
MAXVALUE 9999999999
MINVALUE 1
NOCYCLE
NOCACHE
NOORDER;

CREATE OR REPLACE TRIGGER TRIGGERNAME
BEFORE INSERT
ON TABLENAME
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
SELECT SEQNAME.NEXTVAL
INTO :NEW.PRIMARYKEYNAME
FROM DUAL;

EXCEPTION
WHEN OTHERS THEN
RAISE_APPLICATION_ERROR('-20000','TRIGGERNAME');
END;
/

Greetz,

G

Labels:

Wednesday 14 March 2007

Iterate over Cursor in Oracle

To create a procedure to iterate over the records in a cursor, use the following script

CREATE OR REPLACE PROCEDURE CursorProc IS

CURSOR c_Cursor IS
SELECT col1 FROM Table;

col1 Table.col1%TYPE;

BEGIN

OPEN c_Cursor;
FETCH c_Cursor INTO col1;

WHILE c_Cursor%found loop
dbms_output.put_line('col1 : ' col1);

FETCH c_Cursor INTO col1;
END LOOP;

CLOSE c_Cursor;

END CursorProc;

Greetz,
G

Labels:

ASP.NET 2.0 Wizard and the State Design Pattern

Some time ago, someone asked me to create ASP.NET 2.0 application to send mails to a list of customers.

I will give you a short explanation of the problem at hand.

The list of customer numbers could be retrieved by following a couple of steps.

First we have a radiobuttonlist to make an initial choice

1. Retrieve the list of customers who where brought on by other customers.
2. Retrieve the list of customers who where brought on by employees.
3. Retrieve the list of customers who where brought on by a marketing campaign.
4. Select individual customer numbers from a listbox.
5. Input certain customer numbers.

After step 1, 2 or 3, the retrieved list has to be shown in a grid with row checkboxes, so individual (or all) customer numbers could be selected.

After this step, there has to be a possibility to refine the search on location.

So after step 1, 2 and 3 we have to go to a step to show all numbers. After this step we have to go to a refinement step.

After step 4 and 5 this refining was not necessary.

In the end all steps resulted in another step where we can select a template mail or compose one on our own.

After selecting a template or compose a message on our own, we actually send the letter.

 As you can see, it's quit a conditional flow of steps.

After I read the scenario, I was thinking of using the Wizard control and as usual I was starting to code immediately without thoroughly thinking the problem through. I think I have to do something about that but the enthusiastic me takes over every time :)

In the next button click of the wizard I came up with the following code:

WizardSteps activeWizardStep = (WizardSteps) wizard.ActiveStepIndex;


if (activeWizardStep != WizardSteps.makeYourChoice)
{

switch (activeWizardStep)
{
case WizardSteps.customerThroughCustomer:
case WizardSteps.customerThroughEmployee:
case WizardSteps.customerThroughFamily:
{
// Do some step processing
wizard.ActiveStepIndex = (int)WizardSteps.showCustomerNumberList;
break;
}
case WizardSteps.showCustomerNumberList:
{
//
Do some step processing
wizard.ActiveStepIndex = (int)WizardSteps.refineCustomerList;
break;
}
case WizardSteps.choiceOfCustomerNumber:
case WizardSteps.inputCustomerNumber:
case WizardSteps.refineCustomerList:
{
// Do some step processing
wizard.ActiveStepIndex = (int)WizardSteps.choiceOfMarketingLetter;
break;
}
case WizardSteps.choiceOfMarketingLetter:
{
// Do some step processing
wizard.ActiveStepIndex = (int)WizardSteps.sendLetter;
break;
}
}

}
else
{


switch (stepsChoice.SelectedIndex)
{
case 0:
{
wizard.ActiveStepIndex = (int)WizardSteps.customerThroughCustomer;
break;
}
case 1:
{
wizard.ActiveStepIndex = (int)WizardSteps.customerThroughEmployee;
break;
}
case 2:
{
wizard.ActiveStepIndex = (int)WizardSteps.customerThroughFamily;
break;
}
case 3:
{
wizard.ActiveStepIndex = (int)WizardSteps.choiceOfCustomerNumber;
break;
}
case 4:
{
wizard.ActiveStepIndex = (int)WizardSteps.inputCustomerNumber;
break;
}
}

}

I used following enum for the wizard steps

public enum WizardSteps
{


UnknownStep = -1,
MakeYourChoiceStep = 0,
CustomersThroughCustomerStep = 1,
CustomersThroughEmployeeStep = 2,
CustomersThroughCampaignStep = 3,
ChoiceOfCustomerNumbersStep = 4,
InputCustomerNumbersStep = 5,
ShowCustomersNumberListStep = 6,
RefineCustomerListStep = 7,
ChoiceOfMarketingLetterStep = 8,
SendLetterStep = 9


}


From the moment I started writing it, it felt like smelly code. Maintenance would be horrible. Adding or moving some of the steps would become tricky. No to mention all the design principles who were being violated. Like SRP, Open Closed, and probably some more which I didn't noticed.

I got home and took my book "Head First Design Patterns". The book is actually written for the Java community but it read so appealingly, that I finished it in a couple of days. After reading some of the chapters, it hit me that maybe I could use the "State Design Pattern". The whole scenario sounded like a state machine. I took the basic principle of the pattern and altered a few things so it looked like the following:


Click the picture if you want a sharper image.

So what do we have here:

  • WizardFlowControl: acts as the Context Object

This object delegates all the work to the correct step. The steps determine who their next step will be. The WizardFlowControl will be instantiated when the next button gets clicked. You can think of this class as the hearth. It will regulate everything.

  • Step: acts as the state interface

Step is an abstract class. It receives the actual wizard and the viewstate as a statebag. The class also has an abstract readonly property StepIndex which has to be implemented by the class inheriting Step. It also contains an abstract method Handle which has to be implemented. You can access the wizard and viewstate trough some base properties.

  •  Implementation classes: Inherits Step

These classes are the actual wizardsteps. Because they inherit from the base class Step, the have to implement the property StepIndex and the method Handle. StepIndex determines the actual position in the wizard. Handle does the processing of the wizard step.

Let's see how we can code it. We will begin with the base class Step. It look like this:

public abstract class Step
{


private Wizard _wizard;
private Step _nextStep;
private StateBag _viewState;

public abstract int StepIndex {get;}
public abstract void Handle();

public Wizard Wizard
{
get{return _wizard;}
set {_wizard = value;}
}
public Step NextStep
{
get {return _nextStep;}
set {_nextStep = value;}
}
public StateBag ViewState
{
get {return _viewState;}
set {_nextStep = _viewState;}
}


}

As you can see, no rocket science here. Just an abstract class with four properties, one of them abstract, and an abstract method.

When we take a look at one of the implementation classes, ex. CustomersThroughCustomer, it looks like this:

public class CustomersThroughCustomer : Step
{


public CustomersThroughCustomer(){}

public override int StepIndex
{get { return (int)WizardSteps.CustomersThroughCustomerStep; }
}

public override void Handle()
{

// Process The Step

// Transition to the new state
NextStep = new ShowCustomersNumberList();   

}


}

A little explanation might come in handy here. The readonly StepIndex property returns us the current integer stepindex of the wizard. In the Handle method we do the actual processing. For example we can call some kind of service to get me all customers. Then this list can be bound to a listbox or some other control. After the processing, we set the nextstep. Here we are transitioning to another state.

But something doesn't feel right about the transitioning code. We can clearly see some tight coupling issues here. The next step instantiation just feels awkward. Maybe we can use another design pattern here.

I decided to use the "Factory Design Pattern". I implemented it, using reflection, like this:

public static class StepFactory
{

 

public static Step CreateStepInstance(string stepTypeName, Wizard wizard, StateBag viewState)
{

 

Assembly assembly = Assembly.LoadFrom("WizardLib.dll");
string assemblyName = assembly.FullName;

ObjectHandle wrappedStep = Activator.CreateInstance(assemblyName, stepTypeName);

 

Step step = (Step)wrappedStep.Unwrap();
step.Wizard = wizard;
step.ViewState = viewState;

 

return step;

}


}

Note: for more information you can read my other article Creating instances using reflection

Now that we have our factory, let's use it and change the following code:

// Transition to the new state
NextStep = new ShowCustomersNumberList();   

By this one:

// Transition to the new state
string nextStepName = Wizard.WizardSteps[(int)WizardSteps.ShowCustomersNumberListStep].ID;


NextStep = StepFactory.CreateStepInstance(nextStepName, Wizard);

First we retrieve the name of the ID of the next wizardstep by getting it out of the WizardStep collection using the correct enumeration WizardStep item.

Then we ask the factory to give us the correct next step instance.

Now let's take look at the heart of the wizard, the WizardFlowControl:

public class WizardFlowControl
{


Wizard _wizard;
Step _activeStep;
StateBag _viewState;

public WizardFlowControl(Wizard wizard, StateBag viewState)
{
_wizard = wizard;
_viewState = viewState;
}

public void Handle()
{
      ProcessStep();
      SetNextStep();
}

 

private void ProcessStep()
{
      // Get Current Step
     string activeStepName = _wizard.ActiveStep.ID;
    _activeStep = StepFactory.CreateStepInstance   (activeStepName, _wizard, _viewState);

    // Process the active step
    _activeStep.Handle();
}

 

private void SetNextStep()
{
     _wizard.ActiveStepIndex =    _activeStep.NextStep.StepIndex;
}


}

What's going on here: The WizardFlowControl accepts the wizard and the viewstate. 

For loose coupling I comply to the Inversion Of Control (IoC) principle by implementing the Dependency Injection pattern. This is well described by the master itself, Martin Fowler, in the following article http://www.martinfowler.com/articles/injection.html

After instantiation (in the next button click) we then call Handle. Handle will first determine the active stepindex and asks the factory for the active Step instance. It then calls the Step's Handle method and the step gets processed.

Finally the wizard is set to the next step, which is determined by the step itself.

That's actually it.

Conclusion:

The huge switch-case statement in the next button click of the page is now replaced by two statements:

  • WizardFlowControl wizardFlowControl = new WizardFlowControl(this.wizard, this.ViewState);
  • wizardFlowControl .Handle();

All responsibility is now handed over to the separate step implementations.

We someone asks me to add a step. It is easily done by creating a new class which inherits from the abstract base class Step. We can easily configure its position in the flow by setting it's stepindex to the correct step. And finally we have to decide which step is its predecessor and its successor.

Finally I would point out some of the issues that still bother me.

The fact that we have to name the step implementation classes the same as the wizard step Id's.

We can easily change this and use a config file to create key/value pairs for the wizardstep/step implementation combinations.

The second issue is related to the fact that I implemented the state design pattern in an ASP.NET web app. What about the ViewState?

You cannot access the ViewState from inside the step implementation classes. So I decided to pass the entire viewstate into the the step instances by providing it to the factory. This is probably not a good idea, but I didn't see an other possibility. I really needed the viewstate in the different steps.

If someone reads this post and has some remarks about it, please feel free to comment. I'm still in my learning phase, so I can use every help I can get.

Greetz,

G

Labels: , ,

Javascript Select/Unselect All Checkboxes

Another much used Javascript function is the one where we want to select/unselect a bunch of checkboxes on screen using client side scripting. Again, I inject the script in my code behind

private void InjectJavascript()
{
string toggleCheckboxes =

@"<script type=""text/javascript"">function SetAllCheckBoxes(formValue, checkValue)
{
var theForm;
var countElements;
var objElements;

theForm = document.forms[formValue];
if(!theForm)
return;

objElements = theForm.getElementsByTagName('input');
if(!objElements)
return;

countElements = objElements.length;
// set the check value for all check boxes
for(var i = 0; i < countElements; i++)
{
if (objElements[i].type == 'checkbox')
{
objElements[i].checked = checkValue;
}
}
}
</script>
";

ClientScript.RegisterClientScriptBlock(this.GetType(), "toggleCheckboxes", toggleCheckboxes);

// Wire some javascript client-side events
rbtnSelectAllCheckBoxes.Attributes.Add("onclick", "SetAllCheckBoxes('" + this.Form.ClientID + "',true)");

rbtnUnSelectAllCheckBoxes.Attributes.Add("onclick", "SetAllCheckBoxes('" + this.Form.ClientID + "',false)");
}


Call this void in the Page Load.Add a couple of checkboxes and two radiobuttons to the page.

Name the radiobuttons "rbtnSelectAllCheckBoxes" and "rbtnUnSelectAllCheckBoxes".Give it a try.

Greetz,
G

Labels:

Javascript Select/Unselect checkbox

Every time I have to use JS I get iritated because I always have to look it up on the Net. Let's put it on my blog so I can find it easier.

The problem I had to deal with was creating a JS function to select/Unselect a checkbox. I wrote the JS function in my code behind


private void InjectJavascript()
{

string toggleCheckbox = @"<script type=""text/javascript"">
function SelectUnSelectCheckBox(select)
{
var myCheckBox = document.getElementById('" + MyCheckBox.ClientID + "');";

toggleCheckbox += @" myCheckBox.checked = select;
}</script>";


// Register the javascript
ClientScript.RegisterClientScriptBlock(this.GetType(), "toggleCheckbox", toggleCheckbox);

// Wire some javascript client-side events
rbtnSelectCheckBox.Attributes.Add("onclick", "SelectUnSelectCheckBox(true)");
rbtnUnSelectCheckBox.Attributes.Add("onclick", "SelectUnSelectCheckBox(false)");
}


Call InjectJavascript in the Load of the form. Put a checkbox "MyCheckBox" and two radiobuttons "rbtnSelectCheckBox" and "rbtnUnSelectCheckBox" on the form.

That's it

Greetz,
G


Labels:

Tuesday 13 March 2007

Creating instances using reflection

Let's say,

we have a Class library, ClassLib. This library contains a type CystomType which implements a certain Interface ICustomtype. This interface defines the contract which states a method CustomMethod.

Let's create a instance of CustomType at runtime using reflection and use the method

Assembly assembly = Assembly.LoadFrom("ClassLib.dll");
string assemblyName = assembly.FullName;
ObjectHandle wrappedCustomType =
Activator.CreateInstance(assemblyName,"ClassLib.CustomType");
ICustomType myCustomType = (ICustomType)wrappedCustomType.Unwrap();
myCustomType.CustomMethod();


Don't forget to include the following lines

using System.Reflection;
using System.Runtime.Remoting;

Labels: ,

Factory pattern extended with generics

When I first encountered the Factory design pattern, I was intriged. I started reading about the abstract en method versions of the pattern. I immediatly disliked the method version because of the switch case statement.

This was obvious a violation of the open closed principle. The abstract version was beter.

But then Generics came to the scene and I was thinking of using them to build my own GenericDaoFactory to loose couple the client code from the instantiation of my data access objects

This is how I did it:

I started by creating an abstract DaoBaseClass with some standard mutual CRUD methods:

public abstract class DaoBaseClass <DTOTypeObj>
{

public abstract DTOTypeObj SelectRecord(DTOTypeObj obj);
public abstract void InsertRecord(DTOTypeObj obj);
public abstract void UpdateRecord(DTOTypeObj obj);
public
abstract void DeleteRecord(DTOTypeObj obj);

}


We pass in a Data Transfer Object. These objects just contain some state. Here is an example for the Customer DTO

public struct DTOCustomer
{


// Add all customer transfer properties
private int _customerNumber;
private string _customerAccount;
private int _id;

public int CustomerNumber
{

get { return _customerNumber; }
set
{_customerNumber = value; }

}

public string CustomerAccount
{

get { return _customerAccount; }
set { _customerAccount = value;
}

}

}

The DTO for the employee looks simular. Now let's use the DaoBaseClass and create a DaoCustomer class:

public class DaoCustomer : DaoBaseClass<DTOCustomer>
{

public override DTOCustomer SelectRecord(DTOCustomer obj) {

int customerId = obj.CustomerNumber;

return CustomerService.GetCustomer(obj.CustomerNumber);

}

public override void InsertRecord(DTOCustomer obj)
{

CustomerService.InsertCustomer(obj);

}

}


The other methods are left out to save some space.

What's next? Let's create the generic factory

public class GenericDaoFactory<T, DTO> where T:DaoBaseClass<DTO>, new()
{
private GenericDaoFactory(){}

public static T CreateDaoInstance()
{

T instance = new T();
return instance;

}

}

The factory is quit simple. We pass in the type of daoObject we want and the factory will create an instance for us. So we are working typesafe. We also have to pass in a DTO type with which the dao object will work.

The only thing we have to do now, is use the factory to create some Dao objects. Like this:

public void DoSomeStuffWithCustomersAndEmployees()
{

DaoCustomer daoCustomer =

GenericDaoFactory<DaoCustomer, DTOCustomer>.CreateDaoInstance();


DTOCustomer dtoCustomer = new DTOCustomer();
dtoCustomer.CustomerNumber = 10;
// Fill in some other data ...
daoCustomer.InsertRecord(dtoCustomer);

DaoEmployee daoEmployee =
GenericDaoFactory<DaoEmployee, DTOEmployee>.CreateDaoInstance();

DTOEmployee dtoEmployee = new DTOEmployee();
dtoEmployee.EmployeeNumber = 5;
daoEmployee.DeleteRecord(dtoEmployee);



}

As we can see, we ask the factory to give us a DaoCustomer. It returns us the object and we can start using it. The same happens for the DaoEmployee object.

That's it

Comments are always welcome
Greetings,
G



Labels: , ,

Monday 12 March 2007

Abstract classes / Abstract Methods UML 2 with Visio 2003

Create an abstract class in UML

- Go to the UML Static Structure panel and drag and drop a class on the right pane.
- Double click the class and select the “IsAbstract” checkbox

The class is now abstract. You can see this on the Italic header



Now we are going to add an abstract method

- Double click the class, select the category operations.
- Press the new button.
- Press the method button.
- Unselect the “Has Method” checkbox.
- Select the polymorfic checkbox (it is the default)
- Name the operation

We can now see the abstract method appearing. It’s also in italic.


Labels: , ,