About Hasmukh patel

My Photo
Harrow, London, United Kingdom
Dot-Net developer with expertise in Web, WPF, Win-form applications. Have worked on Asp.net,mvc , WPF and Win-forms projects in c#.net language having Sql-Server/Oracle as database with service oriented architecture using test driven development. Having complete knowledge of SDLC and have successfully worked and implemented it on projects.

Custom Authentication with cookie


In order to implement custom authentication, application’s forms cookie need to override with custom user object with implementation of IPrincipal and IIdentity interfaces.
When application request for authenticate user then system fire an event of Application object.  
Implement authentication in Global.asax.cs
Add Application_AuthenticateRequest event into the Global.asax with AuthenticationTicket extension method.
 
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
      Context.AuthenticationTicket();//invoke extension method
}
 
When user request for login with valid credential, application should authenticate user and set application’s forms cookie with encrypted user information so next time user try to access any resources which required authenticate user, user will be authenticate by Application_AuthenticateRequest using application’s forms cookie.
To set authentication cookie 
Call AuthenticationProcessor.SetAuthenticationTicket(httpContext, user);
 
Create a static class to implement extension methods as below  
 
using System;
using System.Security.Principal;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Security;
using DemoLib.Shared.Models;
 
namespace Mvc3Demo.Core
{
    public static class AuthenticationProcessor
    {
        public static void SetAuthenticationTicket(this HttpContextBase httpContext, User user)
        {
            var ticket = new UserTicket
                             {
                                 Name = user.UserName,
                                 Role = user.Role.RoleName,
                                 Id = user.Id
                             };
 
            var jsonSerializer = new JavaScriptSerializer();
 
            var userData = jsonSerializer.Serialize(ticket);
 
            var authTicket = new FormsAuthenticationTicket(1, user.UserName, DateTime.Now, DateTime.Now.AddHours(1), false, userData);
 
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
 
            var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
 
            httpContext.Response.Cookies.Add(authCookie);
        }
 
        public static void AuthenticationTicket(this HttpContext httpContext)
        {
            HttpCookie authCookie = httpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
 
            if (authCookie == null || string.IsNullOrEmpty(authCookie.Value))
                return;
 
            try
            {
                FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCookie.Value);
                
                var jsonSerializer = new JavaScriptSerializer();
 
                var ticket = jsonSerializer.Deserialize<UserTicket>(authTicket.UserData);
 
                var demoIdentity = new DemoIdentity(ticket.Name)
                                       {
                                           User = ticket,
                                       };
 
                httpContext.User = new DemoPrincipal(demoIdentity);
            }
            catch (Exception ex)
            {
 
            }
        }
 
        public class DemoPrincipal : IPrincipal
        {
            private readonly DemoIdentity _loyaltIdentity;
 
            public DemoPrincipal(DemoIdentity loyaltIdentity)
            {
                _loyaltIdentity = loyaltIdentity;
            }
            public bool IsInRole(string role)
            {
                return role.Contains(_loyaltIdentity.User.Role);
            }
 
            public IIdentity Identity { get { return _loyaltIdentity; } }
 
            public DemoIdentity LoyaltIdentity { get { return _loyaltIdentity; } }
        }
 
        public class DemoIdentity : IIdentity
        {
            public DemoIdentity(string name)
            {
                Name = name;
            }
 
            public string Name { getprivate set; }
            public string AuthenticationType { get { return "Custom"; } }
            public bool IsAuthenticated { get { return true; } }
 
            public UserTicket User { getset; }
 
        }
 
        public class UserTicket
        {
            public int Id { getset; }
            public string Name { getset; }
            public string Token { getset; }
            public string Role { getset; }
        }
    }
}
Sparkle : Create dynamic UI with WPF & Silverlight

Creating dynamic UI project creates UI dynamically based on your assigned entity, properties and property’s attribute. Once you assign entity to DataContext on your control, your user control will create textboxes, dropdown, and checkbox and so on as per you entity and registered controls.
In the present state, the code generates the following UI control with the datatypes mentioned alongside the control:
String = Textbox
Int = Textbox
Long = Textbox
Decimal = Textbox
Boolean/bool = checkbox
datetime = date control
enum (any) = dropdown box

Demo Project :

