Пример #1
0
        public static void SendActivateEmail(MembershipUser user)
        {
            Database db = DatabaseFactory.CreateDatabase("cnGrammit");

            //Create an activation DB record with a unique GUID that
            //Use that as a request variable to the activation page
            Guid activationGuid = Guid.NewGuid();

            DbCommand dbCommand = db.GetStoredProcCommand("usp_InsertUSER_ACTIVATION");
            db.AddInParameter(dbCommand, "@userID", DbType.Guid, user.ProviderUserKey);
            db.AddInParameter(dbCommand, "@GUID", DbType.Guid, activationGuid);
            db.AddOutParameter(dbCommand, "@ID", DbType.Int32, 2);
            db.ExecuteNonQuery(dbCommand);

            StringBuilder bodyMsg = new StringBuilder();

            bodyMsg.Append("So close... <br />  in order to complete enrollment with ScoreBored.net, you'll need to confirm your account.");
            bodyMsg.AppendFormat("<br />UserName: {0}", user.UserName);
            bodyMsg.Append("<br />Password Question: " + user.PasswordQuestion);

            bodyMsg.Append("<br />Click this link to activate your account: <a href=\"");
            bodyMsg.Append(HttpRuntime.Cache.Get("basePath").ToString());

            bodyMsg.Append("Login.aspx?a=" + HttpUtility.UrlEncode(activationGuid.ToString()) + "\">ACTIVATE</a>");

            MailGen mail = new MailGen();
            mail.SendMessage(user.Email, "*****@*****.**", "ScoreBored Account Activation", bodyMsg.ToString());
        }
Пример #2
0
        public ActionResult Login()
        {
            var compdetail = db.AcCompanies.FirstOrDefault();

            ViewBag.CompanyName = compdetail.AcCompany1;
            string userName = string.Empty;

            if (System.Web.HttpContext.Current != null &&
                System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
            {
                System.Web.Security.MembershipUser usr = Membership.GetUser();
                if (usr != null)
                {
                    userName = usr.UserName;
                }
            }

            UserLoginVM vm = new UserLoginVM();

            vm.UserName = userName;
            //ViewBag.Depot = db.tblDepots.ToList();
            //ViewBag.fyears = db.AcFinancialYearSelect().ToList();
            //TempData["SuccessMsg"] = "You have successfully Updated Customer.";
            //ViewBag.ErrorMessage = "not working";
            //var compdetail = db.AcCompanies.FirstOrDefault();
            //Session["CurrentCompanyID"] = compdetail.AcCompanyID;

            //Session["CompanyName"] = compdetail.AcCompany1;
            //ViewBag.CompanyName = compdetail.AcCompany1;
            return(View(vm));
        }
Пример #3
0
 public static UserProfile GetFor(MembershipUser user)
 {
     using (DREAMContext db = new DREAMContext())
     {
         return db.UserProfiles.Find((Guid)user.ProviderUserKey);
     }
 }
Пример #4
0
        public Profile(string providername,
                    string UserName,
                    object ProviderUserKey,
                    string Email,
                    string PasswordQuestion,
                    string Comment,
                    bool IsApproved,
                    bool IsLockedOut,
                    DateTime CreationDate,
                    DateTime LastLoginDate,
                    DateTime LastActivityDate,
                    DateTime LastPasswordChangedDate,
                    DateTime LastLockedOutDate,
                    string RoleId,
                    string RoleName)
        {
            this.UserName = UserName;
            this.ProviderUserKey = ProviderUserKey;
            this.Email = Email;
            this.PasswordQuestion = PasswordQuestion;
            this.Comment = Comment;
            this.IsApproved = IsApproved;
            this.IsLockedOut = IsLockedOut;
            this.CreationDate = CreationDate;
            this.LastLoginDate = LastLoginDate;
            this.LastActivityDate = LastActivityDate;
            this.LastPasswordChangedDate = LastPasswordChangedDate;
            this.LastLockedOutDate = LastLockedOutDate;
            this.RoleId = RoleId;
            this.RoleName = RoleName;

            _CurrentUser = new MembershipUser("DefaultMembershipProvider", this.UserName, this.ProviderUserKey, this.Email, this.PasswordQuestion, this.Comment, this.IsApproved, this.IsLockedOut, this.CreationDate, this.LastLoginDate, this.LastActivityDate, this.LastPasswordChangedDate, this.LastLockedOutDate);
        }
        public ActionResult Create()
        {
            var Perfil = new PerfilUsuario();

            MembershipUserCollection Users = Membership.GetAllUsers();

            MembershipUser[] arr = new MembershipUser[Users.Count];

            Users.CopyTo(arr, 0);

            List<MembershipUser> Usuarios =  arr.ToList();

            List<PerfilUsuario> Perfiles = db.PerfilUsuarios.ToList();

            foreach (var item in Perfiles)
            {
                Usuarios.Remove(Membership.GetUser(item.Username));
            }

            ViewBag.Usuarios = Usuarios;

            var Sucursales = db.Sucursales.OrderBy(s => s.Nombre);

            ViewBag.Sucursales = Sucursales;

            return View(Perfil);
        }
Пример #6
0
        //Загрузка сторінки
        protected void Page_Load(object sender, EventArgs e)
        {
            //отримати з БД інформацію про поточного користувача
            _membershipUser = Membership.GetUser();

            //якщо користувач не авторизований
            if (_membershipUser == null)
            {
                //перекинути його на сторінку авторизації
                Response.Redirect("~/Account/Login.aspx");
            }
            //інакше(отже користувач авторизований)
            else
            {
                var fs = new FavSitesDAL(_membershipUser.UserName);

                fs.OpenConnection(WebConfigurationManager.ConnectionStrings["FavouriteSites"].ConnectionString);

                //встановити як джерело даних елемента керування ASP.NET Web Forms
                //список закладок користувача
                Repeater1.DataSource = fs.GetFaveSitesOfCurrentUserAsList();
                //Установити зв'язок з даними
                Repeater1.DataBind();

                //закрити з'єднання
                fs.CloseConnection();
            }
        }
Пример #7
0
    private void PopulateProfile(System.Web.Security.MembershipUser user = null)
    {
        NWOProfile.StreetAddress  = StreetAddress;
        NWOProfile.Apartment      = Appartment;
        NWOProfile.City           = City;
        NWOProfile.CountryID      = CountryID;
        NWOProfile.Fax            = Fax;
        NWOProfile.FirstName      = FirstName;
        NWOProfile.MiddleInitials = MI;
        NWOProfile.LastName       = LastName;
        NWOProfile.PostalCode     = Zip;
        NWOProfile.Phone1         = Phone;
        NWOProfile.Region         = Region;
        NWOProfile.Phone2         = Phone2;

        if (NWOProfile.ID == 0)
        {
            NWOProfile.CreatedDate = DateTime.Now;
        }

        if (user != null)
        {
            NWOProfile.UserID = new Guid(user.ProviderUserKey.ToString());
        }
    }
Пример #8
0
        public MembershipUser GetUser(String login)
        {
            using (RoleMembershipDataContext db = new RoleMembershipDataContext())
            {
                var result = from u in db.Users where (u.Login == login) select u;

                if (result.Count() == 0)
                {
                    return null;
                }

                User dbuser = result.FirstOrDefault();
                MembershipUser user = new MembershipUser("CustomMembershipProvider",
                                                         dbuser.Login,
                                                         dbuser.UserId,
                                                         String.Empty,
                                                         String.Empty,
                                                         String.Empty,
                                                         true,
                                                         false,
                                                         dbuser.CreatedDate,
                                                         DateTime.Now,
                                                         DateTime.Now,
                                                         DateTime.Now,
                                                         DateTime.Now);

                return user;
            }
        }
Пример #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            users = Membership.GetAllUsers();

            if (IsPostBack)
            {
            }
            else
            {
                Msg.Text = "";
                // Bind users to ListBox.
                UsersListBox.DataSource = users;
                UsersListBox.DataBind();
            }

            // If a user is selected, show the properties for the selected user.

            if (UsersListBox.SelectedItem != null)
            {
                u = users[UsersListBox.SelectedItem.Value];

                EmailLabel.Text = u.Email;
                IsOnlineLabel.Text = u.IsOnline.ToString();
                LastLoginDateLabel.Text = u.LastLoginDate.ToString();
                CreationDateLabel.Text = u.CreationDate.ToString();
                LastActivityDateLabel.Text = u.LastActivityDate.ToString();
                CanLoginLabel.Text = u.IsApproved.ToString();
            }
        }
 public void ChangePassword(MembershipUser user, string newPassword)
 {
     throw new NotImplementedException();
     //var resetPassword = user.ResetPassword();
     //if(!user.ChangePassword(resetPassword, newPassword))
     //    throw new MembershipPasswordException("Could not change password.");
 }
