Wednesday, May 23, 2012

DebugHelper Component
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Reflection;

namespace Sample.Diagnostics
{
    /// 
    /// Utility class that helps diagnose problems by retrieving information about the current debug context.
    /// 
    /// This includes information such as the currently loaded assemblies.
    public sealed class DebugHelper
    {
        #region Construction

        /// 
        /// Restricted Constructor
        /// 
        private DebugHelper()
        {
        }

        #endregion

        #region Static Methods

        /// 
        /// Asserts and the throws, making sure that the error gets handled by client code
        /// 
        /// The type of the exception to throw.
        /// the asserted condition
        /// The failure message.
        [SuppressMessage("Microsoft.Design", "CA1004", Justification = "This method instantiates and throws the exception, it can't be passed in")]
        [DebuggerStepThrough()]
        public static void AssertAndThrow(bool condition, string failureMessage) where TException : Exception
        {
            Debug.Assert(condition, failureMessage);
            if (condition == false)
            {
                ConstructorInfo ctor = typeof(TException).GetConstructor(new Type[] { typeof(string) });
                TException exception = (TException)ctor.Invoke(new object[] { failureMessage });
                throw exception;
            }
        }

        /// 
        /// Asserts and the throws, making sure that the error gets handled by client code
        /// 
        /// The type of the exception to throw.
        /// the asserted condition
        [SuppressMessage("Microsoft.Design", "CA1004", Justification = "This method instantiates and throws the exception, it can't be passed in")]
        [DebuggerStepThrough()]
        public static void AssertAndThrow(bool condition) where TException : Exception
        {
            Debug.Assert(condition, "Assertion Failed");
            if (condition == false)
            {
                ConstructorInfo ctor = typeof(TException).GetConstructor(null);
                TException exception = (TException)ctor.Invoke(null);
                throw exception;
            }
        }

        #endregion
    }
}


Date field validation in Jquery using Jquery.validate.js and Date.js
Pre-requisites
  1. Jquery.Validate.js
  2. Date.js
Note: - The below solution is selecting all date fields by looking for the string "datepicker" in the "data-bind" attribute.
Solution
function validateAllDateFields() {
    jQuery.validator.addMethod("myDate", function (value, element) {        
        if (value.indexOf("_") >= 0 || value == "") {
            return true;
        }
        return Date.parse(value, "mm/dd/yyyy");
    },
        " Please enter a valid date"
    );

    $('input[type=text]').each(function (c) {
        var databindAttr = $(this).attr("data-bind");
        if (databindAttr != null) {
            if (databindAttr.indexOf("datepicker") >= 0) {
                $(this).addClass("myDate");
            }
        }
    });

    $('form').validate({
        errorPlacement: function (error, element) {
            var nextElement = element.next();
            if (nextElement != null) {
                error.insertAfter(nextElement);
            }
        }

    });
}

Tuesday, May 22, 2012

Attributes used in Unit Test class in VSTS.


AssemblyInitializeAttribute : Identifies a method that contains code to be used before all tests in the assembly have run and to allocate resources obtained by the assembly. This class cannot be inherited. Only one method in an assembly may be decorated with this attribute.
Usage
    [TestClass]
    public class UnitTestInitializer
    {
        [AssemblyInitialize]
        public static void InitializeAssembly(TestContext context)
        {
            // Initialize AutoMapper
            AutoMapperBootstrapper.Initialize();
        }
    }
ClassIntializeAttribute : Identifies a method that contains code that must be used before any of the tests in the test class have run and to allocate resources to be used by the test class. This class cannot be inherited. Only one instance of this attribute may be applied to a method.
Usage
        [ClassInitialize]
        public static void InitializeClass(TestContext testContext)
        {
            // Inject objects that get instantiated in StructureMap calls outside of the test's control
            ObjectFactory.Inject(new MemoryCacheProvider());
        }
TestInitializedAttribute : Identifies the method to run before the test to allocate and configure resources needed by all tests in the test class. This class cannot be inherited. This method marked with this attribute will run once for every virtual user iteration in the test.
Usage
        [TestInitialize]
        public void InitializeTest()
        {
            var employeeRepository = new EmployeeRepository(new LookupRepository(), new ContactRepository(new UserRepository()));
            _employeeService = new EmployeeService(employeeRepository );
        }
TestMethodAttribute : Used to identify test methods. This class cannot be inherited.
Usage
        [TestMethod]
        public void GetEmployeeTest()
        {
            var emp = _employeeService .GetEmployee(empId);
            Assert.IsNotNull(emp );
            Assert.IsTrue(emp.Id> 0);
        }
The order in which the methods decorated with the above attributes will be run is :
  1. Methods marked with the AssemblyInitializeAttribute.
  2. Methods marked with the ClassInitializeAttribute.
  3. Methods marked with the TestInitializeAttribute.
  4. Methods marked with the TestMethodAttribute.

Saturday, May 19, 2012

