public async Task <ActionResult <ServicePhotoDto> > AddPhoto(IFormFile file, [FromQuery] string name)
        {
            var service = await _serviceRepository.GetByNameAsync(name);

            var result = await _photoService.AddPhotoAsync(file);

            if (result.Error != null)
            {
                return(BadRequest(result.Error.Message));
            }

            var photo = new ServicePhoto()
            {
                Url      = result.SecureUrl.AbsoluteUri,
                PublicId = result.PublicId
            };

            if (service.Photos.Count == 0)
            {
                photo.IsMain = true;
            }

            service.Photos.Add(photo);

            if (await _serviceRepository.SaveAllAsync())
            {
                return(_mapper.Map <ServicePhotoDto>(photo));
            }

            return(BadRequest("Ocurrió un problema al agregar la foto"));
        }
Beispiel #2
0
        public async Task <ActionResult> Edit([Bind(Include = "ServicePhotoID,FileName,Title")] ServicePhoto servicePhoto, int CompanyServiceId)
        {
            if (ModelState.IsValid)
            {
                db.Entry(servicePhoto).State = EntityState.Modified;
                await db.SaveChangesAsync();

                return(RedirectToAction("Index", new { id = CompanyServiceId }));
            }
            return(View(servicePhoto));
        }
Beispiel #3
0
        public async Task <ActionResult> Create([Bind(Include = "ServicePhotoID,FileName,Title")] ServicePhoto servicePhoto, int CompanyServiceId)
        {
            if (ModelState.IsValid)
            {
                servicePhoto.CompanyService = db.CompanyServices.Find(CompanyServiceId);

                db.ServicePhotos.Add(servicePhoto);
                await db.SaveChangesAsync();

                return(RedirectToAction("Index", new { id = CompanyServiceId }));
            }

            return(View(servicePhoto));
        }
Beispiel #4
0
        // GET: ServicePhotoes/Details/5
        public async Task <ActionResult> Details(int?id)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ServicePhoto servicePhoto = await db.ServicePhotos.FindAsync(id);

            if (servicePhoto == null)
            {
                return(HttpNotFound());
            }
            return(View(servicePhoto));
        }
Beispiel #5
0
        public async Task <ActionResult> DeleteConfirmed(int id, int companyServiceId, string deleteFileName)
        {
            //delete image file first
            PhotoFileManager manager = new PhotoFileManager(PhotoManagerType.Service);

            manager.Delete(deleteFileName, true);

            ServicePhoto servicePhoto = await db.ServicePhotos.FindAsync(id);

            db.ServicePhotos.Remove(servicePhoto);
            await db.SaveChangesAsync();

            return(RedirectToAction("Index", new { id = companyServiceId }));
        }
Beispiel #6
0
        public async Task <IActionResult> Add(ServiceModel model)
        {
            if (model.Names != null &&
                model.Photos != null &&
                model.Texts != null &&
                model.ShortDescs != null)
            {
                Service service = new Service();
                await db.Services.AddAsync(service);

                List <Language> languages = await db.Languages.ToListAsync();

                for (int i = 0; i < languages.Count; i++)
                {
                    if (model.Names[i] != null && model.ShortDescs[i] != null && model.Texts[i] != null)
                    {
                        ServiceLanguage serviceLanguage = new ServiceLanguage()
                        {
                            Name       = model.Names[i],
                            ShortDesc  = model.ShortDescs[i],
                            Text       = model.Texts[i],
                            ServiceId  = service.Id,
                            LanguageId = languages[i].Id
                        };
                        await db.ServiceLanguages.AddAsync(serviceLanguage);
                    }
                }

                foreach (string file in model.Photos)
                {
                    ServicePhoto servicePhoto = new ServicePhoto()
                    {
                        ServiceId = service.Id,
                        Path      = file
                    };
                    await db.ServicePhotos.AddAsync(servicePhoto);
                }
                await db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                return(RedirectToAction(nameof(Add)));
            }
        }