Пример #11
0
        public EditBlogViewModel(string blogId)
        {
            BlogId = Int32.Parse(blogId);
             		_memUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
            SiteUrl = HTTPUtils.GetFullyQualifiedApplicationPath() + "blog/";

            using (var context = new DataContext())
            {
                ThisBlog = context.Blogs.FirstOrDefault(x => x.BlogId == BlogId);

                // Make sure we have a permalink set
                if (String.IsNullOrEmpty(ThisBlog.PermaLink))
                {
                    ThisBlog.PermaLink = ContentUtils.GetFormattedUrl(ThisBlog.Title);
                    context.SaveChanges();
                }

                // Get the list of Authors for the drop down select
                BlogUsers = context.BlogUsers.Where(x => x.IsActive == true).OrderBy(x => x.DisplayName).ToList();

                Categories = context.BlogCategories.Where(x => x.IsActive == true).ToList();

                UsersSelectedCategories = new List<string>();

                _thisUser = context.Users.FirstOrDefault(x => x.Username == _memUser.UserName);
            }

            // Get the admin modules that will be displayed to the user in each column
            getAdminModules();
        }
Пример #12
0
 protected void cargarUsuario()
 {
     System.Web.Security.MembershipUser logUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
     objNUsurio   = objDUsuario.obtenerDatosUsuarioCompleto(logUser.UserName.ToString());
     txtPass.Text = objNUsurio.pass;
     txtId.Text   = objNUsurio.idUser.ToString();
 }
Пример #13
0
        public static Tuple<MembershipPasswordFormat, string, string> ExtractPasswordData(MembershipUser user)
        {
            MembershipPasswordFormat passwordFormat;
            string passwordSalt;
            string password;

            ConnectionStringSettings connectionString = WebConfigurationManager.ConnectionStrings["DefaultConnection"];
            using(SqlConnection conn = new SqlConnection(connectionString.ConnectionString))
            {
                using(SqlCommand cmd = conn.CreateCommand())
                {
                    cmd.CommandText = "SELECT PasswordFormat, PasswordSalt, Password FROM aspnet_Membership WHERE UserId=@UserId";
                    cmd.Parameters.AddWithValue("@UserId", user.ProviderUserKey);
                    conn.Open();
                    using(SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        if(rdr != null && rdr.Read())
                        {
                            passwordFormat = (MembershipPasswordFormat) rdr.GetInt32(0);
                            passwordSalt = rdr.GetString(1);
                            password = rdr.GetString(2);
                        }
                        else
                        {
                            throw new Exception("Error extracting current password data from the database.");
                        }
                    }
                }
            }

            return new Tuple<MembershipPasswordFormat, string, string>(passwordFormat, passwordSalt, password);
        }
        public EditEventViewModel(string eventId)
        {
            EventId = Int32.Parse(eventId);
             		_memUser = Membership.GetUser(HttpContext.Current.User.Identity.Name);
            SiteUrl = HTTPUtils.GetFullyQualifiedApplicationPath() + "event/";

            using (var context = new DataContext())
            {
                ThisEvent = context.Events.FirstOrDefault(x => x.EventId == EventId);

                // Make sure we have a permalink set
                if (String.IsNullOrEmpty(ThisEvent.PermaLink))
                {
                    ThisEvent.PermaLink = ContentUtils.GetFormattedUrl(ThisEvent.Title);
                }

                EventCategories = context.EventCategories.Where(x => x.IsActive == true).ToList();

                UsersSelectedCategories = new List<string>();

                _thisUser = context.Users.FirstOrDefault(x => x.Username == _memUser.UserName);
            }

            // Get the admin modules that will be displayed to the user in each column
            getAdminModules();
        }
