public MemberProfileFieldModel(Member Member)
 {
     this.Member = Member;
 }
        private string SignInMember(String Name, Member Member, bool RememberMe, String ReturnUrl, string SocialComment = "")
        {
            Session["MemberProfile"] = new MemberProfile(Member);

            string CookieName = FormsAuthentication.FormsCookieName;
            string CookiePath = FormsAuthentication.FormsCookiePath;

            if (AppSession.Parameters.GeneralCookieName.Value.Length > 0)
                CookieName = AppSession.Parameters.GeneralCookieName.Value;

            bool isCookiePersistent = RememberMe;
            FormsAuthentication.Initialize();

            AuthMemberTicket _authMemberTicket = AuthMemberTickets.GetLastByMember(Member.MemberID);
            if (_authMemberTicket.Expiration <= DateTime.Now)
            {
                _authMemberTicket.Delete();
                _authMemberTicket.AuthMemberTicketID = 0;
            }

            AuthMemberToken _ticketMemberSession = new AuthMemberToken()
            {
                MemberID = Member.MemberID,
                MemberEmail = Member.Email,
                MemberName = Member.Name,
                Token = _authMemberTicket.AuthMemberTicketID > 0 ? _authMemberTicket.Token : StringTool.RandomString(64)
            };

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(1,
                Member.Email,
                DateTime.Now,
                DateTime.Now + FormsAuthentication.Timeout,
                isCookiePersistent,
                ToJson(_ticketMemberSession),
                CookiePath);

            string cookieEncrypted = FormsAuthentication.Encrypt(authTicket);
            HttpCookie authCookie = new HttpCookie(CookieName, cookieEncrypted);

            if (isCookiePersistent)
                authCookie.Expires = authTicket.Expiration;

            // In order to keep not empty UserData for auth ticket.
            // http://stackoverflow.com/questions/12642516/formsauthenticationticket-isnt-storing-userdata

            if (AppSession.Parameters.GeneralDomainName.Value.Length > 0 && AppSession.Parameters.GeneralDomainName.Value != "localhost")
                 authCookie.Domain = AppSession.Parameters.GeneralDomainName.Value;

            authCookie.HttpOnly = true;
            authCookie.Path = CookiePath;
            Response.Cookies.Add(authCookie);

            AuditEvent.AppEventSuccess(Profile.Member.Email, SocialComment + " " + String.Format(AuditEvent.MemberLoggedIn, Member.Name, Member.Email));
            Member.UpdateLoginTime();

            String RedirectTo = "";
            if (AppSession.ReturnUrl != null && AppSession.ReturnUrl.Length > 0)
                RedirectTo = AppSession.ReturnUrl;
            else
                RedirectTo = RedirectToAfterLogin(ReturnUrl);

            if (AppSession.ReturnUrl != null && AppSession.ReturnUrl.Length > 0)
            {
                //////////////////////////////////////////////////////////////////////////
                // Needs to create session for cross domain auth.
                //////////////////////////////////////////////////////////////////////////
                if (AppSession.SignUpDomain != null && AppSession.SignUpDomain.Length > 0)
                {
                    Uri signInDomain = new Uri(AppSession.ReturnUrl);
                    signInDomain = new Uri(AppSession.ReturnUrl);

                    if (signInDomain.Host.Trim().ToLower().IndexOf(AppSession.Parameters.GeneralDomainName.Value.Trim().ToLower())  == -1)
                        RedirectTo = PrepareCrossDomainAuthToken(Member, RememberMe, ReturnUrl, signInDomain.DnsSafeHost, signInDomain.Port, AppSession.SignInUrl, _ticketMemberSession);
                }
            }

            if (_authMemberTicket.AuthMemberTicketID <= 0)
            {
                _authMemberTicket = new AuthMemberTicket()
                {
                    Token = _ticketMemberSession.Token,
                    MemberID = Member.MemberID,
                    IssueDate = authTicket.IssueDate,
                    Expiration = authTicket.Expiration,
                    IsPersistent = (authTicket.IsPersistent == true ? 1 : 0)
                };

                _authMemberTicket.Save();
            }

            return RedirectTo;
        }
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        // http://stackoverflow.com/questions/342378/cross-domain-login-how-to-login-a-user-automatically-when-transferred-from-one
        ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        private string PrepareCrossDomainAuthToken(Member Member, bool RememberMe, String ReturnUrl, string Host, int Port, string SignInUrl,  AuthMemberToken AuthMemberToken,  string SocialComment = "")
        {
            String RedirectTo = "";
            if (AppSession.ReturnUrl != null && AppSession.ReturnUrl.Length > 0)
                RedirectTo = AppSession.ReturnUrl;
            else
                RedirectTo = RedirectToAfterLogin(ReturnUrl);

            String returnUrl = RedirectTo;

            RedirectTo = String.Format("http://{0}:{1}{2}", Host, Port, SignInUrl);
            RedirectTo += (RedirectTo.IndexOf("?") > 0 ? "&" : "?") + "BackUrl=" + HttpUtility.UrlEncode(returnUrl);
            RedirectTo += (RedirectTo.IndexOf("?") > 0 ? "&" : "?") + "p1=" + HttpUtility.UrlEncode(StringTool.Encrypt(AuthMemberToken.Token)) + "&p2=" + HttpUtility.UrlEncode(StringTool.Encrypt(Member.Email));

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

            }
        }
 /// <summary>
 /// The class constructor.
 /// </summary>
 /// <param name="Member">Member object.</param>
 public MemberProfile(Member Member)
 {
     this.Member = Member;
     this.Language = "eng";
 }