Beispiel #7
0
        // GET: ServicePhotoes/Edit/5
        public async Task <ActionResult> Edit(int?id, int CompanyServiceID)
        {
            if (id == null)
            {
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
            ServicePhoto servicePhoto = await db.ServicePhotos.FindAsync(id);

            if (servicePhoto == null)
            {
                return(HttpNotFound());
            }
            ViewBag.CompanyServiceId = CompanyServiceID;
            ViewBag.ImageType        = PhotoManagerType.Service;
            ViewBag.ImageDirectory   = PhotoFileManager.StorageDirectoryDetection(PhotoManagerType.Service);
            return(View(servicePhoto));
        }
Beispiel #8
0
        public HttpResponseMessage AddServicePhoto()
        {
            var    httpRequest = HttpContext.Current.Request;
            string imageName   = "";

            try
            {
                var postedFile = httpRequest.Files["Image"];
                imageName = new String(Path.GetFileNameWithoutExtension(postedFile.FileName).Take(postedFile.FileName.Length).ToArray()).Replace(" ", "-");
                imageName = imageName + DateTime.Now.ToString("yymmssfff") + Path.GetExtension(postedFile.FileName);
                var FilePath = HttpContext.Current.Server.MapPath("~/Images/" + imageName);
                postedFile.SaveAs(FilePath);
            }
            catch (Exception err)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Image was not saved (" + err.Message + ")"));
            }

            try
            {
                int     ServiceID = Convert.ToInt32(httpRequest["ServiceID"]);
                Service verify    = db.Services.Where(zz => zz.ServiceID == ServiceID).FirstOrDefault();
                if (verify != null)
                {
                    if (imageName != null)
                    {
                        ServicePhoto photo = new ServicePhoto();
                        photo.ServiceID = ServiceID;
                        photo.Photo     = imageName;

                        db.ServicePhotoes.Add(photo);
                        db.SaveChanges();
                    }
                }
            }
            catch
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Image details are invalid"));
            }

            return(Request.CreateResponse(HttpStatusCode.Created));
        }
Beispiel #9
0
 public ActionResult AddPhotoService(ServicePageViewModel model, HttpPostedFileBase upload)
 {
     try
     {
         var pic     = new AddPhotos();
         var pathPic = pic.AddImage(upload, Server.MapPath("/images/Services/"), "/images/Services/");
         var entity  = new ServicePhoto()
         {
             id_service = model.Id,
             photo      = new Photo()
             {
                 name = pathPic,
                 date = DateTime.Now,
             }
         };
         _servicePhotoManager.Add(entity);
         return(RedirectToRoute("ServicePage", new { id = model.Id }));
     }
     catch (Exception)
     {
         return(RedirectToRoute("ServicePage", new { id = model.Id }));
     }
 }
