示例#1
0
        public async Task <ActionResult> SetState(int?id)
        {
            var OfferPage = await db.OfferPages.FindAsync(id);

            if (OfferPage != null)
            {
                var OfferPageActive = await GetActiveOfferPage(OfferPage.OfferTypeId);

                if (OfferPageActive != null)
                {
                    if (!OfferPage.OfferPageActive)
                    {
                        OfferPage.OfferPageActive       = true;
                        OfferPageActive.OfferPageActive = false;
                        db.Entry(OfferPage).State       = EntityState.Modified;
                        db.Entry(OfferPageActive).State = EntityState.Modified;
                        await db.SaveChangesAsync();

                        var OfferPages = db.OfferPages.Include(x => x.OfferType);
                        return(View("Index", await OfferPages.ToListAsync()));
                    }
                }
            }
            return(RedirectToAction("NotFound", "Error"));
        }
示例#2
0
        public async Task <ActionResult> ConfirmAddOrEdit(MailConfiguration model)
        {
            if (ModelState.IsValid == false)
            {
                return(View("AddOrEdit", model));
            }

            MailConfiguration target = null;

            if (model.Id > 0)
            {
                target = await context.MailConfigurations.FindAsync(model.Id);
            }
            else
            {
                target = new MailConfiguration();
                target.CreationDate = DateTime.Now;
            }

            if (target == null)
            {
                return(RedirectToAction("NotFound", "Error"));
            }

            target.Server    = model.Server;
            target.Port      = model.Port;
            target.EnableSSL = model.EnableSSL;
            target.UserName  = model.UserName;
            target.Password  = model.Password;

            context.MailConfigurations.AddOrUpdate(target);
            await context.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public async Task <ActionResult> SetState(int?id)
        {
            var BillingPage = await db.BillingPages.FindAsync(id);

            if (BillingPage != null)
            {
                var BillingPageActive = await GetActiveBillingPage();

                if (BillingPageActive != null)
                {
                    if (!BillingPage.BillingPageActive)
                    {
                        BillingPage.BillingPageActive       = true;
                        BillingPageActive.BillingPageActive = false;
                        db.Entry(BillingPage).State         = EntityState.Modified;
                        db.Entry(BillingPageActive).State   = EntityState.Modified;
                        await db.SaveChangesAsync();

                        var BillingPages = db.BillingPages.Include(h => h.BenefitSection).Include(h => h.IncrementBenefitSection).Include(h => h.LabSection);
                        return(View("Index", await BillingPages.ToListAsync()));
                    }
                }
            }
            return(RedirectToAction("NotFound", "Error"));
        }
示例#4
0
        public async Task <ActionResult> ActiveConfirmed(int id)
        {
            var BlogPage = await db.BlogPages.FindAsync(id);

            if (BlogPage != null)
            {
                var BlogPageActive = await GetActiveBlogPage(BlogPage.BlogTypeId);

                if (BlogPageActive != null)
                {
                    if (BlogPage.BlogPageActive == "EnEdicion" || BlogPage.BlogPageActive == "Desactivada")
                    {
                        BlogPage.BlogPageActive = "Activada";
                        foreach (var newsPage in BlogPage.News)
                        {
                            newsPage.NewsPageActive = "Activada";
                        }

                        BlogPageActive.BlogPageActive = "Desactivada";
                        foreach (var newsPage in BlogPageActive.News)
                        {
                            newsPage.NewsPageActive = "Desactivada";
                        }

                        db.Entry(BlogPage).State       = EntityState.Modified;
                        db.Entry(BlogPageActive).State = EntityState.Modified;
                        await db.SaveChangesAsync();

                        return(RedirectToAction("Index"));
                    }
                }
            }
            return(RedirectToAction("NotFound", "Error"));
        }
示例#5
0
        public async Task <ActionResult> SetState(int?id)
        {
            var HomePage = await db.HomePages.FindAsync(id);

            if (HomePage != null)
            {
                var HomePageActive = await GetActiveHomePage();

                if (HomePageActive != null)
                {
                    if (!HomePage.HomePageActive)
                    {
                        HomePage.HomePageActive        = true;
                        HomePageActive.HomePageActive  = false;
                        db.Entry(HomePage).State       = EntityState.Modified;
                        db.Entry(HomePageActive).State = EntityState.Modified;
                        await db.SaveChangesAsync();

                        var HomePages = db.HomePages.Include(h => h.BlogSection).Include(h => h.CardSection).Include(h => h.FoseSection).Include(h => h.OfferSection);
                        return(View("Index", await HomePages.ToListAsync()));
                    }
                }
            }
            return(RedirectToAction("NotFound", "Error"));
        }
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            MyApplicationUser user = await db.Users.FirstAsync(x => x.Id == id);

            db.Users.Remove(user);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public async Task <ActionResult> Create([Bind(Include = "DocumentTypeId,DocumentName,DocumentDescription,DocumentActive")] DocumentType documentType)
        {
            if (ModelState.IsValid)
            {
                db.DocumentTypes.Add(documentType);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(documentType));
        }
        public async Task <ActionResult> Create([Bind(Include = "ReportTypeId,ReportName,ReportDescription,ReportActive")] ReportType reportType)
        {
            if (ModelState.IsValid)
            {
                db.ReportTypes.Add(reportType);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(reportType));
        }
        public async Task <ActionResult> Create([Bind(Include = "SaDTypeNumberId,SaDTypeNumberCity,SaDTypeNumberPhone,SaDTypeNumberActive")] SaDTypeNumber saDTypeNumber)
        {
            if (ModelState.IsValid)
            {
                db.SaDTypeNumbers.Add(saDTypeNumber);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(saDTypeNumber));
        }
示例#10
0
        public async Task <ActionResult> Create([Bind(Include = "ServiceTypeId,ServiceTypeName,ServiceTypeNameDescription,ServiceTypeProdutcsDescription,ServiceTypeActive")] ServiceType serviceType)
        {
            if (ModelState.IsValid)
            {
                db.ServiceTypes.Add(serviceType);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }

            return(View(serviceType));
        }
        public async Task <ActionResult> ConfirmAddOrEdit(InterestRegion model)
        {
            if (ModelState.IsValid == false)
            {
                return(View("AddOrEdit", model));
            }
            if (model.Id > 0)
            {
                var offe = await db.InterestRegions.FirstOrDefaultAsync(x => x.Name == model.Name && x.Id != model.Id);

                if (offe == null)
                {
                    var interestRegion = await db.InterestRegions.FindAsync(model.Id);

                    if (interestRegion != null)
                    {
                        interestRegion.Name            = model.Name;
                        interestRegion.Active          = model.Active;
                        interestRegion.MailCollection  = model.MailCollection;
                        db.Entry(interestRegion).State = EntityState.Modified;
                        await db.SaveChangesAsync();
                    }
                }
            }
            else
            {
                var region = await db.InterestRegions.FirstOrDefaultAsync(a => a.Name == model.Name);

                if (region == null)
                {
                    region = new InterestRegion()
                    {
                        CreationDate   = DateTime.Now,
                        Name           = model.Name,
                        Active         = model.Active,
                        MailCollection = model.MailCollection
                    };
                    db.InterestRegions.Add(region);
                    await db.SaveChangesAsync();
                }
                else
                {
                    ModelState.AddModelError("", "Ya existe una región con el nombre " + model.Name);
                    return(View("AddOrEdit", model));
                }
            }
            return(RedirectToAction("Index"));
        }
        public async Task <AdministrationServiceResult> create(BranchInputModel inputData)
        {
            AdministrationServiceResult result = new AdministrationServiceResult();

            var state = context.Estados.Where(st => st.Id == inputData.State).FirstOrDefault();

            if (state != null)
            {
                var city = context.Municipios.Where(c => c.Id == inputData.City).FirstOrDefault();
                if (city != null)
                {
                    if (inputData.BranchName.Trim().Length != 0)
                    {
                        if (inputData.BranchAddress.Trim().Length != 0)
                        {
                            Branch branch = getTargetBranch(inputData);

                            if (branch != null)
                            {
                                branch.State = state;
                                branch.City  = city;
                                if (inputData.BranchId == 0)
                                {
                                    context.Branchs.Add(branch);
                                }
                                else
                                {
                                    context.Entry(branch).State = System.Data.Entity.EntityState.Modified;
                                }
                            }
                            else
                            {
                                result.Errors.Add("Sucursal no válida");
                            }
                            await context.SaveChangesAsync();
                        }
                        else
                        {
                            result.Errors.Add("Dirección de sucursal no válida");
                        }
                    }
                    else
                    {
                        result.Errors.Add("Nombre de sucursal no válido");
                    }
                }
                else
                {
                    result.Errors.Add("Ciudad no válida");
                }
            }
            else
            {
                result.Errors.Add("Estado no válido");
            }

            return(result);
        }
        public async Task <ActionResult> DeleteConfirmed(int id)
        {
            Branch branch = await db.Branchs.FindAsync(id);

            db.Branchs.Remove(branch);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
        public async Task <ActionResult> Create(int?id)
        {
            var  name        = "";
            bool active      = false;
            var  httpRequest = System.Web.HttpContext.Current.Request;

            foreach (var form in httpRequest.Form.AllKeys)
            {
                var formValue = httpRequest.Form[form];
                formValue = string.IsNullOrEmpty(formValue) ? null : formValue;
                switch (form)
                {
                case "NombreTipoBlog":
                    name = formValue;
                    break;

                case "EstadoTipoBlog":
                    active = formValue == "true";
                    break;
                }
            }
            var offe = await db.BlogTypes.FirstOrDefaultAsync(x => x.BlogTypeName == name);

            if (offe == null)
            {
                var newId = db.BlogTypes.Add(new BlogType {
                    BlogTypeActive = active, BlogTypeName = name
                });
                await db.SaveChangesAsync();

                return(Json(new AjaxResponse {
                    Success = true, Message = "La categoría se insertó correctamente", Data = newId.BlogTypeId
                }, JsonRequestBehavior.AllowGet));
            }

            return(Json(new AjaxResponse {
                Success = false, Message = "Ya existe una Categoría con ese nombre"
            }, JsonRequestBehavior.AllowGet));
        }
示例#15
0
        public async Task <IActionResult> OnPostAsync()
        {
            if (!ModelState.IsValid)
            {
                return(Page());
            }

            await _dbContext.Courses.AddAsync(Course);

            await _dbContext.SaveChangesAsync();

            Message = AlertMessages.OnCreateMessage;
            return(RedirectToPage("Index"));
        }
示例#16
0
        public async Task <IActionResult> OnPostDeleteAsync(int id)
        {
            var courseToDelete = await _dbContext.Courses.FindAsync(id);

            if (courseToDelete == null)
            {
                return(NotFound(AlertMessages.ThereIsNoCourseWithId(id)));
            }

            _dbContext.Courses.Remove(courseToDelete);
            await _dbContext.SaveChangesAsync();

            Message = AlertMessages.OnDeleteMessage;
            return(RedirectToPage());
        }
示例#17
0
        public async Task <ActionResult> SetState(int?id)
        {
            var SaDPage = await db.SaDPages.FindAsync(id);

            if (SaDPage != null)
            {
                var SaDPageActive = await GetActiveSaDPage();

                if (SaDPageActive != null)
                {
                    if (!SaDPage.SaDPageActive)
                    {
                        SaDPage.SaDPageActive         = true;
                        SaDPageActive.SaDPageActive   = false;
                        db.Entry(SaDPage).State       = EntityState.Modified;
                        db.Entry(SaDPageActive).State = EntityState.Modified;
                        await db.SaveChangesAsync();

                        return(View("Index", await db.SaDPages.ToListAsync()));
                    }
                }
            }
            return(RedirectToAction("NotFound", "Error"));
        }
示例#18
0
        // PUT: odata/Categories(5)
        public async Task <IHttpActionResult> Put([FromODataUri] int key, Delta <Categories> patch)
        {
            Validate(patch.GetEntity());

            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Categories categories = await db.Categories.FindAsync(key);

            if (categories == null)
            {
                return(NotFound());
            }

            patch.Put(categories);

            try
            {
                await db.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!CategoriesExists(key))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }

            return(Updated(categories));
        }
示例#19
0
        public async Task <ActionResult> ActiveConfirmed(int id)
        {
            FosePage FosePage = await db.FosePages.FindAsync(id);

            if (FosePage != null)
            {
                var FosePageActive = await GetActiveFosePage();

                if (FosePageActive != null)
                {
                    if (FosePage.FosePageActive == "EnEdicion" || FosePage.FosePageActive == "Desactivada")
                    {
                        FosePage.FosePageActive = "Activada";
                        foreach (var promocionPage in FosePage.Promocions)
                        {
                            promocionPage.PromocionPageActive = "Activada";
                            foreach (var productPage in promocionPage.ProductPages)
                            {
                                productPage.ProductPageActive = "Activada";
                            }
                        }

                        FosePageActive.FosePageActive = "Desactivada";
                        foreach (var promocionPage in FosePageActive.Promocions)
                        {
                            promocionPage.PromocionPageActive = "Desactivada";
                            foreach (var productPage in promocionPage.ProductPages)
                            {
                                productPage.ProductPageActive = "Desactivada";
                            }
                        }

                        db.Entry(FosePage).State       = EntityState.Modified;
                        db.Entry(FosePageActive).State = EntityState.Modified;
                        await db.SaveChangesAsync();

                        return(RedirectToAction("Index"));
                    }
                }
            }
            return(RedirectToAction("NotFound", "Error"));
        }
示例#20
0
        public async Task <IActionResult> OnPostAsync(int id)
        {
            if (ModelState.IsValid)
            {
                var course = await _dbContext.Courses.FindAsync(id);

                course.Name        = Course.Name;
                course.Description = Course.Description;
                course.Author      = Course.Author;

                await _dbContext.SaveChangesAsync();

                Message = AlertMessages.OnUpdateMessage;
                return(RedirectToPage("Index"));
            }

            return(RedirectToPage());
        }
示例#21
0
        public async Task <AdministrationServiceResult> create(PillarInputModel inputData)
        {
            AdministrationServiceResult result = new AdministrationServiceResult();

            if (inputData.PillarName.Trim().Length != 0)
            {
                if (inputData.PillarDescription.Trim().Length != 0)
                {
                    Pillar pillar = getTargetPillar(inputData);

                    if (pillar != null)
                    {
                        if (inputData.PillarId == 0)
                        {
                            context.Pillars.Add(pillar);
                        }
                        else
                        {
                            context.Entry(pillar).State = System.Data.Entity.EntityState.Modified;
                        }
                    }
                    else
                    {
                        result.Errors.Add("Pilar no válido");
                    }
                    await context.SaveChangesAsync();
                }
                else
                {
                    result.Errors.Add("Descripción de pilar no válida");
                }
            }
            else
            {
                result.Errors.Add("Nombre de pilar no válido");
            }

            return(result);
        }
示例#22
0
        public async Task <ActionResult> SendSug(ContactViewModel model)
        {
            var response = new AjaxResponse {
                Success = false
            };
            var errorMessages = new List <string>();

            try
            {
                if (ModelState.IsValid)
                {
                    var user = new ContactUser
                    {
                        Names        = model.ContactNames,
                        Email        = model.ContactEmail,
                        PhoneNumber  = model.ContactPhoneNumber,
                        Suggests     = model.ContactSuggests,
                        DateCreation = DateTime.Now
                    };
                    var result = storeDB.ContactUsers.Add(user);
                    await storeDB.SaveChangesAsync();

                    response.Success = true;
                    response.Message = "Los datos fueron enviados correctamente";
                    return(Json(response, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    response.Message = "Lo sentimos, no se pudo realizar la operación. Ha ocurrido un error en el servidor.";
                    return(Json(response, JsonRequestBehavior.AllowGet));
                }
            }
            catch (Exception)
            {
                response.Message = "Lo sentimos, no se pudo realizar la operación. Ha ocurrido un error en el servidor.";
                return(Json(response, JsonRequestBehavior.AllowGet));
            }
        }
示例#23
0
        internal static async Task <KeyValuePair <bool, string> > PrepareDataPage(string page, string dir, string pageName, IPagePreview preview, FileType?fileType, FillDataTextPage fillDataTextPage, FillDataImagePage fillDataImagePage)
        {
            try
            {
                var httpRequest = HttpContext.Current.Request;
                foreach (string file in httpRequest.Files)
                {
                    if (!file.Contains("client_imageEncabezado"))
                    {
                        var postedFile = httpRequest.Files[file];
                        var valid      = IsValidImage(postedFile, fileType);

                        if (valid.Value == "Ok")
                        {
                            if (postedFile != null)
                            {
                                var fil          = $"{Path.GetFileNameWithoutExtension(postedFile.FileName)}_{DateTime.Now.Ticks}{postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'))}";
                                var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath(dir), fil);
                                //var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath(dir), postedFile.FileName);
                                if (!postedFile.FileName.StartsWith("/"))
                                {
                                    postedFile.SaveAs(fileSavePath);
                                    //var ext = postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'));
                                    //if (ext == ".pdf")
                                    //{
                                    //    var fileName = SaveToPdf.Save(HttpContext.Current.Server.MapPath(dir), fil);
                                    //    fileName = Path.GetFileName(fileName);
                                    //    if (fileName != null)
                                    //    {
                                    //        fillDataImagePage($"{dir}/{fileName}", file, preview);
                                    //    }
                                    //}
                                    //else
                                    //{
                                    fillDataImagePage($"{dir}/{fil}", file, preview);
                                    //}
                                }
                            }
                        }
                        else
                        {
                            return(valid);
                        }
                    }
                }

                foreach (var form in httpRequest.Form.AllKeys)
                {
                    var inicio_texto_c   = "client_TextEncabezado";
                    var inicio_color_c   = "client_ColorTextEncabezado";
                    var inicio_texto_s   = "server_TextEncabezado";
                    var inicio_color_s   = "server_ColorTextEncabezado";
                    var serverHeaderLink = "server_HeaderLink";
                    var clientHeaderLink = "client_HeaderLink";
                    if (!form.Contains(inicio_texto_c) && !form.Contains(inicio_color_c) && !form.Contains(inicio_texto_s) && !form.Contains(inicio_color_s) &&
                        !form.Contains("idsCliente") && !form.Contains("idsServidor") && !form.Contains(serverHeaderLink) &&
                        !form.Contains(clientHeaderLink))
                    {
                        fillDataTextPage(httpRequest, form, preview);
                    }
                }

                KeyValuePair <bool, string> validFilesHead;
                var heads = FillDataImage("", httpRequest, dir, fileType, page, out validFilesHead);

                if (validFilesHead.Value == "Ok" && heads != null)
                {
                    preview.Encabezado = heads;
                }

                if (page == "BillingPage")
                {
                    KeyValuePair <bool, string> validFilesHead1;
                    var heads1 = FillDataImage("Lab", httpRequest, dir, fileType, "LabSection", out validFilesHead1);

                    if (validFilesHead1.Value == "Ok" && heads1 != null)
                    {
                        var preview1 = preview as BillingPagePreview;
                        if (preview1 != null)
                        {
                            preview1.ImagesLab = heads1;
                        }
                    }
                }


                //if (page == "FosePage")
                //{
                //    KeyValuePair<bool, string> validFilesHead1;
                //    var heads1 = FillDataImage("Fose", httpRequest, dir, fileType, "FosePromocion", out validFilesHead1);

                //    if (validFilesHead1.Value == "Ok" && heads1 != null)
                //    {
                //        var preview1 = preview as FosePagePreview;
                //        if (preview1 != null) preview1.Promocions = heads1;
                //    }
                //}

                //if (page == "BlogPage")
                //{
                //    KeyValuePair<bool, string> validFilesHead1;
                //    var heads1 = FillDataImage("Blog", httpRequest, dir, fileType, "BlogNews", out validFilesHead1);

                //    if (validFilesHead1.Value == "Ok" && heads1 != null)
                //    {
                //        var preview1 = preview as BlogPagePreview;
                //        if (preview1 != null) preview1.NewsPagesBlogs = heads1;
                //    }
                //}

                IFormatter   formatter = new BinaryFormatter();
                MemoryStream stream    = new MemoryStream();
                formatter.Serialize(stream, preview);
                stream.Close();

                var pagePreview = await storeDB.PagePreviews.FindAsync(pageName);

                if (pagePreview != null)
                {
                    storeDB.PagePreviews.Remove(pagePreview);
                    await storeDB.SaveChangesAsync();
                }

                storeDB.PagePreviews.Add(new PagePreview {
                    PageName = pageName, PageValue = stream.GetBuffer()
                });
                await storeDB.SaveChangesAsync();

                return(new KeyValuePair <bool, string>(true, "Los datos fueron enviados correctamente al servidor."));
            }
            catch (Exception)
            {
                return(new KeyValuePair <bool, string>(false, "Ocurrió un error al enviar los datos al servidor"));
            }
        }
        private async Task <JsonResult> PrepareDataFiles(FileType all)
        {
            var    httpRequest = System.Web.HttpContext.Current.Request;
            string pillarLink = "", pillarName = "", pillarImage = "", pillarDescription = "";
            bool   pillarActive = false;
            bool   seSubio      = false;
            int    pillarId     = 0;

            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var valid      = Utils.IsValidImage(postedFile, all);

                if (valid.Value == "Ok")
                {
                    if (postedFile != null)
                    {
                        var fil          = $"{Path.GetFileNameWithoutExtension(postedFile.FileName)}_{DateTime.Now.Ticks}{postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'))}";
                        var fileSavePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/UploadedFiles"), fil);
                        if (!postedFile.FileName.StartsWith("/"))
                        {
                            postedFile.SaveAs(fileSavePath);
                            seSubio = true;
                            switch (file)
                            {
                            case "PillarImage":
                                pillarImage = $"{"~/UploadedFiles"}/{fil}";
                                break;
                            }
                        }
                    }
                }
                else
                {
                    return(Json(new AjaxResponse {
                        Success = false, Message = valid.Value
                    }, JsonRequestBehavior.AllowGet));
                }
            }

            foreach (var form in httpRequest.Form.AllKeys)
            {
                var formValue = httpRequest.Form[form];
                formValue = string.IsNullOrEmpty(formValue) ? null : formValue;
                switch (form)
                {
                case "PillarName":
                    pillarName = formValue;
                    break;

                case "PillarDescription":
                    pillarDescription = formValue;
                    break;

                case "PillarLink":
                    pillarLink = formValue;
                    break;

                case "PillarActive":
                    pillarActive = formValue == "true";
                    break;

                case "PillarId":
                    pillarId = Convert.ToInt32(formValue);
                    break;
                }
            }

            if (seSubio)
            {
                if (!string.IsNullOrEmpty(pillarName) && !string.IsNullOrEmpty(pillarDescription))
                {
                    if (pillarId == 0)
                    {
                        db.Pillars.Add(new Pillar
                        {
                            PillarImage       = pillarImage,
                            PillarName        = pillarName,
                            PillarDescription = pillarDescription,
                            PillarLink        = pillarLink,
                            PillarActive      = pillarActive
                        });
                    }
                    else
                    {
                        Pillar pillar = await db.Pillars.FindAsync(pillarId);

                        if (pillar != null)
                        {
                            pillar.PillarImage       = pillarImage;
                            pillar.PillarName        = pillarName;
                            pillar.PillarDescription = pillarDescription;
                            pillar.PillarLink        = pillarLink;
                            pillar.PillarActive      = pillarActive;
                            db.Entry(pillar).State   = EntityState.Modified;
                        }
                    }
                    await db.SaveChangesAsync();
                }

                return(Json(new AjaxResponse {
                    Success = true, Message = "Los datos fueron subidos correctamente al servidor"
                }, JsonRequestBehavior.AllowGet));
            }
            return(Json(new AjaxResponse {
                Success = false, Message = "Ocurrió un error al subir lo(s) archivo(s)."
            }, JsonRequestBehavior.AllowGet));
        }
示例#25
0
        private async Task <JsonResult> PrepareDataFiles(FileType all)
        {
            var    httpRequest = System.Web.HttpContext.Current.Request;
            string quoteText = "", quoteAuthor = "", quoteAuthorSign = "", quoteImage = "";
            bool   seSubio = false;
            int    quoteId = 0;

            foreach (string file in httpRequest.Files)
            {
                var postedFile = httpRequest.Files[file];
                var valid      = Utils.IsValidImage(postedFile, all);

                if (valid.Value == "Ok")
                {
                    if (postedFile != null)
                    {
                        var fil          = $"{Path.GetFileNameWithoutExtension(postedFile.FileName)}_{DateTime.Now.Ticks}{postedFile.FileName.Substring(postedFile.FileName.LastIndexOf('.'))}";
                        var fileSavePath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath("~/UploadedFiles"), fil);
                        if (!postedFile.FileName.StartsWith("/"))
                        {
                            postedFile.SaveAs(fileSavePath);
                            seSubio = true;
                            switch (file)
                            {
                            case "QuoteAuthorPhoto":
                                quoteImage = $"{"~/UploadedFiles"}/{fil}";
                                break;
                            }
                        }
                    }
                }
                else
                {
                    return(Json(new AjaxResponse {
                        Success = false, Message = valid.Value
                    }, JsonRequestBehavior.AllowGet));
                }
            }

            foreach (var form in httpRequest.Form.AllKeys)
            {
                var formValue = httpRequest.Form[form];
                formValue = string.IsNullOrEmpty(formValue) ? null : formValue;
                switch (form)
                {
                case "QuoteText":
                    quoteText = formValue;
                    break;

                case "QuoteAuthor":
                    quoteAuthor = formValue;
                    break;

                case "QuoteAuthorSign":
                    quoteAuthorSign = formValue;
                    break;

                case "QuoteId":
                    quoteId = Convert.ToInt32(formValue);
                    break;
                }
            }

            if (seSubio)
            {
                if (!string.IsNullOrEmpty(quoteText) && !string.IsNullOrEmpty(quoteAuthor))
                {
                    if (quoteId == 0)
                    {
                        db.Quotes.Add(new Quote
                        {
                            QuoteAuthorPhoto = quoteImage,
                            QuoteText        = quoteText,
                            QuoteAuthor      = quoteAuthor,
                            QuoteAuthorSign  = quoteAuthorSign
                        });
                    }
                    else
                    {
                        Quote quote = await db.Quotes.FindAsync(quoteId);

                        if (quote != null)
                        {
                            quote.QuoteAuthorPhoto = quoteImage;
                            quote.QuoteText        = quoteText;
                            quote.QuoteAuthor      = quoteAuthor;
                            quote.QuoteAuthorSign  = quoteAuthorSign;
                            db.Entry(quote).State  = EntityState.Modified;
                        }
                    }
                    await db.SaveChangesAsync();
                }

                return(Json(new AjaxResponse {
                    Success = true, Message = "Los datos fueron subidos correctamente al servidor"
                }, JsonRequestBehavior.AllowGet));
            }
            return(Json(new AjaxResponse {
                Success = false, Message = "Ocurrió un error al subir lo(s) archivo(s)."
            }, JsonRequestBehavior.AllowGet));
        }
