Ejemplo n.º 1
0
        public ActionResult DeleteConfirmed(int id)
        {
            // remove from db
            //TeacherShared teacherShared = db.TeacherShareds.Find(id);
            TeacherShared teacherShared = tsRepository.getTeacherShared((int)id);
            // store courseId in viewbag
            int theCourseId = teacherShared.CourseId;

            //amh
            //db.TeacherShareds.Remove(teacherShared);
            //db.SaveChanges();
            tsRepository.DeleteTeacherShared((int)id);


            // remove the file also
            string filePath = Path.Combine(Server.MapPath("~/Uploads/TeachersShared/"),
                                           teacherShared.TeacherId.ToString() + "_" +
                                           teacherShared.CourseId.ToString() + "_" +
                                           teacherShared.Id.ToString() + "_" +
                                           teacherShared.FileName);

            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
            }
            catch (Exception e)
            {
                ViewBag.Error(e.Message);
            }

            return(RedirectToAction("Index", theCourseId));
        }
Ejemplo n.º 2
0
 public ActionResult Create(Product product, HttpPostedFileBase file)
 {
     try
     {
         Product prod = new ProductDAL().GetProductList().Where(p => p.ProductName != product.ProductName).FirstOrDefault();
         if (prod == null)
         {
             ViewBag.Error("Eroare la adaugarea produsului: Numele duplicat.");
             return(View(product));
         }
         if (file != null)
         {
             WebImage img = new WebImage(file.InputStream);
             if (img.Width > 450 || img.Height > 300)
             {
                 img.Resize(450, 300);
             }
             img.Save(HttpContext.Server.MapPath("~/Images/")
                      + file.FileName);
             product.ImagePath = "/Images/" + file.FileName;
         }
         new ProductDAL().AddProduct(product);
         return(RedirectToAction("AllProducts"));
     }
     catch
     {
         //ViewBag.Error("Eroare la adaugarea produsului: Completeaza toate campurile." + e.ToString() );
         return(View(product));
     }
 }
Ejemplo n.º 3
0
        public ActionResult Delete(int id)
        {
            StudentShared studentShared = repository.getStudentShared((int)id);

            int theCourseId = studentShared.CourseId;

            repository.DeleteStudentShared((int)id);


            // remove the file also
            string filePath = Path.Combine(Server.MapPath("~/Uploads/StudentsShared/"),
                                           studentShared.CourseId.ToString() + "_" +
                                           studentShared.StudentId.ToString() + "_" +
                                           studentShared.Id.ToString() + "_" +
                                           studentShared.FileName);

            try
            {
                if (System.IO.File.Exists(filePath))
                {
                    System.IO.File.Delete(filePath);
                }
            }
            catch (Exception e)
            {
                ViewBag.Error(e.Message);
            }

            return(RedirectToAction("Index", theCourseId));
        }
Ejemplo n.º 4
0
        public ActionResult Genres(Genre genre)
        {
            // walidacja nie do końca dzialala
            Entities db     = new Entities();
            var      genres = from i in db.Genres select i;

            genres = genres.OrderBy(u => u.NAME);
            if (genre.NAME == null)
            {
                ViewBag.Error = "Nie podano nazwy";
                return(View(genres.ToPagedList(1, 3)));
            }
            genre.NAME = genre.NAME.Trim();
            if (db.Genres.Any(g => g.NAME.ToUpper() == genre.NAME.ToUpper()))
            {
                ViewBag.Error = "Podany gatunek już istnieje w bazie";
                return(View(genres.ToPagedList(1, 3)));
            }
            if (ModelState.IsValid)
            {
                db.Genres.Add(genre);
                db.SaveChanges();
                ViewBag.Success = "Pomyślnie dodano gatunek " + genre.NAME + " do bazy";
                genres          = from i in db.Genres select i;
                genres          = genres.OrderBy(u => u.NAME);
                return(View(genres.ToPagedList(1, 3)));
            }
            else
            {
                ViewBag.Error("Coś poszło nie tak");
                return(View(genres.ToPagedList(1, 3)));
            }
        }
