コード例 #1
0
        protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
        {
            try
            {
                StaffData staffData = SlmMasterBiz.GetStaffData(Login1.UserName.Trim());

                if (staffData != null)
                //if (staffData != null && IsAuthenticated(Login1.UserName.Trim(), Login1.Password.Trim()))
                {
                    FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
                        1,
                        Login1.UserName.Trim(),
                        DateTime.Now,
                        DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
                        Login1.RememberMeSet,
                        staffData.StaffNameTH + "|" + staffData.BranchName + "|" + (staffData.StaffTypeId != null ? staffData.StaffTypeId.Value.ToString() : ""),
                        FormsAuthentication.FormsCookiePath);

                    string encTicket = FormsAuthentication.Encrypt(ticket);
                    Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
                    //Response.Redirect(FormsAuthentication.GetRedirectUrl(Login1.UserName, Login1.RememberMeSet), false);

                    if (Login1.UserName == hddCsmUsername.Value)
                    {
                        Response.Redirect(Server.UrlDecode(hddReturnUrl.Value));
                    }
                    else if (Request["ticketid"] != null && Request["accflag"] == "email")
                    {
                        Response.Redirect("SLM_SCR_004.aspx?ticketid=" + Request["ticketid"] + "&type=" + Request["type"], false);
                    }
                    else
                    {
                        Response.Redirect(FormsAuthentication.DefaultUrl, false);
                    }
                }
                else
                {
                    ((TextBox)Login1.FindControl("Password")).Text = "";
                    _log.Error("Logon failure: unknown user name or bad password.");
                    AppUtil.ClientAlert(Page, "Logon failure: unknown user name or bad password.");
                }
            }
            catch (Exception ex)
            {
                ((TextBox)Login1.FindControl("Password")).Text = "";
                string message = ex.InnerException != null ? ex.InnerException.Message : ex.Message;
                _log.Error("(" + Login1.UserName + ") " + message);
                _log.Debug("(" + Login1.UserName + ") ", ex);
                AppUtil.ClientAlert(Page, "Logon failure: unknown user name or bad password.");
            }
        }
コード例 #2
0
    protected void Login1_LoginError(object sender, EventArgs e)
    {
        Label          lblLoginErrors = (Label)Login1.FindControl("lblLoginErrors");
        MembershipUser userInfo       = Membership.GetUser(Login1.UserName);

        if (userInfo == null)
        {
            lblLoginErrors.Text = "Invalid User Id or Password.";
        }
        else if (userInfo.IsLockedOut)
        {
            lblLoginErrors.Text = "Your account is locked. Please contact Administrator for unlocking the same.";
        }
    }
コード例 #3
0
ファイル: Logon.aspx.cs プロジェクト: penzhaohui/Crab
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string tenantName     = ((TextBox)Login1.FindControl("TenantName")).Text.Trim();
        string tenantUsername = Login1.UserName.Trim();
        Upn    upn            = new Upn(tenantName, tenantUsername);

        bool authenticated = false;

        if (!(authenticated = Membership.ValidateUser(upn.ToString(), Login1.Password)))
        {
            Login1.FailureText = Resources.GlobalResources.FailLogin;
            return;
        }

        Login1.UserName = upn.ToString();
        e.Authenticated = authenticated;

        // http://codeverge.com/asp.net.web-forms/asp-login-remember-me-functionality/390002
        HttpCookie myCookie = new HttpCookie("myCookie");
        Boolean    remember = Login1.RememberMeSet;

        if (remember)
        {
            Int32 persistDays = 15;
            myCookie.Values.Add("username", tenantUsername);
            myCookie.Values.Add("tenantname", tenantName);
            myCookie.Expires = DateTime.Now.AddDays(persistDays); //you can add years and months too here
        }
        else
        {
            myCookie.Values.Add("username", string.Empty); // overwrite empty string is safest
            myCookie.Values.Add("tenantname", string.Empty);
            myCookie.Expires = DateTime.Now.AddMinutes(5); //you can add years and months too here
        }
        Response.Cookies.Add(myCookie);

        /*
         * if (User.Identity.IsAuthenticated)
         * {
         *  FormsIdentity identity = User.Identity as FormsIdentity;
         *  FormsAuthenticationTicket ticket = identity.Ticket;
         *  if (ticket.IsPersistent)
         *  {
         *      Login1.RememberMeSet = true;
         *  }
         * }
         */

        //RememberMe();
    }
コード例 #4
0
        protected void Login1_LoggedIn(object sender, EventArgs e)

        {
            TextBox txtb = (TextBox)Login1.FindControl("UserName");

            if (Roles.IsUserInRole(txtb.Text, "user"))
            {
                Response.Redirect("Protected/BooksUser.aspx");
            }
            else if (Roles.IsUserInRole(txtb.Text, "admin"))
            {
                Response.Redirect("AdminProtected/BooksAdmin.aspx");
            }
        }
