Pages

4.9.19

Promotional Code for Udemy ServiceNow CIS - HR Practice Tests

If you're planning to become ServiceNow Certified Implementation Specialist - Human Resources (CIS-HR), you can prepare for the exam using my practice tests on Udemy. I have created 10 coupons. You can use the code CISHR19 or you can directly click on this link: ServiceNow CIS - HR Tests 50% off

Best of luck in your exam!

19.9.12

Reviewing CLR via C# by Jeffrey Richter

Lately, I finished reading "CLR via C#" by Jeffrey Richter. This 5-star book was very beneficial to me and I thought it would also add value for every .NET developer.

Not only does the book give you a good insight on the features of the framework, but it also digs deep into the inner working of the CLR giving the reader a great knowledge on how to write code that runs under the .NET framework.

The book analyses how the CLR handles our code, how and when it gets converted into intermediate language, how it gets executed and -more importantly- how the developer can interfere with this behavior and get the best out of the framework.

Furthermore, the book explores the fundamentals of the framework; including data types, methods, events, interfaces, generics ... etc. These are the basics of the framework that we all know about but the book explains them in detail so you learn what to use when.

The author, who has extensive experience in the framework since its beginnings, puts the picture clear to the reader about what features of the framework are better be avoided and which of them should be used with caution. Not all features are made for all scenarios!

On the other hand, the book introduces some features that we rarely use or might not know about at all. It also illustrates the best way of using some features that we're familiar with in order to shorten our tasks or make our code more efficient and reliable.

In brief, I think this is a must-read book by every .NET developer.

13.6.12

Difference Between Events And Delegates in C#

It might be the syntax of C# that provides us with shortcuts to write delegates and events that causes this confusion.

In short, a delegate is a class that contains a field that holds a reference to a method and then you can call the method with appropriate parameters. Whereas an event is a variable that you can define and specify one or more delegates to be added to it.

Let's go through these examples to simplify and illustrate the idea.

class Program
{
  static void Main(string[] args)
  {
    DelegatesAndEvents obj = new DelegatesAndEvents();
    obj.Execute();
  }
}


public class DelegatesAndEvents
{
  public delegate void MyDelegate(int val);

  internal void Execute()
  {

    MyDelegate d = new
    MyDelegate(this.MyMethod);

    int val = 15;

    d.Invoke(val);
  }

  void MyMethod(int val)
  {
    Console.WriteLine(val);
    Console.ReadLine();
  }
}


In the previous code, I create a delegate type and name it MyDelegate. This delegate type is designed to call methods that take one parameter of type integer. What actually happens behind the scenes is that the CLR creates a class called MyDelegate and this class would have some fields and a method called Invoke. The invoke method takes one parameter of type integer.

In the execute method, I create an instance of the delegate (recall that a delegate is a class and I can create instances from it like any other class). The constructor of this MyDelegate takes one parameter of type integer. However, what I actually pass to the constructor is the name of the method I want to invoke and it will implicitly understand that I'm passing a reference to the method.

Another point that is worth mentioning is that I could have invoked the method without using the Invoke method. This is just a syntactical shortcut provided by C#. It would be like this:
d(val);


Now let's change our code a little bit. (comment added to show added, removed and changed code)
public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e); // Changed

  internal void Execute()
  {

    MyDelegate d = new
    MyDelegate(this.MyMethod);

    EventArgs e = new EventArgs(); // Added
    object sender = 15; // Added

    d(sender, e); // Changed
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


What I did is just changing the parameters that MyDelegate is designed to take. Instead of taking one parameter of type integer, it now takes 2 parameters of types object and EventArgs, respectively. There's no big deal so far.

Now I will introduce an event and see how to use it. I will change the code a little bit. (comment added to show added, removed and changed code )

public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent; // Added

  internal void Execute()
  {

    MyDelegate d = new MyDelegate(this.MyMethod);

    object sender = 15;
    EventArgs e = new EventArgs();

    MyEvent += new MyDelegate(d); // Added

    MyEvent(sender, e); // Added

    //d(sender, e);  Removed
  }


  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Here's what I did in the last code change.I declared an event of type MyDelegate. In other words, I created an event that can hold delegates of type MyDelegate, so in the future I can use this event to invoke methods with the signature MyDelegate defines (methods that take 2 parameters of type object and EventArgs). And then,instead of invoking MyMethod directly using the delegate, I use the newly created event MyEvent to invoke the method.

As you can see, MyEvent is just a holder of delegates. I can add delegates to this event by using += syntax and passing the delegate instance in the constructor. I can add more than one delegate instance to this event. Look at the following code. (comment added to show added, removed and changed code )

public class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent;

  internal void Execute()
  {

    MyDelegate d = new MyDelegate(this.MyMethod);

    object sender = 15;
    EventArgs e = new EventArgs();

    MyDelegate d2 = new MyDelegate(this.MyMethod2); // Added

    MyEvent += new MyDelegate(d);
    MyEvent += new MyDelegate(d2); // Added

    MyEvent(sender, e);
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }

  // This method is added
  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}

Instead of adding a delegate instance to the event the normal way, There's a syntax shortcut provided by C# that looks like this:
MyEvent += MyMethod;


So I can change my code to look like this: (comment added to show added, removed and changed code )

class DelegatesAndEvents
{

  public delegate void MyDelegate(object sender, EventArgs e);
  public event MyDelegate MyEvent;

  internal void Execute()
  {      

    //MyDelegate d = new MyDelegate(this.MyMethod);  Removed

    object sender = 15;
    EventArgs e = new EventArgs();

    //MyDelegate d2 = new MyDelegate(this.MyMethod2);  Removed

    MyEvent += MyMethod; // Changed
    MyEvent += MyMethod2; // Changed

    MyEvent(sender, e);
  }

  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }


  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Notice that I no longer need to create delegate instances because the new syntax will implicitly create it.

Finally, let me introduce EventHandler, which is a delegate type itself. You can type EventHandler in your code in Visual Studio and press F12 to discover this.

namespace System
{

  [Serializable]
  [ComVisible(true)]
  public delegate void EventHandler(object sender, EventArgs e);

}


As you can see, EventHandler is a delegate type designed to invoke methods that take 2 parameters, object and EventArgs, exactly like MyDelegate that I defined in the previous code. Therefore, I can replace MyDelegate with EventHandlerand everything will be the same. The final code will be like this:

class DelegatesAndEvents
{    

  //public delegate void MyDelegate(object sender, EventArgs e);  Removed
  public event EventHandler MyEvent; // Changed

