Wednesday, February 27, 2013

Telerik ASP.Net MVC Grid–Ajax binding boolean property

When you bind a collection of objects that have a boolean property on them and if you use server side binding, the columns are automatically rendered as check-boxes. But instead, if you use AJAX binding with the telerik MVC grid, they get rendered as literal texts (“true” or “false”). To fix it, what you need to do is to set the ClientTemplate. Here is an example:

grid.Columns(columns => {
columns.Bound(o => o.Value).ClientTemplate("<input type='checkbox' <#=Value?'checked':''#> disabled />");

Where the code that’s highlighted is the binding code and “Value” is the property to which I am binding. Also, I am using the ternary operator to output “checked:’’” if its true, else it outputs nothing.

  

Sunday, February 24, 2013

Javascript–Convert URLs in text to links

Was looking for some code to convert urls in strings to url anchors. Came across this post (JMRWare) and below is the extracted code for javascript:

Thursday, February 21, 2013

ASP.Net MVC–Authorize filter that loads users and roles from the application configuration file

I needed the ability to set the Authorization filter from a config file (instead of setting the roles and users directly on the controller). The main reason for this is that I needed different roles to be authorized to hit the action based on the environment to which it was deployed (dev,qa, prod).

Here is the code:

Saturday, February 16, 2013

C#–Determining if an object implements or derives from a generic class or interface

Imagine you have a generic class and interface that are defined as follows:

public abstract class MyGenericClass<T>
{
}
public interface IMyGenericInterface<T>
{
}

If you were to derive or implement from the above class/interface, you will find that you cannot use the “is” keyword to determine if that class implements or derives from the above interface. Here is what I mean: If I were to implement/derive from the base class like so:

public class MyInt:MyGenericClass<int>
{
}

public class MyInterfacedInt:IMyGenericInterface<int>
{
}

Then I can do the following: (code will run in LinqPad)

MyInt myInt = new MyInt();
MyInterfacedInt myIInt = new MyInterfacedInt();

(myInt is MyInt).Dump();//true
(myIInt is MyInterfacedInt).Dump();//true;

(myInt is MyGenericClass<int>).Dump();//true
(myIInt is IMyGenericInterface<int>).Dump();//true;

But I cannot do the following:

//Will not compile
//(myInt is MyGenericClass<>).Dump();
//(myInt is IMyGenericInterface<>).Dump();

Why is this important? If you plan on loading plugins at run time, then all you know is that they will implement an interface or a base class and you need to check that. One way around this would be to create a non-generic base class or interface and check against that. But that might not be a possibility if you are using a 3rd party API (eg: Prism and the CompositePresentationEvent<> type).

So here is a helper class that can do just that:

static class ReflectionHelper
{
    public static bool IsDerivedOrImplementedFrom<T>(this T objectToCheck, Type parentType) where T : class
    {
        if (objectToCheck == null)
            return false;
        if (parentType.IsInstanceOfType(objectToCheck))
            return true;

        bool checkingInterfaces = parentType.IsInterface;
        Type toCheck = objectToCheck.GetType();
        while (toCheck != null && toCheck != typeof(object)) {
            var cur = toCheck.IsGenericType ? toCheck.GetGenericTypeDefinition() : toCheck;
            if (checkingInterfaces)
            {
                bool implementsParentInterface = toCheck.GetInterfaces()
                                            .Any(ci => {
                                                return ci.IsGenericType ? ci.GetGenericTypeDefinition() == parentType :
                                                    ci == parentType;
                                            });
                if (implementsParentInterface)
                    return true;
            }
            else
            {
                if (parentType == cur)
                {
                    return true;
                }
            }
            toCheck = toCheck.BaseType;
        }
        return false;
    }

}

And here is how you call it:

static void Main(string[] args)
        {
            MyInt myInt = new MyInt();
            MyInterfacedInt myIInt = new MyInterfacedInt();

            "Using the \"is\" keyword".Dump();

            (myInt is MyInt).Dump();//true
            (myIInt is MyInterfacedInt).Dump();//true;

            (myInt is MyGenericClass<int>).Dump();//true
            (myIInt is IMyGenericInterface<int>).Dump();//true;

            //Will not compile
            //(myInt is MyGenericClass<>).Dump();
            //(myInt is IMyGenericInterface<>).Dump();

            "Using IsDerivedOrImplementedFrom".Dump();
           
            myInt.IsDerivedOrImplementedFrom(typeof(MyInt)).Dump(); //true
            myIInt.IsDerivedOrImplementedFrom(typeof(MyInterfacedInt)).Dump();//true
            myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<int>)).Dump();//true
            myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<int>)).Dump();//true

            myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<>)).Dump();//true
            myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<>)).Dump();//true

            "Negative tests Using IsDerivedOrImplementedFrom".Dump();

            myInt.IsDerivedOrImplementedFrom(typeof(MyInterfacedInt)).Dump(); //false
            myIInt.IsDerivedOrImplementedFrom(typeof(MyInt)).Dump();//false
            myInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<string>)).Dump();//false
            myIInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<string>)).Dump();//false

            myInt.IsDerivedOrImplementedFrom(typeof(IMyGenericInterface<>)).Dump();//false
            myIInt.IsDerivedOrImplementedFrom(typeof(MyGenericClass<>)).Dump();//false

            Console.ReadLine();
        }

