Extending EntLib VAB - Part 2.2: Enable unobtrusive jQuery validation for Custom Validator

3 comments


Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

… Continuation from Extending EntLib VAB - Part 2.1: Create custom validators and integrate that with EntLib CABC.

Now lets see how we can enable client side unobtrusive validation for this custom validator by creating adapter for the same and adding the adapter in our custom implementation of DataAnnotationsModelValidatorProvider  (explained in Extending EntLib VAB - Part 1: Enable client side support EntLib VAB and align the validation error keys with MVC ModelState keys) and finally writing unobtrusive jQuery validation.

Extending EntLib VAB - Part 2.1: Create custom validators and integrate that with EntLib CABC

0 comments


Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

Here is the second last installment post of this series. If you are interested in checking the earlier posts here are the links: Extending Enterprise Library (EntLib) Validation Application Block (VAB) – Introduction, Extending EntLib VAB - Part 1: Enable client side support EntLib VAB and align the validation error keys with MVC ModelState keys (I strongly suggest to check at least part 1 of this series as we are going to reuse here a component that we have developed in that post).

In this post we will see how to develop a custom validator for EntLib VAB. If you are developing a custom validator, there are several aspects you have to take care for: Obviously the first and foremost is write your actual validator that works on server side and integrate that with CABC, next is to enable client side validation for your validator (now when we are talking about client side validation, in ASP.NET MVC it is important to write the client side validation in jQuery unobtrusive validation to provide your end user similar kind of experience as they have with other Out-Of-The-Box validators) and lastly as you are working with EntLib provide support so that your custom validator also seamlessly integrates with EntLib Configuration Application Block Console (CABC). In this post we are going to cover all of these.

Extending EntLib VAB - Part 1: Enable client side support EntLib VAB and align the validation error keys with MVC ModelState keys

13 comments


Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

As discussed in my last post EntLib VAB doesn't support client side validation (in js/jQuery) out-of-the-box. And also while validating object graph, EntLib VAB generate Validation Result keys which are different from the ModelState keys in MVC.

In this post we will discuss on this problem.

Solution to this problem is simple. We just need to create an adapter for EntLib VAB validator to MVC ValidationAttribute, i.e. a piece of code is needed that will read the EntLib Validation configuration xml and for each validator it will return the MVC counterpart of the validator, i.e. ValidationAttribute.

As for aligning the validation error keys with MVC ModelState keys, we need to leverage the default model validation of ASP.NET MVC.

And the great news is that one single piece of code addresses combines these two solutions.

Extending Enterprise Library (EntLib) Validation Application Block (VAB) - Introduction

0 comments


Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

Why EntLib VAB?

Those who have worked with ASP.NET MVC know how easily one can implement the model validation using Data Annotation. On top of that, jQuery unobtrusive validation support makes it more enjoyable.

However, for a complex requirement you may want to change the validation specification based on some condition. For example, let us assume that you are working on a multi-tenant application where for same UI screen each tenant requires a different set of validation specifications. Say the end users in U.S. expecting date field to be in ‘mm/dd/yyyy’ format, but for same field end users in India expecting ‘dd/mm/yyyy’ format. Now this is really a simple change of regular expression for the date property in the model. However as the Validation Data Annotations are actually attributes, you cannot change the actual regular expression at run time.

Therefore, the most simplistic solution could be to make different models per tenant having just a different set of validation specification. Nevertheless, if you do that, the application will not be multi-tenant in its true sense, not to mention the other associated downside of it like maintaining a large library of models per tenant, making different views, controllers, areas and so on.

Next thing you can do is to make complex Custom Validation Attribute as shown here just to make the validation specifications dynamic (or tenant specific per say).