Ejemplo n.º 5
0
        public ActionResult Register(Models.User user)
        {
            if (ModelState.IsValid)
            {
                using (var db = new TodoAppDbContext())
                {
                    User userFound = db.Users.SingleOrDefault(u => u.Username == user.Username);
                    if (userFound != null)
                    {
                        ViewBag.Error("User exist");
                        return(RedirectToAction("Index", "Home"));
                    }

                    db.Users.Add(new Models.User
                    {
                        Email    = user.Email,
                        Username = user.Username,
                        Password = Crypto.HashPassword(user.Password)
                    });

                    db.SaveChanges();
                    SignIn(user);
                }
            }
            else
            {
                ModelState.AddModelError("", "Data is incorrect");
            }

            return(RedirectToAction("Index", "Home"));
        }
Ejemplo n.º 6
0
        public async Task <ActionResult> VerifyCode(VerifyCodeViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }

            // O código a seguir protege de ataques de força bruta em relação aos códigos de dois fatores.
            // Se um usuário inserir códigos incorretos para uma quantidade especificada de tempo, então a conta de usuário
            // será bloqueado por um período especificado de tempo.
            // Você pode configurar os ajustes de bloqueio da conta em IdentityConfig
            var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent : model.RememberMe, rememberBrowser : model.RememberBrowser);

            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(model.ReturnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", @"Código inválido.");
                ViewBag.Error("Código inválido.");
                return(View(model));
            }
        }
Ejemplo n.º 7
0
        public ActionResult ForgotPasswordSubmit(ABUserAuth model)
        {
            try
            {
                if (String.IsNullOrEmpty(model.Email))
                {
                    ViewBag.Error = "Please enter email.";

                    return(View("ForgotPassword", model));
                }

                if (!IsValidEmailAddress(model.Email))
                {
                    ViewBag.Error("Email format is not valid.");

                    return(View("ForgotPassword", model));
                }

                var user = User_GetByEmail(model.Email);

                if (user == null)
                {
                    ViewBag.Error = "Email you entered is not exist.";

                    return(View("ForgotPassword", model));
                }

                var template = Get_MaillingListTemplate("forgot_password_user");

                var template_helper = new EmailHelper(template.Title, template.Body);

                template_helper.Parameters.Add("Host", CurrentWebsite.Domain.First());

                template_helper.Parameters.Add("Code", encrypt.GetMD5HashData(user.Email + user.PasswordHash));

                template_helper.Parameters.Add("Email", user.Email);

                template_helper.Sender_Email = CurrentWebsite.Email_Support;

                template_helper.Sender_Name = CurrentWebsite.Name;

                template_helper.Receiver.Add(user.Email);

                SendMail(template_helper);

                ViewBag.RedirectTo = Url.Action("Index", "Home", new { });;

                ViewBag.Message = "Please check your email for instruction to get new password.";
            }
            catch (Exception ex)
            {
                ViewBag.RedirectTo = Url.Action("Index", "Home", new { });

                ViewBag.Message = string.Format("{0}: {1}.", "There was an error getting new password", ex.Message);
            }

            return(View("Message"));
        }
        // GET: Contact/Details/5
        public ActionResult Details(int id)
        {
            DetailContactForm detailContactForm = _repository.Get(SessionManager.User.Id, id)?.ToDetail();

            if (detailContactForm is null)
            {
                ViewBag.Error("Le contact n'existe pas");
                return(RedirectToAction("Index"));
            }

            return(View(detailContactForm));
        }
Ejemplo n.º 9
0
        public ActionResult Login(Users model)
        {
            var user = db.Users.FirstOrDefault(x => x.UserName == model.UserName && x.Password == model.Password);

            if (user != null)
            {
                Session["user"] = user;
                return(RedirectToAction("Index", "Tasks"));
            }
            ViewBag.Error("Kullanıcı adı veya şifre yanlış!");
            return(View());
        }
        // GET: Contact/Delete/5
        public ActionResult Delete(int id)
        {
            DetailContactForm detailContactForm = ServicesLocator.Instance.ContactService.Get(SessionManager.User.Id, id)?.ToDetail();

            if (detailContactForm is null)
            {
                ViewBag.Error("Le contact n'existe pas");
                return(RedirectToAction("Index"));
            }

            return(View(detailContactForm));
        }