A wrapper class to return Json result back to the client.
public class JsonResultWrapper
    {
        public static JsonResultWrapper Create(bool success, string message)
        {
            return new JsonResultWrapper(success, message);
        }

        public static JsonResultWrapper Create(bool success, T data) where T : class
        {
            return new JsonResultWrapperImpl(success, string.Empty, data);
        }

        public static JsonResultWrapper Create(bool success, string message, T data) where T : class
        {
            return new JsonResultWrapperImpl(success, message, data);
        }

        protected JsonResultWrapper(bool success, string message)
        {
            this.Success = success;
            this.Message = message;
        }

        public bool Success { get; private set; }
        public string Message { get; private set; }
    }

    public class JsonResultWrapperImpl : JsonResultWrapper where T : class
    {
        public JsonResultWrapperImpl(bool success, string message, T data)
            : base(success, message)
        {
            this.Data = data;
        }

        public T Data { get; private set; }
    }  

    //How to use this wrapper class.
    public class SampleController : Controller
    {
     public JsonResult Save(Employee emp)
     {
        //Call the Model class to persist the information.
        var id = _employeeService.Save(emp);
        var status = id > 0;
        new Json(JsonResultWrapper.Create(status, "Employee information saved successfully", new SaveResult()
        {Id = id, IsValid = true};
     }
   }

Client code

Role management with Windows Authentication

Solution System.Security.Prinicipal.GenericPrincipal class helps you to create a custom principal. It's constructor takes following parameters.
  • IIdentity Identity - Identity of the current user.
  • string[] roles - Array of current user roles.
Steps to create a custom prinicipal class
  1. Create a custom principal by deriving it from GenericPrinicipal class by passing following parameter values to it's constructure.
    Identity : HttpContext.Current.User.Identity .
    Roles : Array of user roles . User roles can be fetched from the DB or from a service.
  2. Implements the IsInRole virtual property with custom logic to check if the current user is in a specific role.
Components of the solutions LoggedInUser - It contains the properties of the user.
UserRole - it is enumeration of all roles available in the application.
CustomPrincipal - The prinicipal class which is inherited from GenericPrinicipal and implements its construction and IsInRole property.
UserContext - Its a facade class that provides the static method GetPrinicipal() which returns a prinicipal object for the current user.
UserHelper - A static helper class with helper methods to obtain prinicipal, user object and user properties.
Code
    public class LoggedInUser
    {
        public int UserId { get; set; }
        public string UserName { get; set; }
        public string DisplayName { get; set; }
        public UserRole Role { get; set; }
        
        public static LoggedInUser Empty = new LoggedInUser()
        {
            UserName = string.Empty,
            DisplayName = string.Empty,
        };

        public bool IsAuthorized
        {
            get
            {
                return this.UserId > 0 && this.Role != UserRole.Undefined;
            }
        }

        public string[] Roles
        {
            get
            {
                return new string[] { this.Role.ToString() };
            }
        }
    }

    public enum UserRole
    {
        Undefined = 0,
        Representative = 1,
        Manager = 2,
        [Description("System Administrator")]
        Administrator = 3,
        Supervisor = 4
    }
    
    public class CustomPrincipal : GenericPrincipal
    {
        #region Data Members
        
        private List _roles;
        private LoggedInUser _user;

        #endregion

        #region Construction

        public CustomPrincipal(IIdentity identity, LoggedInUser user) : this(identity, user.Roles, user)
        {
        }

        public CustomPrincipal(IIdentity identity, IEnumerable roles, LoggedInUser user) : base(identity, roles.ToArray())
        {
            DebugHelper.AssertAndThrow(identity != null, "No identity passed to principal");
            DebugHelper.AssertAndThrow(user != null, "No user data passed to principal");

            _roles = new List(roles);
            _user = user;            
        }

        public static CustomPrincipal Empty = new MatsPrincipal(new GenericIdentity(""), new List(), LoggedInUser.Empty);

        #endregion

        #region Properties

        public string[] Roles { get { return _roles.ToArray(); } }

        public string UserName { get { return _user.UserName; } } 

        public string DisplayName { get { return _user.DisplayName; } }

        public UserRole Role { get { return _user.Role; } }

        public int UserId { get { return _user.UserId; } }

        public bool IsAuthorized { get { return _user.IsAuthorized; } }

        #endregion

        #region Methods

        public bool IsInRole(UserRole role)
        {
            return IsInRole(role.ToString());
        }

        #endregion
    }
    
    public class UserContext
    {
        public static CustomPrincipal GetPrinicipal(string userName)
        {
           var prinicipal = CustomPrincipal.Empty;
           if (string.IsNullOrEmpty(userName))
           {
               return prinicipal;
           }
           var user = userService.GetLoggedInUser(userName);
           prinicpal = new CustomPrinicipal(HttpContext.Current.User.Identity, user);
           return principal;
        }
    }

    public static class UserHelper
    {
        public static CustomPrincipal CurrentUser
        {
            get
            {
                string userName = UserHelper.CurrentUserName;

                return (userName.IsNullOrWhiteSpace()) ?
                    CustomPrincipal.Empty :
                    UserContext.GetPrincipal(userName);
            }
        }
        
        public static string CurrentUserName
        {
            get
            {
                string userName = (HttpContext.Current != null && HttpContext.Current.User != null) ?
                    HttpContext.Current.User.Identity.Name :
                    string.Empty;

                return userName;
            }
        }
        
        public static int CurrentUserId
        {
            get
            {
                return UserHelper.CurrentUser.UserId;
            }
        }

        public static UserRole CurrentUserRole
        {
            get
            {
                return UserHelper.CurrentUser.Role;
            }
        }
    }