public async Task <IHttpActionResult> RegisterUser(tUser tUser)
        {
            //tUser user = await db.tUsers.FirstAsync(x => x.Email == tUser.Email);

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }
            //var user = db.tUsers.FirstOrDefault(x => x.Email == tUser.Email);
            //if (user != null)
            //{
            //    return Conflict();
            //}

            try
            {
                tUser.ExternalID      = Guid.NewGuid();
                tUser.CreateDateTime  = DateTime.Now;
                tUser.AccountStatusID = 1;
                //tUser.PHSaltID = 1;

                if (tUser.PasswordHash != null)
                {
                    PasswordStorage oPassUtil = new PasswordStorage();
                    //oPassUtil.Hashstring = ;
                    oPassUtil.CreateHash(tUser.PasswordHash);
                    //oPassUtil.VerifyPassword
                    tUser.PasswordHash = oPassUtil.Hashstring;

                    tSalt salt = new tSalt();
                    salt.Salt = oPassUtil.Saltstring;

                    SaltsController sl = new SaltsController();
                    tUser.tSalt = await sl.PosttSalt(salt);

                    tUser.PHSaltID = tUser.tSalt.Id;
                }

                db.tUsers.Add(tUser);
                db.SaveChanges();

                //post new userid to other dbs
                UserData.UserIDsController userIds = new UserData.UserIDsController();
                tUserID userID = new tUserID();
                userID.UserID = tUser.ID;

                await userIds.PosttUserID(userID);

                WebApp.UserIDsController webUsers = new WebApp.UserIDsController();
                await webUsers.PosttUserID(userID);

                //Add default consent to new user's share settings
                tUserSHARESetting            userSHARESetting = new tUserSHARESetting();
                tXrefUserSHARESettingsPurpos userXrefSHARE    = new tXrefUserSHARESettingsPurpos();
                userSHARESetting.AllData        = true;
                userSHARESetting.UserID         = tUser.ID;
                userSHARESetting.SHARESettingID = 1; //allow
                userSHARESetting.SystemStatusID = 1; //valid
                userXrefSHARE.SHARESettingID    = userSHARESetting.ID;
                userXrefSHARE.SHAREPurposeID    = 2; //Research only, any available
                userSHARESetting.tXrefUserSHARESettingsPurposes.Add(userXrefSHARE);

                UserData.UserSHARESettingsController shareController = new UserData.UserSHARESettingsController();
                await shareController.PosttUserSHARESetting(userSHARESetting);

                //return CreatedAtRoute("UsersAPI", new { id = tUser.ID }, tUser);
                return(Ok(tUser));
            }
            catch (Exception ex)
            {
                //Insert Error Log
                tUsersErrLog userErrorLog = new tUsersErrLog();

                userErrorLog.ErrTypeID   = (int)ErrorLogging.enumErrorType.Application;
                userErrorLog.ErrSourceID = (int)AuditLogging.enumApplication.SFCBAL;
                userErrorLog.Code        = ex.HResult.ToString();
                userErrorLog.Description = ex.Message;
                userErrorLog.Trace       = ex.StackTrace;

                db.tUsersErrLogs.Add(userErrorLog);
                db.SaveChanges();

                string ErrMsg = "An error occured and we have logged the error. Please try again later.";

                Exception Err = new Exception(ErrMsg, ex);

                return(InternalServerError(Err));
            }
        }
        public ActionResult EditProfile(customer_profile_table customer_profile_table, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                var allowedExtensions = new[] {
                    ".Jpg", ".png", ".jpg", ".jpeg"
                };
                customer_profile_table existing = ags.customer_profile_table.Find(customer_profile_table.id);
                var password    = existing.password.ToString();
                var newPassword = customer_profile_table.password.ToString();


                if (existing.profileimg == null && customer_profile_table.ImageFile != null)
                {
                    string BigfileName = Path.GetFileNameWithoutExtension(customer_profile_table.ImageFile.FileName);
                    string fileName    = BigfileName.Substring(0, 1);
                    string extension1  = Path.GetExtension(customer_profile_table.ImageFile.FileName);
                    string extension   = extension1.ToLower();
                    if (allowedExtensions.Contains(extension))
                    {
                        fileName = fileName + DateTime.Now.ToString("yyssmmfff") + extension;
                        customer_profile_table.profileimg = "~/customerImage/" + fileName;
                        fileName = Path.Combine(Server.MapPath("~/customerImage/"), fileName);
                        customer_profile_table.ImageFile.SaveAs(fileName);
                    }
                    else
                    {
                        TempData["Message"] = "Only 'Jpg', 'png','jpeg' images formats are alllowed..!";
                        return(RedirectToAction("EditProfile", "MobileClientele"));
                    }
                }


                else if (existing.profileimg != null && customer_profile_table.profileimg != null)
                {
                    if (customer_profile_table.ImageFile != null)
                    {
                        string   path = Server.MapPath(existing.profileimg);
                        FileInfo file = new FileInfo(path);
                        if (file.Exists)
                        {
                            file.Delete();
                        }
                        string BigfileName = Path.GetFileNameWithoutExtension(customer_profile_table.ImageFile.FileName);
                        string fileName    = BigfileName.Substring(0, 1);
                        string extension1  = Path.GetExtension(customer_profile_table.ImageFile.FileName);
                        string extension   = extension1.ToLower();
                        if (allowedExtensions.Contains(extension))
                        {
                            fileName = fileName + DateTime.Now.ToString("yyssmmfff") + extension;
                            customer_profile_table.profileimg = "~/customerImage/" + fileName;
                            fileName = Path.Combine(Server.MapPath("~/customerImage/"), fileName);
                            customer_profile_table.ImageFile.SaveAs(fileName);
                        }
                        else
                        {
                            TempData["Message"] = "Only 'Jpg', 'png','jpeg' images formats are alllowed..!";
                            return(RedirectToAction("EditProfile", "MobileClientele"));
                        }
                    }
                    else
                    {
                        existing.profileimg = existing.profileimg;
                    }
                }
                else
                {
                    existing.profileimg = existing.profileimg;
                }
                existing.name         = customer_profile_table.name;
                existing.email        = customer_profile_table.email;
                existing.phoneno      = customer_profile_table.phoneno;
                existing.weddingdate  = customer_profile_table.weddingdate;
                existing.dob          = customer_profile_table.dob;
                existing.address      = customer_profile_table.address;
                existing.alterphoneno = customer_profile_table.alterphoneno;

                if (existing.customerid != customer_profile_table.customerid)
                {
                    var userCount = (from u in ags.customer_profile_table where u.customerid == customer_profile_table.customerid select u).Count();
                    if (userCount == 0)
                    {
                        existing.customerid = customer_profile_table.customerid;
                    }
                    else
                    {
                        //existing.username = admin_table.username;
                        TempData["Message"] = "This user name is already exist";
                        //return PartialView("Edit", "SuperAdmin");
                        return(RedirectToAction("EditProfile", "MobileClientele"));
                    }
                }


                existing.profileimg = customer_profile_table.profileimg;



                if (existing.datex == null)
                {
                    existing.datex = DateTime.Now.ToString();
                }
                else
                {
                    existing.datex = existing.datex;
                }
                if (password.Equals(newPassword))
                {
                    existing.password = customer_profile_table.password;
                }
                else
                {
                    existing.password = PasswordStorage.CreateHash(customer_profile_table.password);
                }

                ags.SaveChanges();
                TempData["updateSuccess"] = "Your Profile Updated Successfully.!";
                return(RedirectToAction("Profile", "MobileClientele"));
            }
            return(RedirectToAction("EditProfile", "MobileClientele"));
        }
    private void registerUserWithSlowHash()
    {
        bool methodStatus = true;

        if (InputValidation.ValidatePhoneNumber(phoneNumberTextBox.Text) == false)
        {
            methodStatus = false;
            phoneNumberTextBox.CssClass      = "form-control is-invalid";
            phoneNumberTextBoxLabel.Text     = "invalid phone number";
            phoneNumberTextBoxLabel.CssClass = "form-control-label text-danger";
        }

        if (InputValidation.ValidateName(firstNameTextBox.Text) == false)
        {
            methodStatus = false;
            firstNameTextBox.CssClass      = "form-control is-invalid";
            firstNameTextBoxLabel.Text     = "invalid first name";
            firstNameTextBoxLabel.CssClass = "form-control-label text-danger";
        }

        if (InputValidation.ValidateName(middleNameTextBox.Text) == false)
        {
            methodStatus = false;
            middleNameTextBox.CssClass      = "form-control is-invalid";
            middleNameTextBoxLabel.Text     = "invalid middle name";
            middleNameTextBoxLabel.CssClass = "form-control-label text-danger";
        }

        if (InputValidation.ValidateName(lastNameTextBox.Text) == false)
        {
            methodStatus                  = false;
            lastNameTextBox.CssClass      = "form-control is-invalid";
            lastNameTextBoxLabel.Text     = "invalid last name";
            lastNameTextBoxLabel.CssClass = "form-control-label text-danger";
        }

        if (InputValidation.ValidateUserInput(usernameTextBox.Text) == false)
        {
            methodStatus                  = false;
            usernameTextBox.CssClass      = "form-control is-invalid";
            usernameTextBoxLabel.Text     = "invalid username";
            usernameTextBoxLabel.CssClass = "form-control-label text-danger";
        }

        if (InputValidation.ValidateUserInput(passwordTextBox.Text) == false)
        {
            methodStatus                  = false;
            passwordTextBox.CssClass      = "form-control is-invalid";
            passwordTextBoxLabel.Text     = "invalid password";
            passwordTextBoxLabel.CssClass = "form-control-label text-danger";
        }

        if (InputValidation.ValidateEmail(emailTextBox.Text) == false)
        {
            methodStatus               = false;
            emailTextBox.CssClass      = "form-control is-invalid";
            emailTextBoxLabel.Text     = "invalid email address";
            emailTextBoxLabel.CssClass = "form-control-label text-danger";
        }

        if (methodStatus == true)
        {
            String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();

            conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
            conn.Open();

            queryString = "";
            if (customCheck1.Checked)
            {
                queryString = "INSERT INTO webapppersonalfit.userregistration (firstname, middlename, lastname, email, phonenumber, username, userpassword, slowHashSalt, isPT)"
                              + "VALUES(?firstname, ?middlename, ?lastname, ?email, ?phonenumber, ?uname, ?userpassword, ?slowHashSalt, TRUE)";
            }
            else
            {
                queryString = "INSERT INTO webapppersonalfit.userregistration (firstname, middlename, lastname, email, phonenumber, username, userpassword, slowHashSalt, isPT)"
                              + "VALUES(?firstname, ?middlename, ?lastname, ?email, ?phonenumber, ?uname, ?userpassword, ?slowHashSalt, FALSE)";
            }

            cmd = new MySql.Data.MySqlClient.MySqlCommand(queryString, conn);
            cmd.Parameters.AddWithValue("?firstname", firstNameTextBox.Text);
            cmd.Parameters.AddWithValue("?middlename", middleNameTextBox.Text);
            cmd.Parameters.AddWithValue("?lastname", lastNameTextBox.Text);
            cmd.Parameters.AddWithValue("?email", emailTextBox.Text);
            cmd.Parameters.AddWithValue("?phonenumber", phoneNumberTextBox.Text);
            cmd.Parameters.AddWithValue("?uname", usernameTextBox.Text);
            cmd.Parameters.AddWithValue("?userpassword", passwordTextBox.Text);
            //cmd.Parameters.AddWithValue("?slowHashSalt", passwordTextBox.Text);

            String saltHashReturned = PasswordStorage.CreateHash(passwordTextBox.Text);
            int    commaIndex       = saltHashReturned.IndexOf(":");
            String extractedString  = saltHashReturned.Substring(commaIndex + 1);
            commaIndex      = extractedString.IndexOf(":");
            extractedString = saltHashReturned.Substring(commaIndex + 1);
            commaIndex      = extractedString.IndexOf(":");

            extractedString = saltHashReturned.Substring(commaIndex + 1);
            commaIndex      = extractedString.IndexOf(":");
            String salt = extractedString.Substring(0, commaIndex);

            commaIndex      = extractedString.IndexOf(":");
            extractedString = extractedString.Substring(commaIndex + 1);
            String hash = extractedString;
            //from the first : to the second : is the salt
            //from the second : to the end is the hash

            cmd.Parameters.AddWithValue("?slowHashSalt", saltHashReturned);

            cmd.ExecuteReader();
            conn.Close();

            //Registration is successfully completed
            String subject = "PersonalFit Verification Email";
            String body    = "Please click the link below to verify your email.";
            Email.sendEmail(Util.defaultEmail, emailTextBox.Text, subject, body);
        }
    }
