Tanzim Saqib on .NET discovery

March 28, 2008

Simple Form Validation - A Reflection based approach

Filed under: .NET, ASP.NET, C# — Tanzim Saqib @ 5:02 pm

Are you tired of placing multiple Validation controls on Form? If you are bored of following scenario like me, keep on reading the post:

Validators

A simple Email address validation can consist of whether

  • The field is empty
  • Longer than limit
  • Email address format is invalid
  • Already in use

Ordinary solution to this problem is placing multiple validation controls for a single TextBox. You can simply it by replacing all with a single Custom Validator. Our goal is to reduce amount of controls on the form to keep it simple. To do that, we would have to write code for Custom Validator that does it all. We also would like to write minimum code to validate the control without compromising manageability. Let us assume we would write the following code inside the ServerValidate of that control:

protected void cvEmailAddress_ServerValidate(object source, ServerValidateEventArgs args)
{
    ValidationController.ValidateControl<ProfileValidator>(cvEmailAddress, ProfileValidator.Fields.EmailAddress.ToString(), args);
}

Let us declare a ValidationErrorResult object that contains error messages and text to display in the UI:

public sealed class ValidationErrorResult
{
    public string ErrorMessage { get; set; }
    public string Text { get; set; }
}

And an Attribute which would be used to tag a specific method which would be responsible for validation of particular control:

[AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)]
public sealed class ValidationMethodAttribute : Attribute
{
    public ValidationMethodAttribute(string fieldName)
    {
        this.FieldName = fieldName;
    } 

    public string FieldName { get; private set; }
}

If you are already familiar with Attirbute based programming, I hope you know the attribute of this piece of code is in fact ValidationMethod. We will soon see how to use this. The following is the method that checks the value and make a list of ValidationErrorResult that consists of which rules got failed. Notice that the ValidationMethod attribute contains the field name of the object which determines no matter whatever your method name is, that field name helps Validation controller to find this method out for validation.

[ValidationMethod(“Email”)]
public static List<ValidationErrorResult> ValidateEmail(object value)
{
    var email = value as string;
    var results = new List<ValidationErrorResult>(); 

    // Blank
    if (string.IsNullOrEmpty(email))
        results.Add(new ValidationErrorResult()
        {
            ErrorMessage = “You did not provide an Email Address.”,
            Text = “Cannot be left blank”
        }); 

    // Length 128
    if (email.Length > 128)
        results.Add(new ValidationErrorResult()
        {
            ErrorMessage = “You exceeded length limit.”,
            Text = “Keep it less than 129 characters”
        }); 

    // Valid Email Address
    if (!Regex.IsMatch(email, “^[\\w\\.\\-]+@[a-zA-Z0-9\\-]+(\\.[a-zA-Z0-9\\-]{1,})*(\\.[a-zA-Z]{2,3}){1,2}$”))
        results.Add(new ValidationErrorResult()
        {
            ErrorMessage = “You provided an invalid Email Address.”,
            Text = “Invalid Email Address”
        }); 

    // Is Already In Use
    if (IsAlreadyInUse(email))
        results.Add(new ValidationErrorResult()
        {
            ErrorMessage = “You provided an invalid Email Address.”,
            Text = “Invalid Email Address”
        }); 

    return results;
}

Here is the ValidationController which goes through the Validation class and looks for the method that has the attribute which validates the control’s value.

public class ValidationController
{
    public static List<ValidationErrorResult> Validate<T>(string fieldName, object value)
    {
        var results = new List<ValidationErrorResult>();
        var type = typeof(T);
        var methods = type.GetMethods(BindingFlags.Static | BindingFlags.Public); 

        var method = methods.Single<MethodInfo>(delegate(MethodInfo m)
        {
            return ((ValidationMethodAttribute[])m.GetCustomAttributes(typeof(ValidationMethodAttribute), false))[0].FieldName == fieldName;
        }); 

        return (List<ValidationErrorResult>)method.Invoke(null, new object[] { value });
    } 

    public static void ValidateControl<T>(CustomValidator validator, string fieldName, ServerValidateEventArgs args)
    {
        var results = Validate<T>(fieldName, args.Value); 

        if (!(args.IsValid = !(results.Count > 0)))
        {
            validator.ErrorMessage = results[0].ErrorMessage;
            validator.Text = results[0].Text;
        }
    }
}

March 1, 2008

LINQ to Flickr

Filed under: .NET, C#, LINQ — Tanzim Saqib @ 4:06 pm

One of my colleagues Mehfuz Hossain developed a wonderful open source project which allows you to query Flickr photos by LINQ, also lets you insert, delete photos directly to/from Flickr. You wonder how to extend LINQ in such an amazing way? It’s easy by writing your own custom LINQ provider, which was not-so-easy until he came up with another handy open source project named LINQ Extender. He did all the expression parsing stuff to ease our pain. Now you can make your own LINQ to Anything using this so easily.

For your heads up on LINQ extenders, here he wrote an article and LINQ to Flickr, open source project is hosted at Codeplex.