コード例 #5
0
        protected void Page_Load(object sender, EventArgs e)
        {
            HyperLink RegisterHyperLink = Login1.FindControl("RegisterHyperLink") as HyperLink;

            RegisterHyperLink.NavigateUrl = "~/Registration";
            //OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];

            var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);

            if (!String.IsNullOrEmpty(returnUrl))
            {
                RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
            }
        }
コード例 #6
0
        public LogInternals(Login1 parentForm)
        {
            InitializeComponent();
            this.Text      = "Iniciar sesión";
            this.Move     += this.onMove;
            this.firstbase = parentForm;
            this.DB        = new dbop();
            this.msdb      = new msdbop();

            genericDefinitions.arduino = new ctg(this);

            this.arduino = genericDefinitions.arduino;

            this.FormClosing += this.onClose;

            this.txtArduino.TextChanged += (a, b) =>
            {
                if (this.panelArduino.Visible == false)
                {
                    this.panelArduino.Visible = true;
                }
            };

            this.txtuser.KeyUp += (sender, args) =>
            {
                if (args.KeyCode == Keys.Enter && this.txtuser.Text.Trim() != "")
                {
                    this.txtpass.Focus();
                }
            };

            this.txtpass.KeyUp += (sender, args) =>
            {
                if (args.KeyCode == Keys.Enter)
                {
                    this.verify();
                }
            };

            this.MinimizeBox = true;

            this.SizeChanged += (sender, args) =>
            {
                if (this.WindowState == FormWindowState.Minimized)
                {
                    this.firstbase.WindowState = FormWindowState.Minimized;
                }
            };
        }
コード例 #7
0
    /// <summary>
    /// Hides error and warning messages.
    /// </summary>
    private void HideErrorWarnings()
    {
        var plcWarning = Login1.FindControl("plcWarning");
        var plcError   = Login1.FindControl("plcError");

        if (plcWarning != null)
        {
            plcWarning.Visible = false;
        }

        if (plcError != null)
        {
            plcError.Visible = false;
        }
    }
コード例 #8
0
 protected void Login1_LoggedIn(object sender, EventArgs e)
 {
     //Response.Redirect("/administrator");
     if (((CheckBox)Login1.FindControl("RememberMe")).Checked)
     {
         var    ticket    = new FormsAuthenticationTicket(((TextBox)Login1.FindControl("Username")).Text, true, 2880);
         string encrypted = FormsAuthentication.Encrypt(ticket);
         var    cookie    = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted)
         {
             Expires  = System.DateTime.Now.AddMinutes(2880),
             HttpOnly = true
         };
         HttpContext.Current.Response.Cookies.Add(cookie);
     }
 }
コード例 #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //string cadena = ConfigurationManager.ConnectionStrings["TeleBancaConnectionString"].ConnectionString;
        //SqlConnection cnx = new SqlConnection(cadena);

        //cnx.Open();



        Login1.Focus();
        if (!IsPostBack)
        {
            Session["intentos"] = "0";
        }
    }
コード例 #10
0
    protected void btnLogin_Click(object sender, EventArgs e)
    {
        Login1 l1 = new Login1();
        l1.username = txtUsername.Text;
        l1.password = txtPassword.Text;

        if (l1.LoginUser() == true)
        {
            Session["Username"] = l1.username;
            Response.Redirect("Default.aspx");

        }
        else
            lblError.Text = "Invalid Username/Password";
    }
コード例 #11
0
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                Response.Expires         = -1;
                Response.ExpiresAbsolute = DateTime.Now;
                Response.CacheControl    = "no-cache";
                ClearApplicationCache();
                ((Literal)Login1.FindControl("FailureText")).Text    = string.Empty;
                ((Literal)Login1.FindControl("FailureText")).Visible = false;
            }

            projectName        = Server.UrlDecode(Request.QueryString["Project"].ToString());
            Session["project"] = projectName;
        }
