Exemplo n.º 1
0
        public ActionResult UpdateCart(FormCollection frc)
        {
            string[]    quantities = frc.GetValues("quantity");
            List <Cart> lsCart     = (List <Cart>)Session[strCart];

            for (int i = 0; i < lsCart.Count; i++)
            {
                lsCart[i].Quantity = Convert.ToInt32(quantities[i]);
            }
            Session[strCart] = lsCart;
            return(View("Index"));
        }
Exemplo n.º 2
0
        public JsonResult DeleteMul(FormCollection del)
        {
            var res          = false;
            var message      = "";
            var selectedList = del.GetValues("selectRow");

            if (selectedList != null && selectedList.Count() > 0)
            {
                res = mvcControllerService.Delete(selectedList.ToIntList(), null);
            }
            return(Json(new { success = res, message = message }));
        }
Exemplo n.º 3
0
        public ActionResult Update(FormCollection fc)
        {
            string[]    quantities = fc.GetValues("quantity");
            List <Item> cart       = (List <Item>)Session["cart"];

            for (int i = 0; i < cart.Count; i++)
            {
                cart[i].quantity = Convert.ToInt32(quantities[i]);
            }
            Session["cart"] = cart;
            return(View("ViewCart"));
        }
Exemplo n.º 4
0
        /// <summary>
        /// Convert FormCollection To List<Object> With Dictionary.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <returns></returns>
        public static List <T> ToListObject <T>(this FormCollection collection, Dictionary <string, string> Key, string PrimaryKeyName) where T : new()
        {
            IList <PropertyInfo> properties = typeof(T).GetProperties().ToList();
            List <T>             result     = new List <T>();
            int counter = collection.GetValues(PrimaryKeyName.Trim()).Count();

            CheckProperty(properties);
            for (int i = 0; i < counter; i++)
            {
                T item = new T();
                foreach (var property in properties)
                {
                    Type   conversionType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                    object Value          = null;
                    if (!property.CanWrite)
                    {
                        continue;
                    }
                    try
                    {
                        if (Key.ContainsKey(property.Name))
                        {
                            Value = (collection.GetValues(Key[property.Name])[i] == null) ? null : Convert.ChangeType(collection.GetValues(Key[property.Name])[i], conversionType);
                            property.SetValue(item, Value, null);
                        }
                        else
                        {
                            Value = (collection.GetValues(property.Name)[i] == null) ? null : Convert.ChangeType(collection.GetValues(property.Name)[i], conversionType);
                            property.SetValue(item, Value, null);
                        }
                    }
                    catch
                    {
                        continue;
                    }
                }
                result.Add(item);
            }
            return(result);
        }
Exemplo n.º 5
0
        public ActionResult UpdateOrder(FormCollection fc)
        {
            string[]    qty  = fc.GetValues("Qty");
            List <Item> cart = (List <Item>)Session["cart"];

            for (int i = 0; i < cart.Count; i++)
            {
                cart[i].Qty = Convert.ToInt32(qty[i]);
            }
            Session["cart"] = cart;
            //Session["count"] = Convert.ToInt32(Session["count"])+Convert.ToInt32(qty);
            return(View("OrderNow"));
        }