Ejemplo n.º 11
0
        public ActionResult Register(string identidad, string nombre, string Apellido, DateTime FechaNacimiento, string sexo, string Telefono, string correo, string password)
        {
            string UserName = nombre + Apellido;

            IEnumerable <object> listCategoria = null;
            string MensajeError = "";

            try
            {
                listCategoria = db.UDP_Acce_tbUsuario_Insert(UserName, password);


                foreach (UDP_Acce_tbUsuario_Insert_Result Resultado in listCategoria)
                {
                    MensajeError = Resultado.MensajeError;
                }
                if (MensajeError.StartsWith("-1"))
                {
                    ViewBag.Error("Error al registrase, contacte al administrador.");
                    return(View());
                }
                else
                {
                    tbCliente objCliente = new tbCliente();
                    objCliente.clte_Identidad       = identidad;
                    objCliente.clte_Nombre          = nombre;
                    objCliente.clte_Apellido        = Apellido;
                    objCliente.clte_FechaNacimiento = FechaNacimiento;
                    objCliente.clte_Sexo            = sexo;
                    objCliente.clte_Telefono        = Telefono;
                    objCliente.clte_Correo          = correo;
                    objCliente.usu_Id           = Convert.ToInt16(MensajeError);
                    objCliente.clte_UsuarioCrea = 3;
                    objCliente.clte_FechaCrea   = DateTime.Now;

                    db.tbCliente.Add(objCliente);
                    db.SaveChanges();

                    Usuario_Rol usuarioRol = new Usuario_Rol();
                    usuarioRol.id_Rol = 2;
                    usuarioRol.usu_Id = Convert.ToInt16(MensajeError);
                    db.Usuario_Rol.Add(usuarioRol);
                    db.SaveChanges();
                }
            }
            catch (Exception Ex)
            {
                ViewBag.Error = "Se produjo un error al registrar, contacte al administrador";
                return(View());
            }
            ViewBag.Message = "Usuario registrado correctamente, inicie sesión";
            return(RedirectToAction("Index"));
        }
Ejemplo n.º 12
0
        public ActionResult Edit([Bind(Include = "Id,CourseId,StudentId,Description,FileName")] StudentShared studentShared, HttpPostedFileBase FileName)
        {
            int length = FileName.FileName.Length;
            int index  = FileName.FileName.LastIndexOf('\\') + 1;


            string path     = FileName.FileName.Substring(0, index);
            string filename = FileName.FileName.Substring(index);

            //update database
            studentShared.FileName = filename;

            repository.UpdateDbStudentShared(studentShared);


            string oldFiles = studentShared.CourseId + "_" +
                              studentShared.StudentId + "_" +
                              studentShared.Id + "_*.pdf";

            try
            {
                // remove old file
                foreach (string DeleteFileName in Directory.EnumerateFiles
                             (Server.MapPath("~/Uploads/StudentsShared/"), oldFiles))
                {
                    System.IO.File.Delete(Path.Combine(Server.MapPath("~/Uploads/StudentsShared/"), DeleteFileName));
                }

                //repository.CreateFile()
                if (FileName != null && FileName.ContentLength > 0)
                {
                    string filePath = Path.Combine(Server.MapPath("~/Uploads/StudentsShared/"),
                                                   studentShared.CourseId.ToString() + "_" +
                                                   studentShared.StudentId.ToString() + "_" +
                                                   studentShared.Id + "_" +
                                                   Path.GetFileName(FileName.FileName));

                    // store new file
                    FileName.SaveAs(filePath);

                    return(RedirectToAction("Index", studentShared.CourseId));
                }
            }
            catch (Exception e)
            {
                ViewBag.Error(e.Message);
                return(RedirectToAction("Index", studentShared.CourseId));
            }
            return(View());
        }
        public IActionResult Add(Product model)
        {
            var dataService = new ProductService();

            try
            {
                dataService.Add(model);
                return(RedirectToAction("List"));
            }
            catch (Exception ex)
            {
                ViewBag.Error(ex.Message);
                return(View(ex.Message));
            }
        }