コード例 #12
0
    protected void SendPasword(object sender, EventArgs e)
    {
        Page.Validate("SendPassword");

        if (Page.IsValid)
        {
            try
            {
                //-- Enviar Contraseña
                //------------------------------
                string email   = ((TextBox)Login1.FindControl("txtEmail")).Text;
                string usuario = Membership.GetUserNameByEmail(email);
                if (string.IsNullOrEmpty(usuario))
                {
                    ((Literal)Login1.FindControl("ltrMessage")).Text = "<span style='color:red;font-size:10px;'>El email ingresado no pertenece a un Usuario Registrado. <br />Por favor, ingrese un email válido!</span>";
                }
                else
                {
                    //-- LEVANTO EL TEMPLATE
                    //-----------------------------------------------
                    StringBuilder sbTemplate = new StringBuilder(MySite_EMail.GetTemplate("~/Templates/Emails", "RecuperarClave.htm"));
                    if (!string.IsNullOrEmpty(sbTemplate.ToString()))
                    {
                        MembershipUser oUser    = Membership.GetUser(usuario);
                        String         password = oUser.GetPassword();

                        sbTemplate.Replace("{{Usuario}}", usuario);
                        sbTemplate.Replace("{{Contraseña}}", password);
                        sbTemplate.Replace("{{FullSiteName}}", MySite.GetFullSiteName_FromAppConfig());

                        MySite_EMail.Send(email,
                                          null,
                                          "Interfood - Recupero de Contraseña",
                                          sbTemplate.ToString(),
                                          true,
                                          System.Net.Mail.MailPriority.Normal);

                        ((Literal)Login1.FindControl("ltrMessage")).Text = "<span style='color:green;font-size:10px;'>Se han enviado correctamente sus datos privados! <br />Por favor verifique su Correo Electrónico.</span>";
                    }
                }
            }
            catch (Exception ex)
            {
                ((Literal)Login1.FindControl("ltrMessage")).Text = "<span style='color:red;font-size:10px;'>Oooops, ocurrió un error al enviar el Email. <br />Por favor inténtelo mas tarde.</span>";
                Logger.LogExceptionStatic(ex);
            }
        }
    }
コード例 #13
0
 protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
 {
     rbl = (RadioButtonList)Login1.FindControl("RadioButtonList1");
     System.Data.SqlClient.SqlConnection con = new System.Data.SqlClient.SqlConnection(ConfigurationManager.ConnectionStrings["WSConnectionString"].ConnectionString);
     con.Open();
     if (rbl.SelectedIndex == -1)
     {
         Page.ClientScript.RegisterClientScriptBlock(GetType(), "Aad", "alert('请选择用户类型')", true);
     }
     else
     {
         string strSql = "select * from [User] where UserName='******' and password='******' and userid='" + rbl.SelectedItem.Value + "'";
         System.Data.SqlClient.SqlCommand    com = new System.Data.SqlClient.SqlCommand(strSql, con);
         System.Data.SqlClient.SqlDataReader dr  = com.ExecuteReader();
         if (dr.Read())
         {
             Session["username"] = dr.GetString(0);//Login1.UserName.ToString();
             Session["userid"]   = dr.GetString(2);
             if (Session["userid"].ToString() == "学工组" || Session["userid"].ToString() == "用人单位")
             {
                 Session["remark"] = dr.GetString(3);
             }
             e.Authenticated = true;//通过验证
             if (Session["userid"].ToString() == "学生")
             {
                 Response.Redirect("~/u_student/Apply.aspx");
             }
             if (Session["userid"].ToString() == "用人单位")
             {
                 Response.Redirect("~/u_employer/ApplyReview.aspx");
             }
             if (Session["userid"].ToString() == "学工组")
             {
                 Response.Redirect("~/u_stuwg/StudentInfoMgr2.aspx");
             }
             if (Session["userid"].ToString() == "资助中心")
             {
                 Response.Redirect("~/u_fmc/WorkInfoMaintain.aspx");
             }
         }
         else
         {
             e.Authenticated = false;
         }
         dr.Close();
         con.Close();
     }
 }
コード例 #14
0
        protected void LoginButton_Click(object sender, EventArgs e)
        {
            UtilizadorRules utilizadorRules = new UtilizadorRules();
            string          email           = ((TextBox)Login1.FindControl("UserName")).Text;
            string          senha           = ((TextBox)Login1.FindControl("Password")).Text;

            if (utilizadorRules.Login(email, senha) != null)
            {
                Session["email_login"]    = email;
                Session["password_login"] = senha;

                Response.Redirect("MenuPrincipal.aspx");
            }

            //Response.Redirect("RegisterForm.aspx");
        }
コード例 #15
0
ファイル: Login.aspx.cs プロジェクト: kbarke05/Assignment4.2
 protected void btnLogin_Click(object sender, EventArgs e)
 {
     Login1 lc = new Login1(txtUser.Text, txtPassword.Text);
     int personKey = lc.ValidateLogin();
     if (personKey != 0)
     {
         Session["personkey"] = personKey;
         Response.Redirect("Welcome.aspx");
     }
     else
     {
         lblError.Text = "Invalid login";
     }
     
    
 }