  internal void Execute()
  {
    object sender = 15;
    EventArgs e = new EventArgs();

    MyEvent += MyMethod;
    MyEvent += MyMethod;

    MyEvent(sender, e);
  }


  void MyMethod(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }


  void MyMethod2(object sender, EventArgs e)
  {
    Console.WriteLine(sender);
    Console.ReadLine();
  }
}


Normally, you don't go through all of the previous steps. You only see the last portion of code. All I was trying to do is to show you how this last code came.

now I hope it became clear that delegates are just types that you can create instances from. All delegates inherit from the classMulticastDelegate which is used to invoke other methods according to what we define. Events are meant to hold one or more delegate instance and once you raise the event, it invokes all the methods attached with those delegate instance.

8.6.12

Confusion when Passing Reference Type Objects in C#

Everybody knows that when making a method call in C#, reference type objects are passed by reference. In other words, whatever changes you make to your object in the called method will be reflected on the original one.

Let's examine the following code:

    class MyClass
    {
        public int MyInteger;
    }
    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.MyInteger = 5;

            Console.Write("Value before method call: ");
            Console.WriteLine(myClass.MyInteger);
            MyMethod(myClass);
            Console.Write("Value after method call: ");
            Console.WriteLine(myClass.MyInteger);
        }            

        private static void MyMethod(MyClass myClass)
        {
            myClass.MyInteger = 10;
        }
    }
If you run the preceding code, it will show the following result:

Value before method call: 5
Value after method call: 10

This was expected. However, the idea that all reference type objects are passed by reference is not really accurate and the following proves so. If we change "MyMethod" by adding one line so it becomes as the following:
        private static void MyMethod(MyClass myClass)
        {
            myClass = new MyClass();
            myClass.MyInteger = 10;
        }

and then we run the program, guess what the result will be. The result will be as following:

Value before method call: 5
Value after method call: 5

The value of the field "MyInteger" did not change as you might expected. That is because what actually happens when you pass a reference type object to a method is that the reference to that object is copied and the copy is passed to the method. The new copy of the reference points to the same object, so if you make changes in the called method, you will be making changes on the same object. But if you create a new object in the called method, you will be actually changing the reference value that was passed and making it point to a new object. And whatever changes you make after this step will be irrelevant to the original object.

The following diagrams illustrates what happens in the previous 2 examples.

Example 1: What really happens when you pass an object
Example 1: What really happens when you pass an object

Example 2: Creating an instance inside the called method
Example 2: Creating an instance inside the called method



If you wish to make any changes to the object in the called method and have them all reflected on the original object even if you make a new instance in the called method, then what you need is to pass it by reference. You need to add the keyword ref before the object type in the method signature and also when calling the method. The code will look like this:

    class Program
    {
        static void Main(string[] args)
        {
            MyClass myClass = new MyClass();
            myClass.MyInteger = 5;

            Console.Write("Value before method call: ");
            Console.WriteLine(myClass.MyInteger);
            MyMethod(ref myClass);
            Console.Write("Value after method call: ");
            Console.WriteLine(myClass.MyInteger);
        }            

        private static void MyMethod(ref MyClass myClass)
        {
            myClass = new MyClass();
            myClass.MyInteger = 10;
        }
    }


25.4.12

Reference Type vs. Value Type in C#

Types in .NET Framework are either treated by Reference or by Value. Reference types variables are used by a reference (or a pointer) that points to their data. On the other hand, Value types variables are accessed directly through their values.

There are several differences between these 2 kinds of data types. I'll try here to highlight some of them throughout examples.

Reference Type variables are stored in the heap while Value Type variables are stored in the stack. This means that when a reference type variable is no longer used, it can be a candidate for garbage collection. However, a value type variable is removed from the memory once the method using it is over.

Reference types are typically declared using "class" keyword, while the value types are declared by the keyword "struct". Let's see an example of each.

    public class ReferenceType
    {
        public int Field { get; set; }        
    }  

    public struct ValueType
    {
        public int Field { get; set; }
    }

Let's now create a console application that uses the previous types.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType1 = new ReferenceType();
            ReferenceType referenceType2 = new ReferenceType();
            Console.WriteLine(referenceType1.Equals(referenceType2));
            
            Console.WriteLine("Value Type");
            ValueType valueType1 = new ValueType();
            ValueType valueType2 = new ValueType();
            Console.WriteLine(valueType1.Equals(valueType2));

            Console.ReadLine();
        }
   }


You might have expected that the first Console.WriteLine statement would print "true", but the actual result is "false". System.Object is considered the parent type of all other types and it has the method Equals and implements it in a way that doesn't care about the object's fields, but rather on its reference. However, all value types inherit from System.ValueType, which itself inherit from System.Object. System.ValueType overrides the implementation of Equals with a more logical one that depends on the values of object's fields.

Let's now have another example and see how reference types are considered equal.
 
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType1 = new ReferenceType();
            ReferenceType referenceType2 = referenceType1;
            Console.WriteLine(referenceType1.Equals(referenceType2));

            Console.WriteLine("Value Type");
            ValueType valueType1 = new ValueType();
            ValueType valueType2 = valueType1;
            Console.WriteLine(valueType1.Equals(valueType2));

            Console.ReadLine();
        }
   }


Here, both of them print "true". The second Console.WriteLine statement obviously prints true because both objects have the save values for their fields. For the first statement, this explains to us the fact that reference types are used by their reference. In other words, when assigning "referenceType1" to "referenceType2", the CLR only copies referenceType1's reference and assigns it to referenceType2 so both of them become pointing to the same object data in the memory. Let's try the following to better illustrate the idea.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType1 = new ReferenceType();
            ReferenceType referenceType2 = referenceType1;

            Console.WriteLine(referenceType1.Field);

            referenceType2.Field = 5;

            Console.WriteLine(referenceType1.Field);


            Console.ReadLine();
        }
   }
Now you can see that although we didn't directly change the value of referenceType1, it has been changed because it points to the same data that referenceType2 points to. The following example illustrate the idea even more.

    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Reference Type");
            ReferenceType referenceType = new ReferenceType();
            referenceType.Field = 1;
            Console.WriteLine("Before: " + referenceType.Field);
            Pass(referenceType);
            Console.WriteLine("After: " + referenceType.Field);

            Console.WriteLine("");
            Console.WriteLine("Value Type");
            ValueType valueType = new ValueType();
            valueType.Field = 1;
            Console.WriteLine("Before: " + valueType.Field);
            Pass(valueType);
            Console.WriteLine("After: " + valueType.Field);

            Console.WriteLine("");
            Console.WriteLine("Value Type By Reference");
            ValueType valueType2 = new ValueType();
            valueType2.Field = 1;
            Console.WriteLine("Before: " + valueType2.Field);
            Pass(ref valueType2);
            Console.WriteLine("After: " + valueType2.Field);


            Console.ReadLine();
        }

        static void Pass(ReferenceType referenceType)
        {
            referenceType.Field = 2;
        }



        static void Pass(ValueType valueType)
        {
            valueType.Field = 2;
        }


        static void Pass(ref ValueType valueType)
        {
            valueType.Field = 2;
        }

   }