Пример #15
0
        public static DataSet GetUsersInRole(string roleName)
        {
            DataSet ds = (DataSet)HttpContext.Current.Session["dsUsersInRole"];

            if (ds == null)
            {
                // Get all users
                MembershipUserCollection userColl = Membership.GetAllUsers();
                MembershipUser[] users = new MembershipUser[userColl.Count];
                userColl.CopyTo(users, 0);
                ds = DataSetBuilder.CreateDataSetFromBusinessObjectList(
                    users, "UserName");

                // Add check-boxes
                string[] usersInRole = Roles.GetUsersInRole(roleName);
                DataColumn col = ds.Tables[0].Columns.Add("IsInRole", typeof(bool));
                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    string userName = (string)row["UserName"];
                    row["IsInRole"] = Utility.IsNameInList(userName, usersInRole);
                }

                HttpContext.Current.Session["dsUsersInRole"] = ds;
            }

            return ds;
        }
Пример #16
0
        public void SetUpData()
        {
            // if the test user already exists delete it
            Membership.DeleteUser("user1");

            user = Membership.CreateUser("user1", "Password1!", "*****@*****.**");
        }
Пример #17
0
        protected override void AfterEditBeforeCommit(EditEventArgs e)
        {
            string usernameFieldName = GetUsernameFieldName();

            if (e.Values.ContainsKey(usernameFieldName) && e.Values.ContainsKey("Email"))
            {
                string username = e.Values["Username"].ToString();
                System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.Provider.GetUser(username, false /* userIsOnline */);
                string email = e.Values["Email"].ToString();

                currentUser.Email = email;
                System.Web.Security.Membership.Provider.UpdateUser(currentUser);

                ChangePassword(e);
            }

            if (e.Values.ContainsKey("IsApproved"))
            {
                if (e.PrevRow != null)
                {
                    Field field          = e.View.Fields["IsApproved"];
                    bool  isApproved     = Convert.ToBoolean(e.Values["IsApproved"].ToString());
                    bool  prevIsApproved = (bool)e.PrevRow["IsApproved"];

                    if (isApproved != prevIsApproved)
                    {
                        string username = e.PrevRow["Username"].ToString();
                        System.Web.Security.MembershipUser user = System.Web.Security.Membership.Provider.GetUser(username, true);
                        user.IsApproved = isApproved;
                        System.Web.Security.Membership.UpdateUser(user);
                    }
                }
            }
            base.AfterEditBeforeCommit(e);
        }
 public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
 {
     MembershipUser user = new MembershipUser("AgileMindProvider", "test", "test", "test",
                                 string.Empty, string.Empty, true, false, DateTime.Now, DateTime.Now,
                                 DateTime.Now, DateTime.Now, DateTime.Now);
     return user;
 }
Пример #19
0
        public void SetupData()
        {
            // make sure the test user doesn't exist
            Membership.DeleteUser("user1");

            user = Membership.CreateUser("user1", "Password1!", "*****@*****.**");
        }
 private UserViewModel User2UserViewModel(MembershipUser user)
 {
     var result = new UserViewModel {Name = user != null ? user.UserName : "******"};
     if (user != null)
         result.UserId = user.ProviderUserKey is Guid ? (Guid) user.ProviderUserKey : new Guid();
     return result;
 }
Пример #21
0
        public static void SendPasswordEmail(MembershipUser user, string password, PasswordEmailType passwordEmailType)
        {
            assertExists(user);
            assertHasEmail(user);

            string body = passwordEmailTemplate.Replace("<%LoginName%>", user.UserName)
                                               .Replace("<%Password%>", password);

            body = ApplicationLayer.Utility.ShowOptionalTag(body, "passwordEmailType-firstTime",
                                                                   passwordEmailType == PasswordEmailType.FirstTime);
            body = ApplicationLayer.Utility.ShowOptionalTag(body, "passwordEmailType-reset",
                                                                   passwordEmailType == PasswordEmailType.Reset);
            body = ApplicationLayer.Utility.ShowOptionalTag(body, "passwordEmailType-changedByUser",
                                                                   passwordEmailType == PasswordEmailType.ChangedByUser);
            body = ApplicationLayer.Utility.ShowOptionalTag(body, "passwordEmailType-not-changedByUser",
                                                                   passwordEmailType != PasswordEmailType.ChangedByUser);

            MailMessage message = new MailMessage();

            string testRecipients = ConfigurationManager.AppSettings.Get("TestEmailRecipients");
            message.To.Add(testRecipients == null ? user.Email : testRecipients);

            message.Subject = "Your new Total Giro password";
            message.Body = body;
            message.IsBodyHtml = true;

            SmtpClient client = new SmtpClient();
            client.Send(message);
        }
