/// <summary>
        /// Creates a new principal based on the provided username
        /// </summary>
        public INSurveyPrincipal CreatePrincipal(string userName)
        {
            if (this.SingleUserMode)
            {
                return new NSurveyFormPrincipal(new NSurveyFormIdentity("nsurvey_admin", 0, null, null, null, true, true, false), null);
            }
            if ((userName == null) || (userName.Length == 0))
            {
                return new NSurveyFormPrincipal(new NSurveyFormIdentity("anonymous", -1, null, null, null, false, false, false), null);
            }
            //Scenario 1: AD user exists in the database :  UserInfo and rights can be retrieved from the database ( import or creation of valid users...)
            int? id = new Users().GetUserByIdFromUserName(userName);
            if ((id ?? 0) > 0)
            {
                var user = new Users().GetUserById(id ?? 0);
                var authUser = user;
                UserSettingData userSettings = new Users().GetUserSettings(authUser.Users[0].UserId);

                if (userSettings.UserSettings.Rows.Count > 0)
                {
                    List<string> userRightsStr = new List<string>();
                    int[] userRights = new Users().GetUserSecurityRights(authUser.Users[0].UserId);
                    for (int i = 0; i < userRights.Length; i++)
                    {
                        userRightsStr.Add(userRights[i].ToString());
                    }
                    return new NSurveyFormPrincipal(new NSurveyFormIdentity(authUser.Users[0].UserName, authUser.Users[0].UserId, authUser.Users[0].FirstName, authUser.Users[0].LastName, authUser.Users[0].Email,
                     userSettings.UserSettings[0].IsAdmin, userSettings.UserSettings[0].GlobalSurveyAccess,true), userRightsStr.ToArray());
                }
            }
            //TODO : Scenario 2: User doesn't exists in the database
            //Extract as much data from AD ( normally everything to even email should be possible... (and create user in the database for statistics?) 
            //Determine rights based on it's group memberships or it's own rights if present in the database

            
            return new NSurveyFormPrincipal(new NSurveyFormIdentity("anonymous", -1, null, null, null, false, false, false), null);

        }
		/// <summary>
		/// Get the current DB data and fill 
		/// the fields with them
		/// </summary>
		public void BindFields()
		{
            if (UserId < 0)
            {
                ViewState["UserName"] = string.Empty;
                UserNameTextBox.Text = string.Empty;
                FirstNameTextBox.Text = string.Empty;
                LastNameTextBox.Text = string.Empty;
                EmailTextBox.Text = string.Empty;
                NSurveyUserPlaceHolder.Visible = true;
                IsAdminCheckBox.Checked = false;
                HasSurveyAccessCheckBox.Checked = false;
                SurveysListBox.Enabled = false;
                UserSurveysListBox.Enabled = false;

                return;
            }

			// Check if we can edit extended properties
			if (_userProvider is INSurveyUserProvider)
			{
				NSurveyUserPlaceHolder.Visible = true;

				// Retrieve the user data
				NSurveyUserData userData = new Users().GetUserById(UserId);
				NSurveyUserData.UsersRow user = userData.Users[0];
				ViewState["UserName"] = user.UserName;
				UserNameTextBox.Text = user.UserName;
				FirstNameTextBox.Text = user.FirstName;
				LastNameTextBox.Text = user.LastName;
				EmailTextBox.Text = user.Email;
                // attempt to repopulate the PWTB
                //PasswordTextBox.Text = user.Password;
			}
			else
			{
				NSurveyUserPlaceHolder.Visible = false;
			}

			UserSettingData userSettings = new Users().GetUserSettings(UserId);
			if (userSettings.UserSettings.Rows.Count > 0)
			{
				IsAdminCheckBox.Checked = userSettings.UserSettings[0].IsAdmin;
				HasSurveyAccessCheckBox.Checked = userSettings.UserSettings[0].GlobalSurveyAccess;
			}
			else
			{
				IsAdminCheckBox.Checked = false;
				HasSurveyAccessCheckBox.Checked = false;
			}
			SurveysListBox.Enabled = !HasSurveyAccessCheckBox.Checked;
			UserSurveysListBox.Enabled = !HasSurveyAccessCheckBox.Checked;
			BindSurveyDropDownLists();
		}
		/// <summary>
		/// Validate all fields to make sure 
		/// no errors has occured
		/// </summary>
		private bool ValidateFieldOptions()
		{		
			if (!(_userProvider is INSurveyUserProvider))
			{
				return true;
			}

			if (UserNameTextBox.Text.Length == 0)
			{
				MessageLabel.Visible = true;
                ((PageBase)Page).ShowErrorMessage(MessageLabel,((PageBase)Page).GetPageResource("UserNameRequiredMessage"));
				RePopulatePasswordBox();
				return false;
			}

			int userNameId = new Users().GetUserByIdFromUserName(UserNameTextBox.Text);
			if (userNameId != -1 && userNameId != UserId)
			{
				MessageLabel.Visible = true;
                ((PageBase)Page).ShowNormalMessage(MessageLabel,((PageBase)Page).GetPageResource("UserNameTakenMessage"));
				RePopulatePasswordBox();
				return false;
			}

			Regex re = new Regex(@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}" +
				@"\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\" + 
				@".)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
			if (EmailTextBox.Text.Length > 0 && 
				!re.IsMatch(EmailTextBox.Text))
			{
				MessageLabel.Visible = true;
                ((PageBase)Page).ShowErrorMessage(MessageLabel,((PageBase)Page).GetPageResource("InvalidEmailMessage"));
				RePopulatePasswordBox();
				return false;
			}

			return true;
		}
        private void ValidateCredentialsButton_Click(object sender, System.EventArgs e)
        {
            string enteredPwd = PasswordTextBox.Text.Trim();
            string enteredUname = LoginTextBox.Text.Trim();
            if (enteredUname.Length > 0 && enteredPwd.Length > 0)
            {
                string encryptedPwd;

                int? id = new Users().GetUserByIdFromUserName(LoginTextBox.Text);


                if ((id ?? 0) > 0)
                {
                    var sec = new LoginSecurity();
                    var user = new Users().GetUserById(id ?? 0);
                    string pwd = user.Users[0].Password;
                    string salt = user.Users[0].IsPasswordSaltNull() ? null : user.Users[0].PasswordSalt;
                    if (string.IsNullOrEmpty(salt))// Unhashed old style .Create salted password and update
                    {
                        encryptedPwd = new User().EncryptUserPassword(enteredPwd);
                        salt = sec.CreateSaltKey(5);
                    }
                    else
                    {
                        salt = user.Users[0].PasswordSalt;
                        encryptedPwd = sec.CreatePasswordHash(enteredPwd, salt);
                    }

                    if (user.Users[0].Password == encryptedPwd)
                    {

                        var authUser = user;
                        UserSettingData userSettings = new Users().GetUserSettings(authUser.Users[0].UserId);

                        if (userSettings.UserSettings.Rows.Count > 0)
                        {
                            System.Text.StringBuilder userInfos = new System.Text.StringBuilder();
                            userInfos.Append(authUser.Users[0].UserName + ",");
                            userInfos.Append(authUser.Users[0].UserId + ",");
                            userInfos.Append(authUser.Users[0].FirstName + ",");
                            userInfos.Append(authUser.Users[0].LastName + ",");
                            userInfos.Append(authUser.Users[0].Email + ",");
                            userInfos.Append(userSettings.UserSettings[0].IsAdmin + ",");
                            userInfos.Append(userSettings.UserSettings[0].GlobalSurveyAccess);

                            userInfos.Append("|");

                            int[] userRights = new Users().GetUserSecurityRights(authUser.Users[0].UserId);
                            for (int i = 0; i < userRights.Length; i++)
                            {
                                userInfos.Append(userRights[i].ToString());
                                if (i + 1 < userRights.Length)
                                {
                                    userInfos.Append(",");
                                }

                            }

                            if (authUser.Users[0].IsPasswordSaltNull())
                            {
                                authUser.Users[0].PasswordSalt = salt;
                                authUser.Users[0].Password = sec.CreatePasswordHash(enteredPwd, salt);
                                ((INSurveyUserProvider)_userProvider).UpdateUser(authUser);
                            }

                            FormsAuthentication.SetAuthCookie(userInfos.ToString(), false);

                            var x = UserFactory.Create().CreatePrincipal(userInfos.ToString());


                            // ((Wap)this.Master).isTreeStale = true;

                            ((PageBase)Page).SelectedFolderId = null;
                            // ((Wap)this.Master).RebuildTree();
                            UINavigator.NavigateToFirstAccess(x, -1);
                        }
                    }
                }
            }

            MessageLabel.Visible = true;
            ((PageBase)Page).ShowErrorMessage(MessageLabel, ((PageBase)Page).GetPageResource("InvalidLoginPasswordMessage"));
        }