コード例 #16
0
ファイル: Logon.aspx.cs プロジェクト: penzhaohui/Crab
    protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)
    {
        string tenantName     = ((TextBox)Login1.FindControl("TenantName")).Text.Trim();
        string tenantUsername = Login1.UserName.Trim();
        Upn    upn            = new Upn(tenantName, tenantUsername);

        bool authenticated = false;

        if (!(authenticated = Membership.ValidateUser(upn.ToString(), Login1.Password)))
        {
            Login1.FailureText = Resources.GlobalResources.FailLogin;
            return;
        }
        Login1.UserName = upn.ToString();
        e.Authenticated = authenticated;
    }
コード例 #17
0
        /// <summary>
        /// Gain access to our controls in the template control.
        /// </summary>
        private void AssignLocalPointersToControls()
        {
            _loginTable       = Login1.FindControl("LoginTable") as HtmlTable;
            _userNameCombo    = Login1.FindControl("UserNameComboBox") as RadComboBox;
            _userNameText     = Login1.FindControl("UserName") as TextBox;
            _userValidator    = Login1.FindControl("UserNameRequired") as RequiredFieldValidator;
            _changeButton     = Login1.FindControl("ChangeOrganisationButton") as Button;
            _organisationName = Login1.FindControl("OrganisationName") as Label;
            _loginButton      = Login1.FindControl("LoginButton") as Button;

            _authorisationCodeTable = Login1.FindControl("AuthorisationCodeTable") as HtmlTable;
            _authorisationCode      = Login1.FindControl("AuthorisationCode") as TextBox;
            _updateButton           = Login1.FindControl("UpdateButton") as Button;
            _cancelButton           = Login1.FindControl("CancelButton") as Button;
            _organisationUnique     = Login1.FindControl("OrganisationUnique") as CustomValidator;
        }
コード例 #18
0
ファイル: Logon.aspx.cs プロジェクト: penzhaohui/Crab
    private void RememberMe()
    {
        bool rememberMe = ((CheckBox)Login1.FindControl("RememberMe")).Checked;

        // https://blogs.msdn.microsoft.com/friis/2010/08/18/remember-me-checkbox-does-not-work-with-forms-authentication/
        // https://www.codeproject.com/Articles/31914/Beginner-s-Guide-To-ASP-NET-Cookies
        // 浅析ASP.NET 2.0的用户密码加密机制  - http://www.cnblogs.com/AndersLiu/archive/2007/12/28/encode-password-with-salt.html
        // 使用Forms Authentication实现用户注册、登录 (一)基础知识 - http://www.cnblogs.com/AndersLiu/archive/2008/01/01/forms-authentication-part-1.html
        // 使用Forms Authentication实现用户注册、登录 (二)用户注册与登录 - http://www.cnblogs.com/AndersLiu/archive/2008/01/01/forms-authentication-part-2.html
        // 使用Forms Authentication实现用户注册、登录 (三)用户实体替换 - http://www.cnblogs.com/AndersLiu/archive/2008/01/01/forms-authentication-part-3.html
        // Roles-Based Authentication - https://www.codeproject.com/KB/web-security/rolesbasedauthentication.aspx?print=true
        // https://www.codeproject.com/Articles/779844/Remember-Me
        // 细说ASP.NET Forms身份认证 - http://www.cnblogs.com/fish-li/archive/2012/04/15/2450571.html

        //treat the case where we set the remember me check box
        if (rememberMe)
        {
            //clear any other tickets that are already in the response
            Response.Cookies.Clear();

            //set the new expiry date - to thirty days from now
            DateTime expiryDate = DateTime.Now.AddDays(30);

            //create a new forms auth ticket
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(2, Login1.UserName, DateTime.Now, expiryDate, true, String.Empty);

            //encrypt the ticket
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);

            //create a new authentication cookie - and set its expiration date
            HttpCookie authenticationCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            authenticationCookie.Expires = ticket.Expiration;

            //add the cookie to the response.
            Response.Cookies.Add(authenticationCookie);

            HttpCookie cookie = new HttpCookie("Crab_Remember_User_Name", Login1.UserName);
            bool       isSSL  = "HTTPS".Equals(HttpContext.Current.Request.Url.Scheme, StringComparison.OrdinalIgnoreCase);
            //if Secure is true,only https can access it.
            cookie.Secure = isSSL;
            //Prevent java script access it.
            cookie.HttpOnly = true;
            TimeSpan cookiesExistTime = new TimeSpan(2, 0, 0, 0);
            cookie.Expires = DateTime.Now + cookiesExistTime;
            HttpContext.Current.Response.Cookies.Add(cookie);
        }
    }