Пример #22
0
        public EfUser To(EfUser model, System.Web.Security.MembershipUser From)
        {
            model.Username                = From.UserName;
            model.UserID                  = (int)From.ProviderUserKey;
            model.Email                   = From.Email;
            model.PasswordQuestion        = From.PasswordQuestion;
            model.Comment                 = From.Comment;
            model.IsApproved              = From.IsApproved;
            model.Status                  = From.IsLockedOut ? (byte)2 : (byte)1;
            model.CreateOn                = From.CreationDate;
            model.LastLoginDate           = From.LastLoginDate;
            model.LastActivityDate        = From.LastActivityDate;
            model.LastPasswordChangedDate = From.LastPasswordChangedDate;
            model.LastLockoutDate         = From.LastLockoutDate;

            if (From is MembershipUser)
            {
                var nFrom = (MembershipUser)From;
                model.TimeZone  = nFrom.TimeZone;
                model.FirstName = nFrom.FirstName;
                model.LastName  = nFrom.LastName;
            }

            return(model);
        }
        public bool IsResetUrlValid(string hash, out MembershipUser user)
        {
            user = null;
            var isValid = false;
            if (!string.IsNullOrEmpty(hash))
            {
                ResetPasswordModel link = _resetPasswordRespository.Find(hash);

                isValid = (link != null && link.ExpireDate > DateTime.Now);
                if (isValid)
                {
                    user = Membership.Provider.GetUser(link.UserName, false);

                    if (user == null)
                    {
                        string userName = Membership.GetUserNameByEmail(link.UserName);
                        user = Membership.Provider.GetUser(userName, false);
                    }

                    if (user != null && user.IsLockedOut)
                    {
                        user.UnlockUser();
                    }
                }
            }

            return isValid;
        }
Пример #24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            facade = new BusinessFacade(conn);
            mu = Membership.GetUser();

            Datalist_Binding();
        }
Пример #25
0
        protected void ResetPassword_OnClick(object sender, EventArgs e)
        {
            string newPassword = "";

                try
                {

                    u = Membership.GetUser(MemberUserName.Text, false);
                    newPassword = u.ResetPassword(AnswerTextBox.Text);

                    if (newPassword != null)
                    {
                        Msg.Text = "Password reset. Your new password is: " + Server.HtmlEncode(newPassword);
                    }
                    else
                    {
                        Msg.Text = "Password reset failed. Please re-enter your values and try again.";
                    }
                }
                catch (MembershipPasswordException ex)
                {
                    Msg.Text = "Invalid password answer. Please re-enter and try again.";
                    return;
                }
                catch (Exception ee)
                {
                    Msg.Text = ee.Message;
                    return;
                }
        }
Пример #26
0
 public static void MailCustomer(MembershipUser customer, string subject, string body)
 {
     // Send mail to customer
       string to = customer.Email;
       string from = BalloonShopConfiguration.CustomerServiceEmail;
       Utilities.SendMail(from, to, subject, body);
 }
Пример #27
0
        public void ThenAllTheUserSDataIsDeleted()
        {
            Assert.IsTrue(userDeleted);

            membershipUser = Membership.GetUser(userName);
            Assert.IsNull(membershipUser);
        }
Пример #28
0
		public UserAccount(MembershipUser user)
		{
			UserName = user.UserName;
			Email = user.Email;
			PasswordQuestion = user.PasswordQuestion;
			
		}
Пример #29
0
        private HybridMembershipUser GetHybridMembershipUser(System.Web.Security.MembershipUser membershipUser)
        {
            if (membershipUser == null)
            {
                return(null);
            }
            var name   = GetUserNameFromMembershipUserName(membershipUser.UserName);
            var domain = GetDomainFromMembershipUserName(membershipUser.UserName);
            var user   = UserRepository.GetUserByUserName(name, domain);

            if (user == null)
            {
                lock (padLock) {
                    user = UserRepository.GetUserByUserName(name, domain);
                    if (user == null)
                    {
                        user = UserRepository.CreateUserInstance(name, domain);
                        user.Properties.Email = membershipUser.Email;
                        UserRepository.SetPassword(user, Guid.NewGuid().ToString("N"));
                        try {
                            UserRepository.SaveUser(user);
                        } catch (UserNameAlreadyExistsException) {
                            user = UserRepository.GetUserByUserName(name, domain);
                        }
                    }
                }
            }
            return(new HybridMembershipUser(membershipUser, user, Name));
        }
Пример #30
0
 public User(MembershipUser user)
 {
     this.UserName = user.UserName;
     ProfileBase profile = ProfileBase.Create(user.UserName);
     this.FullName = profile.GetPropertyValue("FullName") as string;
     this.Email = user.Email;
 }
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                // ChangePassword will throw an exception rather
                // than return false in certain failure scenarios.
                bool changePasswordSucceeded;
                try
                {
                    a.MembershipUser currentUser = System.Web.Security.Membership.GetUser(User.Identity.Name, userIsOnline: true);
                    changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
                }
                catch (Exception)
                {
                    changePasswordSucceeded = false;
                }

                if (changePasswordSucceeded)
                {
                    return(RedirectToAction("ChangePasswordSuccess"));
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return(View(model));
        }
Пример #32
0
 public UserFormViewModel(string[] allRoles, string[] userRoles, MembershipUser user, ViewMode mode)
 {
     AllRoles = allRoles;
     UserRoles = userRoles;
     User = user;
     Mode = mode;
 }
Пример #33
0
        /// <summary>
        /// Updates information about a user in the data source.
        /// </summary>
        /// <param name="user">A <see cref="T:System.Web.Security.MembershipUser"/> object that represents the user to update and the updated information for the user.</param>
        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            CheckParameter(user.UserName, true, true, true, 256, "UserName");
            CheckParameter(user.Email, RequiresUniqueEmail, RequiresUniqueEmail, false, 256, "Email");

            var membershipUser = user as MembershipUser;

            if (membershipUser == null)
            {
                throw new ArgumentException(string.Format("User is not of type {0}", typeof(MembershipUser).Name), "user");
            }
            var userFromRepository = UserRepository.GetUserById(membershipUser.ProviderUserKey as string);

            userFromRepository = userFromRepository.CreateWritable();
            userFromRepository.Properties.LastLoginDate    = user.LastLoginDate;
            userFromRepository.Properties.Description      = user.Comment;
            userFromRepository.Properties.Email            = user.Email;
            userFromRepository.Properties.Active           = user.IsApproved;
            userFromRepository.Properties.LastActivityDate = user.LastActivityDate;
            UpdateUserInRepository(userFromRepository);
        }