Here is the full code: http://pastebin.com/raw.php?i=Y2nSQc7V

Thursday, February 07, 2013

Linqer–Sql to Linq tool

Came across Linqer, a Sql to LINQ conversion tool. From some preliminary tests, I found that it worked pretty well given some complex queries.

Unfortunately, there is no free version of the tool and it costs $60. This would be a fabulous tool within LinqPad. Hopefully someday LinqPad will include this functionality.

Syncfusion Succinctly Series of ebooks

I have been enjoying the SyncFusion suite of products for about 4 months now. Apart from a stellar set of UI tools, what I have liked about Syncfusion is the constant communication that they provide the developer community. One example of this is the Succintly series of e-books that they release periodically.

You can check out the list of books that they have at: http://www.syncfusion.com/resources/techportal

I found that the jQuery and Javascript books were useful for me as refreshers when I was getting back into Asp.Net MVC programming after spending a while in classic Asp.Net and Silverlight. In addition, I had provided the book on data-structures to a junior developer at work and he liked it very much (and actually noted that it better explained some concepts than his teacher did). I am also interested in looking at the books on Objective-C and GIS.

Just about the only thing I hate about the succintly series is that I need to enter my contact information each time I get download a book from the series. (especially since I have already logged into the site).

Oh! and while you are on their site, get their Metro Studio product for free. It’s the best free resource for metro style icons.

Disclaimer: I received a free copy of Syncfusion’s tools as a door prize at the Denver Visual Studio user group meeting and Syncfusion is also providing me a small cash compensation for this post. But, none of that influenced the comments in this post. I meant to post this as a resource long before I was contacted by Syncfusion.

Monday, January 28, 2013

Convert an object’s property values to a dictionary of string,object

Here is a simple helper function that converts any class object to a dictionary of string,object, where the key is the PropertyName:

public static class ReflectionHelper
{
    public static IDictionary<string, object> ToDictionary<TModel>(this TModel model)
   {
       BindingFlags publicAttributes = BindingFlags.Public | BindingFlags.Instance;
       Dictionary<string, object> dictionary = new Dictionary<string, object>();

       foreach (PropertyInfo property in model.GetType().GetProperties(publicAttributes))
       {
           if (property.CanRead)
               dictionary.Add(property.Name, property.GetValue(model, null));
       }

       return dictionary;
   }
}

public class Test
{
    public string Name{get;set;}
}

void Main()
{
    Test t = new Test{Name = "Raj Rao"};
    foreach(var v in t.ToDictionary())
    {
           Console.WriteLine(v.Key + ":" + v.Value);
    }

}

The output will be:

Name: Raj Rao

This again was inspired by some of the Helper functions available in Asp.Net’s MVC HTML helper class.

Getting rid of magic strings that point at PropertyNames

Often times, you end up with code that includes magic strings that point at property names of a class. I hate this, because it normally ends up causing runtime errors instead of compile time errors.

While working with Asp.Net MVC, I found that you could pass properties to helper methods (such as Html.TextBoxFor) and it would automagically figure out the name of the property and use it to build out the ID and Name fields of the html object. I wanted something similar to that and here is my code:

//The helper class that provides the “GetPropertyName” method
public static class ReflectionHelper
{
    public static string GetPropertyName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> expression)
    {
        MemberExpression body = (MemberExpression) expression.Body;
        return body.Member.Name;
    }
}

//A test class to test what we are doing
public class Test
{
    public string Name{get;set;}
}

//A simple test
void Main()
{
    Test t = new Test();
    Console.WriteLine(t.GetPropertyName(m => m.Name));
}

Monday, December 31, 2012

Sql Server Schema Comparision tool: Open DBDiff

Came across a nice open source tool that allows you to perform schema compares on Sql-Server. I liked it and wanted to share it!

Link: http://opendbiff.codeplex.com/

Description from the codeplex site:

Open DBDiff is an open source database schema comparison tool for SQL Server 2005/2008.
It reports differences between two database schemas and provides a synchronization script to upgrade a database from one to the other.

Screen1.jpg

Sunday, December 09, 2012

jqZoom–Javascript image zooming plugin

Came across this useful jQuery plugin called jqZoom that allows you to setup image zooming on your web-pages: http://www.mind-projects.it/projects/jqzoom/

image