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