コード例 #19
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            string login = "";
            try
            {
                login = Convert.ToString(Request.QueryString["Login"]);
            }
            catch
            {
                login = "";
            }
            if (Request.Cookies["myScrlCookieSA"] != null)
            {
                HttpCookie myScrlCookieSA = new HttpCookie("myScrlCookieSA");
                myScrlCookieSA  = Request.Cookies.Get("myScrlCookieSA");
                Login1.UserName = myScrlCookieSA.Values["UserName"].ToString();
                TextBox txtbox = (TextBox)Login1.FindControl("Password");
                txtbox.Attributes["Value"] = myScrlCookieSA.Values["Password"].ToString();

                DataTable dt = new DataTable();
                objLogin.Username = Login1.UserName;
                objLogin.Password = txtbox.Attributes["Value"];
                dt = objLoginDB.GetDataSet(objLogin, DA_SKORKEL.DA_Login.Login_1.UserLogin);

                if (dt.Rows.Count > 0)
                {
                    if (login == "")
                    {
                        UserSession.UserInfo UInfo = new UserSession.UserInfo();
                        string LoginName           = Convert.ToString(dt.Rows[0]["LoginName"]);
                        UInfo.UserName = Convert.ToString(dt.Rows[0]["vchrUserName"]);
                        UInfo.UserID   = Convert.ToInt64(dt.Rows[0]["intRegistrationId"]);
                        int    TypeId           = Convert.ToInt32(dt.Rows[0]["intUserTypeID"]);
                        string RegistrationType = Convert.ToString(dt.Rows[0]["RegistartionType"]);

                        Session.Add("RegType", RegistrationType);
                        Session.Add("UserTypeId", TypeId);
                        Session.Add("UInfo", UInfo);
                        Session.Add("LoginName", LoginName);
                        Session.Add("ExternalUserId", Convert.ToString(dt.Rows[0]["intRegistrationId"]));
                    }
                }
            }
        }
    }
コード例 #20
0
    //protected void btnOk_Click(object sender, EventArgs e)
    //{
    //    Login();
    //}

    //protected void txtPassword_TextChanged(object sender, EventArgs e)
    //{
    //    Login();
    //}

    private void Login()
    {
        //t_Users dbUser = _userBL.GetUser(txtUsername.Text);
        t_Users dbUser = _userBL.GetUser(Login1.UserName);

        if (dbUser == null)
        {
            //ntf.VisibleOnPageLoad = true;
            //ntf.Text = "Sai ký danh hoặc mật khẩu.";
            //txtUsername.Focus();
            return;
        }
        //string hashedPassword = _stringUT.HashMD5(_stringUT.HashMD5(txtPassword.Text) + dbUser.Salt);
        string hashedPassword = _stringUT.HashMD5(_stringUT.HashMD5(Login1.Password) + dbUser.Salt);

        if (string.Equals(hashedPassword, dbUser.Password))
        {
            HttpCookie cookie;
            System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(1, dbUser.Username, DateTime.Now,
                                                                                                                     DateTime.Now.AddMinutes(HttpContext.Current.Session.Timeout),
                                                                                                                     true, dbUser.Role + "|" + dbUser.ConsumerId, System.Web.Security.FormsAuthentication.FormsCookiePath);
            string hashCookie = System.Web.Security.FormsAuthentication.Encrypt(ticket);
            cookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, hashCookie);
            Response.Cookies.Add(cookie);
            t_Users user = new t_Users();
            user           = dbUser;
            user.LoginTime = user.LoginTime == null ? 0 : user.LoginTime + 1;
            _userBL.UpdateUser(user, dbUser);
            if (dbUser.Role != "consumer" && dbUser.Role != "staff")
            {
                Response.Redirect("~/Supervisor/Logger/MapJS_rev1.aspx?uid=" + user.Username);
            }
            else
            {
                Response.Redirect("~/Consumer/Logger/MapJS_rev1.aspx?uid=" + user.Username);
            }
        }
        else
        {
            //ntf.VisibleOnPageLoad = true;
            //ntf.Text = "Sai ký danh hoặc mật khẩu.";
            //txtUsername.Focus();

            TextBox TextBoxUserName = Login1.FindControl("UserName") as TextBox;
            TextBoxUserName.Focus();
        }
    }