Exemplo n.º 6
0
        public ActionResult Editer(int id, FormCollection collection)
        {
            try
            {
                client.modStade(id, int.Parse(collection.GetValues("NbPlaces").First()), collection.GetValues("Nom").First(), collection.GetValues("Planete").First(), null, null, null, null);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 7
0
        public ActionResult Result(FormCollection form)
        {
            int k = form.AllKeys.Length, n = form.GetValues(0).Length;

            double[]   averages = new double[k];
            double[]   alts;
            double[][] measurements = new double[k][];
            double     sum = 0, avg;

            for (int i = 0; i < form.Keys.Count; i++)
            {
                measurements[i] = form.GetValues(i).Select(x => double.Parse(x)).ToArray();
                averages[i]     = measurements[i].Average();
                sum            += measurements[i].Sum();
            }
            avg  = sum / (k * n);
            alts = averages.Select(x => avg - x).ToArray();
            double ssa = 0, sse = 0;

            ssa = n * (averages.Select(x => Math.Pow((x - avg), 2)).Sum());
            for (int j = 0; j < k; j++)
            {
                for (int i = 0; i < n; i++)
                {
                    sse += Math.Pow(measurements[j][i] - averages[j], 2);
                }
            }
            double Sa2 = ssa / (k - 1);
            double Se2 = (sse / (k * (n - 1)));

            ViewBag.SSE   = sse;
            ViewBag.SSA   = ssa;
            ViewBag.Ftest = Sa2 / Se2;
            ViewBag.Sc    = Math.Pow(((2 * Se2) / (k * n)), 0.5);
            ViewBag.alts  = alts;
            ViewBag.n     = n;
            ViewBag.k     = k;
            return(View());
        }
Exemplo n.º 8
0
        public ActionResult SaveAll(FormCollection input)
        {
            var  IdArray     = input.GetValues("item.Id");
            var  NameArray   = input.GetValues("item.Name");
            var  LinkArray   = input.GetValues("item.Link");
            var  OrderArray  = input.GetValues("item.Order");
            long lanaguageId = 1;

            for (int i = 0; i < IdArray.Count(); i++)
            {
                var Id     = Convert.ToInt64(IdArray[i]);
                var entity = _context.FindDetail <WebMenu>(Id);
                entity.Name = NameArray[i];
                entity.Link = LinkArray[i];
                int  order = 0;
                bool res   = int.TryParse(OrderArray[i], out order);
                entity.Order = order;
                lanaguageId  = entity.LanguageId;
            }
            _context.SaveChange();
            return(RedirectToAction <WebMenuController>(d => d.Index(lanaguageId)));
        }
Exemplo n.º 9
0
        public ActionResult ProductAttributeListValue(int id, FormCollection collection)
        {
            List <ProductAttribute> currentData = paRep.Where(x => x.ProductID == id);
            int indexer = 0;

            foreach (ProductAttribute element in currentData)
            {
                element.Value = collection.GetValues("valueName")[indexer];
                indexer++;
                paRep.Update(element);
            }
            return(RedirectToAction("ProductDetail", new { id = id }));
        }
Exemplo n.º 10
0
        public ActionResult ProductAttributeAdd(Product item, FormCollection collection)
        {
            foreach (string element in collection.GetValues("checkbox"))
            {
                int id = Convert.ToInt32(element);
                ProductAttribute pa = new ProductAttribute();
                pa.ProductID   = item.ID;
                pa.AttributeID = id;
                paRep.Add(pa);
            }

            return(RedirectToAction("ProductAttributeList", new { id = item.ID }));
        }
Exemplo n.º 11
0
        public void CreateRequisition(Requisition requisition, FormCollection form)
        {
            CustomPrincipal user         = (CustomPrincipal)System.Web.HttpContext.Current.User;
            int             departmentId = db.DeptUsers.SingleOrDefault(d => d.DeptUserID == user.UserID).DeptEmployee.DepartmentID;
            Requisition     newReq       = new Requisition
            {
                RequisitionDate = DateTime.Today,
                Status          = Status.Pending,
                EmployeeID      = user.UserID,
            };

            //newReq.RetrievalListID = retrievalListId;

            db.Requisitions.Add(newReq);

            var ItemDescriptions = form.GetValues("ItemDescription");
            var ItemQuantitys    = form.GetValues("ItemQuantity");

            for (int i = 0; i < ItemDescriptions.Count(); i++)
            {
                var temp = ItemDescriptions[i];

                int itemID = (from item in db.Items
                              where item.Description == temp
                              select item.ItemID).FirstOrDefault();


                RequisitionDetail newReqDetail = new RequisitionDetail
                {
                    RequisitionID    = newReq.RequisitionID,
                    ItemID           = itemID,
                    Quantity         = Int32.Parse(ItemQuantitys[i]),
                    QuantityReceived = 0
                };

                db.RequisitionDetails.Add(newReqDetail);
            }
            db.SaveChanges();
        }
Exemplo n.º 12
0
        public ActionResult UpdateProduct(FormCollection frc)
        {
            string[] quantities = frc.GetValues("QtySelected");

            List <CartViewModel> lstCart = (List <CartViewModel>)Session[StrCart];

            for (int i = 0; i < lstCart.Count; i++)
            {
                lstCart[i].Quantity = Convert.ToInt32(quantities[i]);
            }
            Session[StrCart] = lstCart;
            return(View("Index"));
        }
        public ActionResult DepartmentUserAdd(UserAddOrEditViewModel model, FormCollection collection)
        {
            Guid depId = Guid.Empty;

            if (collection.GetValues("depId") != null)
            {
                depId = Guid.Parse(collection.GetValue("depId").AttemptedValue);
            }

            if (!ModelState.IsValid)
            {
                return(View("DepartmentUserAddOrEdit", model));
            }

            string[] lstRoles = null;
            if (collection.GetValues("checkboxRole") != null)
            {
                string strRoles = collection.GetValue("checkboxRole").AttemptedValue;
                lstRoles = strRoles.Split(',');
            }

            var urepo = RF.Concrete <IUserRepository>();
            var drepo = RF.Concrete <IDepartmentRepository>();
            var rrepo = RF.Concrete <IRoleRepository>();

            using (var scope = new TransactionScope())
            {
                model.Entity.Department = drepo.GetByKey(depId);

                urepo.Create(model.Entity);
                urepo.Context.Commit();

                rrepo.AddUserToRoles(model.Entity.ID, lstRoles);

                scope.Complete();
            }

            return(RedirectToAction("DepartmentUser", new { depId = depId, currentPageNum = model.CurrentPageNum, pageSize = model.PageSize }));
        }
Exemplo n.º 14
0
        public ActionResult Editer(int id, FormCollection collection)
        {
            try
            {
                client.modMatch(id, int.Parse(collection.GetValues("IdJediVainqueur").First()), collection.GetValues("Jedi1").First(), collection.GetValues("Jedi2").First(), collection.GetValues("Stade").First());

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 15
0
        public ActionResult Editer(int id, FormCollection collection)
        {
            try
            {
                client.ModTournoi(id, collection.GetValues("Nom").First(), null, null, null, null);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 16
0
        public ActionResult Ajouter(FormCollection collection)
        {
            try
            {
                client.AddTournoi(collection.GetValues("Nom").First(), null, null, null, null);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Exemplo n.º 17
0
        public ActionResult AddressAndPayment(FormCollection values)
        {
            var order = new Order();

            TryUpdateModel(order);
            string BDTAll = "";

            string[] BDTs = values.GetValues("BestDeliverTime");
            if (BDTs != null)
            {
                foreach (var BDT in BDTs)
                {
                    BDTAll = BDTAll + BDT;
                }
            }
            order.BestDeliverTime = BDTAll;
            //var BDT = "";
            //for (int k = 0; k < Request.Form.AllKeys.Length ; k++ )
            //{
            //    if (Request.Form.GetKey(k) == "BestDeliverTime")
            //    {
            //        BDT = BDT + Request.Form.GetValues(k);
            //    }
            //}
            //order.BestDeliverTime = BDT;
            try
            {
                //if (string.Equals(values["PromoCode"], PromoCode, StringComparison.OrdinalIgnoreCase) == false)
                //{
                //    return View(order);
                //}
                //else
                //{
                //order.Username = User.Identity.Name;
                order.OrderDate = DateTime.Now;
                //Save Order
                storeDB.Orders.Add(order);
                storeDB.SaveChanges();
                //Process the order
                var cart = ShoppingCart.GetCart(this.HttpContext);
                cart.CreateOrder(order);
                storeDB.SaveChanges();
                return(RedirectToAction("Complete"));
                //}
            }
            catch
            {
                //Invalid - redisplay with errors
                return(View(order));
            }
        }
Exemplo n.º 18
0
        public ActionResult Delete(FormCollection form)
        {
            HttpResponseMessage response = null;

            try
            {
                var selectedIds = form.GetValues("checked");

                if (selectedIds != null)
                {
                    foreach (var id in selectedIds)
                    {
                        if (Convert.ToString(id).ToUpper() != "FALSE")
                        {
                            Task <HttpResponseMessage> deleteTask = client.DeleteAsync("ContactsAPI/" + id);
                            deleteTask.Wait();
                            response = deleteTask.Result;
                            if (response.IsSuccessStatusCode)
                            {
                                TempData["Status"] = "Successfully deleted";
                                return(RedirectToAction("Index"));
                            }

                            if (response != null)
                            {
                                //ModelState.AddModelError(string.Empty, resp.Content.ReadAsStringAsync().Result);
                                if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
                                {
                                    return(View("NotFound"));
                                }
                                else
                                {
                                    return(View("InternalError"));
                                }
                            }

                            return(View("InternalError"));
                        }
                    }

                    return(View("InternalError"));
                }

                return(View("InternalError"));
            }

            catch
            {
                return(View("InternalError"));
            }
        }
Exemplo n.º 19
0
        public ActionResult Index(FormCollection input)
        {
            var IdArray           = input.GetValues("item.Id");
            var NameArray         = input.GetValues("item.Name");
            var ImageArray        = input.GetValues("item.Image");
            var ContentArray      = input.GetValues("item.Content");
            var PhoneArray        = input.GetValues("item.Phone");
            var EmailArray        = input.GetValues("item.Email");
            var PositonArray      = input.GetValues("item.Position");
            var DepartmentIdArray = input.GetValues("item.WebDepartmentId");
            var Order             = input.GetValues("item.Order");

            long lanaguageId     = 1;
            var  LanguageIdArray = input.GetValues("item.LanguageId");

            if (LanguageIdArray.Count() > 0)
            {
                lanaguageId = Convert.ToInt64(LanguageIdArray[0]);
            }

            for (int i = 0; i < IdArray.Count(); i++)
            {
                var Id     = Convert.ToInt64(IdArray[i]);
                var entity = _context.FindDetail <WebStaff>(Id);
                entity.Name            = NameArray[i];
                entity.Phone           = PhoneArray[i];
                entity.Email           = EmailArray[i];
                entity.Position        = PositonArray[i];
                entity.WebDepartmentId = Convert.ToInt64(DepartmentIdArray[i]);
                var content = ContentArray[i];
                entity.Image       = _context.GetImage(content, "staff");
                entity.Content     = content;
                entity.Order       = int.Parse(Order[i] == ""? "10": Order[i]);
                entity.UpdatedDate = DateTime.Now;
            }
            _context.SaveChange();
            return(RedirectToAction <WebStaffController>(d => d.Index(lanaguageId)));
        }
Exemplo n.º 20
0
        public ActionResult AsignarStock(FormCollection collection)
        {
            var cont       = collection.GetValues(0).Count();
            var articulos  = collection.GetValues(0);
            var sucursales = collection.GetValues(1);
            var cantidades = collection.GetValues(2);

            for (var i = 0; i < cont; i++)
            {
                var art  = int.Parse(articulos[i].ToString());
                var suc  = int.Parse(sucursales[i].ToString());
                var cant = decimal.Parse(cantidades[i].ToString());
                if (cant != 0)
                {
                    StockMovimiento sm = new StockMovimiento();
                    sm.ArticuloID = art;
                    sm.Cantidad   = cant;
                    sm.Fecha      = DateTime.Now;
                    sm.SucursalID = suc;
                    var usuario = (Usuario)System.Web.HttpContext.Current.Session["UsuarioActual"];
                    sm.UsuarioID = usuario.Id;
                    //Si la sucursal NO es el depsósito, le descuento stock
                    if (suc != 1)
                    {
                        _stockArticuloSucursalServicios.DescontarStockDeposito(art, cant);
                    }
                    sm.TipoMovimientoStockID = _tipoMovimientosStockServicios.GetAll().Where(a => a.Nombre.Contains("Repos")).FirstOrDefault().Id;
                    bool bandera = _stockMovimientosServicios.Agregar(sm, suc);
                }
            }

            ViewBag.Sucursales = _sucursalesServicios.GetAll();

            Session["listaStock"] = null;
            string msj = "Stock asignado correctamente!";

            return(RedirectToAction("AsignarStock", new { mensaje = msj }));
        }
Exemplo n.º 21
0
        public ActionResult CheckIn(FormCollection input)//takes class of button that was pressed, and type of button pressed
        {
            int              userID   = int.Parse(input.GetValues("UserID").FirstOrDefault().ToString());
            String           selected = input.GetValues("Selected").FirstOrDefault().ToString(); //get selected button text
            User             temp     = Service.GetCompleteUserByID(userID);                     //get user information
            List <Course>    classes  = temp.Classes;
            List <VisitType> types    = Service.ListAvailableVisitTypes(userID);

            int visitID = -1;//visit ID to attach equipment use to

            var ip = Request.UserHostAddress;

            //this.ShowMessage(MessageType.Success, "User " + User.Identity.Name + " logged in from IP." + ip, true);
            //process selection
            foreach (Course row in classes)
            {
                if (row.Title == selected)                                                                      //process course visit here with redirect to action
                {
                    visitID = Service.SubmitCourseVisit(userID, row.CRN, row.CheckOut, User.Identity.Name, ip); //submit user in if applicable

                    this.ShowMessage(MessageType.Success, temp.FirstName + " " + temp.LastName + " Checked In For: " + row.Title, true);
                    return(RedirectToAction("Welcomee", "Home"));
                }
            }
            foreach (VisitType row in types)
            {
                if (row.Title == selected)                                                                 //process visit type here with redirect to action
                {
                    visitID = Service.SubmitGeneralVisit(userID, row.VisitTypeID, User.Identity.Name, ip); //add selected value


                    this.ShowMessage(MessageType.Success, temp.FirstName + " " + temp.LastName + " Checked In For: " + row.Title, true);
                    return(RedirectToAction("Welcomee", "Home"));
                }
            }
            this.ShowMessage(MessageType.Warning, "Error checking in : " + temp.FirstName + " " + temp.LastName, true);
            return(RedirectToAction("Welcomee", "Home"));
        }
Exemplo n.º 22
0
        public ActionResult EditStoreHours(FormCollection formResults, User model)
        {
            User currentUser = ModelHelpers.GetCurrentUser(db);

            if (currentUser != null)
            {
                for (int i = 0; i < 7; i++)
                {
                    StoreHours hours = currentUser.Store.StoreHours.ElementAt(i);
                    if (formResults.GetValues("StartTime").ElementAt(i).ToString().Length != 0)
                    {
                        string startTime   = formResults.GetValues("StartTime").ElementAt(i).ToString();
                        int    startHour   = int.Parse(startTime.Split(':')[0]);
                        int    startMinute = int.Parse(startTime.Split(':')[1].Split(' ')[0]);
                        hours.StartTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, startHour, startMinute, 0);
                    }

                    if (formResults.GetValues("endTime").ElementAt(i).ToString().Length != 0)
                    {
                        string endTime   = formResults.GetValues("EndTime").ElementAt(i).ToString();
                        int    endHour   = int.Parse(endTime.Split(':')[0]);
                        int    endMinute = int.Parse(endTime.Split(':')[1].Split(' ')[0]);
                        // If the end time is earlier than the start time
                        // We set the month to next month.  It'll be easier that way.
                        hours.EndTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, endHour, endMinute, 0);
                    }
                    if (hours.EndTime.TimeOfDay < hours.StartTime.TimeOfDay)
                    {
                        hours.EndTime = hours.EndTime.AddMonths(1);
                    }
                }
                db.SaveChanges();
                TempData["storeHoursResultMessage"] = "Hours successfully updated!";
                return(RedirectToAction("Index", "Store"));
            }

            return(View("EditStoreHours"));
        }
Exemplo n.º 23
0
        public ActionResult Create(string uriName, FormCollection collection)
        {
            Screen screen = IocHelper.mongoHelper.FindScreenByUriName(uriName);
            Dictionary <string, object> values = new Dictionary <string, object>();

            foreach (string key in screen.ScreenFields.Select(x => x.Name))
            {
                values.Add(key, collection.GetValues(key)[0]);
            }

            IocHelper.mongoHelper.InsertToUnknownCollection(screen, values);

            return(RedirectToAction("Show", new { uriName = uriName }));
        }
        public ActionResult Index(int?franchiseId, FormCollection formcollection)
        {
            var endDate = !String.IsNullOrWhiteSpace(formcollection["txtEndDate"])
                              ? DateTime.Parse(formcollection["txtEndDate"])
                              : DateTime.Today.AddDays(-1 * ((int)DateTime.Today.DayOfWeek + 1));
            var startDate = !String.IsNullOrWhiteSpace(formcollection["txtStartDate"])
                                ? DateTime.Parse(formcollection["txtStartDate"])
                                : endDate.AddDays(-6);

            var vals     = formcollection.GetValues("cbAllTechs");
            var allTechs = vals != null && vals.Length > 0 ? bool.Parse(vals[0]) : false;

            return(View(GetModel(franchiseId ?? UserInfo.CurrentFranchise.FranchiseID, startDate, endDate, true, allTechs)));
        }
 public ActionResult FlightsByAcft(FormCollection form)
 {
     if (Request.IsAuthenticated)
     {
         q.pilotUserName = User.Identity.Name;
         var acftId = int.Parse(form.GetValues("acftId")[0]);
         FlightUpdate(form);
         return(RedirectToAction("FlightsByAcft", new { acftId = acftId }));
     }
     else
     {
         return(RedirectToAction("Login", "Account"));
     }
 }
Exemplo n.º 26
0
        public ActionResult UpdateCart(FormCollection form)
        {
            List <Item> cart = (List <Item>)Session["cart"];

            string[] quantities = form.GetValues("quantity");

            for (int i = 0; i < cart.Count; i++)
            {
                cart[i].Quantity = Convert.ToInt32(quantities[i]);
            }
            Session["cart"]     = cart;
            Session["cartSize"] = cart.Count();
            return(RedirectToAction("Index"));
        }
        public ActionResult DepartmentUserEdit(UserAddOrEditViewModel model, FormCollection collection)
        {
            Guid depId = Guid.Empty;

            if (collection.GetValues("depId") != null)
            {
                depId = Guid.Parse(collection.GetValue("depId").AttemptedValue);
            }

            RF.Concrete <IUserRepository>().Update(model.Entity);
            RF.Concrete <IUserRepository>().Context.Commit();

            return(RedirectToAction("DepartmentUser", new { depId = depId, currentPageNum = model.CurrentPageNum, pageSize = model.PageSize }));
        }
        public ActionResult DeleteAll(FormCollection frm)
        {
            var chkvalue = frm.GetValues("assignChkBx");

            foreach (var id in chkvalue)
            {
                faq_admin _fm  = new faq_admin();
                int       id1  = Convert.ToInt32(id);
                var       data = (from c in db.and_faq_tbl where c.pk_faq_id == id1 select c).First();
                db.and_faq_tbl.Remove(data);
                db.SaveChanges();
            }
            return(RedirectToAction("faq_all_admin", "Admin_faq"));
        }
Exemplo n.º 29
0
        /// <summary>
        /// Convert FormCollection To Single Object With Dictionary.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="collection"></param>
        /// <returns>object</returns>
        public static T ToSingleObject <T>(this FormCollection collection, Dictionary <string, string> Key) where T : new()
        {
            IList <PropertyInfo> properties = typeof(T).GetProperties().ToList();

            T result = new T();

            CheckProperty(properties);

            foreach (var property in properties)
            {
                Type   conversionType = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
                object Value          = null;
                if (!property.CanWrite)
                {
                    continue;
                }
                try
                {
                    if (Key.ContainsKey(property.Name))
                    {
                        Value = (collection.GetValues(Key[property.Name])[0] == null) ? null : Convert.ChangeType(collection.GetValues(Key[property.Name])[0], conversionType);
                        property.SetValue(result, Value, null);
                    }
                    else
                    {
                        Value = (collection.GetValues(property.Name)[0] == null) ? null : Convert.ChangeType(collection.GetValues(property.Name)[0], conversionType);
                        property.SetValue(result, Value, null);
                    }
                }
                catch
                {
                    continue;
                }
            }

            return(result);
        }
Exemplo n.º 30
0
        public RedirectResult resetPassword(FormCollection form)
        {
            User user = new User();

            string[] userInfo;
            if (form.Count < 2)
            {
                for (int i = 0; i < form.Count; i++)
                {
                    userInfo   = form.GetValues(form.AllKeys[i]);
                    user.Email = userInfo[0];
                }
            }
            var userJson = new JavaScriptSerializer().Serialize(user);

            message = webShared.CallWebService("User", "IsUserRegistered", userJson, false);
            if (message != null)
            {
                DateTime date = DateTime.Now;
                int      cod  = (date.Month + date.Day + ((date.Year / 100) + ((date.Hour + date.Minute) * 24)) + 366) - date.Millisecond + date.Second;
                if (cod <= 0)
                {
                    cod += 6000;
                }
                else if (cod > 0 && cod <= 999)
                {
                    cod += 4000;
                }
                Session["resetCod"]     = cod;
                Session["resetPWEmail"] = user.Email;
                MailMessage mail       = new MailMessage();
                SmtpClient  SmtpServer = new SmtpClient("smtp.gmail.com");
                mail.From = new MailAddress("*****@*****.**");
                mail.To.Add($"{user.Email}");
                mail.Subject = "Loja-Faria Email de confirmação";
                mail.Body    = $"Copia o codigo e confirma o teu email. Codigo: {cod}\n" +
                               "Se fechares a sessão terás que repetir este processo.\n"
                               + "Por favor não respondes a este email.";
                SmtpServer.Port        = 587;
                SmtpServer.Credentials = new System.Net.NetworkCredential("*****@*****.**", "123qwe,.-");
                SmtpServer.EnableSsl   = true;
                SmtpServer.Send(mail);
            }
            else
            {
                Session["resetCod"] = 0000;
            }
            return(Redirect(Url.Action("Login", "User", new { message = message })));
        }