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