コード例 #21
0
        protected void Page_Load(object sender, EventArgs e)
        {
            ErrMessage_Span.InnerHtml        = "";
            ErrMessage_Span.Style["display"] = "none";

            // -------------------------------------------------------------------------------------------
            // buscamos el rol Administradores y verificamos que tenga usuarios ... de no ser así, lo más
            // probable es que el sistema se haya recién instalado y estas credenciales son necesarias para
            // poder iniciar el uso de la aplicación

            if (!Roles.RoleExists("Administradores") ||
                Roles.GetUsersInRole("Administradores").Count() == 0)
            {
                if (!Roles.RoleExists("Administradores"))
                {
                    Roles.CreateRole("Administradores");
                }



                if (Membership.GetUser("Administrador") == null)
                {
                    MembershipUser newUser = Membership.CreateUser("Administrador", "administrador", "*****@*****.**");
                }

                Roles.AddUserToRole("Administrador", "Administradores");

                ErrMessage_Span.InnerHtml = "<br />" +
                                            "NOTA IMPORTANTE: hemos encontrado que no existe el rol Administradores o el mismo no " +
                                            "tiene usuarios asociados.<br />" +
                                            "La razón de esta situación es, probablemente, que se está iniciando el uso de la aplicación.<br />" +
                                            "Se ha creado un rol 'Administradores' y se ha agregado el usuario 'Administrador' " +
                                            "(password: administrador) al mismo.<br />" +
                                            "De resultar adecuado, Ud. puede hacer un login ahora usando este usuario.<br /><br />";
                ErrMessage_Span.Style["display"] = "block";
            }

            if (!(Membership.GetAllUsers().Count == 0))
            {
                // solo cuando no existen usuarios registrados, permitimos agregar un usuario a la aplicación
                Login1.CreateUserText = "";
            }

            TextBox tb = (TextBox)Login1.FindControl("UserName");

            tb.Focus();
        }
コード例 #22
0
    protected void Login_LoggedIn(object sender, EventArgs e)
    {
        MembershipUser user     = Membership.GetUser(Login1.UserName);
        TextBox        TextBox1 = (TextBox)Login1.FindControl("UserName");

        Session["LoginName"] = user;

        if (Roles.IsUserInRole(TextBox1.Text, "Admin"))
        {
            Login1.DestinationPageUrl = "~/Default.aspx";
        }

        else if (Roles.IsUserInRole(TextBox1.Text, "Student"))
        {
            SqlConnection cn = new SqlConnection();
            cn.ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\ASPNETDB.MDF;Integrated Security=True;User Instance=True";
            cn.Open();
            // Response.Write(cn.State);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "SELECT Enrollment_Id FROM ENROLLMENT WHERE ('" + DateTime.Now.ToShortDateString() + "' BETWEEN EDate AND DATEADD(month,9,EDATE)) AND (STUDENT_ID IN (SELECT STUDENT_ID FROM STUDENT WHERE USERNAME ='******'))";
            cmd.Connection  = cn;

            int id = Convert.ToInt32(cmd.ExecuteScalar());

            Session["Eid"] = id;

            SqlCommand cmd_id = new SqlCommand();
            cmd_id.CommandText = "SELECT STUDENT_ID FROM ENROLLMENT WHERE ENROLLMENT_ID=" + id;
            cmd_id.Connection  = cn;
            Session["Sid"]     = cmd_id.ExecuteScalar();



            SqlCommand cmdl = new SqlCommand();
            cmdl.CommandText    = "SELECT BATCH_ID FROM ENROLLMENT WHERE Enrollment_id=" + id;
            cmdl.Connection     = cn;
            Session["batch_id"] = Convert.ToInt32(cmdl.ExecuteScalar());
            // Response.Write(" hjgjg " + Session["batch_id"]);
            Login1.DestinationPageUrl = "~/Student/Default.aspx";
        }
        else
        {
            Response.Write("U r an anonymous user");
        }
    }
コード例 #23
0
        protected void Page_PreRender(object sender, EventArgs e)
        {
            TextBox username = Login1.FindControl("UserName") as TextBox;

            if (username != null)
            {
                // iOs
                username.Attributes.Add("autocorrect", "off");
                username.Attributes.Add("autocapitalize", "off");
            }
            // username text box email
            // this doesn't work; use js
            //if (username != null)
            //{
            //    username.Attributes["type"] = "email";
            //}
        }
コード例 #24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //ntf.VisibleOnPageLoad = false;
        if (!IsPostBack)
        {
            // Pi-solution developer
            t_SysParam logo = sysParamBL.FindSingle(s => s.Name == "img_logo");
            imgLogo.Src = (logo == null)? "" : logo.Val;

            t_SysParam companyName = sysParamBL.FindSingle(s => s.Name == "company_name");
            lbCompany.Text = (companyName == null) ? "" : companyName.Val;


            TextBox TextBoxUserName = Login1.FindControl("UserName") as TextBox;
            TextBoxUserName.Focus();
        }
    }