In the demo project following fetures are included

Dynamic UI Controls
Dynamic menus
Dynamic Reports
Dunamic other links

Pre-requisites

VS2008

.Net 3.5 /4.0

And/Or Silverlight 3
Source code will be available at CodePlex.

MVC 2 demo

MVC 2 Demo
Available at CodePlex.
Other details will be updated soon...

Custom Application Configuration

Custom Configuration
Create custom settings in the application settings as below;
    <configSections>
      <!--your other sectiongroups & sections -->
      <section name="viewTypeSettings" type="ConfigTest.ViewTypeSettings,ConfigTest" />        
    </configSections>
 

In order create custom settings in your application config file; create a class which derived from ConfigurationSection class as below


    public class ViewTypeSettings : ConfigurationSection
    {
        static ViewTypeSettings()
        {
            Settings = ConfigurationManager.GetSection("viewTypeSettings"as ViewTypeSettings;
        }
        public static ViewTypeSettings Settings { getprivate set; }
        [ConfigurationProperty("viewTypes")]
        public ViewTypeCollection ViewTypes { get { return this["viewTypes"as ViewTypeCollection; } }
    }
 
Now you can create custom elements as below
 <viewTypeSettings >
    <viewTypes>
      <viewType name="Phone" deviceIdentifiers="iPhone,iPod,Droid,Blackberry"></viewType>
      <viewType name="Tablet" deviceIdentifiers="iPad,Playbook,Transformer,Xoom"></viewType>
    </viewTypes>
  </viewTypeSettings>
 

In order to create custom elements, create a class which derived from ConfigurationElement Class   as below

 
    public class ViewType : ConfigurationElement
    {
        [ConfigurationProperty("name", IsRequired = true)]
        //[StringValidator(InvalidCharacters = "  ~!@#$%^&*()[]{}/;’\"|\\", MinLength = 1, MaxLength = 256)]
        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\", MinLength = 0, MaxLength = 256)]
        public string Name
        {
            get { return this["name"as string; }
            set { this["name"] = value; }
        }
 
        [ConfigurationProperty("deviceIdentifiers", IsRequired = true)]
        [StringValidator(InvalidCharacters = " ~!@#$%^&*()[]{}/;’\"|\\", MinLength = 0, MaxLength = 256)]
        public string DeviceIdentifiers
        {
            get { return this["deviceIdentifiers"as string; }
            set { this["deviceIdentifiers"] = value; }
        }
 
    }
 

 In order to create custom element array , create a class which derived from ConfigurationElementCollection   as below

 
    [ConfigurationCollection(typeof (ViewType), AddItemName = "viewType",
        CollectionType = ConfigurationElementCollectionType.BasicMap)]
    public class ViewTypeCollection : ConfigurationElementCollectionIEnumerable<ViewType
    {
        #region Constructors
 
        static ViewTypeCollection()
        {
            _properties = new ConfigurationPropertyCollection();
        }
 
        #endregion
 
        #region Fields
 
        private static readonly ConfigurationPropertyCollection _properties;
 
        #endregion
 
        #region Properties
 
        protected override ConfigurationPropertyCollection Properties
        {
            get { return _properties; }
        }
 
        public override ConfigurationElementCollectionType CollectionType
        {
            get { return ConfigurationElementCollectionType.AddRemoveClearMap; }
        }
 
        #endregion
 
        #region indexer
 
        public ViewType this[int index]
        {
            get { return (ViewType) BaseGet(index); }
            set
            {
                if (BaseGet(index) != null)
                {
                    BaseRemoveAt(index);
                }
                base.BaseAdd(index, value);
            }
        }
 
        public new ViewType this[string name]
        {
            get { return (ViewType) BaseGet(name); }
        }
        
        #endregion
 
        #region overriden methods
 
        protected override ConfigurationElement CreateNewElement()
        {
            return new ViewType();
        }
 
        protected override object GetElementKey(ConfigurationElement element)
        {
            return (element as ViewType).Name;
        }
 
        public new IEnumerator<ViewType> GetEnumerator()
        {
            var baselsit = base.GetEnumerator();
 
            while (baselsit.MoveNext())
            {
                yield return baselsit.Current as ViewType;
            }
        }
 
        #endregion
    }