Let's move now to another aspect of difference. Add the following 2 lines to the first example and then try to compile.
    
    Console.WriteLine(referenceType1 == referenceType2);
    Console.WriteLine(valueType1 == valueType2);

These 2 lines will not compile. You will get the compilation error message : "Operator '==' cannot be applied to operands of type 'MyNameSpace.ValueType' and 'MyNameSpace.ValueType".

Let's summarize and add some other differences in the following table.
Value Type Reference Type
Where are they stored in memory? Stack Heap
Parent Type System.ValueType System.Object
Inheritance All value types are sealed and you cannot inherit from other types You can normally inherit from other types
Access modifiers protected cannot be used Any access modifier can be used

27.3.12

Custom Validation Controls in ASP.NET

Validation controls in ASP.NET are great tools that reduce the time needed to do such a repetitive task> However, sometimes they don't provide all what we need. We still want to use them but we also want to add more validation that is custom to our business.

Custom Validation controls come to solve this problem. We can use them in conjunction with the normal Validation controls. We can provide either our custom client-side validation or server-side validation, or both.

In many times, we use custom validation controls to validate the entire logic of a form instead of a specific control. For this reason, we can leave the ControlToValidate property empty.

Here's a simple example of using custom validation controls. Suppose we have the following is the HTML:


<asp:Literal ID="lblMobileNumber" runat="server" Text="Mobile Number" />
<asp:TextBox ID="txtMobileNumber" runat="server" />

<asp:Literal ID="lblHomeNumber" runat="server" Text="Home Number" />
<asp:TextBox ID="txtHomeNumber" runat="server" />

<asp:Button runat="server" ID="btnSave" Text="Save" ValidationGroup="Save" />

And suppose that you want to force the user to enter either mobile number or home number, so you add the following custom control.

<asp:CustomValidator ID="cvMobileOrHomeNumber" runat="server" 
ErrorMessage="Please enter either mobile number or home number" ValidationGroup="Save"
ClientValidationFunction="validateMobileOrHomeNumber" 
OnServerValidate="cvMobileOrHomeNumber_ServerValidate" />



In ClientValidationFunction we specify the Javascript function to be executed for validation. This function should accept 2 parameters. The first parameter represents the source of the validation, and the second parameter is the one that we'll use to eventually decide whether the operation is valid or not. Let's create the function.
<script type="text/javascript">

    function validateMobileOrHomeNumber(source, args) {

        if (the operation is valild) {
            args.IsValid = true;
        }
        else {
            args.IsValid = false;
        }

        return;
    }

    </script>


Similarly, we use OnServerValidate to specify the method to be executed at server side. Let's see how to implement it.

protected void cvMobileOrHomeNumber_ServerValidate(object source, ServerValidateEventArgs args)
        {
            if (the operation is valid)
                args.IsValid = true;
            else
                args.IsValid = false;
        }


That's it!

26.8.11

Reviewing Architecting Applications for the Enterprise

Microsoft® .NET: Architecting Applications for the Enterprise by Dino Esposito
My rating: 4 of 5

Interesting and easy-reading book on software architecture using Microsoft technologies. It also provides some helpful best practices in general regardless of the technology. It covers a wide range of many architecture aspects; from presentation patterns to business and data access layers. However, I felt that the book doesn't have a main steam. It gives you tips on every thing but there is nothing that it talks a lot about. All in all, the book is very beneficial and is a must to read for any senior microsoft software developer.

16.8.11

My First Chrome Theme

Snapshot of the theme in Chrome Web Store

Today, I've published a Google Chrome theme. Creating a theme wasn't difficult at all. I used a website that provides the capability of creating Chrome themes online. You can check the website here: Create Chrome Theme Online

My first Chrome theme features a photo that I took in the Jordanian city of Umm Qais. The city resides in the north-west of the country and I think it's not getting  enough attention by tourists and tourism associations.

You can download the theme from this link:
https://chrome.google.com/webstore/detail/gobjieemlhcnpibeobjfodhankgfhoco?hl=en-US

Please try it and tell me what you think.

24.5.11

Abstract vs. Virtual in C#

There are several keywords that can be used for inheritance in object-oriented programming languages. In C#, you can specify a method as abstract or virtual.

In the concrete class, you must override any method marked as abstract. You can override
virtual
methods. In addition, you can provide new implementation for normal methods that are neither
abstract nor virtual. In this case, it's recommended to use the new keyword.

What's the difference between abstract and virtual methods? How can I use them to serve my design? In this article, I'm trying to answer these questions.

Of course the abstract method doesn't have implementation. It just defines the method. But is there any other differences? Let's take an example of two classes. An abstract class and another one that inherits from it.
Class diagram of an abstract class and a concrete one


// the abstract class
public abstract class BaseClass
{
    public abstract string GetAbstractValue();

    public virtual string GetVirtualValue()
    {
        return "Base GetVirtualValue";
    }

    public string GetValue()
    {
        return "Base GetValue";
    }
}


// the concrete class
public class ConcreteClass : BaseClass
{
    public override string GetAbstractValue()
    {
        return "Concrete GetAbstractValue";
    }

    public override string GetVirtualValue()
    {
        return "Concrete GetVirtualValue";
    }

    public string GetValue()
    {
        return "Concrete GetValue";
    }
}

Let's make a console application that uses the above classes. We want to make 2 instances of the concrete class. The first one should be of type
BaseClass and the other one of type ConcreteClass.

The client code should look like this:

class Program
{
    static void Main(string[] args)
    {
        BaseClass instance1 = new ConcreteClass();
            
        Console.WriteLine(instance1.GetAbstractValue());
        Console.WriteLine(instance1.GetVirtualValue());
        Console.WriteLine(instance1.GetValue());


        ConcreteClass instance2 = new ConcreteClass();

        Console.WriteLine(instance2.GetAbstractValue());
        Console.WriteLine(instance2.GetVirtualValue());
        Console.WriteLine(instance2.GetValue());


        Console.Read();
    }
}

Let's now see and compare the results.

The results of running the application