コード例 #25
0
ファイル: Login.xaml.cs プロジェクト: vannhat123/Hello-UWP
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            var login = new Login1 {
                email    = "*****@*****.**",
                password = "******",
            };

            Debug.WriteLine(JsonConvert.SerializeObject(login));
            var httpClient = new HttpClient();
            //httpClient.DefaultRequestHeaders.Add("Authorization", "Basic " + token);
            HttpContent content = new StringContent(JsonConvert.SerializeObject(login), Encoding.UTF8,
                                                    "application/json");
            Task <HttpResponseMessage> httpRequestMessage = httpClient.PostAsync(ApiUrl, content);
            String responseContent = httpClient.PostAsync(ApiUrl, content).Result.Content.ReadAsStringAsync().Result;

            Debug.WriteLine("Response: " + responseContent);
        }
コード例 #26
0
        private void BrowserDetection()
        {
            System.Web.HttpBrowserCapabilities browser = Request.Browser;
            string s = "Browser Capabilities\n"
                       + "Type = " + browser.Type + "\n"
                       + "Name = " + browser.Browser + "\n"
                       + "Version = " + browser.Version + "\n"
                       + "Major Version = " + browser.MajorVersion + "\n"
                       + "Minor Version = " + browser.MinorVersion + "\n"
                       + "Platform = " + browser.Platform + "\n"
                       + "Is Beta = " + browser.Beta + "\n"
                       + "Is Crawler = " + browser.Crawler + "\n"
                       + "Is AOL = " + browser.AOL + "\n"
                       + "Is Win16 = " + browser.Win16 + "\n"
                       + "Is Win32 = " + browser.Win32 + "\n"
                       + "Supports Frames = " + browser.Frames + "\n"
                       + "Supports Tables = " + browser.Tables + "\n"
                       + "Supports Cookies = " + browser.Cookies + "\n"
                       + "Supports VBScript = " + browser.VBScript + "\n"
                       + "Supports JavaScript = " +
                       browser.EcmaScriptVersion.ToString() + "\n"
                       + "Supports Java Applets = " + browser.JavaApplets + "\n"
                       + "Supports ActiveX Controls = " + browser.ActiveXControls
                       + "\n"
                       + "Supports JavaScript Version = " +
                       browser["JavaScriptVersion"] + "\n";

            if (browser.Browser.ToLower() != "firefox")
            {
                ((Label)Login1.FindControl("lblBrowserWarning")).Text = "&#9658; การแสดงผลอาจมีปัญหา หรือใช้งาน ADAMs ไม่ได้<br />&nbsp;&nbsp;&nbsp;&nbsp;เนื่องจากไม่ได้ใช้งานผ่าน Firefox";
            }

            if ((browser.Browser.ToLower() == "internetexplorer" || browser.Browser.ToLower() == "ie") && browser.MajorVersion <= 7)
            {
                ((TextBox)Login1.FindControl("Password")).TextMode = TextBoxMode.Password;
                ((TextBox)Login1.FindControl("Password")).Attributes.Remove("onkeypress");
                ((TextBox)Login1.FindControl("Password")).Attributes.Remove("onfocus");
                ((TextBox)Login1.FindControl("Password")).Attributes.Remove("onblur");

                ((TextBoxWatermarkExtender)Login1.FindControl("txtUsernameWatermark")).Enabled = false;
                ((TextBoxWatermarkExtender)Login1.FindControl("txtPasswordWatermark")).Enabled = false;
            }

            //Response.Write(s);
        }
コード例 #27
0
    protected void MyLoginButton_Click(object sender, EventArgs e)
    {
        //-- 判断是否登录成功
        string UserCode   = "";
        string username   = ((ASPxTextBox)Login1.FindControl("UserName")).Text;
        string password   = ((ASPxTextBox)Login1.FindControl("Password")).Text;
        bool   rememberMe = ((CheckBox)Login1.FindControl("RememberMe")).Checked;

        User userService = new User();

        if (!userService.AuthenticateUser(username, password, out UserCode))
        {
            ((Literal)Login1.FindControl("FailureText")).Text = "用户名或密码错误,请重试。 ";
            return;
        }
        Session["UserCode"] = UserCode;
        FormsAuthentication.RedirectFromLoginPage(UserCode.ToString(), rememberMe);
    }
コード例 #28
0
    protected void login_Click(object sender, EventArgs e)
    {
        Login1 log = new Login1();

        bool loginresult = log.GetLogin(inpemail.Value, inppassword.Value);

        if (loginresult)
        {
            Session["Email"] = inpemail.Value;


            Response.Redirect("Home.aspx");
        }
        else
        {
            Response.Write("Invalid e-mail or password");
        }
    }