Beispiel #10
0
        public async Task <IActionResult> Edit(ServiceModel model, int serviceId)
        {
            if (!model.Texts.IsNull() && !model.Names.IsNull() && !model.ShortDescs.IsNull())
            {
                Service service = await db.Services.Where(s => s.Id == serviceId).Include(s => s.Photos).FirstOrDefaultAsync();

                List <Language> languages = await db.Languages.ToListAsync();


                for (int i = 0; i < languages.Count; i++)
                {
                    ServiceLanguage serviceLanguage = await db.ServiceLanguages
                                                      .Where(sl => sl.ServiceId == serviceId &&
                                                             sl.LanguageId == languages[i].Id)
                                                      .FirstOrDefaultAsync();

                    if (serviceLanguage == null)
                    {
                        serviceLanguage = new ServiceLanguage()
                        {
                            ServiceId  = serviceId,
                            LanguageId = languages[i].Id,
                            Name       = model.Names[i],
                            Text       = model.Texts[i],
                            ShortDesc  = model.ShortDescs[i]
                        };

                        await db.ServiceLanguages.AddAsync(serviceLanguage);
                    }
                    else
                    {
                        serviceLanguage.Name      = model.Names[i];
                        serviceLanguage.ShortDesc = model.ShortDescs[i];
                        serviceLanguage.Text      = model.Texts[i];
                    }
                }

                if (!model.DeletePhotos.IsNull() && !model.DeletePhotos.IsNullOrEmpty())
                {
                    foreach (ServicePhoto sp in service.Photos)
                    {
                        if (model.DeletePhotos.Contains(sp.Path))
                        {
                            string path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "Uploads", "Services", sp.Path);
                            if (System.IO.File.Exists(path))
                            {
                                System.IO.File.Delete(path);
                            }
                            ServicePhoto servicePhoto = await db.ServicePhotos.Where(s => s.ServiceId == serviceId && s.Path == sp.Path).FirstOrDefaultAsync();

                            if (servicePhoto != null)
                            {
                                db.ServicePhotos.Remove(servicePhoto);
                            }
                        }
                    }
                }

                if (!model.Photos.IsNull() && !model.Photos.IsNullOrEmpty())
                {
                    foreach (string file in model.Photos)
                    {
                        ServicePhoto servicePhoto = new ServicePhoto()
                        {
                            ServiceId = service.Id,
                            Path      = file
                        };
                        await db.ServicePhotos.AddAsync(servicePhoto);
                    }
                }


                await db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }

            return(RedirectToAction(nameof(Edit)));
        }