Esempio n. 4
0
        public JsonResult CrearUsuario(string Tipoid, string NumId, string NomUsuario, string ApellidosUsuario, DateTime FechaNacimiento,
                                       string CiudadNacimiento, string DepartamentoNacimiento, string PaisNacimiento, string CiudadResidencia, string DepartamentoResidencia,
                                       string PaisResidencia, string DireccionResidencia, string TelefonoFijo, string TelefonoCelular, string CorreoElectronico, string InstitucionEgreso,
                                       string AnioEgreso, string TipoAfiliacion, string TituloPregrado, string InstitucionPregrado, string AnioGraduacionPregrado, string TituloPosgrado,
                                       string InstitucionPosgrado, string AnioGraduacionPosgrado, string NomEmpresaTrabajo, string Cargo, string DirEmpresa, string TelefonoEmpresa, string Contrasenia)
        {
            Respuesta3 r3 = new Respuesta3();

            r3.message = new List <string>();
            Database  conex = Conexion.getInstancia();
            DataTable dt    = new DataTable();

            dt = conex.ExecuteDataSet("Usp_BuscarUsuario", Tipoid, NumId).Tables[0];
            if (dt.Rows.Count == 0)
            {
                if (string.IsNullOrEmpty(Tipoid.Trim()) || string.IsNullOrWhiteSpace(Tipoid.Trim()))
                {
                    r3.message.Add("<li>Debe seleccionar el tipo de identificación</li>");
                }
                if (string.IsNullOrEmpty(NumId.Trim()) || string.IsNullOrWhiteSpace(NumId.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el número de identificación</li>");
                }
                if (string.IsNullOrEmpty(NomUsuario.Trim()) || string.IsNullOrWhiteSpace(NomUsuario.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el nombre</li>");
                }
                if (string.IsNullOrEmpty(ApellidosUsuario.Trim()) || string.IsNullOrWhiteSpace(ApellidosUsuario.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar los apellidos</li>");
                }
                if (FechaNacimiento.Year > 1999)
                {
                    r3.message.Add("<li>Debe ingresar una fecha de nacimiento válida</li>");
                }
                if (string.IsNullOrEmpty(CiudadNacimiento.Trim()) || string.IsNullOrWhiteSpace(CiudadNacimiento.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar la ciudad de nacimiento</li>");
                }
                if (string.IsNullOrEmpty(DepartamentoNacimiento.Trim()) || string.IsNullOrWhiteSpace(DepartamentoNacimiento.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el departamento de nacimiento</li>");
                }
                if (string.IsNullOrEmpty(PaisNacimiento.Trim()) || string.IsNullOrWhiteSpace(PaisNacimiento.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el país de nacimiento</li>");
                }
                if (string.IsNullOrEmpty(CiudadResidencia.Trim()) || string.IsNullOrWhiteSpace(CiudadResidencia.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar la ciudad de residencia</li>");
                }
                if (string.IsNullOrEmpty(DepartamentoResidencia.Trim()) || string.IsNullOrWhiteSpace(DepartamentoResidencia.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el departamento de residencia</li>");
                }
                if (string.IsNullOrEmpty(PaisResidencia.Trim()) || string.IsNullOrWhiteSpace(PaisResidencia.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el pais de residencia</li>");
                }
                if (string.IsNullOrEmpty(DireccionResidencia.Trim()) || string.IsNullOrWhiteSpace(DireccionResidencia.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar la dirección de residencia</li>");
                }
                if (string.IsNullOrEmpty(TelefonoFijo.Trim()) || string.IsNullOrWhiteSpace(TelefonoFijo.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el teléfono fijo</li>");
                }
                if (string.IsNullOrEmpty(TelefonoCelular.Trim()) || string.IsNullOrWhiteSpace(TelefonoCelular.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el teléfono celular</li>");
                }
                if (string.IsNullOrEmpty(CorreoElectronico.Trim()) || string.IsNullOrWhiteSpace(CorreoElectronico.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el correo electrónico</li>");
                }
                if (string.IsNullOrEmpty(InstitucionEgreso.Trim()) || string.IsNullOrWhiteSpace(InstitucionEgreso.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar la institución de egreso</li>");
                }
                if (string.IsNullOrEmpty(AnioEgreso.Trim()) || string.IsNullOrWhiteSpace(AnioEgreso.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el año de egreso</li>");
                }
                if (string.IsNullOrEmpty(TipoAfiliacion.Trim()) || string.IsNullOrWhiteSpace(TipoAfiliacion.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el tipo de afiliación</li>");
                }
                if (string.IsNullOrEmpty(InstitucionPregrado.Trim()) || string.IsNullOrWhiteSpace(InstitucionPregrado.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar la institución de pregrado</li>");
                }
                if (string.IsNullOrEmpty(TituloPregrado.Trim()) || string.IsNullOrWhiteSpace(TituloPregrado.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el titulo de pregrado</li>");
                }
                if (string.IsNullOrEmpty(AnioGraduacionPregrado.Trim()) || string.IsNullOrWhiteSpace(AnioGraduacionPregrado.Trim()))
                {
                    r3.message.Add("<li>Debe ingresar el año de graduación de pregrado</li>");
                }
                if (r3.message.Count == 0)
                {
                    string newpass = PasswordStorage.CreateHash(Contrasenia);

                    conex.ExecuteDataSet("Usp_CrearUsuario", Tipoid, NumId, NomUsuario, ApellidosUsuario,
                                         FechaNacimiento, CiudadNacimiento, DepartamentoNacimiento,
                                         PaisNacimiento, CiudadResidencia, DepartamentoResidencia, PaisResidencia, DireccionResidencia, TelefonoFijo,
                                         TelefonoCelular, CorreoElectronico, InstitucionEgreso, AnioEgreso,
                                         TipoAfiliacion, TituloPregrado, InstitucionPregrado, AnioGraduacionPregrado, TituloPosgrado,
                                         InstitucionPosgrado, AnioGraduacionPosgrado, NomEmpresaTrabajo, Cargo, DirEmpresa,
                                         TelefonoEmpresa, newpass);
                    r3.existe = "";
                }
            }
            else
            {
                r3.existe = "El usuario ya existe";
            }

            return(Json(r3, JsonRequestBehavior.AllowGet));
        }
Esempio n. 5
0
        public ActionResult EditProfile(admin_table admin_table, FormCollection form)
        {
            if (ModelState.IsValid)
            {
                var allowedExtensions = new[] {
                    ".Jpg", ".png", ".jpg", ".jpeg"
                };
                admin_table existing    = ags.admin_table.Find(admin_table.id);
                var         password    = existing.password.ToString();
                var         newPassword = admin_table.password.ToString();

                var        getEmployeeCategoty = ags.emp_category_table.Where(x => x.status == "publish").ToList();
                SelectList list = new SelectList(getEmployeeCategoty, "emp_category_id", "emp_category");
                ViewBag.categoryList = list;
                if (existing.photo == null && admin_table.ImageFile != null)
                {
                    string BigfileName = Path.GetFileNameWithoutExtension(admin_table.ImageFile.FileName);
                    string fileName    = BigfileName.Substring(0, 1);
                    string extension1  = Path.GetExtension(admin_table.ImageFile.FileName);
                    string extension   = extension1.ToLower();
                    if (allowedExtensions.Contains(extension))
                    {
                        fileName          = fileName + DateTime.Now.ToString("yyssmmfff") + extension;
                        admin_table.photo = "~/adminimage/" + fileName;
                        fileName          = Path.Combine(Server.MapPath("~/adminimage/"), fileName);
                        admin_table.ImageFile.SaveAs(fileName);
                    }
                    else
                    {
                        TempData["Message"] = "Only 'Jpg', 'png','jpeg' images formats are alllowed..!";
                        return(RedirectToAction("EditProfile", "MobileManager"));
                    }
                }


                else if (existing.photo != null && admin_table.photo != null)
                {
                    if (admin_table.ImageFile != null)
                    {
                        string   path = Server.MapPath(existing.photo);
                        FileInfo file = new FileInfo(path);
                        if (file.Exists)
                        {
                            file.Delete();
                        }
                        string BigfileName = Path.GetFileNameWithoutExtension(admin_table.ImageFile.FileName);
                        string fileName    = BigfileName.Substring(0, 1);
                        string extension1  = Path.GetExtension(admin_table.ImageFile.FileName);
                        string extension   = extension1.ToLower();
                        if (allowedExtensions.Contains(extension))
                        {
                            fileName          = fileName + DateTime.Now.ToString("yyssmmfff") + extension;
                            admin_table.photo = "~/adminimage/" + fileName;
                            fileName          = Path.Combine(Server.MapPath("~/adminimage/"), fileName);
                            admin_table.ImageFile.SaveAs(fileName);
                        }
                        else
                        {
                            TempData["Message"] = "Only 'Jpg', 'png','jpeg' images formats are alllowed..!";
                            return(RedirectToAction("EditProfile", "MobileManager"));
                        }
                    }
                    else
                    {
                        existing.photo = existing.photo;
                    }
                }
                else
                {
                    existing.photo = existing.photo;
                }
                existing.name           = admin_table.name;
                existing.email          = admin_table.email;
                existing.phoneno        = admin_table.phoneno;
                existing.alternatephone = admin_table.alternatephone;
                existing.dob            = admin_table.dob;
                existing.address        = admin_table.address;
                existing.userrole       = admin_table.userrole;


                if (existing.username != admin_table.username)
                {
                    var userCount = (from u in ags.admin_table where u.username == admin_table.username select u).Count();
                    if (userCount == 0)
                    {
                        existing.username = admin_table.username;
                    }
                    else
                    {
                        //existing.username = admin_table.username;
                        TempData["Message"] = "This user name is already exist";
                        //return PartialView("Edit", "SuperAdmin");
                        return(RedirectToAction("EditProfile", "MobileManager"));
                    }
                }

                existing.isActive = admin_table.isActive;
                existing.photo    = admin_table.photo;


                if (existing.addedby == null)
                {
                    existing.addedby = Session["username"].ToString();
                }
                else
                {
                    existing.addedby = existing.addedby;
                }
                if (existing.datex == null)
                {
                    existing.datex = DateTime.Now.ToString();
                }
                else
                {
                    existing.datex = existing.datex;
                }
                if (password.Equals(newPassword))
                {
                    existing.password = admin_table.password;
                }
                else
                {
                    existing.password = PasswordStorage.CreateHash(admin_table.password);
                }

                ags.SaveChanges();
                TempData["updateSuccess"] = "Your Profile Updated Successfully.!";
                return(RedirectToAction("UserProfile", "MobileManager"));
            }
            return(RedirectToAction("UserProfile", "MobileManager"));
        }
        public ActionResult Create(customer_profile_table obj)
        {
            if (Session["username"] == null || Session["userlevel"].ToString() != "process_team")
            {
                return(this.RedirectToAction("Logout", "Account"));
            }
            if (ModelState.IsValid)
            {
                var usr = (from u in ags.customer_profile_table where u.customerid == obj.customerid select u).FirstOrDefault();
                var allowedExtensions = new[] {
                    ".Jpg", ".png", ".jpg", ".jpeg"
                };
                var customer = (from u in ags.customer_profile_table where u.customerid == obj.customerid select u).FirstOrDefault();


                if (customer == null)
                {
                    //bool filename = string.IsNullOrEmpty(obj.ImageFile.FileName);
                    if (obj.ImageFile != null)
                    {
                        string BigfileName = Path.GetFileNameWithoutExtension(obj.ImageFile.FileName);
                        string fileName    = BigfileName.Substring(0, 1);
                        string extension1  = Path.GetExtension(obj.ImageFile.FileName);

                        string extension = extension1.ToLower();
                        if (allowedExtensions.Contains(extension))
                        {
                            fileName       = fileName + DateTime.Now.ToString("yyssmmfff") + extension;
                            obj.profileimg = "~/customerImage/" + fileName;
                            fileName       = Path.Combine(Server.MapPath("~/customerImage/"), fileName);
                            obj.ImageFile.SaveAs(fileName);
                        }
                        else
                        {
                            TempData["Message"] = "Only 'Jpg', 'png','jpeg' images formats are alllowed..!";
                            return(RedirectToAction("Customer"));
                        }
                    }
                    if (!string.IsNullOrEmpty(obj.password))
                    {
                        obj.password = PasswordStorage.CreateHash(obj.password);
                    }
                    ags.customer_profile_table.Add(new customer_profile_table
                    {
                        customerid   = obj.customerid,
                        name         = obj.name,
                        email        = obj.email,
                        phoneno      = obj.phoneno,
                        alterphoneno = obj.alterphoneno,
                        dob          = obj.dob,
                        weddingdate  = obj.weddingdate,
                        profileimg   = obj.profileimg,
                        password     = obj.password,
                        address      = obj.address,
                        datex        = DateTime.Now.ToString(),
                        addedby      = Session["username"].ToString()
                    });
                    ags.SaveChanges();
                    return(RedirectToAction("Customer"));
                }
                else
                {
                    TempData["AE"] = "This customer user name is already exist";
                    return(RedirectToAction("Customer"));
                }
            }
            return(View(obj));
        }
Esempio n. 7
0
        public ActionResult Register()
        {
            //Already logged in -> no need to register
            if (!String.IsNullOrEmpty(Session["user"] as string) || !String.IsNullOrEmpty(Session["role"] as string))
            {
                return(RedirectToAction("Index"));
            }

            bool isPost = Request.HttpMethod == "POST";

            if (isPost)
            {
                if (Request["password"] == null || Request["password"] != Request["passwordRepeat"])
                {
                    ModelState.AddModelError("Error", "Die Passwörter stimmen nicht über ein!");
                    return(View());
                }

                string result  = PasswordStorage.CreateHash(Request["password"]);
                var    results = result.Split(':');
                string hash    = results.Last();
                string salt    = results[results.Length - 2];

                bool loggedIn = false;

                string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
                using (MySqlConnection con = new MySqlConnection(constr))
                {
                    MySqlTransaction tr = null;
                    try
                    {
                        con.Open();
                        // innerhalb der Connection con eine Transaktion beginnen
                        tr = con.BeginTransaction();
                        using (MySqlCommand cmd = new MySqlCommand()
                        {
                            Connection = con, Transaction = tr
                        })
                        {
                            cmd.CommandText =
                                "INSERT INTO Benutzer(`E-Mail`, Nutzername, Geburtsdatum, Anlegedatum, Aktiv, Vorname, Nachname, Salt, Hash) " +
                                "VALUES(@mail, @name, @date, CURDATE(), 0, @firstName, @lastName, @salt, @hash)";
                            cmd.Parameters.AddWithValue("mail", Request["mail"]);
                            cmd.Parameters.AddWithValue("name", Request["name"]);
                            cmd.Parameters.AddWithValue("date", !String.IsNullOrEmpty(Request["birthdate"]) ? Request["birthdate"] : "null");
                            cmd.Parameters.AddWithValue("firstName", Request["firstName"]);
                            cmd.Parameters.AddWithValue("lastName", Request["lastName"]);
                            cmd.Parameters.AddWithValue("salt", salt);
                            cmd.Parameters.AddWithValue("hash", hash);
                            var rows = cmd.ExecuteNonQuery();

                            cmd.Parameters.Clear();
                            cmd.Parameters.AddWithValue("id", cmd.LastInsertedId);
                            if (Request["role"] == "Mitarbeiter" || Request["role"] == "Student")
                            {
                                cmd.CommandText = "INSERT INTO `FH Angehörige`(Nummer) VALUES(@id)";
                                cmd.ExecuteNonQuery();
                            }

                            switch (Request["role"])
                            {
                            case "Gast":
                                if (!String.IsNullOrEmpty(Request["expireDate"]))
                                {
                                    cmd.CommandText =
                                        "INSERT INTO Gäste(Nummer, Ablaufdatum, Grund) VALUES(@id, @date, @reason)";
                                    cmd.Parameters.AddWithValue("date", Request["expireDate"]);
                                }
                                else
                                {
                                    cmd.CommandText = "INSERT INTO Gäste(Nummer, Grund) VALUES(@id, @reason)";
                                }
                                cmd.Parameters.AddWithValue("reason", !String.IsNullOrEmpty(Request["reason"]) ? Request["reason"] : "null");
                                break;

                            case "Mitarbeiter":
                                cmd.CommandText = "INSERT INTO Mitarbeiter(Nummer, Telefon, Büro) VALUES(@id, @phone, @office)";
                                cmd.Parameters.AddWithValue("phone", !String.IsNullOrEmpty(Request["phone"]) ? Request["phone"] : "null");
                                cmd.Parameters.AddWithValue("office", !String.IsNullOrEmpty(Request["office"]) ? Request["office"] : "null");
                                break;

                            case "Student":
                                cmd.CommandText = "INSERT INTO Studenten(Nummer, Matrikelnummer, Studiengang) VALUES(@id, @matriculationNumber, @degree)";
                                cmd.Parameters.AddWithValue("matriculationNumber", Request["matriculationNumber"]);
                                cmd.Parameters.AddWithValue("degree", Request["degree"]);
                                break;
                            }
                            rows = cmd.ExecuteNonQuery();

                            tr.Commit();
                        }

                        con.Close();

                        loggedIn = true;
                    }
                    catch (Exception e)
                    {
                        tr?.Rollback();
                        con.Close();
                        ModelState.AddModelError("Error", e.Message);
                        return(View());
                    }
                }

                if (loggedIn)
                {
                    return(RedirectToAction("Index"));
                }
            }

            return(View());
        }
        public ActionResult Create(partner_customer obj)
        {
            if (Session["username"] == null || Session["userlevel"].ToString() != "partner")
            {
                return(this.RedirectToAction("ClientLogout", "Account"));
            }
            var        getloantype = ags.loantype_table.ToList();
            SelectList loantp      = new SelectList(getloantype, "id", "loan_type");

            ViewBag.loantypeList = loantp;
            if (ModelState.IsValid)
            {
                string vendorName = Session["username"].ToString();
                // var customer = (from u in ags.customer_profile_table where u.customerid == obj.customerid select u).FirstOrDefault();
                var vendor = (from u in ags.vendor_table where u.username == vendorName select u).FirstOrDefault();


                if (vendor != null)
                {
                    customer_profile_table customerprofile = new customer_profile_table();
                    customerprofile.name    = obj.name;
                    customerprofile.email   = obj.email;
                    customerprofile.phoneno = obj.phoneno;
                    customerprofile.datex   = DateTime.Now.ToString();
                    customerprofile.addedby = Session["username"].ToString();
                    ags.customer_profile_table.Add(customerprofile);
                    ags.SaveChanges();

                    int latestcustomerid = customerprofile.id;

                    customer_profile_table existing_Customer_Profile = ags.customer_profile_table.Find(customerprofile.id);
                    existing_Customer_Profile.customerid = latestcustomerid.ToString();
                    existing_Customer_Profile.password   = PasswordStorage.CreateHash(existing_Customer_Profile.customerid);
                    ags.SaveChanges();

                    loan_table loan = new loan_table();
                    loan.customerid      = latestcustomerid.ToString();
                    loan.partnerid       = vendor.id.ToString();
                    loan.loantype        = obj.loantype;
                    loan.requestloanamt  = obj.requestloanamt;
                    loan.disbursementamt = "0";
                    loan.loanamt         = "0";
                    loan.rateofinterest  = "0";
                    loan.loanstatus      = "Pending";
                    loan.datex           = DateTime.Now.ToString();
                    loan.addedby         = Session["username"].ToString();
                    ags.loan_table.Add(loan);
                    ags.SaveChanges();


                    //////////////////////////////////////
                    var    superadminid    = (from u in ags.admin_table where u.userrole == "super_admin" select u).FirstOrDefault();
                    string superemployeeid = superadminid.id.ToString();

                    int latestloanid = loan.id;

                    loan_track_table loan_track = new loan_track_table();
                    loan_track.loanid = latestloanid.ToString();
                    if (superemployeeid != null)
                    {
                        loan_track.employeeid = superemployeeid;
                        loan_track.tracktime  = DateTime.Now.ToString();
                    }
                    if (obj.internalcomment != null)
                    {
                        loan_track.internalcomment = obj.internalcomment;
                        loan_track.externalcomment = "Not Updated";
                    }
                    loan_track.datex   = DateTime.Now.ToString();
                    loan_track.addedby = Session["username"].ToString();
                    ags.loan_track_table.Add(loan_track);
                    ags.SaveChanges();


                    ///Assigned Employee

                    loan_track_table loan_track_employee = new loan_track_table();
                    if (Session["userid"] != null)
                    {
                        loan_track_employee.loanid          = latestloanid.ToString();
                        loan_track_employee.employeeid      = superemployeeid;
                        loan_track_employee.tracktime       = DateTime.Now.ToString();
                        loan_track_employee.internalcomment = "Vendor Assigned";
                        loan_track_employee.externalcomment = "Vendor Assigned";

                        loan_track_employee.datex   = DateTime.Now.ToString();
                        loan_track_employee.addedby = Session["username"].ToString();
                        ags.loan_track_table.Add(loan_track_employee);
                        ags.SaveChanges();
                    }


                    vendor_track_table vendor_track = new vendor_track_table();
                    if (Session["userid"] != null)
                    {
                        vendor_track.loanid    = latestloanid.ToString();
                        vendor_track.vendorid  = Session["userid"].ToString();
                        vendor_track.tracktime = DateTime.Now.ToString();
                        vendor_track.comment   = "Assigned to Super Admin";
                        vendor_track.datex     = DateTime.Now.ToString();
                        vendor_track.addedby   = Session["username"].ToString();
                        ags.vendor_track_table.Add(vendor_track);
                        ags.SaveChanges();
                    }


                    //assigned table

                    assigned_table assigned = new assigned_table();
                    assigned.loanid = latestloanid.ToString();
                    if (superemployeeid != null)
                    {
                        assigned.assign_emp_id = superemployeeid;
                    }
                    if (Session["userid"] != null)
                    {
                        assigned.assign_vendor_id = Session["userid"].ToString();
                    }
                    assigned.datex   = DateTime.Now.ToString();
                    assigned.addedby = Session["username"].ToString();
                    ags.assigned_table.Add(assigned);
                    ags.SaveChanges();

                    var userVendor = Session["username"].ToString();
                    var vendorname = ags.vendor_table.Where(x => x.username == userVendor).FirstOrDefault();
                    // Loan notification to Super admin and Admin
                    ags.notification_table.Add(new notification_table
                    {
                        notification = "New Loan has Created for " + obj.name + " By You.",
                        seenstatus   = 1,
                        userid       = vendorname.username,
                        addedby      = Session["username"].ToString(),
                        datex        = DateTime.Now.ToString(),
                    });
                    ags.notification_table.Add(new notification_table
                    {
                        notification = "New Customer " + obj.name + " has Created By" + vendor.companyname + "(Vendor)",
                        seenstatus   = 1,
                        userid       = "super_admin",
                        addedby      = Session["username"].ToString(),
                        datex        = DateTime.Now.ToString(),
                    });
                    ags.SaveChanges();
                    ////////////////////////////////////

                    return(RedirectToAction("Index"));
                }
                else
                {
                    TempData["AE"] = "This customer user name is already exist";
                    return(RedirectToAction("Index"));
                }
            }
            return(View("~/Views/Partner/Create.cshtml", obj));
        }
        public ActionResult Create(customer_profile_table obj)
        {
            if (Session["username"] == null || Session["userlevel"].ToString() != "tele_marketing")
            {
                return(this.RedirectToAction("Logout", "Account"));
            }
            if (ModelState.IsValid)
            {
                var usr = (from u in ags.customer_profile_table where u.customerid == obj.customerid select u).FirstOrDefault();
                var allowedExtensions = new[] {
                    ".Jpg", ".png", ".jpg", ".jpeg"
                };
                var customer = (from u in ags.customer_profile_table where u.customerid == obj.customerid select u).FirstOrDefault();


                if (customer == null)
                {
                    if (obj.ImageFile != null)
                    {
                        string BigfileName = Path.GetFileNameWithoutExtension(obj.ImageFile.FileName);
                        string fileName    = BigfileName.Substring(0, 1);
                        string extension1  = Path.GetExtension(obj.ImageFile.FileName);

                        string extension = extension1.ToLower();
                        if (allowedExtensions.Contains(extension))
                        {
                            fileName       = fileName + DateTime.Now.ToString("yyssmmfff") + extension;
                            obj.profileimg = "~/customerImage/" + fileName;
                            fileName       = Path.Combine(Server.MapPath("~/customerImage/"), fileName);
                            obj.ImageFile.SaveAs(fileName);
                        }
                        else
                        {
                            TempData["Message"] = "Only 'Jpg', 'png','jpeg' images formats are alllowed..!";
                            return(RedirectToAction("Customer"));
                        }
                    }
                    obj.password = PasswordStorage.CreateHash(obj.password);
                    ags.customer_profile_table.Add(new customer_profile_table
                    {
                        customerid   = obj.customerid,
                        name         = obj.name,
                        email        = obj.email,
                        phoneno      = obj.phoneno,
                        alterphoneno = obj.alterphoneno,
                        dob          = obj.dob,

                        profileimg = obj.profileimg,
                        password   = obj.password,
                        address    = obj.address,
                        datex      = DateTime.Now.ToString(),
                        addedby    = Session["username"].ToString()
                    });
                    var employeename = ags.admin_table.Where(x => x.username == Session["username"].ToString()).FirstOrDefault();
                    //Notification to super Admin
                    ags.notification_table.Add(new notification_table
                    {
                        notification = "New Customer " + obj.name + " has Created By" + employeename.name,
                        seenstatus   = 1,
                        userid       = "super_admin",
                        addedby      = Session["username"].ToString(),
                        datex        = DateTime.Now.ToString(),
                    });

                    ags.SaveChanges();
                    return(RedirectToAction("Customer"));
                }
                else
                {
                    TempData["AE"] = "This customer user name is already exist";
                    return(RedirectToAction("Customer"));
                }
            }
            return(View("~/Views/TeleMarketing/TeleMarketing/Create.cshtml", obj));
        }