Пример #34
0
        protected void Page_Load(object sender, EventArgs e)
        {
            user = Membership.GetUser();

             var msgs =
                 from m in JUTCLinq.PhoneMessages
                 where m.UserName == user.UserName
                 select m;

             foreach (var m in msgs)
             {
                 txtMessage.Text += "Time of Message: " + m.Time + "\r\n" + m.Message + "\r\n";

                 JUTCLinq.PhoneMessages.DeleteOnSubmit(m);
             }

             try
             {
                 JUTCLinq.SubmitChanges();
             }
             catch (Exception ex)
             {
                 Console.WriteLine(ex);
             }
        }
Пример #35
0
 private void RellenaIndicadores()
 {
     System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser();
     if (usr != null)
     {
         try
         {
             using (Clases.cKPI_INDICATOR_USERS objIndicador = new Clases.cKPI_INDICATOR_USERS())
             {
                 objIndicador.userid       = Convert.ToInt32(usr.ProviderUserKey);
                 lstIndicadores.DataSource = objIndicador.TopXUltimos(8, string.Empty);
                 lstIndicadores.DataBind();
             }
         }
         finally
         {
             if (lstIndicadores.Items.Count < 8)
             {
                 PanelMas.Visible = false;
             }
         }
     }
     else
     {
         PanelMiLibreria.Visible = false;
     }
 }
        public override MembershipUser CreateUser(string username, string password, string email, 
            string passwordQuestion, string passwordAnswer, bool isApproved, 
            object providerUserKey, out MembershipCreateStatus status)
        {

            bool created = false;
            MembershipUser membershipUser = null;

            try
            {
                created = membershipRepository.Add(username, password, email, out providerUserKey);

                membershipUser = new MembershipUser(this.Name, username, providerUserKey,
                    email, null, null, true, true, 
                    DateTime.Today, DateTime.Today, DateTime.Today, DateTime.Today, DateTime.Today);

                if (created)
                {
                    status = MembershipCreateStatus.Success;
                }
                else
                {
                    status = MembershipCreateStatus.UserRejected;
                }

            }
            catch (Exception)
            {
                status = MembershipCreateStatus.DuplicateUserName;
            }
            

            return membershipUser;
        }
Пример #37
0
        public override System.Web.Security.MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out System.Web.Security.MembershipCreateStatus status)
        {
            BuildingEntities db;
            User             user;
            int count;

            System.Web.Security.MembershipUser result = null;
            status = System.Web.Security.MembershipCreateStatus.Success;

            using (db = new BuildingEntities())
            {
                count = db.Users.Where(val => val.Login.ToLower() == username.ToLower() && !val.Deleted).Count();

                if (count > 0)
                {
                    status = System.Web.Security.MembershipCreateStatus.DuplicateUserName;
                }
                else
                {
                    user            = new User();
                    user.Login      = username;
                    user.Password   = password.ToSha1Base64String();
                    user.Name       = string.Empty;
                    user.Surname    = string.Empty;
                    user.Patronymic = string.Empty;
                    db.Users.AddObject(user);
                    db.SaveChanges();
                    result = ConvertUser(user);
                }
            }
            return(result);
        }
Пример #38
0
        public UserProfileManager(MembershipUser _user)
        {
            if (_user == null) {
                throw new ArgumentNullException("_user");
            }

            UserProfile newProfile = new UserProfile(_user.UserName);
            ProfileBase userProfile = ProfileBase.Create(_user.UserName);
            ProfileGroupBase addressGroup = userProfile.GetProfileGroup("Address");

            userProfile.Initialize(_user.UserName, true);

            newProfile.Properties.Add(new ProfileProperty("Nome", "Name", userProfile["Name"].ToString()));

            newProfile.Properties.Add(new ProfileProperty("Telefone", "Phone", addressGroup["Phone"].ToString()));
            newProfile.Properties.Add(new ProfileProperty("CEP", "CEP", addressGroup["CEP"].ToString()));
            newProfile.Properties.Add(new ProfileProperty("Endereço", "Street", addressGroup["Street"].ToString()));
            newProfile.Properties.Add(new ProfileProperty("Bairro", "Area", addressGroup["Area"].ToString()));
            newProfile.Properties.Add(new ProfileProperty("Estado", "State", addressGroup["State"].ToString()));
            newProfile.Properties.Add(new ProfileProperty("Cidade", "City", addressGroup["City"].ToString()));

            /*newProfile.Properties.Add(new ProfileProperty("FTP: Host", "FtpHost", ftpInfoGroup["FtpHost"].ToString()));
            newProfile.Properties.Add(new ProfileProperty("FTP: Usuário", "FtpUserName", ftpInfoGroup["FtpUserName"].ToString()));
            newProfile.Properties.Add(new ProfileProperty("FTP: Senha", "FtpPassword", ftpInfoGroup["FtpPassword"].ToString()));*/

            this.UserProfile = newProfile;
        }
Пример #39
0
        public ProfileController(IMailService mail)
        {
            _mail = mail;
            _mu = MembershipWrapper.GetUser();

            if (_mu != null) _ua = new UserAccount(_mu.UserName);
        }
Пример #40
0
 protected void cargarUsuario()
 {
     System.Web.Security.MembershipUser logUser = System.Web.Security.Membership.GetUser(User.Identity.Name);
     objNOrientador = objDOrientador.obtenerDatosOrientadorCompleto(logUser.UserName.ToString());
     txtPass.Text   = objNOrientador.pass;
     txtId.Text     = objNOrientador.IDOrientador1.ToString();
 }
Пример #41
0
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //string usuario = ddlUsuario.Text;

            string usuario = txtUsuario.Text;

            string contrasena = txtContrasena.Text;

            Controllers.Configuracion.CustomMembershipProvider controller = new Controllers.Configuracion.CustomMembershipProvider();

            if (controller.ValidateUser(usuario, contrasena))
            {
                Session["usuario"] = Membership.GetUser(usuario);

                Session["accesos"] = Roles.GetRolesForUser(usuario);


                FormsAuthentication.RedirectFromLoginPage(usuario, true);
            }
            else
            {
                this.LiteralError.Text = "Usuario o Password Incorrectos.";
            }
            System.Web.Security.MembershipUser u = Membership.GetUser(usuario, false);
            var timeSpan = u.LastPasswordChangedDate - u.CreationDate;

            /*  if (timeSpan < 60)
             * {
             *    Response.Redirect("~/Configuracion/Usuarios/EditarClave.aspx");
             * }*/
        }