What do you conclude from the results?

Let's make another experiment before conclusion. Let's remove the following 2 methods from the
ConcreteClass

  • GetVirtualValue
  • GetValue

Try to run the application and notice the results.

The results after removing the 2 methods

From the previous results we can conclude the following:


Abstract Virtual No Keyword
Can have implementation?  No Yes Yes
Can override? Must Can but not a must You can declare a new method with the same name
Which keyword to use to provide new implementation in the concrete class? override override No keyword needed
If an object is created of the base class type, which method will be executed? Concrete implementation The parent implementation will be called only if no implementation is provided in the concrete class Parent implementation
If an object is created of the concrete class type, which method will be executed? Concrete implementation Concrete implementation The parent implementation will be called only if no implementation is provided in the concrete class

29.12.10

Executing Stored Procedures in Parallel using ADO.NET

In some cases, when every milisecond counts, you might need to execute several stored procedures at the same time. At the same time here means that when calling the first stored procedure, you don't want to wait for its result in order to call the second one.

In other words, if the two stored procedures are independent, it would be a brilliant idea to improve performance by executing them in parallel.

Say, for example, that you have two stored procedures: SP1 and SP2. Everyone of them takes 3 seconds. If you want to call them in sequence, this would mean you'll need to wait for 6 seconds. Calling them in parallel will let them both execute in around 3 seconds.

In this article, I will give an example of an ASP.NET web page that calls 2 parallel stored procedures in its load method.

Let's say that you have 2 stored procedure named SP1 and SP2. Everyone of them returns a result set. Every result set is independent from the other. For simplicity, I'll say that you are only interested in the first record of the result set and you want to display this value in a Literal control.

If you want to call them sequentially, or synchronously, this would typically be what you write:

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection cnn = new SqlConnection("Your connection string");
    SqlCommand cmd1;
    SqlCommand cmd2;
    SqlDataReader reader1;
    SqlDataReader reader2;
 
    try
    {
        cnn.Open();
 
        cmd1 = new SqlCommand("SP1", cnn);
        cmd1.CommandType = System.Data.CommandType.StoredProcedure;
        reader1 = cmd1.ExecuteReader();
 
        if (reader1.Read())
        {
            Literal1.Text = reader1[0].ToString();
        }
 
        if (!reader1.IsClosed)
        {
            reader1.Close();
        }
 
        cmd2 = new SqlCommand("SP2", cnn);
        cmd2.CommandType = System.Data.CommandType.StoredProcedure;
        reader2 = cmd2.ExecuteReader();
 
        if (reader2.Read())
        {
            Literal2.Text = reader2[0].ToString();
        }
 
        if (!reader2.IsClosed)
        {
            reader2.Close();
        }
    }
    catch (Exception ex)
    {
        // raise an exception or do whatever logic you want
    }
    finally
    {
        if (cnn.State != System.Data.ConnectionState.Closed)
            cnn.Close();
    }
}

However, if you want to call them asynchronously, you need to create to different connections. They can both use the same connection string. In addition, you'll need to use BeginExecuteReader and EndExecuteReader instead of the usual ExecuteReader


Your code will look more like this:

protected void Page_Load(object sender, EventArgs e)
{
    SqlConnection cnn1 = new SqlConnection("Your connection string");
    SqlConnection cnn2 = new SqlConnection("Your connection string");
    SqlCommand cmd1;
    SqlCommand cmd2;
    IAsyncResult result1;
    IAsyncResult result2;
    SqlDataReader reader1;
    SqlDataReader reader2;
 
    try
    {
        cnn1.Open();
 
        cmd1 = new SqlCommand("SP1", cnn1);
        cmd1.CommandType = System.Data.CommandType.StoredProcedure;
        result1 = cmd1.BeginExecuteReader(CommandBehavior.SingleRow);
 
        cnn2.Open();
        cmd2 = new SqlCommand("SP2", cnn2);
        cmd2.CommandType = System.Data.CommandType.StoredProcedure;
        result2 = cmd2.BeginExecuteReader(CommandBehavior.SingleRow);
 
        reader1 = cmd1.EndExecuteReader(result1);
 
        if (reader1.Read())
        {
            Literal1.Text = reader1[0].ToString();
        }
 
        reader1.Close();
 
        reader2 = cmd2.EndExecuteReader(result2);
 
        if (reader2.Read())
        {
            Literal2.Text = reader2[0].ToString();
        }
 
        reader2.Close();
    }
    catch (Exception ex)
    {
        // raise an exception or do whatever logic you want
    }
    finally
    {
        if (cnn1.State != System.Data.ConnectionState.Closed)
            cnn1.Close();
 
        if (cnn2.State != System.Data.ConnectionState.Closed)
            cnn2.Close();
    }
}

3.11.10

Adding Days to Dates in Javascript

There's no built-in function in the Javascript Date object that adds days to an existing date. However, there's a way to make it work by using the Date contructor.

    var date = Date(year, month, day);

Using this constructor, we can acomplish this task. Let's say that we're having a date variable called today and you want to alert a date that is 15 days after this date. The following should do the job.

function displayDates() {
        var today = new Date();
     
        var date = Date(today.getFullYear(), today.getMonth(), today.getDate() + 15);
       
        // Remember that today.getDate()
        function retrieves the days part of the date
     
        alert(date);
    }

Don't worry, if today is October, 25 2010, Javascript will automatically realize that adding 15 days to this date will move us to the next month; November.

In order to make our task a little bit simpler amd more reusable, let's make benifit of the Date's prototype and add a function to the Date objects. Add the following to the same page.

Date.prototype.AddDays =  function(numberOfDays) {
        return new Date(this.getFullYear(), this.getMonth(), this.getDate() + numberOfDays);
    }

This will allow us to easily add days to any date that we make in the future. The following code illustrates how to use it.

function displayDates() {
        var today = new Date();
   
        alert(today.AddDays(5));
    }

To complete the set of functions, add the following as well.

Date.prototype.AddMonths =  function(numberOfMonths) {
        return new Date(this.getFullYear(), this.getMonth() + numberOfMonths, this.getDate());
    }
    
    Date.prototype.AddYears =  function(numberOfYears) {
        return new Date(this.getFullYear() + numberOfYears, this.getMonth(), this.getDate());
    }


Of course, you know that if what we need to do is subtracting days, then we can send a negative numberOfDays value.

11.4.10

AJAX-Like File Uploading

Introduction


Currently, there's no direct way to upload files in a web page without refreshing the page. If you have an interactive page that is AJAX-enabled, you would like to support uploading files in a way similar to AJAX behavior.