コード例 #29
0
        //Is called whenever the login form is submitted
        protected void ValidateUser(object sender, EventArgs e)
        {
            String       nick   = ((TextBox)Login1.FindControl("UserName")).Text;
            String       passwd = ((TextBox)Login1.FindControl("Password")).Text;
            LoggedInUser result = Starter.loginUser(nick, passwd);

            if (result != null)
            {
                Session["loggedInUser"] = result;
                //Redirect if successful
                FormsAuthentication.RedirectFromLoginPage(nick, Login1.RememberMeSet);
                //((Label)Login1.FindControl("FailureText")).Text = "Success";
            }
            else
            {
                //((TextBox)Login1.FindControl("FailureText")).Text = "Failure";
            }
        }
コード例 #30
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //CultureInfo inf1 = System.Threading.Thread.CurrentThread.CurrentCulture;
        //CultureInfo inf2 = System.Threading.Thread.CurrentThread.CurrentUICulture;

        if (Request.QueryString["login"] != null && !IsPostBack)
        {
            Login1.UserName = Request.QueryString["login"];
            if (Request.IsAuthenticated)
            {
                FormsAuthentication.SignOut();
            }
        }
        else if (Request.IsAuthenticated)
        {
            Response.Redirect(FormsAuthentication.DefaultUrl, true);
        }

        if (!IsPostBack)
        {
            Form.DefaultButton = Login1.FindControl("LoginButton").UniqueID;
        }


        if (Request.QueryString["pwd"] != null)
        {
            //Login1. Password = Request.QueryString["pwd"];
            //Object o =Login1.Controls;
            TextBox pwd = (TextBox)Login1.FindControl("Password");
            if (pwd != null)
            {
                //pwd.Text = Request.QueryString[ "pwd" ];

                if (!Page.ClientScript.IsStartupScriptRegistered("InitPwd"))
                {
                    Page.ClientScript.RegisterStartupScript(this.GetType(), "InitPwd",
                                                            String.Format("<script language=\"javascript\">document.getElementById('{0}').value='{1}';</script>", pwd.ClientID, Request.QueryString["pwd"])
                                                            );
                }
            }
        }
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Cache.SetNoStore();
    }
コード例 #31
0
    void btnItem_Click(object sender, EventArgs e)
    {
        // Check if should send password
        if (IsForgottenPassword)
        {
            SetForgottenPasswordMode();

            TextBox        txtUserName        = (TextBox)Login1.FindControl("UserName");
            LocalizedLabel lblForgottenResult = (LocalizedLabel)Login1.FindControl("lblForgottenResult");
            if (txtUserName != null)
            {
                // Reset password
                string siteName = CMSContext.CurrentSiteName;
                lblForgottenResult.Visible = true;
                bool success;
                lblForgottenResult.Text = UserInfoProvider.ForgottenEmailRequest(txtUserName.Text.Trim(), siteName, "Logon page", SettingsKeyProvider.GetStringValue(siteName + ".CMSSendPasswordEmailsFrom"), null, UserInfoProvider.GetResetPasswordUrl(siteName), out success);
            }
        }
    }
コード例 #32
0
ファイル: Login.aspx.cs プロジェクト: masteroren/MyBuyList
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!this.IsPostBack)
        {
            if (Session["AnonymousUsersMenu"] != null)
            {
                this.lblTitle.Text = "על מנת לשמור את התפריט, עליך להתחבר/להירשם";

                Session.Remove("AnonymousUsersMenu");
            }
            else if (this.ReturnUrl.Contains("personalarea.aspx"))
            {
                this.lblTitle.Text = "על מנת לגשת לרשימות השמורות, עליך להתחבר/להירשם";
            }

            if (this.ReturnUrl.Contains("quickmenu.aspx") || this.ReturnUrl.Contains("shoppinglist.aspx"))
            {
                this.lblTitle.Text    = "על מנת להשלים את הפעולה, עליך להתחבר/להירשם";
                this.lblTitle.Visible = true;
            }
            if (this.ReturnUrl.Contains("recipeedit.aspx"))
            {
                this.lblTitle.Text    = "על מנת ליצור מתכון חדש, עליך להתחבר/להירשם";
                this.lblTitle.Visible = true;
            }
            if (this.ReturnUrl.Contains("menuedit.aspx"))
            {
                this.lblTitle.Text    = "על מנת ליצור תפריט חדש, עליך להתחבר/להירשם";
                this.lblTitle.Visible = true;
            }

            if (!string.IsNullOrEmpty(this.ReturnUrl))
            {
                HyperLink lnk = (HyperLink)this.Login1.FindControl("CreateUserLink");
                lnk.NavigateUrl += string.Format("?ReturnUrl={0}", Request["ReturnUrl"]);

                lnk              = (HyperLink)this.Login1.FindControl("PasswordRecoveryLink");
                lnk.NavigateUrl += string.Format("?ReturnUrl={0}", Request["ReturnUrl"]);
            }
        }

        Form.DefaultButton = Login1.FindControl("LoginButton").UniqueID;
    }