TopMenu

Thursday, 25 February 2016

Sometime it’s required to change a default behavior of an external component. In this blog post we’ll see how to change the validation trigger default behavior. We’ll cover the unobtrusive javascript with Jquery validation with Asp.net mvc application.

Problem – The validation doesn’t trigger while user is entering data in the input field. Default behavior shows errors either on ‘onfocusout’ or when submitting the form.

Solution – Write a custom handler for ‘onkeyup’ event, attach it with JQuery validator and trigger the unobtrusive js event for form invalidation. Here’s the complete code snippet that will do the trick for you by enabling the ‘onkeyup’ event:Explanation -1. Get the validator object.

var $validatr = $('form').data('validator');

2. Adding a new event handler for ‘onkeyup’ event of Validator object. The handler takes two argument the source element and the event occurred. Validate the element, if it’s invalid trigger the unobtrusive form validation event, which would build up the validation errors summary.

Tuesday, 16 February 2016

Recently I came through a post from Rown miller as he created a simple interceptor to log poor performing queries or failing queries. Which really seems promising to track down those queries. Although there already an awesome well known tool Glimpse. This help you tracking down the server processing time and other informational data with very quick setup. It also log the queries if your Asp.net application is using EntityFramework. But it’s limited to Web applications. So what about Windows, WPF and other standalone apps?

I just extended the interceptor class as a library and included the support to introduce a custom logger to write queries on any target. By introducing an Interface for logging:

///<summary>/// Implement this logger for any custom targets where queries should be logged.///</summary>publicinterfaceIQueryLogger{ void Write(paramsstring[] content);
}

Checkout the original interceptor here. I have tweaked it a little to have filter for including StackTrace. Here’s the updated class.

Friday, 5 February 2016

This TypeInitializationException occurs when a Type is failed to load because during Type initialization. Normally, When this exception occurs the InnerException property contains the actual exception details about why the initialization failed. But sometime it happens to be Null and so we have Questions about the same.

Let’s take an example –

classProgram

{

static Program()

{

var initialBootDrive = Directory.Exists("C:\\logs\\BootLogs");

if(!initialBootDrive)

{

thrownewIOException("Directory does not exist");

}

}

staticvoid Main(string[] args)

{

Console.WriteLine("Press any key");

Console.ReadLine();

}

}

This will cause the exception to occur. Because the static constructors can not be called explicitly but will execute when the Type will be first accessed. In this case the Type will be accessed for initialization.

The above case is special case which I want to discuss in this post. The TypeInitialization will occur with null InnnerException.

There is no “View Detais” options. Moreover if click “Copy exception detail to the clipboard”.

You’ll get this –

System.TypeInitializationException was unhandled Message: An unhandled exception of type 'System.TypeInitializationException' occurred in mscorlib.dll Additional information: The type initializer for 'TypeInitializationExceptionTest.Program' threw an exception.

Not much details. Right? There’s no Inner Exception so you’ll never know what causes this exception to occur.

The reason, is that TypeInitializer of Entry method(Main) class is failed. Since no type was initialized at this very moment, so the TypeInitializer has no type information to report about the failed type in TypeInitializationException.

As explained more by Jon Skeet, “Once a type initializer has failed once, it is never retried. The type is dead for the lifetime of the AppDomain. (Note that this is true for all type initializers, not just for types with static constructors. A type with static variables with initializer expressions, but no static constructors, can exhibit subtle differences in the timing of the type initializer execution - but it'll still only happen once.”

But if you remove the static constructor from the Entry Type (i.e. Program) to other class and then refer that class in Entry method. you'll get the InnerException on TypeInitialization exception.

staticclassBootStrapper

{

publicstaticbool Initializing;

static BootStrapper()

{

var initialBootDrive = Directory.Exists("C:\\logs\\BootLogs");

if (!initialBootDrive)

{

thrownewIOException("Directory does not exist");

}

}

}

classProgram

{

staticvoid Main(string[] args)

{

// The first access to the class will cause the static constructor to execute.

BootStrapper.Initializing = true;

Console.WriteLine("Press any key");

Console.ReadLine();

}

}

Now if you run it you’ll get the expected behavior.

Final Remark – Keep the Entry (Main) class as clean as possible from Static member or constructor initialization that throws exception. If necessary either avoid throwing exception, or only throw exception when those member are being accessed in during execution of application.

Monday, 1 February 2016

In previous post we learnt basic understanding of Expression and few insights how Expression represents the code as Data. Also we learn how to compile and invoke an Expression. In this post you’ll learn

We have defined the Lambda type as Func with two argument of int and return type int. Then supply the body and parameters expression. And the expression is complete. Now if you look at the lambda in debug mode it will look like exactly that it supposed to be. Now to execute it, we have to do the same as declared Expressions.

var result = lambda.Compile()(2, 3);

The method can be generalized with generics and then it can be called with any types:

I hope you must be comfortable building the expressions, so let’s move on and build a little complex and useful expression which would help reducing the duplicate code.

Creating a simple dynamic Linq expression

Now we have a class ‘TestDemo’ and we want to convert the list of objects of `TestDemo` to another list of objects of class ‘SelectListItem’. This is a class in Asp.net MVC which represents the items source of HTML Dropdownlist and its very common case. So assuming that we have 10-11 types of such classes like `TestDemo` which would get converted to Dropdownlist to show on view. In real scenario, let’s assume these classes are DbContext entities pulling data from DB and converting them to Dropdownlist compatible objects.

For multiple classes the LINQ would go like:

This code is one of the question from SO. Where the person asked to refactor this code. And ofcourse this looks bit awkward to have same LINQ select criteria repeated to all classes. Now assume if you have such 10-12 classes how the method would look.

So the solution was to create a Generic method which can supply the expression and return the list of ‘SelectListItem’.

This is a generic Extension method for IQueryables so it can be invoked via any IQueryable type. And T is the Type of entity on which this will be invoked. In our case T will be TestDemo, TestDemo1 etc..

To start building the expression we will again break it down to it’s expression tree.

i => newSelectListItem { Text = i.Name, Value = i.Id.ToString() };

So we have following items so far:

Parameters = i

Body = new SelectListItem { Text = i.Name, Value = i.Id.ToString() }

NodeType = Lambda

So let’ start with creating the parameters first:

var paramExpr = Expression.Parameter(typeof(T), "i");

Now we’ll create the body as second step. But I’ll discuss the body part in details because it has a couple of things to perform.

- Create a new object of SelectedListItem

- Fill the properties of the object by parameter i.e. i

- Call ToString() method on i.Id property.

First we need information about the properties of both source and target classes which will get mapped during object creation. Below we have used Reflection to get the property info of both classes and create a map so that we can easily identify the mapping between properties.

Let’s see how our expression look like with Debugger visualizer.Well looks good. Now all we have do is supply this express to Select and everything will be done by LINQ. Add below line to invoke the Expression on Select and return the List.

return source.Select(selectExpression).ToList();

Here’s a complete method source, Now instead of all the if..else from our sample snippet we can simple call this method like:

db.TestDemo1.GetList();

db.TestDemo2.GetList();

db.TestDemo3.GetList();

db.TestDemo4.GetList();

Similarly you can build any type of Expression and use it for Dynamic Linq. The objects mapping tool Automapper is using Expressions to build dynamic projection to map objects.

Hope you enjoyed reading this post. Don’t forget to like/comment/share about posts to support the blog.