Unfortunately, the XMLHttpRequest object doesn't support uploading files; therefore, I am trying to upload files using a workaround.

Background


First of all, before diving in to the subject, let's review some basic concepts of HTML forms. If you are already familiar with HTML forms, you can skip this section.

Basically, there are two main ways to submit a form. The first one is by clicking on an input control of type submit. Like the following:

<input type="submit" id="mySubmitButton" name="mySubmitButton" value="Submit Form" />

The other way is by calling a JavaScript code that submits the form, like the following:


function submitMyForm() {
         var theForm = document.forms['myForm'];
         theForm.submit();
    }

A form in HTML has several attributes that indicate how the form should be submitted; the following are some of these attributes:
  • action: it's a path to a web page to which the form should be submitted
  • method: the method of submitting the form (possible values include: POST, GET ...etc.)
  • enctype: the way the submitted data should be encrypted
  • target: the frame in which the form should be submitted

Once a page is submitted, either by clicking on the Submit button or by calling a JavaScript that submits the form, the browser checks the action of the form to be submitted, and then it will load the action -web page- sending it the contents of the form, encrypted using the encryption method specified in the encrypt attribute.

Prepare the Page


Two pages are going to be used to implement this technique. The first one will hold the HTML content, including the file upload control. The second one will contain the server-side code to save the file to the server.

Let's start by adding controls to the first page. Of course, we'll need to add a file upload control. In addition, we'll add an iFrame and a form. The HTML body of the page will look like this:

<body>
 
<!-- This is the form that we added -->
<form id="myForm" name="myForm" target="myIFrame" method="post" action="SaveFile.aspx"
enctype="multipart/form-data">
</form>
 
<!-- This is the form which is added by default -->
<form id="form1" runat="server">
 
<!-- This is the file upload control -->
<input type="file" id="myFile" name="myFile" runat="server" />
 
<!-- This is a normal button that will be used
to the JavaScript function to upload the file -->
<input type="button" value="Upload File" />
 
<!-- This is an iFrame in which the form will be submitted -->
<iframe style="display: none;" id="myIFrame" name="myIFrame"></iframe>
 
</form>
</body>

Note that we added the form outside the form that was added by default to the page. We also set the action property to the second page URL, as mentioned earlier. The iFrame style is set to keep it hidden so we won't notice it when the file is being uploaded.


JavaScript


Now, we want to let the button call a JavaScript to submit the form and upload the file. In order to do that, we'll add a JavaScript function to the page and call it uploadFile. We'll also call this function at the button's click event. The following is the JavaScript function:

<script type="text/javascript">

function uploadFile() {
 
     // get the form that we added
     var theForm = document.forms['myForm'];
 
     // some browsers don't recognize the line above,
     // so this line is added for browser compatability
     if (!theForm)
          theForm = document.myForm;    
 
     if (!theForm.onsubmit || (theForm.onsubmit() != false)) {
 
          // get the file upload control
          var theFile = document.getElementById("myFile");
 
          // add the file upload control inside the form
          theForm.appendChild(theFile);
 
          // submit the form
          theForm.submit();
     }
}

</script>

Save the File


The second page, SaveFile.aspx, contains the code that saves the file on loading, as follows:

protected void Page_Load(object sender, EventArgs e)
{
     Request.Files["myFile"].SaveAs("path on the server to save the file");
}

Compatible Browsers


This technique was tested on Microsoft Explorer 8 and Google Chrome.

Iff statement in VB.NET

As a C# developer, I'm accustomed to using the one-line conditional statement; (condition) ? (true condition code) : (false condition code); So when I started to write VB.NET recently, which I abandoned several years ago, I found it nice to use the Iff function.

Any way, I was surprised by its behavior, until I came back to my common sense and realized that Iff is not a keyword in VB.NET but rather it's a function, like any other function.

The following statement will always cause a run-time error:

Dim x As MyObject
Dim y As Integer
x = Nothing
y = Iff(x IsNot Nothing, x.MyValue, 5)

You might wonder, why it causes a run-time error when I'm asking it to return 5 when x is nothing. But, in fact, because Iff is like any function, it receives 3 parameters; the first one is the condition, the second one is the value to be returned when the condition is true and the third is the value that should be returned when the condition is false. The last 2 parameters are always evaluated regardless of the condition.

Implement Sequence in Sql Server

Problem


In many cases, a database developer would rely on the DBRMS to generate and auto-increment a primary key in a table. In Oracle, for instance, the "Sequence" feature provides an encapsulated functionality to handle incrementing any particular variable. A sequence is not necessarily attached to a particular table, but rather, it's considered an independent entity that can be used amongst several tables.

In Sql Server, however, the sequence feature is replaced by the Identity column feature. One and only one column in any table can be defined as identity, and then the Sql Server will take over the job of incrementing this column with the certain value specified by the developer.

In some cases, a developer might need to make a column auto-incremented while it's not the table's primary key. Since Sql Server allows only one identity in a table, which might sound logical because a table wouldn't and shouldn't have more than one identity, a developer should handle incrementing this column manually.

One solution to this problem can be reading the last value of the field and then incrementing it and inserting the new record with the incremented value. However, this has integrity issue. Suppose two users consume the table simultaneously, both of them will read the same value and increment it with the same amount resulting in the same field for both records.

Solution


Another solution that proved its efficiency is the following:

1. Create a table with the column that you want to be incremented

CREATE TABLE [MyTable](
 
[SomeInfo] [nvarchar](50) NULL,
 
[IncrementedColumn] [int] NULL
 
) ON [PRIMARY]

2. Create a table and call it sequence

CREATE TABLE [Sequence](
 
 [SequenceColumn] [int] NULL
 
) ON [PRIMARY]

3. Insert a value into sequence table to start incrementing from it.

INSERT INTO Sequence (SequenceColumn)
 
VALUES (5)

4. Whenever you want to insert a new record into 'MyTable', update the sequence using the following:

DECLARE @NewSequence INT
 
UPDATE Sequence
SET @NewSequence = SequenceColumn = SequenceColumn + 1

and then you can use @NewSequence to insert a record into 'MyTable'

Creating a Numeric TextBox Control

Numeric TextBox

Introduction


In this article, we'll learn step-by-step how to create a custom textbox control that only accepts numeric characters. The control will allow the client code to specify whether it should work as an integer or decimal textbox.

This custom control will be implemented using Visual Studio 2008. However, the same code can be written using previous versions of Visual Studio. The programming languages I'm going to use are: C# and JavaScript.

Prepare the Project