Пример #42
0
    protected void Button1_Click(object sender, EventArgs e)
    {
        // To get the username, we will have to use the Membership class in System.Web.Security namespace
        System.Web.Security.MembershipUser user = System.Web.Security.Membership.GetUser();


        Uploads upload = new Uploads();

        upload.UserName = user.UserName;


        if (System.Web.Security.Roles.IsUserInRole("Admin"))
        {
            upload.IsApproved = true;
        }
        else
        {
            upload.IsApproved = false;
        }
        upload.IsDeleted = false;


        upload.CreatedOn = Convert.ToString(DateTime.Now);


        upload.TopicsId      = Convert.ToInt16(DropDownList2.SelectedValue);
        upload.IsDeleted     = false;
        upload.UploadsTypeId = Convert.ToInt16(DropDownList3.SelectedValue);

        upload.Title = UploadFileTitle.Text;

        if (FileUpload1.HasFile)
        {
            string UploadFolderRelativePath = "~/Uploads/";
            string UploadFolderAbsolutePath = Server.MapPath(UploadFolderRelativePath);

            string FullFilePath     = string.Format("{0}/{1}", UploadFolderAbsolutePath, FileUpload1.FileName);
            string FileRelativePath = string.Format("{0}/{1}", UploadFolderRelativePath, FileUpload1.FileName);

            FileUpload1.SaveAs(FullFilePath);
            upload.Path = FileRelativePath;
        }



        UploadsBL.Add(upload);


        Email send = new Email();

        send.to = "*****@*****.**";

        send.subject = System.Web.Security.Membership.GetUser().Email;

        send.body = "New user add some file <a href='http://localhost:2709/WebUI/Admin/ManageUploads.aspx'>click Link to approved the file</a>";

        EmailBL.sendmail(send);
    }
Пример #43
0
        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }

            string temp = user.UserName;

            SecUtility.CheckParameter(ref temp, true, true, true, 256, "UserName");
            temp = user.Email;
            SecUtility.CheckParameter(ref temp,
                                      RequiresUniqueEmail,
                                      RequiresUniqueEmail,
                                      false,
                                      256,
                                      "Email");
            user.Email = temp;


            var query = from u in db.Users
                        where u.Id == (int)user.ProviderUserKey
                        select u;

            var usr = query.FirstOrDefault();

            if (usr == null)
            {
                throw new ProviderException(GetExceptionText(1));
            }

            if (RequiresUniqueEmail)
            {
                var q = from u in db.Users
                        where u.Id != (int)user.ProviderUserKey &&
                        u.Email == user.Email
                        select u;

                if (q.Any())
                {
                    throw new ProviderException(GetExceptionText(7));
                }
            }

            usr.Email         = user.Email;
            usr.Comment       = user.Comment;
            usr.IsApproved    = user.IsApproved;
            usr.LastLoginDate = user.LastLoginDate;
            if (user is MembershipUser)
            {
                var muser = (MembershipUser)user;

                usr.FirstName = muser.FirstName;
                usr.LastName  = muser.LastName;
            }

            db.SaveChanges();
        }
Пример #44
0
        protected override void AfterEditBeforeCommit(EditEventArgs e)
        {
            string username = e.Values["Username"].ToString();

            System.Web.Security.MembershipUser currentUser = System.Web.Security.Membership.Provider.GetUser(username, false /* userIsOnline */);
            string email = e.Values["Email"].ToString();

            currentUser.Email = email;
            System.Web.Security.Membership.Provider.UpdateUser(currentUser);
            base.AfterEditBeforeCommit(e);
        }
Пример #45
0
        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            var hybridMembershipUser = user as HybridMembershipUser;

            if (hybridMembershipUser == null)
            {
                throw new ArgumentException(string.Format("User is not of type {0}", typeof(HybridMembershipUser).Name), "user");
            }
            PrimaryMembershipProvider.UpdateUser(hybridMembershipUser.PrimaryMembershipUser);
            base.UpdateUser(hybridMembershipUser);
        }
