Tuesday, December 4, 2012

Web API Sample

Web Api framework is Http based and can be accessed from broad range of clients like Browser, Mobile App etc.

REST uses some common HTTP methods to insert/delete/update/retrieve information. These Http methods are:
1.GET - Requests a specific representation of a resource
2.PUT - Creates or updates a resource with the supplied representation
3.DELETE - Deletes the specified resource
4.POST - Submits data to be processed by the identified resource

Data Type supported:

  • XML
  • JSON
  • ATOM

This sample application demonstrates how to use Web API framework to return all posts from your blog in Json format.
My Blogs
    Add Blog
    Delete Blog
    public class BlogPost
    {
       public int Id {get; set;}
       public string Title {get; set;}
       public string Content {get; set;}
       public string Labels {get; set;}
    }
    
    public namespace SampleWebApi.Controllers
    {
        using System.Net;
        using System.Net.Http;
        using System.Web.Http;
    
        
    
         public class BlogController:ApiController    
            {
                static List posts = new List  
                    {              
                        new BlogPost{ Id = 1, Title= "Web Api Framework on .NET", Content = "services exposed over plain HTTP", Labels= "" },              
                        new BlogPost{ Id = 2, Title= "MVC4", Content= "Mobile Support", Labels= "" },              
                        new BlogPost{ Id = 3, Title = "KnockoutJS", Content= "Javascript based MVVM framework", Labels= ""}          
                    };
    
    
                public BlogPost GetBlogPost(int id)
                {
                    return posts.Find(m => m.Id == id);
                }
    
                public IEnumerable GetAllPosts()        
                {              
    
                    return posts;        
                }
    
                public BlogPost PostBlog(BlogPost post)
                {
                    posts.Add(post);
                    return post;
                    
                }
    
                public void PutBlog(int id, BlogPost post)
                {
                    var blog = posts.Find(m => m.Id == id);
                    blog.Title = post.Title;
                    blog.Content = post.Content;                
                }
    
                public void DeleteBlog(int id)
                {
                    var post = posts.Find(m => m.Id == id);
                    posts.Remove(post);
                }
            }
    }
    
    
    
    

    What is new in ASP.NET 4.5

    URL - http://www.asp.net/vnext/overview/aspnet/whats-new

    Friday, November 23, 2012

    Generic based Configuration Settings Reader


    Interface to read any config file Implementation

    How to Log custom information in Workflow Foundation 4

    To log exception details and any custom information inside your workflow, you need

    1. A reference to Microsoft's SqlTrackingParticipant assembly. For the source code of SqlTrackingParticipant component and the schema of the Tracking Database, use the link Windows Communication Foundation (WCF) and Windows Workflow Foundation (WF) Samples for .NET Framework 4.
    2. Develop a Custom Activity using the below code.Use this activity inside your workflow and set the important properties that you want to log into the tracking database.
    3. Add below Configuration in the Web.Config file of your workflow project.
    References http://msdn.microsoft.com/en-us/library/ee622983.aspx

    Friday, October 19, 2012

    Getting Entity Framework Exception Details

    Sunday, October 7, 2012

    Could not load file or assembly 'SqlTrackingParticipant' or one of its dependencies. An attempt was made to load a program with an incorrect format

    Problem Statement:   Could not load file or assembly 'SqlTrackingParticipant' or one of its dependencies. An attempt was made to load a program with an incorrect format

    Solution :  CLR is unable to load the assembly because the assembly is not complied in X64 platform. Change it to "Any CPU" using "Right Click on the Project -> Properties -> Build -> Platform target.

    Friday, October 5, 2012

    highlighting a row in JqGrid based on a column value

    function hightlightGridRows(grid, colName, valueToCheck) {     
        var grid_ids = grid.jqGrid('getDataIDs');
        var rowcount = grid_ids.length;
        var columnNames = grid.jqGrid('getGridParam', 'colNames');
        
        $.each(columnNames, function (i, v) {
            columnNames[i] = v.toUpperCase();
        });
    
        var colNameInUpper = colName.toUpperCase();
    
        if ($.inArray(colNameInUpper, columnNames) > -1) {
            for (var counter = 0; counter < rowcount; counter++) {
                var rowid = grid_ids[counter];
                var aRow = grid.jqGrid('getRowData', rowid);
                var celldata = grid.getCell(rowid, colName);
    
                if (celldata == valueToCheck) {
                    var trElement = $("#" + rowid, grid);
                    trElement.removeClass('ui-widget-content');
                    trElement.addClass("gridHighlightRow");
                }
            }
        }
        else {
            alert("Invalid column name to evaluate the condition for highlighting rows in the grid");
        }
    
    }
    
    where
    ui-widget-content = It is css class that is applied by default to a JqGrid row.
    gridHighlightRow = It is the custom css class to highlight grid row.
    References: http://tpeczek.codeplex.com/

    Update an item of a querystring using Jquery

    function updateQuerystring(str, itemToReplace, value) {
        if (str != null) {
            var pairs = str.split('&');
            $.each(pairs, function (i, v) {
                if (v.indexOf(itemToReplace) >= 0) {
                    pairs[i] = itemToReplace + "=" + value;
                }
            });
            str = '';
            $.each(pairs, function (i, v) {
                if (pairs[i].indexOf("?") >= 0)
                    str = pairs[i];
                else
                    str = str.concat("&" + pairs[i]);
            });
        }
    
        return str;
    }
    

    Extension class for IEnumerable( Of T)

    public static class IEnumerableExtensions
        {
            /// 
            /// ForEach extension method for IEnumerable(Of T)
            /// 
            /// The element type of the IEnumerable object
            /// The IEnumerable(Of T) source
            /// The delegate to perform on each element of the IEnumerable(Of T)
            public static void ForEach(this IEnumerable source, Action action)
            {
                if (action == null)
                {
                    throw new ArgumentNullException("action");
                }
    
                foreach (T item in source)
                {
                    action(item);
                }
            }
    
            /// 
            /// Converts an IEnumerable(Of T) to a delimited string
            /// 
            /// The element type of the IEnumerable object
            /// The IEnumerable(Of T) object
            /// The delimiter to be used in the output string
            /// Delimited string representation of the items
            /// Null or empty items are ignored
            public static string ToDelimitedString(this IEnumerable items, string separator)
            {
                if (items == null || items.Count() == 0)
                {
                    return string.Empty;
                }
    
                return string.Join(separator, items.Where(i => i != null && !i.ToString().IsNullOrWhiteSpace()));
            }
    
            /// 
            /// Converts an IEnumerable(Of T) to a comma-delimited string
            /// 
            /// The element type of the IEnumerable object
            /// The IEnumerable(Of T) object
            /// Comma-delimited string representation of the items
            /// Null or empty items are ignored
            public static string ToSpaceDelimitedString(this IEnumerable items)
            {
                return items.ToDelimitedString(" ");
            }
    
            /// 
            /// Converts an IEnumerable(Of T) to a space-delimited string
            /// 
            /// The element type of the IEnumerable object
            /// The IEnumerable(Of T) object
            /// Space-delimited string representation of the items
            /// Null or empty items are ignored
            public static string ToCommaDelimitedString(this IEnumerable items)
            {
                return items.ToDelimitedString(",");
            }
        }
    

    Masking SSN in C#

     public static string MaskSSN(string ssn)
            {
                string pattern = @"(?:\d{3})-(?:\d{2})-(\d{4})";
                return (null != ssn) ? Regex.Replace(ssn, pattern, "XXX-XX-$1") : string.Empty;
            }
    

    Storing files in DB in asp.net MVC

    CSHTML
    @using (Html.BeginForm("SaveFile", "MyController", FormMethod.Post, new { enctype = "multipart/form-data", id = "fileAjaxForm", autocomplete="off" }))
    {
    
    }
    
    
    
    Controller
    public JsonResult SaveFile(HttpPostedFileBase resumeFile)
    {  
       if (resumeFile != null && resumeFile.ContentLength > 0)
       {
            int size = resumeFile.ContentLength;
            byte[] fileData = resumeFile.InputStream.Read(fileData, 0, size);
            DataAccess.SaveFileData(Path.GetFileName(resumeFile.FileName),resumeFile.ContentType, fileData)  
       }
    }
    
    DB
    Field Name Type
    FileName nvarchar(255)
    Content Type nvarchar(255)
    Content image

    What’s New in EF5

    EF 5 includes a number of new features and bug fixes to the EF4.3 release. Most of the new features are only available in applications targeting .NET 4.5, see the Compatibility section for more details.
    1. Enum support allows you to have enum properties in your entity classes.
    2. Spatial data types can now be exposed in your model using the DbGeography and DbGeometry types.
    3. The Performance enhancements –
      3.1 Automatic Compilation of Linq to Entities queries.
      3.2 67% increase in performance over 4.0
    4. Code First will now detect if you have LocalDb or SQL Express available for creating new databases. Visual Studio 2012 includes LocalDb, whereas Visual Studio 2010 includes SQL Express.
    5. Code First will add tables to existing database if the target database doesn’t contain any of the tables from the model. The EF Designer in Visual Studio 2012 also has some new features:
    6. DbContext code generation for new models means that any new models created using the EF Designer will generate a derived DbContext and POCO classes by default. You can always revert to ObjectContext code generation if needed. Existing models will not automatically change to DbContext code generation.
    7. Multiple-diagrams per model allow you to have several diagrams that visualize subsections of your overall model. Shapes on the design surface can also have coloring applied.
    8. Table-Valued functions in an existing database can now be added to your model.
    9. Batch import of stored procedures allows multiple stored procedures to be added to the model during model creation.

    Monday, September 3, 2012

    Best way to manage your connection strings in ASP.NET

    Best way to manage your connection strings in ASP.NET/MVC

    Storing the connection strings in a separate file ConnectionString.config file
    
      
    
      
    
        
    
    
    
    Referencing the file in your Web.Config file.
    
    

    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;
                }
            }
        }
        
    

    Tuesday, January 17, 2012

    JqGrid and DataTable comparision













    jqGridDatatableDatatable (server side)
    Data format JSON (returned by server) HTML(embedded in web page) JSON(returned by server)
    SortingServer sideClient sideServer side
    Paging Server side Client side Server side
    Filtering/Search Server side
    Supports both toolbar search and Custom search
    Client side
    Provides API for column search
    Server side
    Editing Supports both in-line editing and form editing (we can display the selected record in a pop-up for editing). Form editing not supported. In-line editing is supported by jEditable plugin. Form editing not supported. In-line editing is supported by jEditable plugin.
    Add/Delete Built-in support jEditable and data tables editable plugins required.jEditable and data tables editable plugins required.
    Performance Better performance with high volume of data. Not suited for high volume of data. Slows down with high volume of data.
    Development Extensive Documentation and examples available Easy to use Relatively involves more client side scripting.
    Asp.Net MVC Helper methods Both commercial and open source libraries available.

    Open source library (Lib.Web.Mvc) on codeplex Library provides helper methods for different operations and creating grid control in the view.

    It also allows to configure/format columns on the server side using data annotations e.g., we can define a javascript function for column rendering, which can display images, format strings, etc. and attach the formatter function to the column using attribute.

    Server side validation can be implemented using data annotations.
    Not available Not available

    Knockout 2.0.0 released

    Knockout 2.0.0 released

    ConfigSource property in Web.Config file



    configSource
    You can use the configSource property of a ConfigurationSection to specify a separate file where the configuration of that section is stored.

    Ex: All Connection strings are stored in a separate file "ConnectionStrings.config"



    Content of ConnectionStrings.config



    connectionString="Data Source=(local);Initial Catalog=Sample;Integrated Security=True;MultipleActiveResultSets=True"
    providerName="System.Data.SqlClient" />

    connectionString="metadata=res://*/MatsModel.csdl|res://*/SampleModel.ssdl|res://*/SampleModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=(local);Initial Catalog=Sample;Integrated Security=True;MultipleActiveResultSets=True;Application Name=EntityFramework""
    providerName="System.Data.EntityClient" />


    Benefits

    1. Using include files can result in a more logical and modular structure for configuration files.

    2. File-access security and permissions can be used to restrict access to sections of configuration settings.

    3. Settings in an include file that are not used during application initialization can be modified and reloaded without requiring an application restart.

    ASP.NET MVC Execution Process

    1. Request to an ASP.NET MVC application first pass through the UrlRoutingModel, which is a HTTP Module.
    2. This model parses the request and performs route selection.
    3. This UrlRoutingModel selects the first route object that matches the current request.
    4. If no routes found, the UrlRoutingModel does nothing and fall back the request to ASP.NET or IIS.
    5. From the Route object, it obtains IRouteHandler that is associated with the Route object. In MVC, the instance of IRouteHandler is MVCRouteHandler.
    6. IRouteHandler creates an instance of IHttpHandler object and passes it to IHttpContext object. In MVC, The instance of IHttpHandler is MvcHandler.
    7. The MVCHandler object then selects the appropriate controller that will ultimately handle the request.