Pages

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();
    }
}

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...