First of all, let's prepare the project and the files that we're going to use. Please follow these simple steps:
  1. Create a new project of type Class Library and name it MyCustomControls.
  2. Create new ClassLibrary project
  3. Make sure that you add a reference to the System.Web library.
  4. Add reference to System.Web
  5. By default, Visual Studio will add a file named 'Class1.cs'. Please delete this file and add two files with the following names: NumericTextBox.cs and NumericTextBoxExtention.cs. In addition, create a new folder with the name 'Resources' and add a JavaScript file with the name 'NumericTextBox.js'.
  6. Insert the required files
  7. In order to make the JavaScript embedded in the component, we need to change its BuildAction property to 'Embedded Resource'. Please refer to the figure below:
  8. Change javascript file BuildAction property to Embedded Resource

The C# Code


Why two C# files?

As you may have already noticed, we have two C# files. Both of them will be used to implement the same class; NumericTextBox. However, the keyword partial will be added to the definition so the compiler will know that both classes represent one class in the end. The NumericTextBox.cs file will be used to implement the logic of our control, while the NumericTextBoxExtention.cs will contain any fields or properties.

Please have a look at the code below to see how we're going to define the NumericTextBox class in the NumericTextBox.cs file. Code Snippet 2 shows the code in the NumericTextBoxExtention.cs file.

