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 JsonResult AssignRoleMembers(long RoleID, int[] AssignMembers, bool Assign)
        {
            MemberListModel _model = new MemberListModel();

            foreach (int MemberID in AssignMembers)
            {
                Web.Admin.Logic.Objects.Member Member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
                Web.Admin.Logic.Objects.Role Role = Web.Admin.Logic.Collections.Roles.GetBy(RoleID);

                if (RoleID > 0)
                {
                    if (Member.IsBuiltIn)
                    {
                        if (Member.Name.Trim().ToLower() == "admin" && Role.Name.Trim().ToLower() == "admins")
                        {
                            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberNoRemovedAdminFromRole, Member.Name, Member.Email, Role.Name));
                            continue;
                        }
                    }
                    else
                    {
                        MemberRole _roleMember = new MemberRole();
                        _roleMember.MemberID = MemberID;
                        _roleMember.RoleID = RoleID;

                        if (Role.Name.ToLower() == "blocked")
                            ResetPasswordfailedAttemps(MemberID);

                        if (Assign)
                        {
                            _roleMember.Save();
                            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberAssigToRole, Member.Name, Member.Email, Role.Name));
                        }
                        else
                        {
                            _roleMember.Delete();
                            AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberRemovedFromRole, Member.Name, Member.Email, Role.Name));
                        }
                    }
                }
                else if (!Assign)
                {
                    if (Member.IsBuiltIn)
                    {
                        AuditEvent.AppEventWarning(Profile.Member.Email, String.Format(AuditEvent.MemberNoRemovedAdminFromRole, Member.Name, Member.Email, Role.Name));
                        continue;
                    }
                    else
                    {
                        MemberRole _roleMember = new MemberRole();
                        _roleMember.MemberID = MemberID;
                        _roleMember.DeleteAll();

                        ResetPasswordfailedAttemps(MemberID);
                        AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberRemovedFromAllRole, Member.Name, Member.Email));
                    }
                }
            }

            _model.Role = Roles.GetBy(RoleID);

            return Json(new
            {
                Html = ""

            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult RemoveFromRole(long MemberID, long RoleID)
        {
            Member member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
            Role role = Web.Admin.Logic.Collections.Roles.GetBy(RoleID);

            // Ignore admin in admins role
            if (member.Name.ToLower() == "admin" && role.Name.ToLower() == "admins")
            {
                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberNoRemovedAdminFromRole, member.Name, member.Email, role.Name));
            }
            else
            {
                MemberRole memberrole = new MemberRole();
                memberrole.MemberID = MemberID;
                memberrole.RoleID = RoleID;
                memberrole.Delete();

                AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberRemovedFromRole, member.Name, member.Email, role.Name));
            }

            if (role.Name.ToLower() == "blocked")
            {
                MemberAttempt MemberAttempt = MemberAttempts.GetValid(MemberID, DateTime.Now, MemberAttemptTypes.LoginPasswordFailed);
                if (MemberAttempt.AttemptID > 0)
                {
                    MemberAttempt.Attempts = 0;
                    MemberAttempt.Save();
                }
            }

            MemberListModel model = new MemberListModel();

            model.Members.Add(member);

            return Json(new
            {
                Html = this.RenderPartialView(@"_MemberRoleList", model),
            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult RemoveMember(int[] RemoveMembers)
        {
            MemberListModel _model = new MemberListModel();
            List<Member> _deleted = new List<Member>();

            foreach (int MemberID in RemoveMembers)
            {
                Member member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
                if (member.IsBuiltIn)
                {
                    member.WasDeleted = false;
                    member.UIMessage = String.Format("\"{0}\"<{1}> is built in and can't be deleted.", member.Name, member.Email);
                    member.UIMessageType = UIMessageType.Warning;
                    AuditEvent.AppEventWarning(Profile.Member.Email, member.UIMessage);
                }else if (member.Delete())
                {
                    member.WasDeleted = true;
                    member.UIMessage = String.Format("\"{0}\"<{1}>  has been deleted.", member.Name, member.Email);
                    member.UIMessageType = UIMessageType.Success;
                    AuditEvent.AppEventSuccess(Profile.Member.Email, member.UIMessage);
                }
                _deleted.Add(member);
            }

            _model.Members = _deleted;

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

            }, 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 JsonResult GetRemoveMemberDialog(int[] RemoveMembers)
        {
            MemberListModel _model = new MemberListModel();
            foreach (int MemberID in RemoveMembers)
            {
                Member role = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
                _model.Members.Add(role);
            }

            return Json(new
            {
                Html = this.RenderPartialView(@"_RemoveMembers", _model),

            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetEditMemberDialog(int MemberID)
        {
            Member member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
            MemberListModel _model = new MemberListModel();
            _model.Members.Add(member);

            return Json(new
            {
                Html = this.RenderPartialView(@"_EditMember", _model),

            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetAssignRoleMembersDialog(long RoleID, int[] AssignMembers, bool Assign)
        {
            MemberListModel _model = new MemberListModel();
            foreach (int MemberID in AssignMembers)
            {
                Member member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
                _model.Members.Add(member);
            }

            _model.Role = Roles.GetBy(RoleID);
            _model.Assign = Assign;

            return Json(new
            {
                Html = this.RenderPartialView(@"_AssignRoleMembers", _model),

            }, JsonRequestBehavior.AllowGet);
        }
        public JsonResult AssignRolesToMember(long MemberID, long[] AssignRoles)
        {
            Member member = Web.Admin.Logic.Collections.Members.GetBy(MemberID);
            foreach (long _roleID in AssignRoles)
            {
                Role Role = Web.Admin.Logic.Collections.Roles.GetBy(_roleID);
                if (Role.RoleID > 0)
                {
                    MemberRole memberrole = new MemberRole();
                    memberrole.MemberID = MemberID;
                    memberrole.RoleID = Role.RoleID;
                    memberrole.Save();

                    AuditEvent.AppEventSuccess(Profile.Member.Email, String.Format(AuditEvent.MemberAssigToRole, member.Name, member.Email, Role.Name));
                }
            }

            MemberListModel model = new MemberListModel();
            model.Members.Add(member);

            return Json(new
            {
                Html = this.RenderPartialView(@"_MemberRoleList", model),
            }, JsonRequestBehavior.AllowGet);
        }