31 March 2013

MVC- Custom Data Annotations validation server and client side







           public class TestModel2
            {
                public int Id { get; set; }
                [Required(ErrorMessage = "Name is Required")]
                public string Name { get; set; }
                [Required(ErrorMessage = "Email is Required")]
                [RegularExpression(@"^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$",
                     ErrorMessage = "Please enter valid email")]
                public string Email { get; set; }
                [StringLength(300)]
                public string Description { get; set; }
                [Compare("Email", ErrorMessage = 
                    "User name should be email id")]
                public string Username { get; set; }
                public DateTime PlanStratDate { get; set; }
                public DateTime PlanEndDate { get; set; }
                public string ExternalId { get; set; }
            }

           






       
        public class TestModel2
            {
                public int Id { get; set; }
                [Required(ErrorMessage = "Name is Required")]
                public string Name { get; set; }
                [Required(ErrorMessage = "Email is Required")]
                [RegularExpression(@"^[\w\.=-]+@[\w\.-]+\.[\w]{2,3}$", 
                ErrorMessage = "Please enter valid email")]
                public string Email { get; set; }
                [StringLength(300)]
                public string Description { get; set; }
                [Compare("Email", ErrorMessage =
                "User name should be email id")]
                public string Username { get; set; }
                public DateTime PlanStratDate { get; set; }
                [GratherThen("PlanStratDate")]
                public DateTime PlanEndDate { get; set; }
                [ExternalIdPattern]
                public string ExternalId { get; set; }
            }

        






       public class ExternalIdPatternAttribute : ValidationAttribute , IClientValidatable
        {
            public ExternalIdPatternAttribute() : 
            base("External id should be match with system pattern") { }

            public override bool IsValid(object value)
            {
                const string matchingPattern = "code4help";
                return Convert.ToString(value).Contains(matchingPattern);
            }

            public IEnumerable[ModelClientValidationRule] GetClientValidationRules
            (ModelMetadata metadata, ControllerContext context)
                {
                   var errorMessage = ErrorMessageString;
                    var extidrule = new ModelClientValidationRule();
                    extidrule.ErrorMessage = errorMessage;
                    extidrule.ValidationType = "externalidpattern";
                    //extidrule.ValidationParameters.Add("otherpropertyname",
                         otherPropertyName);

                    yield return extidrule;
                }
         }


                
                


        public class GratherThenAttribute : ValidationAttribute , IClientValidatable
            {
                public string OtherProperty { get; set; }

                public GratherThenAttribute(string oprop)
                    : base("{0} should be grather then {1}")
                {
                    this.OtherProperty = oprop;
                }

                protected override ValidationResult IsValid(object value,
                 ValidationContext validationContext)
                {
                    var validationResult = ValidationResult.Success;
                    var otherPropertyval = 
                    validationContext.ObjectType.GetProperty(this.OtherProperty);
                    if (otherPropertyval.PropertyType == new DateTime().GetType())
                    {
                        var edate = (DateTime)value;
                        var sdate = 
                        (DateTime)otherPropertyval.GetValue(validationContext.ObjectInstance,
                         null);

                        if (edate.CompareTo(sdate) < 1)
                            validationResult = new ValidationResult(ErrorMessageString);
                    }
                    else
                        validationResult =
                            new ValidationResult(
                                "An error occurred while validating the property.
                                 OtherProperty is not of type DateTime");
                    return validationResult;
                }

                public IEnumerable[ModelClientValidationRule] 
                    GetClientValidationRules(ModelMetadata metadata, 
                    ControllerContext context)
                        {
                            var errorMessage = ErrorMessageString;

                            var extidrule = new ModelClientValidationRule();
                            extidrule.ErrorMessage = errorMessage;
                            extidrule.ValidationType = "gratherthen";
                            extidrule.ValidationParameters.Add("otherproperty", OtherProperty);

                            yield return extidrule;
                        }
                    }

            






            $.validator.addMethod("externalidpattern", function (value, element, params) {
            return Date.parse(value) > Date.parse($(params).val());
            });
            $.validator.unobtrusive.adapters.add("externalidpattern", [], function (options) {
                options.rules["externalidpattern"] = "#" + options.params.otherpropertyname;
                options.messages["externalidpattern"] = options.message;
            });

            $.validator.addMethod("gratherthen", function (value, element, params) {
                return Date.parse(value) > Date.parse($(params).val());
            });
            $.validator.unobtrusive.adapters.add("gratherthen", ["otherproperty"], function (options) {
                options.rules["gratherthen"] = "#" + options.params.otherpropertyname;
                options.messages["gratherthen"] = options.message;
            });

            




JSON and XML serialization





             public class TestModel
            {
                public int id { get; set; }
                public string Name { get; set; }
                public List[string] lstskill { get; set; }
                public DateTime Birthday { get; set; }
                public bool Active { get; set; }
                public List[personaldata] Datalst { get; set; }
                public personaldata data { get; set; }
            }
            public class personaldata
            {
                public string data1 { get; set; }
                public string data2 { get; set; }
            }

           




         NOTE: Please add reference of dll 
              [System.Runtime.Serialization.Json]
            
            

         public class JsonHelper
            {
                /// 
                /// JSON Serialization
                /// 
                public static string JsonSerializer[T](T t)
                {
                    DataContractJsonSerializer ser =
                     new DataContractJsonSerializer(typeof(T));
                    MemoryStream ms = new MemoryStream();
                    ser.WriteObject(ms, t);
                    string jsonString = Encoding.UTF8.GetString(ms.ToArray());
                    ms.Close();
                    return jsonString;
                }
                /// 
                /// JSON Deserialization
                /// 
                public static T JsonDeserialize[T](string jsonString)
                {
                    DataContractJsonSerializer ser =
                     new DataContractJsonSerializer(typeof(T));
                    MemoryStream ms =
                     new MemoryStream(Encoding.UTF8.GetBytes(jsonString));
                    T obj = (T)ser.ReadObject(ms);
                    return obj;
                }
            }

        






        public ActionResult Index()
           {
               var model = new Models.TestModel
               {
                   Active = true,
                   Birthday = DateTime.Now,
                   data = new Models.personaldata
                   {
                       data1 = "data1",
                       data2 = "data2",
                   },
                   Datalst = new List[Models.personaldata]
                   {
                       new Models.personaldata
                       {
                           data1 = "ldata1",
                           data2 = "ldata2",
                       },
                       new Models.personaldata
                       {
                           data1 = "ldata1",
                           data2 = "ldata2",
                       },
                   },
                   id = 3,
                   lstskill = new List[string]
                   {
                       "skill1",
                       "skill2",
                   },
                   Name = "name1"
               };

               var strjson = Helper.JsonHelper.
                       JsonSerializer[Models.TestModel](model);

               var strmodel = Helper.JsonHelper.
                           JsonDeserialize[Models.TestModel](strjson);


               return View();
           }

            






        public class XMLHelper
            {
                public static string XMLSerialize[T](T obj)
                {
                    XmlSerializer serializer = 
                    new XmlSerializer(obj.GetType());
                    using (StringWriter writer = new StringWriter())
                    {
                        serializer.Serialize(writer, obj);
                        return writer.ToString();
                    }
                }

                public static object XMLDeSerialize[T](string data)
                {
                    StringReader rdr = new StringReader(data);
                    XmlSerializer xmlSerializer =
                     new XmlSerializer(typeof(T));
                    var result = (T)xmlSerializer.Deserialize(rdr);
                    return result;
                }
            }

            




        public ActionResult Index1()
          {
              var model = new Models.TestModel1
              {
                  Active = true,
                  Birthday = DateTime.Now,
                  data = new Models.personaldata1
                  {
                      data1 = "data1",
                      data2 = "data2",
                  },
                  Datalst = new List[Models.personaldata1]
                  {
                      new Models.personaldata1
                      {
                          data1 = "ldata1",
                          data2 = "ldata2",
                      },
                      new Models.personaldata1
                      {
                          data1 = "ldata1",
                          data2 = "ldata2",
                      },
                  },
                  id = 3,
                  lstskill = new List[string]
                  {
                      "skill1",
                      "skill2",
                  },
                  Name = "name1"
              };

              var strXML = Helper.XMLHelper.XMLSerialize[Models.TestModel1](model);
              var strmodel = Helper.XMLHelper.XMLDeSerialize[Models.TestModel1](strXML);
              return View();
          }

            




        [XmlRoot("TestModel1")]
            public class TestModel1
            {
                public int id { get; set; }
                [XmlAttribute("Name")]
                public string Name { get; set; }
                [XmlElement(ElementName = "lstskill")]
                public List[string] lstskill { get; set; }
                [XmlAttribute("Birthday")]
                public DateTime Birthday { get; set; }
                public bool Active { get; set; }
                [XmlElement(ElementName = "Datalst")]
                public List[personaldata1] Datalst { get; set; }
                [XmlElement(ElementName = "data")]
                public personaldata1 data { get; set; }
            }
            public class personaldata1
            {
                [XmlAttribute("data1")]
                public string data1 { get; set; }
                [XmlAttribute("data2")]
                public string data2 { get; set; }
            }

             


29 January 2013

MVC – Authentication using OAuth





























            public static class OAuthReg
            {
                public static void RegisterOAuth()
                {
                    OAuthWebSecurity.RegisterLinkedInClient(
                         consumerKey: "111111",
                        consumerSecret: "11111111");

                    OAuthWebSecurity.RegisterTwitterClient(
                        consumerKey: "111111",
                        consumerSecret: "11111111");

                    OAuthWebSecurity.RegisterFacebookClient(
                        appId: "1111111",
                        appSecret: "11111111");

                    OAuthWebSecurity.RegisterGoogleClient();

                }
            }


            For register we need to add code in Global.asax file in Application Start Method 


            Models.OAuthReg.RegisterOAuth();
        




           public class HomeController : Controller
            {

                [HttpPost]
                public ActionResult Logon(string provider, string returnUrl)
                {
                    return new ExternerLoginResult(provider, 
                    Url.Action("LogonCallBack", new { returnUrl }));
                }

                [HttpPost]
                public ActionResult LogonCallBack(string returnUrl)
                {
                    AuthenticationResult result = 
                    OAuthWebSecurity.VerifyAuthentication(
                    Url.Action("LogonCallBack", new { ReturnUrl = returnUrl }));
                    if (!result.IsSuccessful)
                        return new EmptyResult();
                    ViewBag.UserName = result.UserName;
                    return View("LoginConfirm");
                }


                #region
                internal class ExternerLoginResult : ActionResult
                {
                    public ExternerLoginResult(string _provider,
                     string _returnUrl)
                    {
                        this.Provider = _provider;
                        this.ReturnUrl = _returnUrl;
                    }

                    public string Provider { get; set; }
                    public string ReturnUrl { get; set; }
                    public override void ExecuteResult(ControllerContext context)
                    {
                        OAuthWebSecurity.RequestAuthentication(this.Provider,
                         this.ReturnUrl);
                    }
                }
                #endregion
            }

        




           
            1: Logon
           
            @model ICollection
            @{
                ViewBag.Title = "Logon";
            }
            

Logon

@using (Html.BeginForm()) {
@foreach (var item in Model) { }
} 2: LoginConfirm @{ ViewBag.Title = "LoginConfirm"; }

LoginConfirm

@ViewBag.UserName




27 January 2013

MVC- Authentication/Authorization









            //
            // GET: /Index/
            [Authorize]
            public ActionResult Index()
            {
                return View();
            }
        




            [Authorize]
            public class IndexController : Controller
            {
                //
                // GET: /Index/
                public ActionResult Index()
                {
                    return View();
                }

            }
        







            For Controller:

            [Authorize(Roles="Administrator, User")]
            public class IndexController : Controller
            {
                //
                // GET: /Index/

                public ActionResult Index()
                {
                    return View();
                }

            }

            For Action Method:

            //
            // GET: /Index/
            [Authorize(Roles = "Administrator, User")]
            public ActionResult Index()
            {
                return View();
            }

            [Authorize(Roles = "User")]
            public ActionResult User()
            {
                return View();
            }

        










            public class CustomAuth : AuthorizeAttribute
            {
                 public override void OnAuthorization(
                            AuthorizationContext filterContext)
                   {
                    base.OnAuthorization(filterContext);
                    if (filterContext.RequestContext.
                            HttpContext.User.Identity.IsAuthenticated)
                    {
                        //TODO: Add code for validate user
                    }
          }
      }


            For use this atherization code see below code block.


            [CustomAuth]
            public ActionResult Index1()
            {
                return View();
            }

        




            public class CustomAuth : AuthorizeAttribute
            {
                public string[] _roles;
                public CustomAuth()
                {
                    _roles = new string[] { "Administrator" };
                }

                public CustomAuth(string[] roles)
                {
                    _roles = roles;
                }

                public override void OnAuthorization(
                        AuthorizationContext filterContext)
                {
                    base.OnAuthorization(filterContext);
                    if (filterContext.RequestContext.
                            HttpContext.User.Identity.IsAuthenticated)
                    {
                        //TODO: Add code for validate user
                        //TODO: Check Roles
                    }
                }
            }



            [CustomAuth(new [] { "Administrator", "User" })]
            public ActionResult Index2()
            {
                return View();
            }

        


1 January 2013

At End of year 2012


































31 December 2012

Custom Membership provider MVC

























            public class UserInfo
            {
                public int Id { get; set; }
                [Required(ErrorMessage = "Please enter username")]
                [Remote("UserExists", "Register")]
                public string UserName { get; set; }
                [Required(ErrorMessage = "Please enter password")]
                public string Password { get; set; }
            }
            






         public class CustomMemberShipProvider : MembershipProvider
        {
            #region Data Initialization
            //
            // Properties from web.config, default all to False
            //
            private string _ApplicationName;
            private bool _EnablePasswordReset;
            private bool _EnablePasswordRetrieval = false;
            private bool _RequiresQuestionAndAnswer = false;
            private bool _RequiresUniqueEmail = true;
            private int _MaxInvalidPasswordAttempts;
            private int _PasswordAttemptWindow;
            private int _MinRequiredPasswordLength;
            private int _MinRequiredNonalphanumericCharacters;
            private string _PasswordStrengthRegularExpression;
            private MembershipPasswordFormat 
            _PasswordFormat = MembershipPasswordFormat.Hashed;

            public override void Initialize(string name, NameValueCollection config)
            {
                if (config == null)
                    throw new ArgumentNullException("config");

                if (name == null || name.Length == 0)
                    name = "CustomMembershipProvider";

                if (String.IsNullOrEmpty(config["description"]))
                {
                    config.Remove("description");
                    config.Add("description", "Custom Membership Provider");
                }

                base.Initialize(name, config);

                _ApplicationName = 
                    GetConfigValue(config["applicationName"], System.Web.Hosting.HostingEnvironment.ApplicationVirtualPath);
                _MaxInvalidPasswordAttempts = 
                    Convert.ToInt32(GetConfigValue(config["maxInvalidPasswordAttempts"], "5"));
                _PasswordAttemptWindow = 
                    Convert.ToInt32(GetConfigValue(config["passwordAttemptWindow"], "10"));
                _MinRequiredNonalphanumericCharacters = 
                    Convert.ToInt32(GetConfigValue(config["minRequiredNonalphanumericCharacters"], "1"));
                _MinRequiredPasswordLength =
                    Convert.ToInt32(GetConfigValue(config["minRequiredPasswordLength"], "6"));
                _EnablePasswordReset = 
                     Convert.ToBoolean(GetConfigValue(config["enablePasswordReset"], "true"));
                _PasswordStrengthRegularExpression = 
                    Convert.ToString(GetConfigValue(config["passwordStrengthRegularExpression"], ""));

            }


            private UserInfoEntities _user = new UserInfoEntities();


            public override int MaxInvalidPasswordAttempts
            {
                get { return _MaxInvalidPasswordAttempts; }
            }

            public override int MinRequiredNonAlphanumericCharacters
            {
                get { return _MinRequiredNonalphanumericCharacters; }
            }

            public override int MinRequiredPasswordLength
            {
                get { return _MinRequiredPasswordLength; }
            }

            public override int PasswordAttemptWindow
            {
                get { return _PasswordAttemptWindow; }
            }

            public override MembershipPasswordFormat PasswordFormat
            {
                get { return _PasswordFormat; }
            }

            public override string PasswordStrengthRegularExpression
            {
                get { return _PasswordStrengthRegularExpression; }
            }

            public override bool RequiresQuestionAndAnswer
            {
                get { return _RequiresQuestionAndAnswer; }
            }

            public override bool RequiresUniqueEmail
            {
                get { return _RequiresUniqueEmail; }
            }


            //
            // A helper function to retrieve config values from the configuration file.
            //  
            private string GetConfigValue(string configValue, string defaultValue)
            {
                if (string.IsNullOrEmpty(configValue))
                    return defaultValue;

                return configValue;
            }

            public override string ApplicationName
            {
                get { return "/"; }
                set { _ApplicationName = value; }
            }

            #endregion



            public override bool ChangePassword(string username, string oldPassword, string newPassword)
            {
                var objdbuser = _user.UserInfoes
                .Where(x => x.UserName.Equals(username)&&
                x.Password.Equals(oldPassword)).FirstOrDefault();
                if (objdbuser == null)
                    return false;
                objdbuser.Password = newPassword;
                _user.SaveChanges();
                return true;
            }

            public override bool ChangePasswordQuestionAndAnswer(string username, 
            string password, string newPasswordQuestion, string newPasswordAnswer)
            {
                throw new NotImplementedException();
            }

            public override MembershipUser CreateUser(string username, 
            string password, string email, string passwordQuestion, string passwordAnswer,
             bool isApproved, object providerUserKey, out MembershipCreateStatus status)
            {
                try
                {
                    _user.UserInfoes.AddObject(new App_Data.UserInfo { Password = password,
                     UserName = username });
                    _user.SaveChanges();
                    status = MembershipCreateStatus.Success;
                    return GetUser(username, false);
                }
                catch (Exception)
                {
                    status = MembershipCreateStatus.ProviderError;
                    return null;
                }
            }

            public override bool DeleteUser(string username, bool deleteAllRelatedData)
            {
                var objdbuser = _user.UserInfoes
                .Where(x => x.UserName.Equals(username)).FirstOrDefault();
                if (objdbuser == null)
                    return false;
                //TODO: Delete User
                return true;
            }

            public override bool EnablePasswordReset
            {
                get { throw new NotImplementedException(); }
            }

            public override bool EnablePasswordRetrieval
            {
                get { throw new NotImplementedException(); }
            }

            public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex,
             int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }

            public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex,
             int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }

            public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
            {
                throw new NotImplementedException();
            }

            public override int GetNumberOfUsersOnline()
            {
                throw new NotImplementedException();
            }

            public override string GetPassword(string username, string answer)
            {
                throw new NotImplementedException();
            }

            public override MembershipUser GetUser(string username, bool userIsOnline)
            {
                var objdbuser = _user.UserInfoes.Where(x => x.UserName
                .Equals(username)).FirstOrDefault();
                var user = new MembershipUser("CustomeMProvider",
                                              objdbuser.UserName,
                                              null,
                                              objdbuser.UserName,
                                              null,
                                              null,
                                              true,
                                              false,
                                              DateTime.MinValue,
                                              DateTime.MinValue,
                                              DateTime.MinValue,
                                              DateTime.MinValue,
                                              DateTime.MinValue);
                return user;
            }

            public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
            {
                throw new NotImplementedException();
            }

            public override string GetUserNameByEmail(string email)
            {
                var objdbuser = _user.UserInfoes
                .Where(x => x.UserName.Equals(email)).FirstOrDefault();
                if (objdbuser == null)
                    return objdbuser.UserName;
                else
                    return string.Empty;
            }

            public override string ResetPassword(string username, string answer)
            {
                throw new NotImplementedException();
            }

            public override bool UnlockUser(string userName)
            {
                throw new NotImplementedException();
            }

            public override void UpdateUser(MembershipUser user)
            {
                var objdbuser = _user.UserInfoes
                .Where(x => x.UserName.Equals(user.UserName)).FirstOrDefault();
                if (objdbuser == null)
                    return;
                //TODO: Update User Information
            }

            public override bool ValidateUser(string username, string password)
            {
                var objdbuser = _user.UserInfoes.Where(x => x.UserName.Equals(username) 
                && x.Password.Equals(password)).FirstOrDefault();
                if (objdbuser == null)
                    return false;
                return true;
            }
         }
   

       




          
            
           
            
          
        
        And

          
              
                
                
              
            

          






         
             public class RegisterController : Controller
            {
                App_Data.UserInfoEntities _db = new App_Data.UserInfoEntities();

                public ActionResult Login()
                {
                    return View(new UserInfo());
                }

                [HttpPost]
                public ActionResult Login(UserInfo objuser, 
                string returnUrl, FormCollection fc)
                {
                    if (ModelState.IsValid)
                    {
                        if (Membership.ValidateUser(objuser.UserName, objuser.Password))
                        {
                            var chkrember = false;
                            if (!string.IsNullOrEmpty(Convert.ToString(fc["chkrmber"])))
                                chkrember = Convert.ToBoolean(fc["chkrmber"]);

                            FormsAuthentication.SetAuthCookie(objuser.UserName, chkrember);
                            if (Url.IsLocalUrl(returnUrl))
                            {
                                return Redirect(returnUrl);
                            }
                            else
                            {
                                return RedirectToAction("Index", "Home");
                            }
                        }
                        else
                        {
                            ModelState.AddModelError("", "The user name or 
                            password provided is incorrect.");
                        }
                    }
                    return View(objuser);
                }

                public ActionResult Register()
                {
                    return View(new UserInfo());
                }

                [HttpPost]
                public ActionResult Register(UserInfo objuser)
                {
                    if (!ModelState.IsValid)
                        return View(objuser);

                    MembershipCreateStatus createStatus;
                    Membership.CreateUser(objuser.UserName, objuser.Password, 
                    objuser.UserName, passwordQuestion: null, passwordAnswer: null, 
                    isApproved: true, providerUserKey: null, status: out createStatus);

                    if (createStatus != MembershipCreateStatus.Success)
                    {
                        ModelState.AddModelError("", "Error occurs in create user");
                        return View(objuser);

                    }
                    return new EmptyResult();
                }

                public JsonResult UserExists(string username)
                {
                    var objuser = _db.UserInfoes
                    .Where(x => x.UserName.Equals(username)).FirstOrDefault();

                    if (objuser == null)
                        return Json(true, JsonRequestBehavior.AllowGet);
                    else
                        return Json(string.Format("an account for address {0} already exists.",
                            username), JsonRequestBehavior.AllowGet);
                }

            }
             






Useful Code At End of 2012







            protected void Page_Load(object sender, EventArgs e)
            {
                var ip = "192.168.4.159";
                var ip1 = "192.168.3.158";
                var ip2 = "192.168.5.156";

                var v1 = IsGreaterOrEqual(ip1, string.Empty);
                var v3 = IsInRange(ip1, ip2, ip);
                var v4 = IsEqual(ip1, ip2);
            }
            public bool IsValidIP(string IP)
            {
                IPAddress ot;
                bool valid = false;
                if (string.IsNullOrEmpty(IP))
                {
                    valid = false;
                }
                else
                {
                    valid = IPAddress.TryParse(IP, out ot);
                }
                return valid;
            }
            public bool IsGreaterOrEqual(string IPFrom, string IPTo)
            {
                return IPAddressToLongBackwards(IPFrom) <= IPAddressToLongBackwards(IPTo);
            }
            public bool IsInRange(string IPFrom, string IPTo, string IP)
            {
                var ipf = IPAddressToLongBackwards(IPFrom);
                var ip = IPAddressToLongBackwards(IP);
                var ipt = IPAddressToLongBackwards(IPTo);
                if (ipf <= ip)
                {
                    if (ip <= ipt)
                        return true;
                    else
                        return false;
                }
                else
                    return false;
            }
            public bool IsEqual(string IPFrom, string IP)
            {
                return IPAddress.Parse(IPFrom).Equals(IPAddress.Parse(IP));
            }
            private uint IPAddressToLongBackwards(string IPAddr)
            {
                System.Net.IPAddress oIP = System.Net.IPAddress.Parse(IPAddr);
                byte[] byteIP = oIP.GetAddressBytes();

                uint ip = (uint)byteIP[0] << 24;
                ip += (uint)byteIP[1] << 16;
                ip += (uint)byteIP[2] << 8;
                ip += (uint)byteIP[3];

                return ip;
            }
         
        




            var mydatetime = DateTime.Now;

            var aest = TimeZoneInfo.FindSystemTimeZoneById("AUS Eastern Standard Time");
            var cst = TimeZoneInfo.FindSystemTimeZoneById("Central Europe Standard Time");

            //Response.Write(mydatetime.ToString());
            //Response.Write(mydatetime.ToUniversalTime());


            var tempdate1 = TimeZoneInfo.ConvertTime(mydatetime, aest);
            var tempdate2 = TimeZoneInfo.ConvertTime(mydatetime, cst);

            var tempoffset1 = cst.GetUtcOffset((tempdate1));
            var tempoffset2 = aest.GetUtcOffset((tempdate2));


            var ct = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
            var tempoffset3 = ct.GetUtcOffset((mydatetime));

            Response.Write(tempoffset1);
            Response.Write(tempoffset2);

            Response.Write(tempoffset3);


            Response.Write(tempoffset1 - tempoffset2);

       




            public class ProjectResource
            {
                public int Id { get; set; }
                public string Name { get; set; }
                public int Hour { get; set; }
                public int Rate { get; set; }
                public double Salary { get; set; }
                public int Type { get; set; }
            }

           var p = new ProjectResource { Hour = 2, Id = 8, Name = "project1", Rate = 5, Salary = 40000, Type = 5 };

            var p1 = new ProjectResource();

            foreach (var item in p.GetType().GetProperties().Where(x => x.Name != "EntityKey" && x.Name != "EntityState"))
            {
                p1.GetType().GetProperty(item.Name).SetValue(p1, item.GetValue(p, null), null);
            }