Please note that the partial classes is a feature added to .NET version 2.0 and later versions. If you're using a 1.* version of .NET, you can alternatively place all your code in one class.

   1:  //
   2:  // Code Snippet 1
   3:  //
   4:   
   5:  using System;
   6:  using System.Web.UI;
   7:   
   8:  [assembly: WebResource("MyCustomControls.Resources.NumericTextBox.js", "text/javascript")]
   9:  namespace MyCustomControls
  10:  {
  11:      [ToolboxData(@"<{0}:NumericTextBox Text="""" runat=""server""></{0}:NumericTextBox>")]
  12:      public partial class NumericTextBox : System.Web.UI.WebControls.TextBox
  13:      {
  14:   
  15:      }
  16:  }




   1:  //
   2:  // Code Snippet 2
   3:  //
   4:   
   5:  namespace MyCustomControls
   6:  {
   7:      public partial class NumericTextBox : System.Web.UI.WebControls.TextBox
   8:      {
   9:   
  10:      }
  11:  }

Fields and properties

There are some attributes added in Code Snippet 1. Don't worry about them now, we'll talk about them later in this article. Now we want to see what properties we need to implement in the NumericTextBoxExtention.cs file.

Let's think of properties that we might need. First of all, we've said previously that our control will work for both integers and decimals. So it would be wise to add a property named Type. This property can be of type int or string. However, I think it's a better practice to add an enum named TextBoxType and let our property's type be of this enum.

Additionally, we'll need a property to specify the number of integers allowed. And, in the case of the decimal textbox, we'll also need a property to specify the maximum number of fractions allowed after the decimal point. Furthermore, we'll add a property to specify whether this control should accept negative values or not. Please have a look at Code Snippet 3 to see how this will be implemented.


   1:  //
   2:  // Code Snippet 3
   3:  //
   4:   
   5:  public enum TextBoxType
   6:  {
   7:      Integer,
   8:      Decimal
   9:  }
  10:   
  11:  private int _NumberOfFraction = 0;
  12:  private int _NumberOfInteger = 0;
  13:  private bool _AllowNegative = false;
  14:  private TextBoxType _Type = TextBoxType.Integer;
  15:   
  16:  public int NumberOfFraction
  17:  {
  18:      get { return _NumberOfFraction; }
  19:      set { _NumberOfFraction = value; }
  20:  }
  21:   
  22:  public int NumberOfInteger
  23:  {
  24:      get { return _NumberOfInteger; }
  25:      set { _NumberOfInteger = value; }
  26:  }
  27:   
  28:  public bool AllowNegative
  29:  {
  30:      get { return _AllowNegative; }
  31:      set { _AllowNegative = value; }
  32:  }
  33:   
  34:  public TextBoxType Type
  35:  {
  36:      get { return _Type; }
  37:      set { _Type = value; }
  38:  }


Attributes

In order to let the compiler know that there's a resource that should be attached here, we need to add an attribute to the namespace, as you can see in Code Snippet 1. We've specified the path of the JavaScript file following the pattern: "Project Name.Folder Name.File Name".

In Visual Studio, drag and drop any ASP.NET control to your page. It will automatically create the necessary tags and attributes. In order to let our control have the same behavior, we've added an attribute to the class name. Please refer to Code Snippet 1. {0} will be replaced by a value that you specify in your web.config or in any config file. For ASP.NET controls, it's by default asp.

Please refer to Code Snippet 4 to see how you can specify this value in your web.config. So when dragging and dropping our control to a web page, it will look like Code Snippet 5.


   1:  <!--//
   2:  // Code Snippet 4
   3:  //-->
   4:   
   5:  <pages>
   6:  <controls>
   7:  <add tagPrefix="mcc" namespace="MyCustomControls" assembly="MyCustomControls"/>
   8:  .
   9:  .
  10:  .


   1:  <!--//
   2:  // Code Snippet 5
   3:  //-->
   4:   
   5:  <mcc:NumericTextBox Text="" runat="server"></mcc:NumericTextBox>


Override OnPreRender

We need to override OnPreRender to implement the way we want the control to be pre-rendered. In other words, we want to let the OnPreRender method know that we want our control not only do what a normal textbox does, but also have other features.

There are basically two things that we're going to do in the OnPreRender method. The first thing is to add code that will let the method add a reference to our JavaScript file. And, the second this is adding calls to JavaScript functions on certain events. Please refer to Code Snippet 6.


   1:  //
   2:  // Code Snippet 6
   3:  //
   4:   
   5:  protected override void OnPreRender(EventArgs e)
   6:  {
   7:       base.OnPreRender(e);
   8:   
   9:       ClientScriptManager scriptManager = this.Page.ClientScript;
  10:       string resourceFilePath = "MyCustomControls.Resources.NumericTextBox.js";
  11:   
  12:       // This will register a Javascript block witht the name 'NumericTextBoxScript'
  13:       scriptManager.RegisterClientScriptInclude("NumericTextBoxScript",
  14:       scriptManager.GetWebResourceUrl(this.GetType(), resourceFilePath));
  15:   
  16:       if (this.Type == TextBoxType.Decimal)
  17:            this.Attributes.Add("onkeydown", string.Format("return CheckDecimal(this,'{0}','{1}', {2})", NumberOfInteger, NumberOfFraction, _AllowNegative.ToString().ToLower()));
  18:       else if (this.Type == TextBoxType.Integer)
  19:            this.Attributes.Add("onkeydown", string.Format("return CheckInteger({0})", _AllowNegative.ToString().ToLower()));
  20:   
  21:       this.Attributes.Add("onkeyup", string.Format("return CheckNegative(this)", _AllowNegative.ToString().ToLower()));
  22:  }


JavaScript Code


We're going to have three JavaScript functions. The first one, CheckInteger, will be called on the keydown event if the control is working as an integer textbox. The second, CheckDecimal, will be called on the keydown event when the control is working as a decimal textbox. Finally, the third function, CheckNegative, will be called on the keyup event no matter how the control is working.

CheckInteger will simply check whether the ASCII code of the character pressed is within the allowed list. It will also make sure that there's no more than one dash (-) in the textbox.

The reason why this function is being called on the keydown event, not the keyup, is that the keydown event is raised prior to setting the value of the textbox, so I still have a chance to terminate this action. Therefore, if the function returns false on the keydown event, the character won't be added to the textbox.

On the other hand, if the function returns false on the keyup event, nothing will change. However, the benefit of the keyup event is that it allows me to read the value of the textbox, since it's raised after the value has been set.


   1:  //
   2:  // Code Snippet 7
   3:  //
   4:   
   5:  function CheckInteger(allowNegative) {
   6:       if ((event.keyCode >= 48 && event.keyCode <= 57 && event.shiftKey == false) || // 0-9 numbers
   7:            (event.keyCode >= 96 && event.keyCode <= 105 && event.shiftKey == false) || // 0-9 numbers (the numeric keys at the right of the keyboard)
   8:            (event.keyCode >= 37 && event.keyCode <= 40) || // Left, Up, Right and Down
   9:            event.keyCode == 8 || // backspaceASKII
  10:            event.keyCode == 9 || // tabASKII
  11:            event.keyCode == 16 || // shift
  12:            event.keyCode == 17 || // control
  13:            event.keyCode == 35 || // End
  14:            event.keyCode == 36 || // Home
  15:            event.keyCode == 46) // deleteASKII
  16:                 return true;
  17:       else if (event.keyCode == 189 && allowNegative == true) { // dash (-)
  18:            if (sender.value.indexOf('-', 0) > -1)
  19:                 return false;
  20:            else
  21:                 return true;
  22:       }
  23:       else
  24:            return false;
  25:  }

CheckDecimal is very similar to CheckInteger. But they are different in certain things. CheckDecimal will treat a numeric character in a different way than the other allowed keys. This is because when a number is pressed, we need to check if the number of integers and fractions is still within the limits.

In addition, it will have a special treatment to the decimal point character. It shouldn't be the first character in the textbox, and it shouldn't appear more than once.


   1:  //
   2:  // Code Snippet 8
   3:  //
   4:   
   5:  function CheckDecimal(sender, numberOfInteger, numberOfFrac, allowNegative) {
   6:      var valueArr;
   7:   
   8:      if ((event.keyCode >= 37 && event.keyCode <= 40) || // Left, Up, Right and Down
   9:          event.keyCode == 8 || // backspaceASKII
  10:          event.keyCode == 9 || // tabASKII
  11:          event.keyCode == 16 || // shift
  12:          event.keyCode == 17 || // control
  13:          event.keyCode == 35 || // End
  14:          event.keyCode == 36 || // Home
  15:          event.keyCode == 46) // deleteASKII
  16:          return true;
  17:      else if (event.keyCode == 189 && allowNegative == true) { // dash (-)
  18:          if (sender.value.indexOf('-', 0) > -1)
  19:              return false;
  20:          else
  21:              return true;
  22:      }
  23:   
  24:      valueArr = sender.value.split('.');
  25:   
  26:      if (event.keyCode == 190) { // decimal point (.)
  27:          if (valueArr[0] != null && valueArr[1] == null)
  28:              return true;
  29:          else
  30:              return false;
  31:      }
  32:   
  33:      if ((event.keyCode >= 48 && event.keyCode <= 57 && event.shiftKey == false) || // 0-9 numbers
  34:  (event.keyCode >= 96 && event.keyCode <= 105 && event.shiftKey == false)) {  // 0-9 numbers (the numeric keys at the right of the keyboard)
  35:          if (valueArr[1] == null) {
  36:              if (valueArr[0].indexOf('-', 0) > -1)
  37:                  numberOfInteger++;
  38:   
  39:              if (valueArr[0].length <= numberOfInteger)
  40:                  return true;
  41:          }
  42:          else {
  43:              if (valueArr[1].length <= numberOfFrac)
  44:                  return true;
  45:          }
  46:      }
  47:   
  48:      return false;
  49:  }


When the key is up, the CheckNegative function will make sure that the dash/minus character is added to the left.


   1:  //
   2:  // Code Snippet 9
   3:  //
   4:   
   5:  function CheckNegative(sender) {
   6:      if (event.keyCode == 189) { // dash (-)
   7:          if (sender.value.indexOf('-', 0) > 0)
   8:              sender.value = sender.value.replace('-', '');
   9:      }
  10:  }

Implementing a Motor Race Using the Strategy Design Pattern

Introduction


In this article, we will learn about the Strategy Pattern by implementing it on a motor racing game. Strategy pattern is one of the many design patterns defined by the Gang of Four (GoF). A design pattern is a definition of a problem that other developers have faced before you, and they found a solution that might help you if you’re facing the same problem or a similar one. To know more about design patterns, please visit the www.dofactory.com site.

Background


Strategy pattern is used when you have objects that have many things in common but they also have different ways of behavior in certain situations. In this article, we'll design a small game (Motor Race), and we'll use Strategy pattern to implement the design. Again, this design is inspired by a solution that previous developers faced before and where they came up with this design pattern.

Game description


The game is a racing between different mobility motors; cars, motor-bikes, and buses; they all have many shared properties and behaviors, like, Motor Name, Color, but they also have different behaviors on certain points, like: the way that they look and get displayed, or the way they move. Cars and buses move on four wheels, but motor-bikes move on two wheels. The game will have many cars, motor-bikes, and buses racing. All the cars will have the same appearance, the same applies for motor-bikes and buses. Our goal now is to put a design for this game to be used in the client code, keeping in mind that we want our design to be reusable, meaning that if any time I decide to add a new mobility option (like a bike), I don’t want to rewrite the code for it, I'd just want to add the minimum amount of code and reuse the code that is already written. We also need our design not to have any redundant code, meaning if I have a code segment that is repeated in different places, I should group them in one place. Another thing to mention is that we’ll use C# to implement our design.


Using the code


First of all, let’s agree that we have three different types of objects that belong to the same group, and they have things in common; cars, motor-bikes, and buses are all mobility motors, so why don’t we make just one class for all of them and call it MobilityMotor and put all the shared properties in it, and then inherit this class into Car, MotorBike, and Bus? But the pattern doesn’t say so, because it's a better practice to implement an interface rather than extend and inherit a class, so what we should do now is create an interface and call it IMobilityMotor, putting the shared properties and methods there:

  1. // Code 1
  2.  
  3. using System;
  4. namespace MotorRace
  5.  
  6. {
  7.     public interface IMobilityMotor
  8.     {
  9.        // We will add new property later in this
  10.        // article to set the moving behavior of the object
  11.        string MotorName
  12.        {
  13.                get;
  14.                set;
  15.        }
  16.        string MotorColor
  17.        {
  18.                get;
  19.                set;
  20.        }
  21.        void Move();
  22.        void Display();
  23.     }
  24. }

Now, let's implement this interface three times, one for a Car class, one for a MotorBike class, and one for a Bus class. I'll show here how to make a Car class, and you can do the same for the MotorBike and Bus classes.

  1. // Code 2
  2.  
  3. using System;
  4. namespace MotorRace
  5. {
  6.     public class Car : IMobilityMotor
  7.     {
  8.         private string motorName;
  9.         private string motorColor;
  10.         // We will add new property later in this article
  11.         // to set the moving behavior of the object
  12.         public Car()
  13.         {
  14.             motorName = string.Empty;
  15.             motorColor = string.Empty;
  16.         }
  17.         public string MotorName
  18.         {
  19.             get
  20.             {
  21.                 return motorName;
  22.             }
  23.             set
  24.             {
  25.                 motorName = value;
  26.             }
  27.         }
  28.         public string MotorColor
  29.         {
  30.             get
  31.             {
  32.                 return motorColor;
  33.             }
  34.             set
  35.             {
  36.                 motorColor = value;
  37.             }
  38.         }
  39.         public void Move()
  40.         {
  41.             // We will add code later
  42.             // in this article to move object
  43.         }
  44.         public void Display()
  45.         {
  46.             // Add code here to display car,
  47.             // this code is only for car objects
  48.         }
  49.     }
  50. }

Now, just create two new classes for MotorBike and Bus, doing the same as you did for the Car. You will end up with a result that’s shown in the diagram below. Don't pay attention now to the MovingBehavior property in the MotorBike, Car, and Bus classes, you’ll understand it later in this article.



And now, we want to create classes to implement the moving behaviors, so we’ll create an interface and call it IMovingBehavior. This interface will be implemented by two classes: FourWheelsMoving and TwoWheelsMoving, and it will contain a Move() method that will be implemented by the two classes, as follows:

  1. // Code 3
  2.  
  3. using System;
  4. namespace MotorRace
  5. {
  6.     public interface IMovingBehavior
  7.     {
  8.         void Move();
  9.     }
  10. }

Now, let’s implement the IMovingBehavior interface by the FourWheelsMoving class, and then also by the TwoWheelsMoving class.

  1. // Code 4
  2. using System;
  3. namespace MotorRace
  4. {
  5.     public class FourWheelsMoving : IMovingBehavior
  6.     {
  7.         public FourWheelsMoving()
  8.         {
  9.         }
  10.         public void Move()
  11.         {
  12.             // We will add code later
  13.             // in this article to move object
  14.         }
  15.     }
  16. }

Let’s now understand what we have done. We have created two interfaces: one for a mobility motor (cars, motor-bikes, and buses), and another one for the way they move. As we mentioned before, there are two ways to move, either on four wheels or on two wheels. So, we implemented two classes from the IMovingBehavior interface, and we implemented three classes from the IMobilityMotor interface. In this design, we implement a high level of reusability, so if we need to add a new motor in the future, for example, a bike, or a lorry, all that we need to do is to implement a new class for it from IMobilityMotor, and if we have a new motor that moves on three wheels, or a motor that flies like a helicopter, then we just implement a new behavior class from the IMovingBehavior interface.

But the question now is how will a Car object know what its behavior is and the way it should move? To solve this, let’s add a new property to IMobilityMotor to set the correct behavior, and we’ll also add an implementation of this property in the Car, MotorBike, and Bus classes, as follows:

  1. // Code 1 (Updated)
  2.  
  3. using System;
  4. namespace MotorRace
  5. {
  6.     public interface IMobilityMotor
  7.     {
  8.         // We will add new property later in this
  9.         // article to set the moving behavior of the object
  10.         IMovingBehavior MovingBehavior
  11.         {
  12.             get;
  13.             set;
  14.         }
  15.         .
  16.         .
  17.         .
  18.         .

  1. // Code 2 (Updated)
  2. using System;
  3. namespace MotorRace
  4. {
  5.     public class Car
  6.     {
  7.         private string motorName;
  8.         private string motorColor;
  9.         // We will add new property later in this
  10.         // article to set the moving behavior of the object
  11.         IMovingBehavior movingBehavior;
  12.         public IMovingBehavior MovingBehavior
  13.         {
  14.             get
  15.             {
  16.                 return movingBehavior;
  17.             }
  18.             set
  19.             {
  20.                 movingBehavior = value;
  21.             }
  22.         }
  23.  
  24.         .
  25.         .
  26.         .
  27.         .
  28.         .

Now, we should implement the Move() method in the Car, MotorBike, and Bus classes, as follows:

  1. // Code 2 (Updated)
  2. using System;
  3. namespace MotorRace
  4. {
  5.     public class Car
  6.     {
  7.  
  8.         .
  9.         .
  10.         .
  11.         .
  12.         .
  13.  
  14.         public void Move()
  15.         {
  16.             movingBehavior.Move();
  17.             /* Here, the Car object will know that
  18.             movingBehavior is of type
  19.             FourWheelsMoving, because when its value was set
  20.             it was initiated to FourWheelsMoving instance,
  21.             so when we call the Move() method,
  22.             it will call the Move() method
  23.             in FourWheelsMoving class. */
  24.         }
  25.  
  26.         .
  27.         .
  28.         .
  29.         .
  30.         .



Conclusion


So we can now get to this conclusion: the Strategy pattern defines a family of algorithms, encapsulating each one by grouping similar algorithms in one place and separating the parts that vary.

Promotional Code for Udemy ServiceNow CIS - HR Practice Tests

If you're planning to become ServiceNow Certified Implementation Specialist - Human Resources (CIS-HR), you can prepare for the exam usi...