Ejemplo n.º 14
0
        public ActionResult Establecimientos(EstablecimientosModel obj)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    using (ProduccionTuBajonSVEntities modelo = new ProduccionTuBajonSVEntities())
                    {
                        //realizamos la consulta a la tabla categorias
                        var listaidestablecimientos = (from d in modelo.establecimientos
                                                       select d.Id_establecimiento).ToList();
                        //Creamos una lista tipo input select para que se muestre
                        if (listaidestablecimientos.Count() < 1)
                        {
                            ViewBag.Correlativo = 1;
                        }
                        else
                        {
                            ViewBag.Correlativo = listaidestablecimientos.Max();
                        }
                        var tablaestablecimientos = new establecimientos();
                        tablaestablecimientos.Id_establecimiento = ViewBag.Correlativo;
                        tablaestablecimientos.Imagen             = "";
                        tablaestablecimientos.Nombre_tienda      = obj.Nombre_tienda;
                        tablaestablecimientos.Direccion          = obj.Direccion;
                        tablaestablecimientos.Telefono           = obj.Telefono;
                        tablaestablecimientos.Categoria          = obj.Categoria;
                        tablaestablecimientos.Tipo_entrega       = obj.Tipo_entrega;
                        tablaestablecimientos.Precio             = obj.Precio;
                        tablaestablecimientos.Horario            = obj.Horario;
                        tablaestablecimientos.Descripcion        = obj.Descripcion;
                        tablaestablecimientos.latitud            = obj.latitud;
                        tablaestablecimientos.longitud           = obj.longitud;

                        modelo.establecimientos.Add(tablaestablecimientos);
                        modelo.SaveChanges();
                    }
                }
                catch
                {
                    ViewBag.Error("registro no completado");
                    return(View());
                }
            }

            ViewBag.Exito = "Registro Completo";
            return(View());
        }
        public async Task <IActionResult> RetrievePassword(RetrieveViewModel model)
        {
            bool sendResult = false;

            if (ModelState.IsValid)
            {
                Student student = new Student();
                switch (model.RetrieveWay)
                {
                case RetrieveType.UserName:     //通过用户名修改密码
                    student = await this.UserManager.FindByNameAsync(model.Account);

                    if (student != null)
                    {
                        string code = await this.UserManager.GeneratePasswordResetTokenAsync(student);

                        sendResult = await SendEmail(student.Id, code, student.Email);
                    }
                    break;

                case RetrieveType.Email:      //通过邮箱修改密码
                    student = await this.UserManager.FindByEmailAsync(model.Account);

                    if (student != null)
                    {
                        string code = await this.UserManager.GeneratePasswordResetTokenAsync(student);

                        sendResult = await SendEmail(student.Id, code, student.Email);
                    }
                    break;
                }

                if (student == null)
                {
                    ViewBag.Error("用户不存在,请重新输入");
                    return(this.View("Retrieve", model));
                }
            }

            ViewBag.Message = "已发送邮件至您的邮箱,请注意查收";
            ViewBag.Failed  = "信息发送失败";
            return(this.View(sendResult));
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> Create([Bind("StudentID,FirstName,LastName,InstructorID")] StudentM student)
        {
            //TODO: Need ref. to Instructor TD from Login Instructor//

            if (ModelState.IsValid)
            {
                if (HttpContext.Session.GetInt32(SessionLoggedID) != null)
                {
                    var PassID = HttpContext.Session.GetInt32(SessionLoggedID);
                    student.InstructorID = (int)PassID;
                    _context.Add(student);
                    await _context.SaveChangesAsync();

                    return(RedirectToAction("Index"));
                }
            }
            ViewBag.Error("An Error Occured, Please Re-Log into your account");
            return(RedirectToAction("Logout", "Instructors"));
        }
Ejemplo n.º 17
0
        public ActionResult Login(FormCollection form, bool rememberMe = false)
        {
            String email    = form["Email"].ToString();
            String password = form["Password"].ToString();

            //This verifies the email the user input actually exists
            bool userExists = db.Users.Any(m => m.userEmail.Equals(email));


            if (userExists)
            {
                //If password matches it will now load up the record where that email exists in the database
                UsersModels User = db.Users.SingleOrDefault(user => user.userEmail == email);

                string matchingpw = User.password.ToString();
                int    myuserid   = User.userID;
                Session["WHATEVER"] = myuserid;

                //With the loaded two variables it now will check to see if the password written matches the password on file
                if (string.Equals(password, matchingpw))
                {
                    //This logs the user into the site
                    FormsAuthentication.SetAuthCookie(email, rememberMe);

                    return(RedirectToAction("Index", "Home"));
                }
                else
                //If password is wrong it will return an error
                {
                    ViewBag.Error = "The password is incorrect.";
                    return(ViewBag.Error());
                }
            }

            else
            //If email is wrong it will return an error
            {
                ViewBag.Error2 = "The email is incorrect.";
                return(ViewBag.Error2());
            }
        }
Ejemplo n.º 18
0
 public ActionResult Edit(int id, Propietario p)
 {
     try
     {
         // TODO: Add update logic here
         if (ModelState.IsValid)
         {
             int res = repositorioPropietario.Modificacion(p);
             return(RedirectToAction(nameof(Index)));
         }
         else
         {
             return(View());
         }
     }
     catch (Exception ex)
     {
         ViewBag.Error(ex.Message);
         return(View());
     }
 }
Ejemplo n.º 19
0
        public ActionResult Register([Bind(Include = "UserID, Email, Username, Password, FirstName, LastName, DateOfBirth, RoleID")] User user)
        {
            if (User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Index"));
            }
            if (ModelState.IsValid)
            {
                if (db.Users.SingleOrDefault(u => u.Username == user.Username) != null)
                {
                    ViewBag.Error("User exist");
                    return(View());
                }

                db.Users.Add(new Models.User
                {
                    DateOfBirth = user.DateOfBirth,
                    FirstName   = user.FirstName,
                    LastName    = user.LastName,
                    Points      = 0,
                    Email       = user.Email,
                    Username    = user.Username,
                    Password    = Crypto.HashPassword(user.Password),
                    RoleID      = db.Roles.SingleOrDefault(r => r.RoleName == "user").RoleID
                });

                db.SaveChanges();
                SignIn(user);
            }
            else
            {
                ModelState.AddModelError("", "Data is incorrect");
            }

            return(View(user));
        }
Ejemplo n.º 20
0
        public ActionResult GuardarEditar(string idProspecto, string notas, string cierre_previsto, string nombreEstado, int Estado, string UsuarioAsig, int probabilidad, string nombreOp, string clientePot, string clienteFi, int id_prioridad, string Ingreso, string tipoMoneda, string fechaActual, int tipContacto)
        {
            try
            {
                Entidades db = new Entidades(CD.ConexDinamicaEntidades(Session["datasour"].ToString(), Session["catalog_user"].ToString(), Session["user"].ToString(), Session["password"].ToString()));
                Ingreso = Ingreso.Replace(",", ".");
                decimal   nvo_ingreso = Convert.ToDecimal(Ingreso);
                PROSPECTO pROSPECTO   = db.PROSPECTO.Find(idProspecto);

                pROSPECTO.nombre          = nombreOp;
                pROSPECTO.porcentajeGanar = probabilidad;
                pROSPECTO.codigo_tipoMon  = tipoMoneda;
                pROSPECTO.ingreso         = nvo_ingreso;
                pROSPECTO.tipoCliente     = tipContacto;
                pROSPECTO.notas           = notas;
                pROSPECTO.cierre_previsto = cierre_previsto;
                if (UsuarioAsig != "" && UsuarioAsig != null)
                {
                    pROSPECTO.id_usuario = UsuarioAsig;
                }


                if (tipContacto == 1)
                {
                    pROSPECTO.idCliente = Convert.ToString(clienteFi);
                }
                else
                {
                    pROSPECTO.idCliente = Convert.ToString(clientePot);
                }

                pROSPECTO.id_estadoOporunidad = Estado;

                if (id_prioridad == 0)
                {
                    pROSPECTO.id_prioridad = 0;
                }
                else
                {
                    pROSPECTO.id_prioridad = id_prioridad;
                }


                // Crear el Historico de la Oportunidad
                HISTORICO Historico = new HISTORICO();

                Historico.id_oportunidad = pROSPECTO.id_oportunidad;
                Historico.fecha          = @DateTime.Now;
                Historico.titulo         = "Editó la oportunidad";
                Historico.id_usuario     = Session["alias"].ToString();


                ViewBag.CodEmpresa = "";



                if (ModelState.IsValid)
                {
                    db.HISTORICO.Add(Historico);
                    db.Entry(pROSPECTO).State = EntityState.Modified;
                    db.SaveChanges();
                    return(RedirectToAction("Editar", "PROSPECTO", new { id = pROSPECTO.id_oportunidad, tipoCli = pROSPECTO.tipoCliente, cliente = pROSPECTO.idCliente }));
                }
            }
            catch
            {
                ViewBag.Error("Ocurrio un error al editar la oportunidad");
            }
            ViewBag.Error("");
            if (tipContacto == 1)
            {
                return(RedirectToAction("Editar", "PROSPECTO", new { id = idProspecto, tipoCli = tipContacto, cliente = clienteFi }));
            }
            else
            {
                return(RedirectToAction("Editar", "PROSPECTO", new { id = idProspecto, tipoCli = tipContacto, cliente = clientePot }));
            }
        }
Ejemplo n.º 21
0
        public ActionResult Edit([Bind(Include = "Id,CourseId,TeacherId,Description,FileName")] TeacherShared teacherShared, HttpPostedFileBase FileName)
        {
            int length = FileName.FileName.Length;
            int index  = FileName.FileName.LastIndexOf('\\') + 1;


            string path     = FileName.FileName.Substring(0, index);
            string filename = FileName.FileName.Substring(index);

            //update database
            teacherShared.FileName = filename;
            //amh
            //db.Entry(teacherShared).State = System.Data.Entity.EntityState.Modified;
            //db.SaveChanges();
            tsRepository.UpdateTeacherShared(teacherShared);

            string oldFiles = teacherShared.TeacherId + "_" +
                              teacherShared.CourseId + "_" +
                              teacherShared.Id + "_*.pdf";

            try
            {
                // remove old file
                foreach (string DeleteFileName in Directory.EnumerateFiles
                             (Server.MapPath("~/Uploads/TeachersShared/"), oldFiles))
                {
                    System.IO.File.Delete(Path.Combine(Server.MapPath("~/Uploads/TeachersShared/"), DeleteFileName));
                }

                //repository.CreateFile()
                if (FileName != null && FileName.ContentLength > 0)
                {
                    string filePath = Path.Combine(Server.MapPath("~/Uploads/TeachersShared/"),
                                                   teacherShared.TeacherId.ToString() + "_" +
                                                   teacherShared.CourseId.ToString() + "_" +
                                                   teacherShared.Id + "_" +
                                                   Path.GetFileName(FileName.FileName));

                    // store new file
                    FileName.SaveAs(filePath);

                    return(RedirectToAction("Index", teacherShared.CourseId));
                }
            }
            catch (Exception e)
            {
                ViewBag.Error(e.Message);
                return(RedirectToAction("Index", teacherShared.CourseId));
            }

            // amh
            //ViewBag.CourseId = new SelectList(db.Courses, "Id", "Name", teacherShared.CourseId);
            var courses = repository.GetAllCourses();

            ViewBag.CourseId = new SelectList(courses, "Id", "Name", teacherShared.CourseId);

            //amh
            //return RedirectToAction("Index", teacherShared.CourseId);
            var teachers = repository.GetAllTeachers();

            ViewBag.TeacherId = new SelectList(teachers, "Id", "SSN", teacherShared.TeacherId);
            return(RedirectToAction("Index", teacherShared.CourseId));
        }
 public ActionResult WithdrawAmount(string AccountNumber, string AccountPinNumber, decimal FundsToWithdraw, bool USD, bool EUR, bool JPY, bool CNY, bool RUB, bool HKD)
 {
     if (db.Accounts.Where(a => a.AccountNumber == AccountNumber).Any()) //Checks to see if account number exists in the database
     {
         //Select record that has matching account number and pinnumber and check if funds are available
         var query = from a in db.Accounts where a.AccountNumber.Contains(AccountNumber) && a.AccountPinNumber.Contains(AccountPinNumber) && (a.AccountBalance >= FundsToWithdraw) select a;
         if (query == null) //There is no account number with that matching pin number and or the funds are not available, display error
         {
             ViewBag.Error("The pin number didn't match or there were not enough available funds. Please check your details and try again.");
         }
         else //The account number matches that pin number
         {
             if (ModelState.IsValid)
             {
                 Account  account_i = new Account();
                 Currency currency  = new Currency();
                 if (USD != false)
                 {
                     currencyAmount = (decimal)1.37;//If USD FundsToWithdraw * 1.3700
                 }
                 if (EUR != false)
                 {
                     currencyAmount = (decimal)1.13;//If EUR FundsToWithdraw * 1.1300
                 }
                 if (JPY != false)
                 {
                     currencyAmount = (decimal)152.45;//If JPY FundsToWithdraw * 152.4600
                 }
                 if (CNY != false)
                 {
                     currencyAmount = (decimal)1.37;//If CNY FundsToWithdraw * 1.3700
                 }
                 if (RUB != false)
                 {
                     currencyAmount = (decimal)1.37;//If RUB FundsToWithdraw * 1.3700
                 }
                 if (HKD != false)
                 {
                     currencyAmount = (decimal)1.37;//Else If HKD FundsToWithdraw * 1.3700
                 }
                 var query2 = from a in db.Accounts where a.AccountNumber.Contains(AccountNumber) && a.AccountPinNumber.Contains(AccountPinNumber) && (a.AccountBalance >= FundsToWithdraw) select a;
                 if (query2 != null)
                 {
                     account_i.AccountBalance = (account_i.AccountBalance - FundsToWithdraw);
                     FundsToWithdraw          = (FundsToWithdraw * currencyAmount);//If USD FundsToWithdraw * 1.3700 etc
                     Transaction transaction = new Transaction();
                     transaction.TransactionAmount  = FundsToWithdraw;
                     transaction.TransactionGetUser = HttpContext.User.Identity.Name;
                     transaction.TransactionType    = "Withdraw";
                     transaction.TransactionTime    = DateTime.Now;
                     db.SaveChanges();
                     return(RedirectToAction("SuccessView"));
                 }
                 else
                 {
                     ViewBag.Error("Not enough funds");
                 }
             }
         }
     }
     else
     {
         ViewBag.Error("AccountNumber does not exist");
     }
     return(View(db));
 }
Ejemplo n.º 23
-1
        public ActionResult EditDetail(int OrderID, int id, OrderDetail od)
        {
            try
            {
                od = data.OrderDetails.Single(n => n.BookID == id && n.OrderID == OrderID);
                var number = od.Number;
                var o      = data.Orders.Single(C => C.ID == od.OrderID);
                if (od == null)
                {
                    return(RedirectToAction("Er404", "loi/"));
                }
                else
                {
                    if (ModelState.IsValid)
                    {
                        if (od.Number <= 0)
                        {
                            ViewBag.Error("Số lượng không được bé hơn hoặc bằng không");
                            return(View());
                        }
                        if (o.ModifiedBy != null)
                        {
                            o.ModifiedBy = Session["UserName"].ToString();
                        }
                        if (o.ModifiedDate == null || o.ModifiedDate != null)
                        {
                            o.ModifiedDate = DateTime.Now;
                        }
                    }
                    UpdateModel(od);
                    data.SaveChanges();

                    //gửi mail vào sau khi thay đổi thành công dữ liệu
                    string content = System.IO.File.ReadAllText(Server.MapPath("~/Areas/Admin/Content/template/update_od.html"));

                    content = content.Replace("{{UserName}}", o.User.Name);
                    content = content.Replace("{{OrderID}}", od.OrderID.ToString());
                    content = content.Replace("{{Book}}", od.Book.Name);
                    if (od.Number > number || od.Number <= number)
                    {
                        content = content.Replace("{{change}}", "số lượng thành" + od.Number.ToString() + " thành công");
                    }
                    var toEmail = ConfigurationManager.AppSettings["ToEmailAddress"].ToString();

                    new MailHelper().SendMail(o.User.Email, "Thay đổi đơn hàng thành công", content);
                    new MailHelper().SendMail(toEmail, "Thay đổi đơn hàng thành công", content);
                    //gửi mail vào sau khi thay đổi thành công dữ liệu end
                }
                return(RedirectToAction("Edit", new { id = OrderID }));
            }
            catch
            {
                return(RedirectToAction("Er404", "loi/"));
            }
        }