示例#26
0
        //[ValidateAntiForgeryToken]
        public async Task <ActionResult> Join(int?id)
        {
            var response = new AjaxResponse {
                Success = false
            };

            try
            {
                if (ModelState.IsValid)
                {
                    if (string.IsNullOrEmpty(Request.Form["TeamInterestArea"]))
                    {
                        response.Message = "Debe especificar al menos un área de interés";
                        return(Json(response, JsonRequestBehavior.AllowGet));
                    }

                    List <InterestArea>   interestAreas   = storeDB.InterestAreas.ToList();
                    List <InterestRegion> interestRegions = storeDB.InterestRegions.ToList();
                    JoinTeamViewModel     model           = GetJoinTeamPage(interestAreas, interestRegions);

                    if (model.TeamInterestArea.Contains("Mostrador") && string.IsNullOrEmpty(model.InterestRegion))
                    {
                        response.Message = "Debe especificar al menos una región de interés";
                        return(Json(response, JsonRequestBehavior.AllowGet));
                    }

                    var existe = await storeDB.UserJoinedToTeams.FirstOrDefaultAsync(x => x.Email == model.TeamEmail);

                    if (existe == null)
                    {
                        var interestAreaIds   = Request.Form["TeamInterestArea"].Split(',');
                        var interestRegionIds = Request.Form["InterestRegion"].Split(',');

                        var user = new UserJoinedToTeam
                        {
                            Names        = model.TeamNames,
                            Email        = model.TeamEmail,
                            PhoneNumber  = model.TeamPhoneNumber,
                            Lastnames    = model.TeamLastnames,
                            Address      = model.TeamAddress,
                            DateCreation = DateTime.Now,
                            InterestArea = model.TeamInterestArea
                        };

                        List <string> areaAddresses = interestAreas.Where(a => interestAreaIds.Contains(a.InterestAreaId.ToString()))
                                                      .SelectMany(a => a.MailCollection.Split(';'))
                                                      .Distinct()
                                                      .ToList();
                        List <string> interestAddresses = null;

                        if (model.TeamInterestArea.Contains("Mostrador"))
                        {
                            interestAddresses = interestRegions.Where(r => interestRegionIds.Contains(r.Id.ToString()))
                                                .SelectMany(r => r.MailCollection.Split(';'))
                                                .Distinct()
                                                .ToList();
                        }

                        bool mailSent = SendMail(areaAddresses, interestAddresses, model);
                        if (mailSent == false)
                        {
                            response.Message = "Ocurrió un error al enviar su solicitud";
                            return(Json(response, JsonRequestBehavior.AllowGet));
                        }

                        storeDB.UserJoinedToTeams.Add(user);
                        await storeDB.SaveChangesAsync();

                        response.Success = true;
                        response.Message = "Gracias por unirse a nuestro Equipo";
                        return(Json(response, JsonRequestBehavior.AllowGet));
                    }
                    response.Message = "Ya existe una persona registrada con esa dirección de correo electrónico";
                    return(Json(response, JsonRequestBehavior.AllowGet));
                }
                response.Message = "Lo sentimos, no se pudo realizar la operación. Ha ocurrido un error en el servidor.";
                return(Json(response, JsonRequestBehavior.AllowGet));
            }
            catch (Exception)
            {
                response.Message = "Lo sentimos, no se pudo realizar la operación. Ha ocurrido un error en el servidor.";
                return(Json(response, JsonRequestBehavior.AllowGet));
            }
        }