public JsonResult RemoveAuditEvents(List<int> Items)
        {
            RequestResultModel Model = new RequestResultModel();

            if (Items != null)
            {
                foreach (int Item in Items)
                    AuditEvents.GetBy(Item).Delete();

                Model.Message = "Selected audit items have been removed successfully.";
            }
            else
            {
                AuditEvents.RemoveAll();
                Model.Message = "All audit items have been removed successfully.";
            }

            Model.InfoType = RequestResultInfoType.Success;
            Model.Title = "Removing Audit Items";

            return Json(new
            {
                NotifyType = NotifyType.PageInline,
                Html = this.RenderPartialView(@"_RequestResultPageInLine", Model)

            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult SetShowInSignUp(bool Flag, int FieldID)
        {
            ProfileFields.SetShowInSignUp(Flag, FieldID);

            RequestResultModel _model = new RequestResultModel();
            _model.InfoType = RequestResultInfoType.Success;

            return Json(new
            {
                NotifyType = NotifyType.PageInline,
                Html = "",

            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult SaveFieldGroup(int GroupID, string Name, string Description, string Order, bool IsActive, bool AdminUseOnly)
        {
            ProfileFieldGroup fieldGroup = ProfileFieldGroups.GetBy(GroupID);
            String Message = "";

            if (fieldGroup.FieldGroupName.Trim().ToLower() != Name.Trim().ToLower())
            {
                if (ProfileFieldGroups.GetByName(Name.Trim()).FieldGroupID > 0)
                    Message = "The group \"" + Name + "\" already exists.";
            }

            if (fieldGroup.FieldGroupName.Trim().ToLower().Length == 0)
                    Message = "The group name should not be empty.";

            if (Message != "")
            {
                RequestResultModel _model = new RequestResultModel();
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.Message = Message;
                AuditEvent.AppEventWarning(Profile.Member.Email, Message);

                return Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model),

                }, JsonRequestBehavior.AllowGet);
            }

            fieldGroup.FieldGroupName = Name;
            fieldGroup.FieldGroupDescription = Description;
            fieldGroup.IsActive = IsActive ? 1 : 0;
            fieldGroup.AdminUseOnly = AdminUseOnly ? 1 : 0;
            fieldGroup.Save();

            if (GroupID > 0)
                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" profile group has been updated.", Name));
            else
                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" profile group has been added.", Name));

            if (Order != "")
                ProfileFieldGroups.UpdateOrder(Order);

            return Json(new
            {
                NotifyType = -1,
                Html = "",

            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SignIn(string Name, string Password, bool RememberMe, string ReturnUrl, string RequestID, string SessionID)
        {
            if (AppSession.Parameters.LDAPEnabled.Value == "true" && Name.IndexOf("@") <= 0)
            {
                Name = String.Format("{0}@{1}", Name, AppSession.Parameters.LDAPDomain.Value);
            }

            RequestResultModel _model = new RequestResultModel();
            Member Member = Members.GetByEmailOrName(Name, Name);

            if (AppSession.ReturnUrl == null || AppSession.ReturnUrl.Length > 0)
            {

            }
            else if (ReturnUrl == null || ReturnUrl.Trim().Length == 0 || ReturnUrl.Trim().Replace("/", "").Replace("\\", "").Length == 0)
            {
                _model.Title = GetLabel("Account.Controller.Warning");
                _model.Message = GetLabel("Account.Controller.WrongUser");
                _model.InfoType = RequestResultInfoType.Information;
                AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongUser, Name, Name), AuditEvent.GetSessionDetails("The return URL is empty. This is not allowed. Please add ReturnUrl to the link or set Redirect After SingIn parameter under Settings->Rules."));

                Session["MemberProfile"] = null;

                return Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }

            if (Member.MemberID > 0)
            {
                List<Role> rolesByMember = Web.Admin.Logic.Collections.Roles.GetByMember(Member.MemberID);

                // Check if account is not activated.
                Role _searchRole = rolesByMember.Where(t => t.Name.ToLower() == "Not Activated".ToLower()).FirstOrDefault();
                if (_searchRole != default(Role))
                {
                    _model.Title = GetLabel("Account.Controller.Warning");
                    _model.Message = GetLabel("Account.Controller.NotActivated");
                    _model.InfoType = RequestResultInfoType.Information;
                    AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountNotActivated, Member.Name, Member.Email));

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                // Check if account was blocked.
                MemberProfile profile = new MemberProfile(Member);
                _searchRole = rolesByMember.Where(t => t.Name.ToLower() == "Blocked".ToLower()).FirstOrDefault();
                Role _searchRoleIsAdmin = profile.Roles.Where(t => t.Name.ToLower() == "Admins".ToLower()).FirstOrDefault();

                if (_searchRole != default(Role) && _searchRoleIsAdmin == default(Role))
                {
                    _model.Title = GetLabel("Account.Controller.Warning");
                    _model.Message = GetLabel("Account.Controller.AccountBlocked");
                    _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                    AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountAccountBlocked, Member.Name, Member.Email));

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model),
                        RedirectTo = (AppSession.Parameters.RulesPasswordFailedRedirect != null & AppSession.Parameters.RulesPasswordFailedRedirect.Value.Length  > 0) ? AppSession.Parameters.RulesPasswordFailedRedirect.Value : ""

                    }, JsonRequestBehavior.AllowGet);
                }
            }

            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // The member email can be changed by LDAP auth because the first part of e-mail can be different with user network id. //
            //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            bool IsAuthenticate = Authenticate(ref Name, Password);

            // LDAP auth was fine but a member has been just created. Try to load the member.
            if (IsAuthenticate && Member.MemberID <= 0)
            {
                Member = Members.GetByEmailOrName(Name, Name);
            }

            if (Member.MemberID > 0 && IsAuthenticate)
            {
                String RedirectTo = "";
                RedirectTo = SignInMember(Name, Member, RememberMe, ReturnUrl);

                return Json(new
                {
                    IsLocalUrl = Url.IsLocalUrl(ReturnUrl),
                    RedirectTo = RedirectTo

                }, JsonRequestBehavior.AllowGet);

            }
            else if (Member.MemberID > 0)
                AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.MemberWrongPassword, Member.Name, Member.Email));
            else if (Member.MemberID <= 0)
                AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.MemberWrongEmail, Name));

            _model.Title = GetLabel("Account.Controller.Warning");
            _model.Message = GetLabel("Account.Controller.WrongUser");
            _model.InfoType = RequestResultInfoType.ErrorOrDanger;
            // AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongUser, Member.Name, Member.Email), AuditEvent.GetSessionDetails());

            return Json(new
            {
                NotifyType = NotifyType.DialogInline,
                Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult ChangePasswordAccount(string Password, string Confirmation, string Token, String ReturnUrl)
        {
            if (Token != null && Token.Length > 0)
            {
               ActionToken actionToken = ActionTokens.GetBy(Token, ActionTokenTypes.PasswordReset);
               if (actionToken.ActionID <= 0)
               {
                   AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongResetPassLink, Token) + " Member redirected to: " + (ReturnUrl != null ? ReturnUrl : ""));

                   return Json(new
                   {
                       RedirectTo = ((ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : Url.Content("~/")),
                   }, JsonRequestBehavior.AllowGet);
               }
            }

            if (AppSession.Parameters.RegistrationResetPassword.Value == "false")
            {
                if (AppSession.IsMemberInAdminRole)
                {

                }
                else
                {
                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to do activation but the activation was switched off. ", AuditEvent.GetSessionDetails());
                    return Json(new
                    {
                        RedirectTo = ((ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : Url.Content("~/")),
                    }, JsonRequestBehavior.AllowGet);
                }
            }

            RequestResultModel model = new RequestResultModel();

            model.Title = GetLabel("Account.Controller.Warning");
            model.Message = GetLabel("Account.Controller.WrongResetPassLink");
            model.InfoType = RequestResultInfoType.Warning;

            if ((Password != null && Password.Length > 0 && Password.Length < AppSession.PasswordMaxLength) ||
                (Confirmation != null && Confirmation.Length > 0 && Confirmation.Length < AppSession.PasswordMaxLength))
            {
                model.Message = String.Format("{0}", String.Format(GetLabel("Account.CreateAccount.PasswordLength"), AppSession.PasswordMaxLength));
                model.InfoType = RequestResultInfoType.ErrorOrDanger;
            }
            else if (Password.Trim() != Confirmation.Trim())
            {
                model.Message = String.Format("{0}", GetLabel("Account.CreateAccount.PasswordNoMatch"));
                model.InfoType = RequestResultInfoType.ErrorOrDanger;
            }
            else if (Token != null && Token.Length > 0)
            {
                try
                {
                    ActionToken actionToken = ActionTokens.GetBy(Token, ActionTokenTypes.PasswordReset);
                    if (actionToken.ActionID <= 0)
                    {
                        AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongResetPassLink, Token));

                        return Json(new
                        {
                            RedirectTo = (actionToken.ReturnURL != null && actionToken.ReturnURL.Length > 0) ? actionToken.ReturnURL : ((ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl :  @Url.Content("~/")),
                        }, JsonRequestBehavior.AllowGet);
                    }

                    Member Member = Members.GetByEmail(actionToken.Email);
                    if (Member.MemberID > 0)
                    {
                        Member.Password = Password;
                        Member.SavePassword();
                        actionToken.Delete();

                        try
                        {
                            if (!SendChangePasswordDoneEmail(Member.Name, Member.Email, Password))
                            {
                                AuditEvent.AppEventError(Member.Email, "Password changed notification e-mail has not been send!");
                            }
                        }
                        catch (Exception ex)
                        {
                            AuditEvent.AppEventError(Member.Email, "Send password changed notification: Something went wrong with e-mail notification: " + ex.Message, AuditEvent.GetSessionDetails(ex.StackTrace), true);
                        }

                        model.Title = GetLabel("Account.Controller.Congrat");
                        model.Message = GetLabel("Account.Controller.PassChanged");
                        model.InfoType = RequestResultInfoType.Success;
                        AuditEvent.AppEventSuccess(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountPassChanged, Member.Name, Member.Email));
                    }
                    else
                    {
                        AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongResetPassLink, Token));

                        return Json(new
                        {
                            RedirectTo = (actionToken.ReturnURL != null && actionToken.ReturnURL.Length > 0) ? actionToken.ReturnURL : ((ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : Url.Content("~/")),
                        }, JsonRequestBehavior.AllowGet);

                    }
                }
                catch
                {
                    // Log - wrong activation token
                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongResetPassLink, Token));
                }
            }

            return Json(new
            {
                Status = model.InfoType,
                NotifyType = NotifyType.DialogInline,
                Html = this.RenderPartialView(@"_RequestResultDialogInLine", model)

            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Register(string Name, string Email, string Password, string Confirmation, string ReturnUrl, List<ProfileFieldInfo> FieldInfo, string RequestID, string SessionID, int TimeZoneOffset)
        {
            AppParams.RefreshAppParameters();
            string AfterSingUpRedirectUrl = "";

            if (AppSession.Parameters.RegistrationSelfRegistration.Value == "false")
            {
                if (AppSession.IsMemberInAdminRole)
                {

                }
                else
                {

                    if (ReturnUrl == null || ReturnUrl.Trim().Length == 0)
                        ReturnUrl = (ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : ((AppSession.Parameters.RulesRedirectAfterLogin.Value != null && AppSession.Parameters.RulesRedirectAfterLogin.Value.Length > 0) ? AppSession.Parameters.RulesRedirectAfterLogin.Value : Url.Content("~/"));

                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to Register notification but it was switched off. ", AuditEvent.GetSessionDetails());
                    return new RedirectResult(ReturnUrl);
                }
            }

            RequestResultModel _model = new RequestResultModel();

            if (AppSession.IsEmail(Name))
            {
                _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.NameLooksLikeEmail"));
            }

            if (Name == null || Name.Trim().Length == 0 ||
               ((Password == null || Password.Trim().Length == 0)) ||
               Email == null || Email.Trim().Length == 0 ||
               Password != Confirmation ||
               !AppSession.IsEmail(Email) ||
               (Password != null && Password.Length > 0 && Password.Length <=3) ||
               (Confirmation != null && Confirmation.Length > 0 && Confirmation.Length <=3))
            {
                if (Name == null || Name.Trim().Length == 0)
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.NameIsEmpty"));

                if ((Password == null || Password.Trim().Length == 0))
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.PasswordIsEmty"));

                if (Email == null || Email.Trim().Length == 0)
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.EmailIsEmpty"));

                if (Email != null && !AppSession.IsEmail(Email))
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.EmailWrongFromat"));

                if (Password != Confirmation)
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.PasswordNoMatch"));

                if ((Password != null && Password.Length > 0 && Password.Length < AppSession.PasswordMaxLength) ||
                (Confirmation != null && Confirmation.Length > 0 && Confirmation.Length < AppSession.PasswordMaxLength))
                {
                    _model.Message += String.Format("<li>{0}</<li>", String.Format(GetLabel("Account.CreateAccount.PasswordLength"), AppSession.PasswordMaxLength));
                }
            }

            // Check mandatory fields
            if (FieldInfo != null)
            {
                foreach (ProfileFieldInfo Field in FieldInfo)
                {
                    ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));
                    if (profileField.IsMandatory == 1 && (Field.Value == null || Field.Value.Trim().Length == 0))
                    {
                        _model.Message += String.Format("<li>{0}</li>", String.Format(GetLabel("Account.CreateAccount.Mandatory"), profileField.FieldName));
                    }

                    if (profileField.IsMandatory == 1 && profileField.FieldTypeID == ProfileFieldTypeEnum.CheckBox && Field.Value != null && Field.Value.ToLower() == "false")
                    {
                        _model.Message += String.Format("<li>{0}</li>", String.Format(GetLabel("Account.CreateAccount.Mandatory"), profileField.FieldName));
                    }
                }
            }

            bool nonAlphaNumeric = Name.Replace(" ", "").All(c => char.IsLetterOrDigit(c));
            if (!nonAlphaNumeric)
            {
                _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.NameNonAlfaNum"));
            }

            if (_model.Message.Length > 0)
            {
                _model.Message = String.Format("<ul class=\"error-message-list\">{0}</ul>", _model.Message);
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;

                return Json(new
                {
                    Status = RequestResultInfoType.ErrorOrDanger,
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }

            // Check email format
            if (!AppSession.IsEmail(Email))
            {
                _model.Title = GetLabel("Account.Controller.Warning");
                _model.Message = GetLabel("Account.Controller.WrongEmail");
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                AuditEvent.AppEventError(AppParams.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongEmail, Name, Email));
            }
            else
            {
                if (!AppSession.IsMailDomainAllowed(Email))
                {
                    _model.Title = GetLabel("Account.Controller.Warning");
                    _model.Message = GetLabel("Account.Controller.DomainNotAllowed");
                    _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                    AuditEvent.AppEventError(AppParams.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountDomainNotAllowed, Name, Email));
                }
                else
                {
                    Member Member = Members.GetByEmailOrName(Email, Name);

                    if (Member.MemberID > 0)
                    {
                        _model.Title = GetLabel("Account.Controller.Warning");
                        _model.Message = GetLabel("Account.Controller.AccountExists");
                        _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                        AuditEvent.AppEventError(AppParams.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountAccountExists, Name, Email));
                    }
                    else
                    {
                        // Was account activated ?
                        // Was account blocked ?

                        Member member = new Logic.Objects.Member();
                        member.Name = Name;
                        member.Email = Email;
                        member.Password = Password;
                        member.IsBuiltIn = false;
                        member.Created = DateTime.UtcNow;

                        member.Save();

                        try
                        {
                            string ActivateToken = Web.Admin.Logic.StringTool.RandomString(20);

                            if (!SendActivationEmail(Name, Email, ActivateToken)){
                                throw new Exception("Creating an account notification e-mail has not been send!");
                            }

                            ActionToken actionToken = new ActionToken();
                            actionToken.Email = Email;
                            actionToken.Token = HttpUtility.UrlDecode(ActivateToken);
                            actionToken.ActionType = ActionTokenTypes.SelfActivation;
                            actionToken.ReturnURL = AppSession.ReturnUrl != null ? AppSession.ReturnUrl : ( AppSession.Parameters.RulesRedirectAfterLogout.Value != "" ? AppSession.Parameters.RulesRedirectAfterLogout.Value : "") ;
                            actionToken.Save();

                            if (member.MemberID > 0)
                            {
                                string[] RoleNames = AppParams.RegistrationMemberRegistrationToRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                                foreach (String RoleName in RoleNames)
                                {
                                    Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                                    if (role.RoleID > 0)
                                    {
                                        MemberRole memberrole = new MemberRole();
                                        memberrole.MemberID = member.MemberID;
                                        memberrole.RoleID = role.RoleID;
                                        memberrole.Save();
                                    }
                                }
                            }

                            if (FieldInfo != null)
                            {
                                foreach (ProfileFieldInfo Field in FieldInfo)
                                {
                                    ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));

                                    MemberProfileField memberProfileField = new MemberProfileField();
                                    memberProfileField.MemberID = member.MemberID;
                                    memberProfileField.FieldID = int.Parse(Field.ID);
                                    memberProfileField.FieldValue = Field.Value;

                                    if (Field.Value == null || Field.Value.Trim().Length == 0)
                                        memberProfileField.Delete();
                                    else
                                        memberProfileField.Save();
                                }
                            }

                             Domain _domain = Domains.GetByName(AppSession.SignUpDomain);

                             if (_domain.DomainID > 0)
                              {
                                  MemberDomain _memberDomain = new MemberDomain();
                                  _memberDomain.DomainID = _domain.DomainID;
                                  _memberDomain.MemberID = member.MemberID;
                                  _memberDomain.Save();
                              }

                            if (AppSession.Parameters.RulesRedirectAfterSignUp.Value != null && AppSession.Parameters.RulesRedirectAfterSignUp.Value.Length > 0)
                                AfterSingUpRedirectUrl = AppSession.Parameters.RulesRedirectAfterSignUp.Value;

                            _model.Title = GetLabel("Account.Controller.Congrat");
                            _model.Message = GetLabel("Account.Controller.ActivationMailSent");
                            _model.InfoType = RequestResultInfoType.Success;
                            AuditEvent.AppEventSuccess(AppParams.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountActivationMailSent, Name, Email));

                        }
                        catch (Exception ex) {
                            try
                            {
                                // Try to delete member if notification was failed.
                                member.Delete();
                            }
                            catch { }

                            _model.Title = GetLabel("Account.Controller.Warning");
                            _model.Message = GetLabel("Account.Controller.CantSendNotification");
                            _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                            AuditEvent.AppEventError(Email ,"Registration: Something went wrong with e-mail notification: " + ex.Message, AuditEvent.GetSessionDetails(ex.StackTrace),true);
                        }
                    }
                }
            }

            return Json(new
               {
               Status = _model.InfoType,
               RedirectTo = AfterSingUpRedirectUrl,
               NotifyType = NotifyType.DialogInline,
               Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

               }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SaveProfile(List<ProfileFieldInfo> FieldInfo, string TimeZoneID)
        {
            System.Threading.Thread.Sleep(1000);
            RequestResultModel _model = new RequestResultModel();
            _model.InfoType = RequestResultInfoType.ErrorOrDanger;
            _model.Message = "";

            // Check mandatory fields
            foreach (ProfileFieldInfo Field in FieldInfo)
            {
                ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));
                if (profileField.IsMandatory == 1 && (Field.Value == null || Field.Value.Trim().Length == 0))
                {
                    _model.Message += String.Format("<li>{0}</li>", String.Format(GetLabel("Account.CreateAccount.Mandatory"), profileField.FieldName));
                }

                if (profileField.IsMandatory == 1 && profileField.FieldTypeID == ProfileFieldTypeEnum.CheckBox && Field.Value != null && Field.Value.ToLower() == "false")
                {
                    _model.Message += String.Format("<li>{0}</li>", String.Format(GetLabel("Account.CreateAccount.Mandatory"), profileField.FieldName));
                }

            }

            if (_model.Message.Length > 0)
            {
                _model.Message = String.Format("<ul class=\"error-message-list\">{0}</ul>", _model.Message);
                return Json(new
                {
                    Status = RequestResultInfoType.ErrorOrDanger,
                    NotifyType = NotifyType.DialogInline,
                    Message = HttpUtility.HtmlDecode(this.RenderPartialView(@"_RequestResultPageInLine", _model))

                }, JsonRequestBehavior.AllowGet);
            }

            if (Profile.Member.TimeZoneID != TimeZoneID)
                AuditEvent.AppEventInfo(AppSession.Profile.Member.Email, String.Format("Member updated time zone to: \"{0}\" ", Profile.Member.TimeZoneID));

            Profile.Member.TimeZoneID = TimeZoneID;
            Profile.Member.UpdateTimeZone();

            String FieldValues = "";
            List<MemberProfileField> memberProfileFields = MemberProfileFields.GetByMember(Profile.Member.MemberID);
            foreach (ProfileFieldInfo Field in FieldInfo)
            {
                String Value = Field.Value != null ? Field.Value.Trim() : Field.Value;
                ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));
                MemberProfileField memberProfileField = MemberProfileFields.GetField(memberProfileFields, int.Parse(Field.ID));

                if (profileField.Encrypted == 1 && memberProfileField.FieldValue != null && memberProfileField.FieldValue.Length > 0)
                {
                    memberProfileField.FieldValue = Encryptor.DecryptStringAES(memberProfileField.FieldValue, AppSession.EncryptionKey);
                }

                if (Value != memberProfileField.FieldValue)
                    FieldValues += String.Format("<b>Name</b>:  {0} <b>Before:</b>  \"{1}\" <b>Now:</b>  \"{2}\"<br/>", profileField.FieldName, memberProfileField.FieldValue, Value);

                memberProfileField.MemberID = Profile.Member.MemberID;
                memberProfileField.FieldID = int.Parse(Field.ID);
                memberProfileField.FieldValue = Value;

                if (profileField.Encrypted == 1 && memberProfileField.FieldValue != null && memberProfileField.FieldValue.Length > 0)
                {
                    memberProfileField.FieldValue = Encryptor.EncryptStringAES(memberProfileField.FieldValue, AppSession.EncryptionKey);
                }

                memberProfileField.Save();
            }

            memberProfileFields = MemberProfileFields.GetByMember(Profile.Member.MemberID);

            List<MemberFieldNameValue> MemberFieldNameValues = new List<MemberFieldNameValue>();
            foreach (MemberProfileField memberField in memberProfileFields)
                MemberFieldNameValues.Add(new MemberFieldNameValue { Name = memberField.ProfileFieldID.ToString(), Value = memberField.FieldValue, Type = (int)ProfileFields.GetBy(memberField.FieldID).FieldTypeID});

            _model.Message = "Your profile has been updated successfully.";
            _model.InfoType = RequestResultInfoType.Success;

            AuditEvent.AppEventInfo(AppSession.Profile.Member.Email, String.Format("Profile of \"{0}\" {1} member has been updated successfully.",AppSession.Profile.Member.Name,AppSession.Profile.Member.Email) , AuditEvent.GetSessionDetails(FieldValues));

            return Json(new
            {
                Status = RequestResultInfoType.Success,
                NotifyType = NotifyType.DialogInline,
                Message = HttpUtility.HtmlDecode(this.RenderPartialView(@"_RequestResultPageInLine", _model)),
                MemberFields = MemberFieldNameValues,
                TimeZoneID = Profile.Member.TimeZoneID != null && Profile.Member.TimeZoneID.Length > 0 ? Profile.Member.TimeZoneID : ""

            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult SaveRole(RoleInfo Info)
        {
            RequestResultModel _model = new RequestResultModel();

            if (Info.Name == null || Info.Name.Trim().Length == 0)
            {
                _model = new RequestResultModel();
                _model.Title = "Warning";
                _model.Message = "Name is empty. Please, enter role name.";
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }

            if (!AppSession.IsColor(Info.Color))
            {
                _model = new RequestResultModel();
                _model.Title = "Warning";
                _model.Message = "Wrong color value or format, please check.";
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }

            if (Info.RoleID > 0)
            {
                Role role = Web.Admin.Logic.Collections.Roles.GetBy(Info.RoleID);
                Role roleExists = Web.Admin.Logic.Collections.Roles.GetBy(Info.Name);

                // The role has been deleted.
                if (role.RoleID <= 0)
                {
                    _model.Title = "Warning";
                    _model.Message = String.Format("Role '{0}' doesn't exist. Please, refresh role list and try again.", roleExists.Name);
                    AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                // The role already esists.
                if (roleExists.RoleID > 0 && Info.RoleID != roleExists.RoleID)
                {
                    _model.Title = "Warning";
                    _model.Message = String.Format("Role '{0}' already exists. Please, change role name and try again.", roleExists.Name);
                    AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                if (!role.IsBuiltIn)
                {
                    role.Name = Info.Name;
                    role.IsBuiltIn = false;
                }
                else
                {
                    role.IsBuiltIn = true;
                }

                role.Settings = Info.Settings;
                role.BackColor = Info.Color != null ? Info.Color.Replace("#", "") : "FFFFFF";
                role.ForeColor = Role.ContrastColor(role.BackColor.Replace("#", ""));
                role.Save();

                _model = new RequestResultModel();
                _model.Message = String.Format("Role \"{0}\"has been updated.",role.Name);
                _model.HideInSeconds = 4000;
                AuditEvent.AppEventSuccess(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model)

                }, JsonRequestBehavior.AllowGet);

            }
            else
            {
                Role roleExists = Web.Admin.Logic.Collections.Roles.GetBy(Info.Name);

                // The role already esists.
                if (roleExists.RoleID > 0)
                {
                    _model.Title = "Warning";
                    _model.Message = String.Format("Role '{0}' already exists. Please, change role name and try again.", roleExists.Name);

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                Role Role = new Role();
                Role.Name = Info.Name;
                Role.Settings = Info.Settings;
                Role.BackColor = Info.Color != null ? Info.Color.Replace("#", "") : "FFFFFF";
                Role.ForeColor = Role.ContrastColor(Role.BackColor.Replace("#", ""));
                Role.IsBuiltIn = false;
                Role.Save();

                _model.Message = String.Format("New role \"{0}\" has been created.",Role.Name);

                return Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }
        }
        public JsonResult SaveMember(MemberInfo Info)
        {
            RequestResultModel _model = new RequestResultModel();
            _model.InfoType = RequestResultInfoType.ErrorOrDanger;
            _model.Message = "";

            Member member = null;

            if (AppSession.IsEmail(Info.Name))
            {
                _model.Message += String.Format("<li>{0}</<li>", "The member's name looks like an e-mail address. Please change it.");
            }

            if (Info.Name == null || Info.Name.Trim().Length == 0 ||
                ((Info.Password == null || Info.Password.Trim().Length == 0 ) && Info.MemberID == 0) ||
                Info.Email == null || Info.Email.Trim().Length == 0 ||
                Info.Password != Info.Confirmation ||
                !AppSession.IsEmail(Info.Email))
            {
                if (Info.Name == null || Info.Name.Trim().Length == 0)
                    _model.Message += String.Format("<li>{0}</li>","Name is empty. Please, enter member name.");

                if ((Info.Password == null || Info.Password.Trim().Length == 0) && Info.MemberID == 0)
                    _model.Message += String.Format("<li>{0}</li>","Password is empty. Please, enter member password.");

                if (Info.Email == null || Info.Email.Trim().Length == 0)
                    _model.Message += String.Format("<li>{0}</li>","Email is empty. Please, enter member email.");

                if (Info.Email!= null && !AppSession.IsEmail(Info.Email))
                    _model.Message += String.Format("<li>{0}</li>","Email has wrong format. Please, check it.");

                if (Info.Password != Info.Confirmation)
                    _model.Message += String.Format("<li>{0}</li>","Password does not match confirmation. Please, check it.");

                Member Member = Web.Admin.Logic.Collections.Members.GetBy(Info.MemberID);
                AuditEvent.AppEventWarning(Profile.Member.Email, String.Format(AuditEvent.SavingMemberInfo, Member.Name, Member.Email, _model.Message));
            }

            // Check mandatory fields
            if (Info.FieldInfo != null)
            {
                foreach (ProfileFieldInfo Field in Info.FieldInfo)
                {
                    ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));
                    if (profileField.IsMandatory == 1 && (Field.Value == null || Field.Value.Trim().Length == 0))
                    {
                        _model.Message += String.Format("<li>{0}</li>", String.Format(GetLabel("Account.CreateAccount.Mandatory"), profileField.FieldName));
                    }

                    if (profileField.IsMandatory == 1 && profileField.FieldTypeID == ProfileFieldTypeEnum.CheckBox && Field.Value != null && Field.Value.ToLower() == "false")
                    {
                        _model.Message += String.Format("<li>{0}</li>", String.Format(GetLabel("Account.CreateAccount.Mandatory"), profileField.FieldName));
                    }

                }
            }

            bool nonAlphaNumeric = Info.Name.Replace(" ", "").All(c => char.IsLetterOrDigit(c));
            if (!nonAlphaNumeric)
            {
                _model.Message += String.Format("<li>{0}</<li>", "The name contains non-alpha numeric characters (#@!$ etc...). Please change it.");
            }

            if (_model.Message.Length > 0)
            {
                _model.Message = String.Format("<ul class=\"error-message-list\">{0}</ul>", _model.Message);
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;

                return Json(new
                {
                    Status = RequestResultInfoType.ErrorOrDanger,
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }

            if (Info.MemberID > 0)
                member = Web.Admin.Logic.Collections.Members.GetBy(Info.MemberID);

            Member existsMember = Web.Admin.Logic.Collections.Members.GetByEmailOrName(Info.Email.Trim(), Info.Name.Trim());
            if (Info.MemberID <= 0 && existsMember.MemberID > 0)
            {
                _model.Title = "Warning";
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.Message = String.Format("Member \"{0}\" &lt;{1}&gt; already exists. Please, change member email and try again.", existsMember.Name, existsMember.Email);
                AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }
            else if (Info.MemberID > 0)
            {
                if (existsMember.MemberID > 0 && Info.MemberID != existsMember.MemberID)
                {
                    _model.Title = "Warning";
                    _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                    _model.Message = String.Format("Member \"{0}\" &lt;{1}&gt; already exists. Please, change member email and try again.", existsMember.Name, existsMember.Email);
                    AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                if (!member.IsBuiltIn)
                {
                    member.Name = Info.Name;
                    member.IsBuiltIn = false;
                }
                else
                {
                    member.IsBuiltIn = true;
                }

                member.Email = Info.Email;
                member.Password = Info.Password;
                member.TimeZoneID = Info.TimeZoneID;
                member.Save();

                if (member.Password != null && member.Password.Length > 0){
                    member.SavePassword();
                }

                if (Info.FieldInfo != null)
                {
                    List<MemberProfileField> memberProfileFields = MemberProfileFields.GetByMember(member.MemberID);
                    foreach (ProfileFieldInfo Field in Info.FieldInfo)
                    {
                        ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));
                        MemberProfileField memberProfileField = MemberProfileFields.GetField(memberProfileFields, int.Parse(Field.ID));

                        if (profileField.Encrypted == 1 && memberProfileField.FieldValue != null && memberProfileField.FieldValue.Length > 0)
                        {
                            memberProfileField.FieldValue = Encryptor.DecryptStringAES(memberProfileField.FieldValue, AppSession.EncryptionKey);
                        }

                        if (memberProfileField != null)
                        {
                            memberProfileField.MemberID = member.MemberID;
                            memberProfileField.FieldID = int.Parse(Field.ID);
                            memberProfileField.FieldValue = Field.Value != null ? Field.Value.Trim() : Field.Value;

                            if (profileField.Encrypted == 1 && memberProfileField.FieldValue != null && memberProfileField.FieldValue.Length > 0)
                            {
                                memberProfileField.FieldValue = Encryptor.EncryptStringAES(memberProfileField.FieldValue, AppSession.EncryptionKey);
                            }

                            memberProfileField.Save();

                        }
                    }
                }

                 List<Domain> _domains = Domains.Get();
                 foreach (Domain _domain in _domains)
                 {
                     MemberDomain _memberDomain = new MemberDomain();
                     _memberDomain.DomainID = _domain.DomainID;
                     _memberDomain.MemberID = member.MemberID;

                     if (Info.Domains != null)
                     {
                         if (Info.Domains.Where(t => t == _domain.DomainID).FirstOrDefault() != default(int))
                             _memberDomain.Save();
                         else
                             _memberDomain.Delete();
                     }
                     else
                         _memberDomain.Delete();
                 }

                _model = new RequestResultModel();
                _model.Message = String.Format("\"{0}\"<{1}> has been updated.",member.Name,member.Email);
                _model.HideInSeconds = 2000;
                AuditEvent.AppEventSuccess(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                Member memberExists = Web.Admin.Logic.Collections.Members.GetByEmail(Info.Email);
                if (memberExists.MemberID > 0)
                {
                    _model.Title = "Warning";
                    _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                    _model.Message = String.Format("\"{0}\" <{1}> already exists. Please, change member email and try again.", memberExists.Name, memberExists.Email);
                    AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                Member Member = new Member();
                Member.Name = Info.Name;
                Member.Email = Info.Email;
                Member.Password = Info.Password;
                Member.IsBuiltIn = false;
                Member.TimeZoneID = Info.TimeZoneID;
                Member.Save();

                if (Info.FieldInfo != null)
                {
                    List<MemberProfileField> memberProfileFields = MemberProfileFields.GetByMember(Member.MemberID);
                    foreach (ProfileFieldInfo Field in Info.FieldInfo)
                    {

                        ProfileField profileField = ProfileFields.GetBy(int.Parse(Field.ID));
                        MemberProfileField memberProfileField = MemberProfileFields.GetField(memberProfileFields, int.Parse(Field.ID));
                        memberProfileField.MemberID = member.MemberID;
                        memberProfileField.FieldID = int.Parse(Field.ID);
                        memberProfileField.FieldValue = Field.Value;
                        memberProfileField.Save();
                    }
                }

                _model.InfoType = RequestResultInfoType.Success;
                _model.Message = String.Format("\"{0}\"<{1}> has been created.", Member.Name, Member.Email);
                AuditEvent.AppEventSuccess(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model),
                    MemberID = Member.MemberID

                }, JsonRequestBehavior.AllowGet);

            }
        }
        public ActionResult ResetAvatarImage(long MemberID = 0)
        {
            RequestResultModel _model = new RequestResultModel();

            try
            {
                if (MemberID > 0 && MemberID == Profile.Member.MemberID && Profile.Member.Avatar != null && Profile.Member.Avatar.Length > 0)
                {
                    string Path = String.Format("{0}/{1}.jpg", Server.MapPath("~/Avatar"), Profile.Member.Avatar);
                    if (System.IO.File.Exists(Path))
                    {
                        System.IO.File.Delete(Path);
                    }

                    Profile.Member.Avatar = null;
                    Profile.Member.UpdateAvatar();
                }
                else if ((MemberID > 0 && MemberID != Profile.Member.MemberID && AppSession.IsMemberInAdminRole))
                {
                    Member Member = Members.GetBy(MemberID);
                    string Path = String.Format("{0}/{1}.jpg", Server.MapPath("~/Avatar"), Member.Avatar);
                    if (System.IO.File.Exists(Path))
                    {
                        System.IO.File.Delete(Path);
                    }

                    Member.Avatar = null;
                    Member.UpdateAvatar();
                }

                _model.Title = GetLabel("Account.Controller.Congrat");
                _model.InfoType = RequestResultInfoType.Success;
                _model.Message = "Avatar image has been reset.";

            }
            catch (Exception ex)
            {
                _model.Title = GetLabel("Account.Controller.Warning");
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.Message = "Avatar image has noot been reset: " + ex.Message;
            }

            String Message = this.RenderPartialView(@"_RequestResultPageInLine", _model);
            String FileURL = Url.Content("~/Content/images/no-photo.png");

            MemberSocialNetwork _memberNetwork = MemberSocialNetworks.GetByMemberID(MemberID);
            if (_memberNetwork.MemberSocialNetworkID > 0 && _memberNetwork.SocialNetworkID == 1)
                FileURL = String.Format("https://graph.facebook.com/{0}/picture?type=large",_memberNetwork.SocialNetworkUserID);
            else if (_memberNetwork.MemberSocialNetworkID > 0 && _memberNetwork.SocialNetworkID == 2)
                FileURL = String.Format("http://api.twitter.com/1/users/profile_image?screen_name={0}&size=bigger", _memberNetwork.SocialNetworkUserID); ;

            return Json(new
            {
                NotifyType = NotifyType.PageInline,
                Html = Message,
                FileURL = FileURL
            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult RemoveMemberToken(string Email)
        {
            RequestResultModel _model = new RequestResultModel();
            Member Member = Web.Admin.Logic.Collections.Members.GetByEmail(Email);

            if (!AppSession.IsEmail(Email))
            {
                _model.Title = GetLabel("Member.Controler.Warning");
                _model.Message = GetLabel("Member.Controler.WrongEmail");
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;

                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.SentRandomPasswordBadFormat, Email));
            }
            else
            {
                if (Member.MemberID <= 0)
                {
                    _model.Title = GetLabel("Member.Controler.Warning");
                    _model.Message = GetLabel("Member.Controler.AccountNotExists");
                    _model.InfoType = RequestResultInfoType.Warning;

                    AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.SentRandomPasswordNotExist, Email));
                }
                else
                {
                    string Token = Web.Admin.Logic.StringTool.RandomString(20);

                    MemberToken ExistToken = MemberTokens.GetByMember(Member.MemberID);
                    if (ExistToken.Delete())
                    {
                        _model.Title = GetLabel("Member.Controler.Congrat");
                        _model.Message = GetLabel("Member.Controler.MemberTokenRemoved");
                        _model.InfoType = RequestResultInfoType.Success;

                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("\"{0}\"<{1}> token has been removed by \"{2}\"<{3}>.", Member.Name, Email, Profile.Member.Name, Profile.Member.Email));
                    }
                }

            }

            MemberListModel _ListModel = new MemberListModel();
            _ListModel.Members.Add(Member);

            return Json(new
            {
                Status = _model.InfoType,
                NotifyType = NotifyType.DialogInline,
                Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model),
                TokenPanel = this.RenderPartialView(@"_MemberToken", _ListModel),

            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult ImportMembers()
        {
            System.Threading.Thread.Sleep(200);

            CultureInfo provider = CultureInfo.InvariantCulture;
            List<Member> MemberResult = new List<Member>();
            int LineNumber = 1;

            try
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    String FileContent = "";
                    HttpPostedFileBase PostedFile = Request.Files[i];

                    using (System.IO.Stream input = PostedFile.InputStream)
                    {
                        byte[] buffer = new byte[PostedFile.InputStream.Length];
                        input.Read(buffer, 0, buffer.Length);
                        FileContent = System.Text.ASCIIEncoding.UTF8.GetString(buffer);
                    }

                    if (FileContent.Length > 0)
                    {
                        string[] Lines = FileContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberUploadHasStarted, Lines.Length));

                        int Added = 0;
                        int Failed = 0;
                        int Exists = 0;

                        foreach (String Line in Lines)
                        {
                            System.Threading.Thread.Sleep(1);

                            if (LineNumber == 1 || Line == null || Line.Trim().Length == 0)
                            {
                                LineNumber++;
                                continue;
                            }

                            List<string> Values = new List<string>();
                            CsvParser parser = new CsvParser(Line);

                            foreach (string s in parser)
                                Values.Add(s.Trim());

                            if (Values.Count >= 11)
                            {
                                Member Member = Web.Admin.Logic.Collections.Members.GetByEmail(Values[2]);
                                if (Member.MemberID > 0)
                                {
                                    Member.UIMessage = "Member already exists.";
                                    Member.UILineNumber = LineNumber;
                                    Member.UIMessageType = Logic.UIMessageType.Warning;
                                    AuditEvent.AppEventWarning(Profile.Member.Email, String.Format(AuditEvent.MemberUploadMemberExists, Member.Name, Member.Email));
                                    Exists++;
                                }
                                else
                                {
                                    Member.Name = Values[0];
                                    Member.Email = Values[2];

                                    bool randomPassword = false;
                                    if (Values[3] == null || Values[3].Trim().Length == 0)
                                    {
                                        Member.Password = Web.Admin.Logic.StringTool.RandomString(10);
                                        randomPassword = true;
                                    }
                                    else
                                    {
                                        Member.Password = Values[3];
                                    }

                                    Member.Avatar = Values[4];

                                    if(Values[5] != null && Values[5].Length > 0)
                                    {
                                        try{

                                            if (Member.Avatar == null || Member.Avatar.Trim().Length == 0)
                                            {
                                                Member.Avatar = Web.Admin.Logic.StringTool.RandomString(24);
                                            }

                                            SaveAvatarFromBase64FromByteArray(Member.Avatar, Values[5]);

                                        }
                                        catch { Member.Avatar = ""; }
                                    }

                                    if(BuiltInRoleMember.ContainsMember(Member.Name))
                                        Member.IsBuiltIn = true;
                                    else
                                        Member.IsBuiltIn = false;

                                    try
                                    {
                                        Member.LastLogin = DateTime.ParseExact(Values[6], "dd.MM.yyyy HH:mm:ss", provider);
                                    }
                                    catch { }

                                    try
                                    {
                                        Member.Created = DateTime.ParseExact(Values[7], "dd.MM.yyyy HH:mm:ss", provider);
                                    }
                                    catch { }

                                    Member.Save();
                                    Added ++;

                                    if(Values[1] != null && Values[1].Length > 0)
                                    {
                                        string[] toRols = Values[1].Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries);
                                        foreach (string RoleName in toRols)
                                        {
                                            Role Role = Roles.GetBy(RoleName);
                                            if (Role.RoleID > 0)
                                            {
                                                MemberRole MemberRole = new MemberRole();
                                                MemberRole.MemberID = Member.MemberID;
                                                MemberRole.RoleID = Role.RoleID;
                                                MemberRole.Save();
                                            }
                                            else
                                            {
                                                // Create new role ?

                                            }
                                        }
                                    }

                                    Member.UIMessage = "Member has been added." + (randomPassword ? " (Random password)" : "");
                                    Member.UIMessageType = Logic.UIMessageType.Success;
                                    Member.UILineNumber = LineNumber;
                                    AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberUploadedItemAdded, Member.Name, Member.Email));
                                }

                                MemberResult.Add(Member);
                                if (Values[8] != null && Values[8].Trim().Length > 0)
                                {
                                    MemberToken Token = MemberTokens.GetByMember(Member.MemberID);

                                    if (Token.MemberTokenID <= 0)
                                        Token = MemberTokens.GetByToken(Values[8].Trim());

                                    if (Token.MemberTokenID <= 0)
                                    {
                                        MemberToken MemberToken = new MemberToken();
                                        MemberToken.MemberID = Member.MemberID;
                                        MemberToken.Token = Values[8];
                                        MemberToken.GeneratedBy = Values[9];

                                        try
                                        {
                                            MemberToken.Created = DateTime.ParseExact(Values[10], "dd.MM.yyyy HH:mm:ss", provider);
                                        }
                                        catch { }

                                        try
                                        {
                                            if (Values.Count == 12)
                                                MemberToken.Modified = DateTime.ParseExact(Values[11], "dd.MM.yyyy HH:mm:ss", provider);
                                        }
                                        catch { }

                                        MemberToken.Save();
                                    }
                                    else
                                    {
                                        Member member = Web.Admin.Logic.Collections.Members.GetBy(Token.MemberID);
                                        Member.UIMessage = String.Format("Member has been added, but API token \"{0}\" already exists in database for member \"{1}\" <{2}>", Values[8], member.Name, member.Email);
                                        Member.UIMessageType = Logic.UIMessageType.Warning;
                                    }
                                }
                            }
                            else if (Values.Count > 0)
                            {
                                Member Member = new Member();

                                Member.UIMessage = "Wrong line format. Number of columns: " + Values.Count.ToString();
                                Member.UIMessageType = Logic.UIMessageType.ErrorOrDanger;
                                Member.UILineNumber = LineNumber;
                                MemberResult.Add(Member);
                                Failed++;

                                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberUploadWrongLineFormat,LineNumber,Values.Count));
                            }

                            LineNumber++;
                        }

                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberUploadHasStarted, Lines.Length, Added, Exists, Failed));
                    }
                }

                System.Threading.Thread.Sleep(1000);
                MemberListModel Model = new MemberListModel();
                Model.Members = MemberResult;

                return Json(new
                {
                    NotifyType = NotifyType.Dialog,
                    Html = this.RenderPartialView(@"_ImportMembersResult", Model)

                }, "text/html", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

                RequestResultModel _model = new RequestResultModel();

                _model.Title = "Warning";
                _model.Message = String.Format("Something went wrong: {0}", HttpUtility.HtmlEncode(ex.Message));
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.HideInSeconds = 0;
                _model.Height = 250;

                AuditEvent.AppEventError(Profile.Member.Email, _model.Message, AuditEvent.GetSessionDetails(ex.StackTrace));

                return Json(new
                {
                    Status = "Ok",
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialog", _model)

                }, "text/html", JsonRequestBehavior.AllowGet);

            }
        }
        public ActionResult SendRandomPassword(string Email)
        {
            RequestResultModel _model = new RequestResultModel();
            Member Member = Web.Admin.Logic.Collections.Members.GetByEmail(Email);

            if (!AppSession.IsEmail(Email))
            {
                _model.Title = GetLabel("Member.Controler.Warning");
                _model.Message = GetLabel("Member.Controler.WrongEmail");
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;

                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.SentRandomPasswordBadFormat,Email));
            }
            else
            {
                if (Member.MemberID <= 0)
                {
                    _model.Title = GetLabel("Member.Controler.Warning");
                    _model.Message = GetLabel("Member.Controler.AccountNotExists");
                    _model.InfoType = RequestResultInfoType.Warning;

                    AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.SentRandomPasswordNotExist,Email));
                }
                else
                {
                    string Password =  Web.Admin.Logic.StringTool.RandomString(10);
                    Member.Password = Password;
                    Member.SavePassword();

                    bool result = SendRandomPasswordEmail(Member.Name, Email,Password);

                    if (result)
                    {
                        _model.Title = GetLabel("Member.Controler.Congrat");
                        _model.Message = GetLabel("Member.Controler.RandomPassSent");
                        _model.InfoType = RequestResultInfoType.Success;

                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.SentRandomPasswordSent, Member.Name, Email));
                    }
                    else
                    {
                        _model.Title = GetLabel("Member.Controler.Congrat");
                        _model.Message = GetLabel("Member.Controler.RandomPassDidNotSend");
                        _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                        AuditEvent.AppEventError(Profile.Member.Email, _model.Message);
                    }
                }

            }

            return Json(new
            {
                Status = _model.InfoType,
                NotifyType = NotifyType.DialogInline,
                Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult SortFields(String Fields,int GroupID)
        {
            ProfileFields.UpdateOrder(Fields, GroupID);

            RequestResultModel _model = new RequestResultModel();
            _model.InfoType = RequestResultInfoType.Success;

            return Json(new
            {
                NotifyType = NotifyType.PageInline,
                Html = "",

            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SetAvatarImage(ImageInfo ImageInfo)
        {
            RequestResultModel _model = new RequestResultModel();

            string Name = Web.Admin.Logic.StringTool.RandomString(24).ToLower();
            string Path = String.Format("{0}/{1}.jpg", Server.MapPath("~/Avatar"), Name);

            try
            {
                System.Drawing.Image OriginalImage = AppSession.AvatarTempImage;

                using (Bitmap bmp = new Bitmap(AppSession.AvatarImageSize, AppSession.AvatarImageSize, OriginalImage.PixelFormat))
                {
                    using (Graphics Graphic = System.Drawing.Graphics.FromImage(bmp))
                    {
                        Graphic.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
                        Graphic.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        Graphic.PixelOffsetMode = System.Drawing.Drawing2D.PixelOffsetMode.HighQuality;

                        Graphic.DrawImage(OriginalImage, new System.Drawing.Rectangle(0, 0, AppSession.AvatarImageSize, AppSession.AvatarImageSize), ImageInfo.sizeX, ImageInfo.sizeY, ImageInfo.sizeW, ImageInfo.sizeH, System.Drawing.GraphicsUnit.Pixel);

                        MemoryStream streamThumb = new MemoryStream();
                        bmp.SetResolution(OriginalImage.HorizontalResolution, OriginalImage.VerticalResolution);
                        bmp.Save(streamThumb, System.Drawing.Imaging.ImageFormat.Jpeg);

                        FileStream fs = new FileStream(Path, FileMode.Create);
                        byte[] imageBytes = streamThumb.ToArray();
                        fs.Write(imageBytes, 0, imageBytes.Length);
                        fs.Close();
                        fs.Dispose();

                        bmp.Dispose();
                        Graphic.Dispose();
                        OriginalImage.Dispose();

                        AppSession.AvatarTempImage.Dispose();
                        AppSession.AvatarTempImage = null;
                        streamThumb.Close();
                        streamThumb.Dispose();
                        System.GC.Collect();

                        if (ImageInfo.MemberID > 0 && AppSession.Profile.Member.MemberID == ImageInfo.MemberID)
                        {
                            if (Profile.Member.Avatar != null && Profile.Member.Avatar.Length > 0)
                            {
                                string PathPrev = String.Format("{0}/{1}.jpg", Server.MapPath("~/Avatar"), Profile.Member.Avatar);
                                if (System.IO.File.Exists(PathPrev))
                                {
                                    System.IO.File.Delete(PathPrev);
                                }
                            }

                            Profile.Member.Avatar = Name;
                            Profile.Member.UpdateAvatar();
                        }
                        else if (ImageInfo.MemberID > 0 && AppSession.Profile.Member.MemberID != ImageInfo.MemberID && AppSession.IsMemberInAdminRole)
                        {
                            Member Member = Members.GetBy(ImageInfo.MemberID);
                            if (Member.Avatar != null && Member.Avatar.Length > 0)
                            {
                                string PathPrev = String.Format("{0}/{1}.jpg", Server.MapPath("~/Avatar"), Member.Avatar);
                                if (System.IO.File.Exists(PathPrev))
                                {
                                    System.IO.File.Delete(PathPrev);
                                }
                            }

                            Member.Avatar = Name;
                            Member.UpdateAvatar();

                        }
                    }
                }

                _model.Title = GetLabel("Account.Controller.Congrat");
                _model.InfoType = RequestResultInfoType.Success;
                _model.Message = "Avatar image has been set.";

            }
            catch (Exception ex)
            {
                _model.Title = GetLabel("Account.Controller.Warning");
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.Message = "Avatar image has noot been set: " + ex.Message;
            }

            String Message = this.RenderPartialView(@"_RequestResultPageInLine", _model);

            return Json(new
            {
                NotifyType = NotifyType.PageInline,
                Html = Message,
                FileURL = Url.Content(String.Format("~/Avatar/{0}.jpg",Name))
            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult ImportRoles()
        {
            System.Threading.Thread.Sleep(200);
            CultureInfo provider = CultureInfo.InvariantCulture;

            List<Role> RoleResult = new List<Role>();
            try
            {
                for (int i = 0; i < Request.Files.Count; i++)
                {
                    System.Threading.Thread.Sleep(1);

                    String FileContent = "";
                    HttpPostedFileBase PostedFile = Request.Files[i];

                    using (System.IO.Stream input = PostedFile.InputStream)
                    {
                        byte[] buffer = new byte[PostedFile.InputStream.Length];
                        input.Read(buffer, 0, buffer.Length);
                        FileContent = System.Text.ASCIIEncoding.UTF8.GetString(buffer);
                    }

                    if (FileContent.Length > 0)
                    {
                        string[] Lines = FileContent.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.RoleUploadHasStarted, Lines.Length));

                        int LineNumber = 1;
                        foreach (String Line in Lines)
                        {
                            if (LineNumber == 1 || Line == null || Line.Trim().Length == 0)
                            {
                                LineNumber++;
                                continue;
                            }

                            List<string> Values = new List<string>();
                            CsvParser parser = new CsvParser(Line);

                            foreach (string s in parser)
                                Values.Add(s.Trim());

                            if (Values.Count >= 4)
                            {
                                Role Role = Web.Admin.Logic.Collections.Roles.GetBy(Values[0]);
                                if (Role.RoleID > 0)
                                {
                                    Role.UIMessage = "Role already exists.";
                                    Role.UILineNumber = LineNumber;
                                    Role.UIMessageType = Logic.UIMessageType.Warning;
                                    AuditEvent.AppEventWarning(Profile.Member.Email, String.Format(AuditEvent.RoleUploadMemberExists, Role.Name));
                                }
                                else
                                {
                                    Role.Name = Values[0];
                                    Role.Settings = Values[1];

                                    if (Values[3].Trim().Length == 0)
                                        Role.BackColor = "aaaaaa";
                                    else
                                        Role.BackColor = Values[2];

                                    if (Values[3].Trim().Length == 0)
                                        Role.ForeColor = "000000";
                                    else
                                        Role.ForeColor = Values[3];

                                    if (BuiltInRoleMember.ContainsRole(Role.Name))
                                        Role.IsBuiltIn = true;
                                    else
                                        Role.IsBuiltIn = false;

                                    try
                                    {
                                        Role.Created = DateTime.ParseExact(Values[4], "dd.MM.yyyy HH:mm:ss", provider);
                                    }
                                    catch { }

                                    try
                                    {
                                        Role.Modified = DateTime.ParseExact(Values[5], "dd.MM.yyyy HH:mm:ss", provider);
                                    }
                                    catch {
                                    }

                                    Role.Save();

                                    Role.UIMessage = "Role has been added.";
                                    Role.UIMessageType = Logic.UIMessageType.Success;
                                    Role.UILineNumber = LineNumber;
                                    AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.RoleUploadedItemAdded, Role.Name));

                                }

                                RoleResult.Add(Role);
                            }
                            else if (Values.Count > 0)
                            {
                                Role Role = new Role();

                                Role.UIMessage = "Wrong line format. Number of columns: " + Values.Count.ToString();
                                Role.UIMessageType = Logic.UIMessageType.ErrorOrDanger;
                                Role.UILineNumber = LineNumber;
                                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.RoleUploadWrongLineFormat, LineNumber, Values.Count));

                                RoleResult.Add(Role);
                            }

                            LineNumber++;
                        }

                    }
                }

                System.Threading.Thread.Sleep(1000);
                RoleListModel Model = new RoleListModel();
                Model.Roles = RoleResult;

                return Json(new
                {
                    NotifyType = NotifyType.Dialog,
                    Html = this.RenderPartialView(@"_ImportRolesResult", Model)

                }, "text/html", JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {

              RequestResultModel _model = new RequestResultModel();

              _model.Title = "Warning";
              _model.Message = String.Format("Something went wrong: {0}",HttpUtility.HtmlEncode(ex.Message));
              _model.InfoType = RequestResultInfoType.ErrorOrDanger;
              _model.HideInSeconds = 0;
              _model.Height = 250;

              AuditEvent.AppEventError(Profile.Member.Email, _model.Message, AuditEvent.GetSessionDetails(ex.StackTrace));

              return Json(new
              {
                  NotifyType = NotifyType.DialogInline,
                  Html = this.RenderPartialView(@"_RequestResultDialog", _model)

              }, "text/html", JsonRequestBehavior.AllowGet);

            }
        }
        public ActionResult UploadAvatarImage(long MemberID = 0)
        {
            System.Threading.Thread.Sleep(2000);

            Boolean FileOK = false;
            Boolean FileSaved = false;
            String Message = "";

            if (Request.Files.Count > 0)
            {
                String FileExtension = Path.GetExtension(Request.Files[0].FileName).ToLower();
                String[] allowedExtensions = { ".png", ".jpeg", ".jpg", ".gif", ".bmp" };
                for (int i = 0; i < allowedExtensions.Length; i++)
                {
                    if (FileExtension.ToLower() == allowedExtensions[i])
                    {
                        FileOK = true;
                        break;
                    }
                }
            }

            try
            {
                String Guid = System.Guid.NewGuid().ToString();
                byte[] buffer = new byte[Request.Files[0].InputStream.Length];
                AppSession.AvatarTempImage = ProcessImage(Request.Files[0].InputStream, 640, 480);
                FileSaved = true;
            }
            catch (Exception ex)
            {
                RequestResultModel _model = new RequestResultModel();
                _model.Title = GetLabel("Account.Controller.Warning");
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.Message = ex.Message + (ex.InnerException != null ? " " + ex.InnerException.Message : "") ;

                Message = this.RenderPartialView(@"_RequestResultPageInLine", _model);
            }

            if (FileOK && FileSaved)
                return Content("{\"Message\": \"\", \"MemberID\":" + MemberID + ", \"Name\":\"" + Web.Admin.Logic.StringTool.RandomString(24).ToLower() + "\"}", "text/html");
            else
                return Content("{\"Message\":" + ToJson(Message) + ", \"MemberID\":" + MemberID + ", \"Name\":\"\"}", "text/html");
        }
        public ActionResult ChangePassword()
        {
            string ReturnUrl = Request.QueryString["ReturnUrl"];
            ReturnUrl = (ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : ((AppSession.Parameters.RulesRedirectAfterLogin.Value != null && AppSession.Parameters.RulesRedirectAfterLogin.Value.Length > 0) ? AppSession.Parameters.RulesRedirectAfterLogin.Value : Url.Content("~/"));

            if (AppSession.Parameters.RegistrationResetPassword.Value == "false")
            {
                if (AppSession.IsMemberInAdminRole)
                {

                }
                else
                {
                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to do change password but it was switched off. ", AuditEvent.GetSessionDetails());
                    return new RedirectResult(ReturnUrl);
                }
            }

            string Token = Request.QueryString["t"];
            RequestResultModel model = new RequestResultModel();

            model.Title = GetLabel("Account.Controller.Warning");
            model.Message = GetLabel("Account.Controller.WrongResetPassLink");
            model.InfoType = RequestResultInfoType.Warning;

            if (Token != null && Token.Length > 0)
            {
                try
                {
                    ActionToken actionToken = ActionTokens.GetBy(Token, ActionTokenTypes.PasswordReset);
                    if (actionToken.ActionID <= 0)
                    {
                        AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongResetPassLink, Token) + " Member redirected to: " + ReturnUrl,AuditEvent.GetSessionDetails());
                        return new RedirectResult(ReturnUrl);
                    }

                    Member Member = Members.GetByEmail(actionToken.Email);
                    if (Member.MemberID > 0)
                    {
                        ChangePasswordModel _model = new ChangePasswordModel();
                        _model.Name = Member.Name;
                        _model.Email = Member.Email;
                        _model.Token = Token;
                        return View("ChangePassword", _model);
                    }
                    else
                    {
                        AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongResetPassLink, Token) + " Member redirected to: " + ReturnUrl, AuditEvent.GetSessionDetails());
                        return new RedirectResult(ReturnUrl);
                    }
                }
                catch
                {
                    // Log - wrong activation token
                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongResetPassLink, Token));
                }
            }

            AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongResetPassLink, (Token != null ? Token : "[IsEmpty]")) + " Member redirected to: " + ReturnUrl, AuditEvent.GetSessionDetails());
               return new RedirectResult(ReturnUrl);
        }
        public JsonResult RemoveFieldGroup(int GroupID)
        {
            ProfileFieldGroup fieldGroup = ProfileFieldGroups.GetBy(GroupID);
            RequestResultModel _model = new RequestResultModel();

               if(fieldGroup.FieldGroupID > 0)
               {
                 fieldGroup.Delete();

                _model.InfoType = RequestResultInfoType.Success;
                _model.Message = "The group \"" + fieldGroup.FieldGroupName + "\" has been removed.";

                if (GroupID > 0)
                    AuditEvent.AppEventSuccess(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model),

                }, JsonRequestBehavior.AllowGet);
            }
               else
               {
                _model.InfoType = RequestResultInfoType.Success;
                _model.Message = "The group doesn't exist.";

                AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model),

                }, JsonRequestBehavior.AllowGet);

               }
        }
        public ActionResult Activate()
        {
            if (AppSession.Parameters.RegistrationSelfActivation.Value == "false")
            {
                if (AppSession.IsMemberInAdminRole)
                {

                }
                else
                {
                    string ReturnUrl = AppSession.ReturnUrl;
                    ReturnUrl = (ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : ((AppSession.Parameters.RulesRedirectAfterLogin.Value != null && AppSession.Parameters.RulesRedirectAfterLogin.Value.Length > 0) ? AppSession.Parameters.RulesRedirectAfterLogin.Value : Url.Content("~/"));

                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to activate an account but it was switched off. ", AuditEvent.GetSessionDetails());
                    return new RedirectResult(ReturnUrl);
                }
            }

            string Token = Request.QueryString["t"];
            RequestResultModel model = new RequestResultModel();

            model.Title = GetLabel("Account.Controller.Warning");
            model.Message = GetLabel("Account.Controller.WrongActiveLink");
            model.InfoType = RequestResultInfoType.Information;

            if (Token != null && Token.Length > 0)
            {
                try
                {
                    // Review activation token
                    ActionToken actionToken = ActionTokens.GetBy(Token, ActionTokenTypes.SelfActivation);
                    if (actionToken.ActionID <= 0)
                    {
                        string ReturnUrl = AppSession.ReturnUrl;
                        ReturnUrl = (ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : ((AppSession.Parameters.RulesRedirectAfterLogin.Value != null && AppSession.Parameters.RulesRedirectAfterLogin.Value.Length > 0) ? AppSession.Parameters.RulesRedirectAfterLogin.Value : Url.Content("~/"));

                        AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to activate an account but token doesn't exist.", AuditEvent.GetSessionDetails());
                        return new RedirectResult(ReturnUrl);
                    }

                    if (actionToken.ReturnURL != null && actionToken.ReturnURL.Length > 0)
                        AppSession.ReturnUrl = actionToken.ReturnURL;

                    Member Member = Members.GetByEmail(actionToken.Email);
                    if (Member.MemberID > 0)
                    {
                        // Remove registration roles
                        string[] RoleNames = AppParams.RegistrationMemberRegistrationToRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (String RoleName in RoleNames)
                        {
                            Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                            if (role.RoleID > 0)
                            {
                                MemberRole memberrole = new MemberRole();
                                memberrole.MemberID = Member.MemberID;
                                memberrole.RoleID = role.RoleID;
                                memberrole.Delete();
                            }
                        }

                        // Add activation roles
                        RoleNames = AppParams.RegistrationMemberActivationToRoles.Value.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                        foreach (String RoleName in RoleNames)
                        {
                            Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleName.Trim());
                            if (role.RoleID > 0)
                            {
                                MemberRole memberrole = new MemberRole();
                                memberrole.MemberID = Member.MemberID;
                                memberrole.RoleID = role.RoleID;
                                memberrole.Save();
                            }
                        }

                        string ReturnURL = actionToken.ReturnURL;
                        // AuditEvent.AppEventInfo(Member.Email, "ActionToken.ReturnURL = " + actionToken.ReturnURL + " Session back URL: " + AppSession.ReturnUrl);
                        actionToken.Delete();

                        try
                        {
                            if (!SendActivationDoneEmail(Member.Name, Member.Email, ReturnURL))
                            {
                                AuditEvent.AppEventError(Member.Email, "Activation notification e-mail has not been send!", AuditEvent.GetSessionDetails());
                            }
                        }
                        catch (Exception ex)
                        {
                            AuditEvent.AppEventError(Member.Email, "Activation: Something went wrong with e-mail notification: " + ex.Message, AuditEvent.GetSessionDetails(ex.StackTrace), true);
                        }

                        model.Title = GetLabel("Account.Controller.Congrat");
                        model.Message = GetLabel("Account.Controller.Activated").Replace("{{name}}", actionToken.Email);
                        model.InfoType = RequestResultInfoType.Success;
                        AuditEvent.AppEventSuccess(Member.Email, String.Format(AuditEvent.AccountActivated, Member.Name, Member.Email));
                    }

                }
                catch (Exception ex)
                {
                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Something wrong with activation: " + ex.Message, AuditEvent.GetSessionDetails(ex.StackTrace),true);
                }
            }
            else
            {
                  AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongActiveLink, Token));
            }

            return View("ActivateAccount", model);
        }
        public JsonResult RemoveProfileFields(int[] Fields)
        {
            foreach(int Field in Fields)
            {
                ProfileField field = ProfileFields.GetBy(Field);
                field.Delete();
                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" field has been deleted.", field.FieldName));
            }

            RequestResultModel _model = new RequestResultModel();
            _model.InfoType = RequestResultInfoType.Success;
            _model.Message = "All selected fields (and their data) have been deleted.";

            return Json(new
            {
                NotifyType = NotifyType.PageInline,
                Html = this.RenderPartialView(@"_RequestResultPageInLine", _model),

            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SendChangePasswordLink(string Name, string Email, string RequestID, string SessionID)
        {
            if (AppSession.Parameters.RegistrationResetPassword.Value == "false")
            {
                if (AppSession.IsMemberInAdminRole)
                {

                }
                else
                {
                    string ReturnUrl = AppSession.ReturnUrl;
                    ReturnUrl = (ReturnUrl != null && ReturnUrl.Length > 0) ? ReturnUrl : ((AppSession.Parameters.RulesRedirectAfterLogin.Value != null && AppSession.Parameters.RulesRedirectAfterLogin.Value.Length > 0) ? AppSession.Parameters.RulesRedirectAfterLogin.Value : Url.Content("~/"));

                    AuditEvent.AppEventError(AppSession.Parameters.GeneralAdminEmail.Value, "Somebody tries to request changing password but it was switched off. ", AuditEvent.GetSessionDetails());
                    return new RedirectResult(ReturnUrl);
                }
            }

            RequestResultModel _model = new RequestResultModel();

            if (Name == null || Name.Trim().Length == 0 ||
               Email == null || Email.Trim().Length == 0 ||
               !AppSession.IsEmail(Email))
            {
                _model = new RequestResultModel();
                _model.Title = "Warning";
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;

                if (Name == null || Name.Trim().Length == 0)
                    _model.Message = String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.NameIsEmpty"));

                if (Email == null || Email.Trim().Length == 0)
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.EmailIsEmpty"));

                if (Email != null && !AppSession.IsEmail(Email))
                    _model.Message += String.Format("<li>{0}</<li>", GetLabel("Account.CreateAccount.EmailWrongFromat"));

                _model.Message = String.Format("<ul>{0}</ul>", _model.Message);

                return Json(new
                {
                    Status = RequestResultInfoType.ErrorOrDanger,
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);

            }

               Member Member = Members.GetByEmailName(Email, Name);

               if (!AppSession.IsEmail(Email))
               {
               _model.Title = GetLabel("Account.Controller.Warning");
               _model.Message = GetLabel("Account.Controller.WrongEmail");
               _model.InfoType = RequestResultInfoType.ErrorOrDanger;
               AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountWrongEmail, Member.Name, Member.Email));
               }
               else
               {
               if (Member.MemberID <= 0)
               {
                   _model.Title = GetLabel("Account.Controller.Warning");
                   _model.Message = GetLabel("Account.Controller.AccountDoesntExist");
                   _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                   AuditEvent.AppEventWarning(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountAccountDoesntExist, Name, Email));
               }
               else
               {
                   try
                   {
                       string ResetToken = Web.Admin.Logic.StringTool.RandomString(20);

                       if (!SendChangePasswordEmail(Name, Email, ResetToken))
                       {
                           throw new Exception("Changing password link notification e-mail has not been send!");
                       };

                       _model.Title = GetLabel("Account.Controller.Congrat");
                       _model.Message = GetLabel("Account.Controller.ResetPassMail");
                       _model.InfoType = RequestResultInfoType.Success;

                       ActionToken actionToken = new ActionToken();
                       actionToken.Email = Email;
                       actionToken.Token = HttpUtility.UrlDecode(ResetToken);
                       actionToken.ActionType = ActionTokenTypes.PasswordReset;
                       actionToken.ReturnURL = AppSession.ReturnUrl != null ? AppSession.ReturnUrl : (AppSession.Parameters.RulesRedirectAfterLogout.Value != "" ? AppSession.Parameters.RulesRedirectAfterLogout.Value : "");
                       actionToken.Save();

                       AuditEvent.AppEventSuccess(AppSession.Parameters.GeneralAdminEmail.Value, String.Format(AuditEvent.AccountResetPassMail, Member.Name, Member.Email));

                   }
                   catch (Exception ex) {
                       _model.Title = GetLabel("Account.Controller.Warning");
                       _model.Message = GetLabel("Account.Controller.CantSendNotification");
                       _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                       AuditEvent.AppEventError(Email ,"Send change password link: Something went wrong with e-mail notification: " + ex.Message, AuditEvent.GetSessionDetails(ex.StackTrace),true);
                    }
               }
               }

               return Json(new
               {
               Status = _model.InfoType,
               NotifyType = NotifyType.DialogInline,
               Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

               }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult AddField(String Name, String FieldType, String Comment, String PossibleValues, String SelectText, String IsMandatory, String ShowInSignup, String SortValues, String IsActive, String AdminUseOnly, String VerticalLayout, int FieldGroupID, bool Encrypted, int[] SelectedDomains, int[] SelectedRoles)
        {
            ProfileField profileField = ProfileFields.GetByName(Name);
            String Message = "";

            if (profileField.FieldID > 0 && profileField.FieldName.Trim().ToLower() == Name.Trim().ToLower())
                Message = "The field \"" + Name + "\" already exists.";

            if (Name.Trim().ToLower().Length == 0)
                Message = "The field name should not be empty.";

            if (Message != "")
            {
                RequestResultModel _model = new RequestResultModel();
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.Message = Message;

                AuditEvent.AppEventWarning(Profile.Member.Email, Message);

                return Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model),

                }, JsonRequestBehavior.AllowGet);
            }

            profileField.FieldName = Name;
            profileField.Comment = Comment;
            profileField.FieldTypeID = (ProfileFieldTypeEnum)int.Parse(FieldType);
            profileField.PossibleValues = PossibleValues;
            profileField.TextSelectValue = SelectText;
            profileField.IsMandatory = (IsMandatory == "True" ? 1 : 0);
            profileField.ShowInSignUp = (ShowInSignup == "True" ? 1 : 0);
            profileField.SortValues = SortValues == "True" ? 1 : 0;
            profileField.IsActive = IsActive == "True" ? 1 : 0;
            profileField.AdminUseOnly = AdminUseOnly == "True" ? 1 : 0;
            profileField.VerticalLayout = VerticalLayout == "True" ? 1 : 0;
            profileField.FieldGroupID = FieldGroupID;
            profileField.Encrypted = Encrypted == true ? 1 : 0;
            profileField.Save();

            if (SelectedDomains != null)
            {
                List<Domain> _domains = Domains.Get();
                foreach (Domain _domain in _domains)
                {
                    DomainProfileField _domainField = new DomainProfileField();
                    _domainField.DomainID = _domain.DomainID;
                    _domainField.ProfileFieldID = profileField.FieldID;

                    if (SelectedDomains.Where(t => t == _domain.DomainID).FirstOrDefault() != default(int))
                        _domainField.Save();
                }
            }

            if (SelectedRoles != null)
            {
                List<Role> _roles = Web.Admin.Logic.Collections.Roles.Get();
                foreach (Role _role in _roles)
                {
                    RoleProfileField _roleField = new RoleProfileField();
                    _roleField.RoleID = _role.RoleID;
                    _roleField.ProfileFieldID = profileField.FieldID;

                    if (SelectedRoles.Where(t => t == _role.RoleID).FirstOrDefault() != default(int))
                        _roleField.Save();
                }
            }

            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("The \"{0}\" field has been added.", Name));

            return Json(new
            {
                NotifyType = -1,
                Html = "",

            }, JsonRequestBehavior.AllowGet);
        }
        public ActionResult SaveSettings(List<ParamNameValue> ParamNameValues)
        {
            List<ParamNameValue> WrongParams = new List<ParamNameValue>();
            string GeneralSecretAdminUrlOld = AppParams.GeneralSecretAdminUrl.Value;
            string AppApiSecretURL = AppParams.AppApiSecretURL.Value;

            foreach (ParamNameValue Param in ParamNameValues)
            {
                if (Param.Name == null || Param.Name.Length == 0)
                    continue;

                Parameter Parameter = Parameters.GetBy(Param.Name);
                Parameter.MemberID = Profile.Member.MemberID;

                string oldValue = Parameter.Value;
                Param.Value = Param.Value == null ? "" : Param.Value;

                if (Parameter.Type == ParameterType.Bool)
                {
                    if (Param.Value.ToLower() == "true")
                        Param.Value = Parameter.Value = "true";
                    else
                        Param.Value = Parameter.Value = "false";
                }
                else if (Parameter.Type == ParameterType.SmallInteger || Parameter.Type == ParameterType.RadioInteger)
                {
                    long value = -1;
                    bool result = long.TryParse(Param.Value, out value);
                    Parameter.Value = result ? Param.Value : Parameter.Value;

                    if (!result)
                        WrongParams.Add(Param);
                }
                else
                {
                    Parameter.Value = Param.Value;
                }

                if (oldValue != Param.Value)
                    Parameter.Save();

                if (AppParams.GeneralAuditEnabled.Value == "true" && Param.Value != oldValue)
                    AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format("Changed: {0} -> from \"{1}\" to \"{2}\"", Parameter.Name, oldValue, Parameter.Value));
            }

            AppParams.RefreshAppParameters();
            List<ParamNameValue> ParamValues =  new List<ParamNameValue>();
            List<Parameter> Params = Parameters.Get();

            ////////////////////////////////////////////
            // Change admin route
            ////////////////////////////////////////////
            bool AdminRouteChaned = false;
            string RelativeAdminPath = "{controller}/{action}/{id}";
            if (AppParams.GeneralSecretAdminUrl != null && AppParams.GeneralSecretAdminUrl.Value.Length > 0 && GeneralSecretAdminUrlOld != AppParams.GeneralSecretAdminUrl.Value)
            {
                RouteCollection routes = RouteTable.Routes;
                using (routes.GetWriteLock())
                {
                    RelativeAdminPath = Path.Combine(AppSession.Parameters.GeneralSecretAdminUrl.Value.Replace("/", "\\"), RelativeAdminPath.Replace("/", "\\")).Replace("\\", "/");

                    if (RelativeAdminPath[0] == '/')
                        RelativeAdminPath = RelativeAdminPath.Remove(0, 1);

                    Route route = (Route)routes["Admin-Secret-Path"];
                    route.Url = RelativeAdminPath;

                }

                // If admin route changed redirect admin to correct url
                AdminRouteChaned = true;
            }
            else if ((AppParams.GeneralSecretAdminUrl == null || AppParams.GeneralSecretAdminUrl.Value.Length == 0) && GeneralSecretAdminUrlOld != AppParams.GeneralSecretAdminUrl.Value)
            {
               RouteCollection routes = RouteTable.Routes;
               using (routes.GetReadLock())
               {
                   Route route = (Route)routes["Admin-Secret-Path"];
                   route.Url = "Admin/" + RelativeAdminPath;
               }

               AdminRouteChaned = true;
            }

            ////////////////////////////////////////////
            // Change API route
            ////////////////////////////////////////////
            bool APIRouteChaned = false;
            string RelativeAPIPath = "{action}/{id}";
            if (AppParams.AppApiSecretURL != null && AppParams.GeneralSecretAdminUrl.Value.Length > 0 && AppApiSecretURL != AppParams.AppApiSecretURL.Value)
            {
                RouteCollection routes = RouteTable.Routes;
                using (routes.GetWriteLock())
                {
                    RelativeAPIPath = Path.Combine(AppSession.Parameters.AppApiSecretURL.Value.Replace("/", "\\"), RelativeAPIPath.Replace("/", "\\")).Replace("\\", "/");

                    if (RelativeAdminPath[0] == '/')
                        RelativeAdminPath = RelativeAPIPath.Remove(0, 1);

                    Route route = (Route)routes["API-Secret-Path"];
                    route.Url = RelativeAPIPath;

                }

                // If API route changed redirect admin to correct url
                APIRouteChaned = true;
            }
            else if ((AppParams.AppApiSecretURL == null || AppParams.AppApiSecretURL.Value.Length == 0) && AppApiSecretURL != AppParams.AppApiSecretURL.Value)
            {
                RouteCollection routes = RouteTable.Routes;
                using (routes.GetReadLock())
                {
                    Route route = (Route)routes["API-Secret-Path"];
                    route.Url = "Admin/API/" + RelativeAPIPath;
                }

                APIRouteChaned = true;
            }

            foreach(Parameter Param in Params)
                ParamValues.Add( new ParamNameValue{ Name = Param.Name, Value = Param.Value, Type = Param.Type.ToString()});

            string Message = "";
            string AdminUrlChanged = "";
            string APIUrlChanged = "";
            RequestResultModel _model = new RequestResultModel();

            if (AdminRouteChaned)
            {
                AdminUrlChanged = String.Format("<br/><strong>Admin URL has been changed. Click <a href=\"{0}\">here</a> to redirect to actual admin URL.</strong>", Url.Action("", "Settings"));
            }

            if (APIRouteChaned)
            {
                string Path = (AppParams.AppApiSecretURL.Value.Length > 0 ? AppParams.AppApiSecretURL.Value : "Admin/API");
                APIUrlChanged = String.Format("<br/>API URL has been changed. Please update all API clients. Here is base url now: <strong>{0}</strong>", Path);
            }

            if (WrongParams.Count == 0)
            {
                _model.Title = GetLabel("Account.Controller.Congrat");
                _model.InfoType = RequestResultInfoType.Success;
                _model.Message = "Application settngs have been saved." + AdminUrlChanged + APIUrlChanged;
                Message = this.RenderPartialView(@"_RequestResultDialogInLine", _model);
            }
            else
            {
                _model.Title = GetLabel("Account.Controller.Warning");
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                _model.Message = "Some parametrs have not been saved. Please check." + AdminUrlChanged + APIUrlChanged;
                Message = this.RenderPartialView(@"_RequestResultDialogInLine", _model);
            }

            return Json(new
            {
                Message = Message,
                Settings = ParamValues,
            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult SaveDomain(DomainInfo Info)
        {
            RequestResultModel _model = new RequestResultModel();

            if (Info.Name == null || Info.Name.Trim().Length == 0)
            {
                _model = new RequestResultModel();
                _model.Title = "Warning";
                _model.Message = "Name is empty. Please, enter domain name.";
                _model.InfoType = RequestResultInfoType.ErrorOrDanger;
                AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.DialogInline,
                    Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }

            if (Info.DomainID > 0)
            {
                Domain domain = Web.Admin.Logic.Collections.Domains.GetBy(Info.DomainID);
                Domain domainExists = Web.Admin.Logic.Collections.Domains.GetByName(Info.Name);

                // The domain has been deleted.
                if (domain.DomainID <= 0)
                {
                    _model.Title = "Warning";
                    _model.Message = String.Format("Domain '{0}' doesn't exist. Please, refresh role list and try again.", domainExists.Name);
                    AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                // The domain already esists.
                if (domainExists.DomainID > 0 && Info.DomainID != domainExists.DomainID)
                {
                    _model.Title = "Warning";
                    _model.Message = String.Format("Domain '{0}' already exists. Please, change domain name and try again.", domainExists.Name);
                    AuditEvent.AppEventWarning(Profile.Member.Email, _model.Message);

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                domain.Name = Info.Name;
                domain.Description = Info.Description;
                domain.Save();

                _model = new RequestResultModel();
                _model.Message = String.Format("Domain \"{0}\"has been updated.", domain.Name);
                _model.HideInSeconds = 4000;
                AuditEvent.AppEventSuccess(Profile.Member.Email, _model.Message);

                return Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model)

                }, JsonRequestBehavior.AllowGet);

            }
            else
            {
                Domain domainExists = Web.Admin.Logic.Collections.Domains.GetByName(Info.Name);

                // The domain already esists.
                if (domainExists.DomainID > 0)
                {
                    _model.Title = "Warning";
                    _model.Message = String.Format("Domain '{0}' already exists. Please, change domain name and try again.", domainExists.Name);
                    _model.InfoType = RequestResultInfoType.ErrorOrDanger;

                    return Json(new
                    {
                        NotifyType = NotifyType.DialogInline,
                        Html = this.RenderPartialView(@"_RequestResultDialogInLine", _model)

                    }, JsonRequestBehavior.AllowGet);
                }

                Domain Domain = new Domain();
                Domain.Name = Info.Name;
                Domain.Description = Info.Description;
                Domain.Save();

                _model.Message = String.Format("New domain \"{0}\" has been created.", Domain.Name);

                return Json(new
                {
                    NotifyType = NotifyType.PageInline,
                    Html = this.RenderPartialView(@"_RequestResultPageInLine", _model)

                }, JsonRequestBehavior.AllowGet);
            }
        }