Пример #46
0
        protected override void AfterCreateBeforeCommit(CreateEventArgs e)
        {
            string username = e.Values["Username"].ToString();
            string email    = e.Values["Email"].ToString();

            //string tempPassword = e.Values["Password"].ToString();
            string tempPassword;

            if (e.Values.ContainsKey("Password"))
            {
                tempPassword = e.Values["Password"].ToString();
            }
            else
            {
                tempPassword = GetRandomPassword((View)e.View);
                //e.Values.Add("Password", tempPassword);
            }
            System.Web.Security.MembershipCreateStatus status = CreateUser(username, tempPassword, email);

            if (status == MembershipCreateStatus.Success)
            {
                string role = GetRole(e.Values);
                if (String.IsNullOrEmpty(role))
                {
                    System.Web.Security.Membership.Provider.DeleteUser(username, true);
                    throw new DuradosException(Map.Database.Localizer.Translate("Failed to create user, Role is missing"));
                }
                System.Web.Security.Roles.AddUserToRole(username, role);

                if (e.Values.ContainsKey("IsApproved"))
                {
                    bool isApproved = Convert.ToBoolean(e.Values["IsApproved"].ToString());

                    if (!isApproved)
                    {
                        System.Web.Security.MembershipUser user = System.Web.Security.Membership.Provider.GetUser(username, true);
                        user.IsApproved = false;
                        System.Web.Security.Membership.UpdateUser(user);
                    }
                }

                base.AfterCreateBeforeCommit(e);
            }
            else
            {
                e.Cancel = true;
            }

            if (e.Cancel)
            {
                throw new DuradosException(ErrorCodeToString(status));
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser();
        if (usr != null)
        {
            //LabelDebug.Text = ":::" + usr.ToString() + "\n";
            //LabelDebug.Text = usr.ProviderUserKey.ToString();

            string script = "alert(\"Hello " + usr.UserName + ": " + usr.ProviderUserKey + "!\");";
            ScriptManager.RegisterStartupScript(this, GetType(),
                                                "ServerControlScript", script, true);
        }
    }
Пример #48
0
        //Send Email Method
        internal static void SendResetEmail(System.Web.Security.MembershipUser user)
        {
            var emailSendModel = new SmtpEmail();


            emailSendModel.Bcc.Add(user.Email);

            emailSendModel.Subject = "Password Reset";
            string link = "http://www.utdbaike.com/Account/ResetPassword/?username="******"&reset=" + HashResetParams(user.UserName, user.ProviderUserKey.ToString());

            emailSendModel.Body  = "<p>" + user.UserName + " please click the following link to reset your password: <a href='" + link + "'>" + link + "</a></p>";
            emailSendModel.Body += "<p>If you did not request a password reset you do not need to take any action.</p>";
            emailSendModel.Send();
        }
Пример #49
0
        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            using (var db = new DataAccess.CSSDataContext())
            {
                var login = db.Logins.FirstOrDefault(p => p.Id == Convert.ToInt32(user.ProviderUserKey));

                if (login != null)
                {
                    login.Email    = user.Email;
                    login.Username = user.UserName;

                    db.SubmitChanges();
                }
            }
        }
Пример #50
0
        public override void UpdateUser(System.Web.Security.MembershipUser member)
        {
            global::SoftFluent.Samples.GED.Security.User user = global::SoftFluent.Samples.GED.Security.User.LoadByUserName(member.UserName);
            if (user == null)
            {
                return;
            }


            user.Email = member.Email;

            user.LastLoginDate    = member.LastLoginDate.ToUniversalTime();
            user.LastActivityDate = member.LastActivityDate.ToUniversalTime();
            user.Save();
        }
    private void NewSearch()
    {
        System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser();
        SqlConnection conn;
        SqlCommand    comm;
        SqlDataReader reader;
        string        connectionString =
            ConfigurationManager.ConnectionStrings[
                "Assignment4"].ConnectionString;

        conn = new SqlConnection(connectionString);
        comm = new SqlCommand(
            "Select RecipeName, CookingTime, Portions, Description, UserName, Privacy " +
            "From [Assignment4].[dbo].[User] " +
            "inner Join UserRecipe on UserRecipe.UserId = [Assignment4].[dbo].[User].UserId " +
            "inner Join Recipe on Recipe.RecipeId=UserRecipe.RecipeId " +
            "where Privacy = 0" +
            "Union " +
            "Select RecipeName, CookingTime, Portions, Description, UserName, Privacy " +
            "From [Assignment4].[dbo].[User] " +
            "inner Join UserRecipe on UserRecipe.UserId = [Assignment4].[dbo].[User].UserId " +
            "inner Join Recipe on Recipe.RecipeId=UserRecipe.RecipeId " +
            "where privacy = 1 and UserName="******"Search Results:";
            //myRepeater.Visible = true;
        }
        catch
        {
            dbErrorLabel.Text =
                "Error loading the details!<br />";
        }
        finally
        {
            conn.Close();
        }
    }
Пример #52
0
 protected void myLogin_LoginError(object sender, EventArgs e)
 {
     myLogin.FailureText = "Your login attempt was not successful. Please try again.".ToErrorMessageFormat();
     System.Web.Security.MembershipUser usrInfo = System.Web.Security.Membership.GetUser(myLogin.UserName);
     if (usrInfo != null)
     {
         if (usrInfo.IsLockedOut)
         {
             myLogin.FailureText = "Your account has been locked out because of too many invalid login attempts. Please contact MIS at local 123 to have your account unlocked.".ToErrorMessageFormat();
         }
         else if (!usrInfo.IsApproved)
         {
             myLogin.FailureText = "Your account has not yet been approved. You cannot login until an administrator has approved your account.<br>To have your account approved, please contact MIS at local 123.".ToErrorMessageFormat();
         }
     }
 }
Пример #53
0
        protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
        {
            Guid userId = JocysCom.ClassLibrary.Security.Helper.GetUserId <Guid>(ResetKeyLabel.Text);
            var  user   = Data.User.GetUser(userId);

            System.Web.Security.MembershipUser muser = Membership.GetUser(user.UserName);
            // Reset password: Start
            string tempPassword = muser.ResetPassword();

            muser.ChangePassword(tempPassword, NewPassword.Text);
            Membership.UpdateUser(muser);
            // Reset password: End
            SuccessPanel.Visible        = true;
            ChangePasswordPanel.Visible = false;
            RedirectionPanel.Visible    = true;
        }