Beispiel #11
0
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (selectedService != null)
                {
                    bool error   = false;
                    var  service = DbContextObject.db.Service.Where(item => item.ID == selectedService.ID).FirstOrDefault();
                    var  titles  = DbContextObject.db.Service.Where(item => item.Title.ToLower() == txbTitle.Text.ToLower()).ToList();

                    try
                    {
                        error = Convert.ToInt32(txbDuration.Text) > 14400 ? true : false;
                    }
                    catch
                    {
                        throw new Exception("Длительность должна быть указана числом!");
                    }
                    if (error)
                    {
                        throw new Exception("Неверно введённые данные!");
                    }
                    else
                    {
                        try
                        {
                            service.Title             = txbTitle.Text;
                            service.Cost              = Convert.ToDecimal(txbCost.Text);
                            service.Description       = txbDescription.Text;
                            service.Discount          = int.Parse(txbDiscount.Text);
                            service.DurationInSeconds = int.Parse(txbDuration.Text);
                            if (!string.IsNullOrEmpty(mainImpagePath) && !string.IsNullOrWhiteSpace(mainImpagePath))
                            {
                                File.Copy(mainImpagePath, service.MainImagePath.Trim(), true);
                            }
                            for (int i = 0; i < photoPath.Count; i++)
                            {
                                ServicePhoto servicePhoto = new ServicePhoto();
                                servicePhoto.ServiceID = selectedService.ID;
                                servicePhoto.PhotoPath = $"Услуги школы\\" + System.IO.Path.GetFileName(photoPath[i]);
                                File.Copy(photoPath[i], $"Услуги школы\\{System.IO.Path.GetFileName(photoPath[i])}", true);
                                DbContextObject.db.ServicePhoto.Add(servicePhoto);
                                DbContextObject.db.SaveChanges();
                            }
                            DbContextObject.db.SaveChanges();
                            NavigationService.GoBack();
                        }
                        catch
                        {
                            throw new Exception("Неверно введены данные");
                        }
                    }
                }
                else
                {
                    bool error  = false;
                    var  titles = DbContextObject.db.Service.Where(item => item.Title.ToLower() == txbTitle.Text.ToLower()).ToList();
                    if (titles.Count != 0)
                    {
                        error = true;
                    }
                    try
                    {
                        if (Convert.ToInt32(txbDuration.Text) > 14400)
                        {
                            error = true;
                        }
                    }
                    catch
                    {
                        throw new Exception("");
                    }
                    if (error)
                    {
                        throw new Exception("Неверные введены данные ");
                    }
                    else
                    {
                        Service service = new Service();
                        service.Title = txbTitle.Text;
                        try
                        {
                            service.Cost              = Convert.ToDecimal(txbCost.Text);
                            service.Description       = txbDescription.Text;
                            service.Discount          = Convert.ToInt32(txbDiscount.Text);
                            service.DurationInSeconds = Convert.ToInt32(txbDuration.Text);
                            if (!string.IsNullOrEmpty(mainImpagePath) && !string.IsNullOrEmpty(mainImpagePath))
                            {
                                File.Copy(mainImpagePath, $"Услуги школы\\{System.IO.Path.GetFileName(mainImpagePath)}");
                                service.MainImagePath = $"Услуги школы\\{System.IO.Path.GetFileName(mainImpagePath)}";
                            }
                            DbContextObject.db.Service.Add(service);
                            for (int i = 0; i < photoPath.Count; i++)
                            {
                                ServicePhoto photo = new ServicePhoto();
                                photo.ServiceID = service.ID;
                                photo.PhotoPath = $"Услуги школы\\{System.IO.Path.GetFileName(photoPath[i])}";
                                File.Copy(photoPath[i], $"Услуги школы\\{System.IO.Path.GetFileName(photoPath[i])}", true);
                                DbContextObject.db.ServicePhoto.Add(photo);
                                DbContextObject.db.SaveChanges();
                            }
                            DbContextObject.db.SaveChanges();
                            NavigationService.GoBack();
                        }
                        catch
                        {
                            throw new Exception("Неверно введны данные");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
Beispiel #12
0
 public void Delete(ServicePhoto servicePhoto)
 {
     _context.ServicePhotos.Remove(servicePhoto);
 }
Beispiel #13
0
        public async Task <IActionResult> Upload(int serviceId, List <IFormFile> files)
        {
            try
            {
                var servicePhoto = await _serviceRepository.GetServiceAsync(serviceId);

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

                if (files != null && files.Count == 0)
                {
                    return(BadRequest("Null file"));
                }

                var photos = await _repository.GetPhotos(serviceId);

                var numberOfphotos = 0;
                foreach (var ph in photos)
                {
                    numberOfphotos++;
                }

                if (numberOfphotos >= 8)
                {
                    return(BadRequest("Number of allowed photos limited to 8."));
                }

                var results = new List <ServicePhotoResource>();

                if (files != null)
                {
                    foreach (var file in files)
                    {
                        if (file.Length == 0)
                        {
                            return(BadRequest("Empty file"));
                        }

                        if (file.Length > _photoAppSettings.MaxBytes)
                        {
                            return(BadRequest("Maximum file size exceeded"));
                        }

                        if (!_photoAppSettings.IsSupported(file.FileName))
                        {
                            return(BadRequest("Invalid file type"));
                        }

                        var awsServiceSettings = new AwsServiceClientSettings(file, _awsAppSettings.BucketName,
                                                                              _awsAppSettings.SubFolderService, _awsAppSettings.BucketLocation,
                                                                              _awsAppSettings.PublicDomain);

                        var photoUrl = await _awsServiceClient.UploadAsync(awsServiceSettings);

                        var photo = new ServicePhoto {
                            Url = photoUrl
                        };
                        servicePhoto.Photos.Add(photo);

                        await _unitOfWork.CompleteAsync();

                        results.Add(_mapper.Map <ServicePhoto, ServicePhotoResource>(photo));
                    }
                }

                if (results.Count > 0)
                {
                    return(Ok(results));
                }
                else
                {
                    return(BadRequest("Unable to upload"));
                }
            }
            catch (Exception ex)
            {
                var message = $"Message: {ex.Message}\n Source:{ex.Source} \n Expection:{ex.InnerException}";
                return(BadRequest(message));
            }
        }