February 6, 2008

A "transactional" generic DbHelper for LINQ to SQL

Filed under: .NET, C#, LINQ — Tanzim Saqib @ 7:34 am

In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer. When the application runs, LINQ to SQL translates into SQL the language-integrated queries in the object model and sends them to the database for execution. When the database returns the results, LINQ to SQL translates them back to objects that you can work with in your own programming language. You may want to make a data access layer that separates the data operation from business layer like the following:

DbHelper.Insert<Student>(
    new Student()
    {
        FirstName = “Tanzim”,
        LastName = “Saqib”,
        Email = “me@TanzimSaqib.com”,
        Website = “http://www.TanzimSaqib.com”
}, true);    // Use Transaction?

To make use of such transactional generic DbHelper, you might want to write a singeton DbHelper class like the following. You might notice that the class is singleton, it’s static and the DataContext is being used is private, and only initialized using the connection string if not yet.

public static class DbHelper
{
    private const string CONNECTION_CONFIG_NAME = “StudentServerConnectionString”;

    private static StudentServerDataContext _StudentServerDataContext = null;

    public static StudentServerDataContext GetDataContext()
    {
        if(_StudentServerDataContext == null)
            _StudentServerDataContext = new StudentServerDataContext
                (ConfigurationManager.ConnectionStrings
                [CONNECTION_CONFIG_NAME].ConnectionString);

        return _StudentServerDataContext;
    }

    public static void CleanUp()
    {
        _StudentServerDataContext.Dispose();
        _StudentServerDataContext = null;
    }

    // … code edited to save space

On application wide error or on end you can dispose the context so CleanUp method is useful here. To implement an Insert method see the following. You will find I have used a TransactionScope which ensures that the transaction is taking place without any interruption. If there is really any error the scope.Complete() method never gets invoked. This is how it ensures that the code inside the TransactionScope is taking place as a transaction. It is available from .NET 2.0 framework.

public static void Insert<T>(T t, bool isTransactional) where T : class
{
    if (isTransactional)
    {
        using (var scope = new TransactionScope())
        {
            Insert<T>(t);

            // On any Exception, Complete() method won’t be invoked.
            // So, the transaction will be automatically rollbacked.
            scope.Complete();
        }
    }
    else
        Insert<T>(t);
}

public static void Insert<T>(T t) where T : class
{
    using (var db = GetDataContext())
    {
        db.GetTable<T>().InsertOnSubmit(t);

        try
        {
            db.SubmitChanges();
        }
        catch (Exception e)
        {
            // TODO: log Exception
            throw e;
        }
    }
}

I did not show other methods as part of the CRUD implementation. The rest is left open for you to implement.

February 5, 2008

[New Article] 7 ways to do Performance Optimization of an ASP.NET 3.5 Web 2.0 portal

Filed under: .NET, ASP.NET, C#, LINQ, Workflow — Tanzim Saqib @ 5:29 am

Web 2.0 applications are widely developed. These applications often work with third party contents, aggregate them, make various use of them and then make something useful and meaningful to the users. For the past few years, developers were also engaged with such endeavors and a lot of their websites have not addressed performance issues, thus resulting in an unpleasant experience to the users.

Performance is a vast area and great results can never be achieved by a silver bullet. This article explores some of the key performance issues that can occur while developing a Web 2.0 portal using server side multithreading and caching. It also demonstrates model driven application development using Windows Workflow Foundation.

URL: http://dotnetslackers.com/articles/aspnet/SevenWaysToDoPerformanceOptimizationOfAnASPNET35Web20Portal.aspx

January 25, 2008

HttpRequestFactory vs. XMLHttpRequest in Volta

Filed under: .NET, C#, Volta — Tanzim Saqib @ 5:21 pm

HttpRequestFactory was designed for use by tiersplitting internally and was not supposed to be exposed as part of the Volta API as Danny van Velzen from Microsoft Volta team told me today. So, its better if you use XMLHttpRequest instead because this factory class might not show up in the later releases. You will find this class in Microsoft.LiveLabs.Volta.Xml namespace.  As like as JavaScript’s one, in this .NET version you can also Open URL, specify method name, and of course pass credentials. You can track response text, xml, status code, status text and also you can abort.

To retrieve your content, you must subscribe to ReadyStateChange event with a HtmlEventHandler which you can find in Microsoft.LiveLabs.Volta.Html namespace and check the status code. If it is 200 that means "HTTP OK", you can take the ResponseText or ResponseXML. See this example:

string content = string.Empty;
var request = new XMLHttpRequest();

request.ReadyStateChange += delegate()
{
    if (request.Status == 200)
        content = request1.ResponseText;
};

request.Open("POST", "http://tanzimsaqib.com/feed/", true);

However, you cannot fetch cross domain content by XMLHttpRequest. The Volta compiler creates client side JavaScript XMLHttpRequest and lets developers write code in .NET friendly way. So, I do not think there is any way to retrieve cross domain content in Volta, and leaving us on the same old HttpRequest class.

Newer Posts »

Powered by WordPress