Пример #54
0
        public override void UpdateUser(System.Web.Security.MembershipUser user)
        {
            using (var db = new ClimbingContext())
            {
                var u = db.UserProfiles.Find(user.ProviderUserKey);
                if (u == null)
                {
                    return;
                }

                /*if (db.UserProfiles.Count(usr => usr.Iid != u.Iid && usr.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase)) > 0)
                 *  throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateEmail);*/
                u.Email    = user.Email;
                u.Inactive = user.IsLockedOut;
                db.SaveChanges();
            }
        }
        public TUser To(TUser model, System.Web.Security.MembershipUser From)
        {
            Set(model, UserColumnType.Username, From.UserName);
            Set(model, UserColumnType.UserID, From.ProviderUserKey);
            Set(model, UserColumnType.Email, From.Email);
            Set(model, UserColumnType.PasswordQuestion, From.PasswordQuestion);
            Set(model, UserColumnType.Comment, From.Comment);
            Set(model, UserColumnType.IsApproved, From.IsApproved);
            Set(model, UserColumnType.IsLockedOut, From.IsLockedOut);
            Set(model, UserColumnType.CreateOn, From.CreationDate);
            Set(model, UserColumnType.LastLoginDate, From.LastLoginDate);
            Set(model, UserColumnType.LastActivityDate, From.LastActivityDate);
            Set(model, UserColumnType.LastPasswordChangedDate, From.LastPasswordChangedDate);
            Set(model, UserColumnType.LastLockoutDate, From.LastLockoutDate);

            return(model);
        }
    private void NewSearch()
    {
        System.Web.Security.MembershipUser usr = System.Web.Security.Membership.GetUser();
        if (usr != null)
        {
            //LabelDebug.Text = ":::" + usr.ToString() + "\n";
            //LabelDebug.Text = usr.ProviderUserKey.ToString();

            SqlConnection conn;
            SqlCommand    comm;
            SqlDataReader reader;
            string        connectionString =
                ConfigurationManager.ConnectionStrings[
                    "Assignment4"].ConnectionString;
            conn = new SqlConnection(connectionString);
            comm = new SqlCommand("SELECT UserName, RecipeName, SubmissionDate " +
                                  "FROM aspnet_Users INNER JOIN ProjectUserRecipe ON aspnet_Users.UserId = ProjectUserRecipe.UserId " +
                                  "INNER JOIN Project_Recipe ON ProjectUserRecipe.RecipeId = Project_Recipe.RecipeId " +
                                  "WHERE aspnet_Users.UserId = '" + usr.ProviderUserKey.ToString() + "' " +
                                  "ORDER BY SubmissionDate DESC", conn);



            try
            {
                conn.Open();
                reader = comm.ExecuteReader();
                //myRepeater.DataSource = reader;
                //myRepeater.DataBind();
                myGridView.DataSource = reader;
                myGridView.DataBind();
                reader.Close();
            }
            catch (Exception ex)
            {
                string script = "alert(\"ERROR BRO!: " + ex.ToString() + "\");";
                ScriptManager.RegisterStartupScript(this, GetType(),
                                                    "ServerControlScript", script, true);
            }
            finally
            {
                conn.Close();
            }
        }
    }
        public void SendResetEmail(System.Web.Security.MembershipUser user)
        {
            string site = Common.Settings.Manager.Instance.System.WebsiteUrl.ToString();

            if (!site.EndsWith("\\") && !site.EndsWith("/"))
            {
                site += "/";
            }

            EmailView <ViewModels.Account.RecoveryViewModel>("~/Views/Templates/AccountRecoveryEmail.aspx",
                                                             new ViewModels.Account.RecoveryViewModel()
            {
                Email          = user.Email,
                ResetPwAddress = site + "Account/Recovery/?username="******"&reset=" + HashResetParams(user.UserName, user.ProviderUserKey.ToString()),
                IpAddress      = Common.Utilities.GetClientIpAddress(Request),
                UserName       = user.UserName
            }, user.Email, "Account Recovery");
        }
Пример #58
0
    protected void SubmitAns_Click(object sender, EventArgs e)
    {
        System.Web.Security.MembershipUser user = System.Web.Security.Membership.GetUser();

        Question question = new Question();


        question.Title       = QuestionTitleV.Text;
        question.Description = DescriptionV.Text;
        question.UserName    = user.UserName;

        if (System.Web.Security.Roles.IsUserInRole("Admin"))
        {
            question.IsApproved = true;
        }
        else
        {
            question.IsApproved = false;
        }


        question.CreatedOn = Convert.ToString(DateTime.Now);
        question.IsDeleted = false;


        QuestionBL.Add(question);

        Email email = new Email();

        email.to = System.Configuration.ConfigurationManager.AppSettings["Mail"];

        email.subject = QuestionTitleV.Text;


        email.body = QuestionTitleV.Text + "..............." + System.Web.Security.Membership.GetUser().Email + "................" + DescriptionV.Text + "<br/>" + "http://localhost:4949/WebUI/Admin/Default.aspx";


        EmailBL.sendmail(email);


        QuestionTitleV.Text = " ";

        DescriptionV.Text = " ";
    }
Пример #59
0
        protected void ResetPassword_OnClick(object sender, EventArgs e)
        {
            string newPassword;

            System.Web.Security.MembershipUser u = Membership.GetUser(txtRecover.Text, false);

            if (u == null)
            {
                Msg.Text = "Usuario " + Server.HtmlEncode(txtRecover.Text) + " No encontrado.";
                return;
            }

            try
            {
                newPassword = u.ResetPassword();
            }
            catch (MembershipPasswordException)
            {
                Msg.Text = "Respuesta Invalida.";
                return;
            }
            catch (Exception)
            {
                //Msg.Text = e.Message;
                return;
            }

            if (newPassword != null)
            {
                MailController mail = new MailController();
                mail.SendMailRecovery("Solicitud Cambio de Clave ServiTarjeta", txtRecover.Text, Server.HtmlEncode(newPassword));
                Msg.Text      = "Correcto: Enviada la nueva contraseña a su correo electronico.";
                Msg.ForeColor = System.Drawing.Color.Red;


                // Msg.Text = "Contraseña reseteada. Su nueva Clave es: " + Server.HtmlEncode(newPassword);
            }
            else
            {
                Msg.Text = "Recuperacion de Contraseña fallido.";
            }
        }
Пример #60
-1
        public WebMoneyManager(MembershipUser u, string wmId, string targetPurse)
            : this(u)
        {
            if (!String.IsNullOrEmpty(wmId))
            {
                WmId? id = WmId.TryParse(wmId);
                if (!id.HasValue)
                {
                    throw new ArgumentException();
                }

                m_TargetWmId = id.Value;
            }

            if (!String.IsNullOrEmpty(targetPurse))
            {
                Purse? p = Purse.TryParse(targetPurse);
                if (!p.HasValue)
                {
                    throw new ArgumentException();
                }

                m_TargePurse = p.Value;
            }
        }