So to mitigate the issue and to have a lot cleaner and manageable solution, Enterprise Library Validation Application Block can be utilized. Using EntLib Configuration Application Block Console (CABC), you can create tenant specific validation configuration on your Model and inject appropriate validation configuration at runtime. EntLib VAB comes with a set of useful validators like Not Null Validator (Required in MVC), Regular Expression Validator, String Length Validator, Property Compare Validator and so on. It also gives a facility to the developers so that they can design and develop their own validators and integrate the same with EntLib CABC.

So in a way it’s awesome… well almost.

ASP.NET MVC: ActionNameSelector and ActionMethodSelector (or another approach to submit form to multiple action methods) – Part II

0 comments


Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

Hope you enjoyed the first part of this blog post.

In this part I’ll discuss about how you can make your own ActionMethodSelector Attribute (though I'll use the out-of-the-box ActionNameSelectorAttribute ActionNameAttribute).

Lets first discuss the problem statement: I’ve one form which has two radio buttons and I want the form to be posted to two different Action Methods based on selection.

ASP.NET MVC: ActionNameSelector and ActionMethodSelector (or another approach to submit form to multiple action methods) – Part I

0 comments

Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

At work I have recently faced a requirement to post a single form to multiple Action methods in a controller based on the context. For example, in the view there is a Form and there are several radio buttons; now my form should be posted to the Action method based on the radio button selection.
As usual I Googled it and found that internet is glutted with various approaches. Some of them are: 1. Posting to single action method and use a switch mechanism inside it, 2. Using multiple forms, 3. Using named submit button and assigning different values to those.
However there is one concept that I liked most and that is making use of ActionNameSelector and ActionMethodSelector.

What are these?
Well these are attributes that influence/affects the selection of action methods… yes you got it right. I’ve quoted it from MSDN and just like some of you (maybe) I didn't understood a thing when I read those lines... ;)
You can check the below MSDN links:
ActionNameSelectorAttribute Class, ActionMethodSelectorAttribute Class.
Hmmm… so what are these anyway. 

Filter an object array using delegates, without using LINQ

0 comments

Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

Variant 1: Filtering a .net simple type array using delegate

Using delegate filter an array of Integers. Delegate takes to arguments, one is the value from the array and the second one is the number, the array member with value greater than this number will be returned(filtered).
Declaration:

   1: public static class Common
   2:     {
   3:         public delegate bool IntFilter(int value, int number);
   4:  
   5:         public static int[] FilterArrayOfInts(int[] ints, IntFilter filter)
   6:         {
   7:             ArrayList aList = new ArrayList();
   8:             foreach (int i in ints)
   9:                 if (filter(i, 30))
  10:                     aList.Add(i);
  11:             return (int[])aList.ToArray(typeof(int));
  12:         }
  13:  
  14:     }
  15:  
  16: public class Filters
  17: {
  18:     public static bool GreaterThanNumber(int value, int number)
  19:     {
  20:         return value >= number;
  21:     }
  22: }

Invocation:
   1: int[] targetArray = { 10, 20, 30, 60, 50, 25 };
   2: int[] filteredArray = Common.FilterArrayOfInts(targetArray, Filters.GreaterThanNumber);
   3: Console.WriteLine("====Filtered Array====");
   4: foreach (int num in filteredArray)
   5:     Console.WriteLine(num);

Output:

Customizing Validation Attributes in MVC

2 comments

Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

Background

As many of you already know, MVC provides validation attribute functionality to validate view models. A few very commonly used validation attributes are: Required, RegularExpression and Range. Below is one simple example:


public class Person
    {
        [Required(ErrorMessage = "Please Enter your name")]
        public string Name { get; set; }
 
        [Required(ErrorMessage = "Please Enter your Email")]
        [RegularExpression(".+\\@.+\\‥+", ErrorMessage = "Please Enter valid Email")]
        public string Email { get; set; }
 
        [Required(ErrorMessage = "Please Enter your Phone")]
        public string Phone { get; set; }
    }


Which will give you the following output:
This default behavior is good for less complex application, where you can apply factory made validation without any considerable effort from your side.

You can also enable client side validation(validation will be done at client side without server post back) by adding/modifying the following lines in the
1. Web.config file:
<configuration>
  <appSettings>
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
</configuration>

2. Layout / View page (of course you can use the latest version of jQuery):
    <script src="~/Scripts/jquery-1.9.1.min.js"></script>
    <script src="~/Scripts/jquery.validate.min.js"></script>
    <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>


So far so good, Now lets complicate it

Lets assume that this application is going to be used by people from different regions and every region has a specific format for phone number. Every region has a separate set of special characters to be allowed for the phone number.

ASP.NET Session State Modes: Some bullet points

0 comments

Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

Dive directly into topic, No beating around the bush

ASP.NET session state mode can be broadly classified into two modes: In-Proc and Out-Of-Proc.

As the name suggests In-Proc mode maintains session state data in memory of the web server. This means if the web application or the IIS restarts the session data is lost.

Out-Of-Proc maintains the data separately outside the memory of web server. This means your session data is not lost even if the web application/IIS restarts. This mode can again be classified into three categories: StateServer, SQLServer and Custom.

Fastest way to find row count of all tables in SQL

0 comments


Below is the syntax for the query which does exactly what the title suggests.


SELECT  T.NAME AS [TABLE NAME],I.ROWS AS [ROWCOUNT] 
FROM SYS.TABLES AS T INNER JOIN SYS.SYSINDEXES AS I 
ON T.OBJECT_ID = I.ID AND I.INDID < 2 
ORDER BY I.ROWS DESC 


.NET: Asynchronous Callback Approach in ADO.NET

1 comments

Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

I am studying Professional ASP.NET 4 in C# and VB book from Wrox Publication. It is a great book with really easy-to-understand basic examples. As I'm a novice in ASP.NET/.NET Framework, it really helped me a lot in understanding the technology. Wrox also lets you download the codes used in the examples in the books. Anyone interested can download the same from this link: Code for Professional ASP.NET 4 in C# and VB.

But sometimes, I found some mistakes in the examples, provided in the book. I tried the same code in my machine, but I was unable to produce the desired result. So  I'm going to discuss on a similar mistake I've found in the book recently and also going to discuss the workaround.

We're going to discuss on Asynchronous Callback Approach in ADO.NET. Before we jump straight  into the topic first let me explain what is Asynchronous Processing in ADO.NET.

Introduction

In general, in ADO.NET, each command is executed sequentially, i.e. code waits for the previous command to be completed before it starts executing the next command.
Asynchronous approach lets you do the processing in a parallel manner. Using this approach two sql commands can be executed in parallel using the same connection.This comes real handy when you are dealing with multiple data sources, like you have two GridView controls in your page, one for displaying employee's personal details, another for displaying the employee's payment change history. Apart from processing the command executions in parallel it also lets you perform other tasks(those are not dependent on the output of command execution) without completing the command execution.

SQL : CSV To Table using xml

0 comments

Note: Thank you for visiting my blog. However, this blog is not maintained actively anymore. This post is now also in my new blog. Feel free to leave a comment there.

In this article I'm going to discuss about how to convert a comma separated string to a table to enable it for set based operation. 
Lets say we've a table which has the definition like this :

Create Table Employee 
(     
    EmpId Int,     
    EmployeeName varchar(100) 
)

Problem Statement
You need to retrieve  Employee Name based on EmpId provided. Now it is easier to retrieve the data when you have the EmpIds separately and the same can be used as below :
Select * from Employee where EmpId in (10,21,32,43,54,74,78,47,56,12,68)
The above query treats every EmpId separately. Now what if you get all the EmpIds in a single comma separated string like : '10,21,32,43,54,74,78,47,56,12,68,'. In that case you can not write query as below:
Select * from Employee where EmpId in ('10,21,32,43,54,74,78,47,56,12,68,')
The above query will not treat the EmpIds separately, but as a single csv string as a result this query will produce an erroneous result or may not parsed at all.