Пример #1
0
        public ActionResult Create(PictureViewModel vm)
        {
            try
            {
                //Smestanje slike na drajv
                string fileName = Guid.NewGuid().ToString() + "_" + vm.Picture.FileName;
                string putanja  = Path.Combine(Server.MapPath("~/Content/images"), fileName);

                vm.Picture.SaveAs(putanja);

                PictureDto dto = new PictureDto
                {
                    Alt = "slikaaaa",
                    Src = "Content/images/" + fileName
                };


                OpPictureInsert op = new OpPictureInsert();
                op.Slika = dto;
                OperationResult rez = _manager.executeOperation(op);
                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Пример #2
0
        public async Task HandleAsync_Should_Update_User_When_Picture_Is_Not_Null()
        {
            var pictureDto = new PictureDto(Array.Empty <byte>(), "image/jpg");
            var command    = new UpdateUserCommand(Guid.NewGuid(), DefaultUserSettings.ServiceActive,
                                                   DefaultUserSettings.AnnouncementPreferenceLimit, DefaultUserSettings.AnnouncementSendingFrequency,
                                                   pictureDto);
            var user = User.Builder()
                       .SetId(command.UserId)
                       .SetEmail("*****@*****.**")
                       .SetServiceActive(command.ServiceActive)
                       .SetAnnouncementPreferenceLimit(command.AnnouncementPreferenceLimit)
                       .SetAnnouncementSendingFrequency(command.AnnouncementSendingFrequency)
                       .Build();
            var getUserResult = GetResult <User> .Ok(user);

            const string pictureUrl = "pictureUrl";

            _userGetterServiceMock.Setup(x => x.GetByIdAsync(It.IsAny <Guid>())).ReturnsAsync(getUserResult);
            _blobContainerServiceMock
            .Setup(x => x.UploadFileAsync(It.IsAny <byte[]>(), It.IsAny <string>(), It.IsAny <string>()))
            .ReturnsAsync(pictureUrl);
            _communicationBusMock
            .Setup(x => x.DispatchDomainEventsAsync(It.IsAny <User>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);
            _userRepositoryMock.Setup(x => x.UpdateAsync(It.IsAny <User>())).Returns(Task.CompletedTask);
            _integrationEventBusMock.Setup(x => x.PublishIntegrationEventAsync(It.IsAny <IIntegrationEvent>()))
            .Returns(Task.CompletedTask);

            Func <Task> result = async() => await _commandHandler.HandleAsync(command);

            await result.Should().NotThrowAsync <Exception>();
        }
Пример #3
0
 protected override void Because_of()
 {
     _source = new Picture {
         ImageData = new byte[1000000]
     };
     _dest = Mapper.Map <Picture, PictureDto>(_source);
 }
Пример #4
0
        public ActionResult Create(HttpPostedFileBase file, PictureDto model)
        {
            try
            {
                if (file != null)
                {
                    var userName = System.Web.HttpContext.Current.User.Identity.Name;

                    Guid userId = Guid.Parse(System.Web.HttpContext.Current.Session["UserId"].ToString());

                    Stream s    = file.InputStream;
                    byte[] data = new byte[file.ContentLength + 1];
                    s.Read(data, 0, file.ContentLength);
                    model.Data   = data;
                    model.UserId = userId;
                    PictureModel.Init(DbName).Create(model);
                    return(RedirectToAction("Index"));
                }
                else
                {
                    return(View());
                }
            }
            catch
            {
                return(View());
            }
        }
        public IActionResult PictureUpload(PictureDto body)
        {
            using EFCoreContextWrite context = new EFCore.EFCoreContextWrite();
            if (!string.IsNullOrEmpty(body.PictureTitle) && !string.IsNullOrEmpty(body.PictureExplain))
            {
                string token = _httpContext.HttpContext.Request.Headers["Authorization"];

                AuthRedis.GetUserByToken(token, out UserInfo userInfo);
                PictureInfo PictureInfos = new PictureInfo()
                {
                    Id               = SequenceID.GetSequenceID(),
                    CreateTime       = DateTime.Now,
                    Disable          = false,
                    PictureContent   = body.url,
                    UserID           = userInfo.id,
                    LastModifiedTime = DateTime.Now,
                    PictureExplain   = body.PictureExplain,
                    PictureTitle     = body.PictureTitle,
                    RecommendIndex   = body.Index,
                    PictureType      = body.PictureType,
                    PhotoType        = body.PhotoType
                };
                context.Add(PictureInfos);
                context.SaveChanges();
                PictureRedis.Del();
            }
            return(Ok(new ApiResponse()));
        }
Пример #6
0
 public int Update(PictureDto picture)
 {
     if (picture.Data != null)
     {
         picture.Thumbnail = imageResize(picture.Data);
     }
     return(PictureRepository.Update(picture));
 }
Пример #7
0
        public virtual async Task DeletePicture(PictureDto pictureDto)
        {
            var picture = await _pictureService.GetPictureById(pictureDto.Id);

            if (picture != null)
            {
                await _pictureService.DeletePicture(picture);
            }
        }
Пример #8
0
        public async Task OnGetAsync(long id)
        {
            Dto = await _service.GetByIdAsync(id);

            if (Dto == null)
            {
                throw new KuDataNotFoundException();
            }
        }
Пример #9
0
        public virtual void DeletePicture(PictureDto pictureDto)
        {
            var picture = _pictureService.GetPictureById(pictureDto.Id);

            if (picture != null)
            {
                _pictureService.DeletePicture(picture);
            }
        }
Пример #10
0
        public ActionResult Details(int id)
        {
            OpPictureBase op = new OpPictureBase();

            op.criteria.Id = id;
            var        result = _manager.executeOperation(op);
            PictureDto dto    = result.Items[0] as PictureDto;

            return(View(dto));
        }
Пример #11
0
        public static PictureDto ConvertToDto(Picture picture)
        {
            PictureDto newPicture = new PictureDto();

            newPicture.Id      = picture.Id;
            newPicture.Name    = picture.Name;
            newPicture.EventId = picture.EventId;
            newPicture.Image   = picture.Image;
            return(newPicture);
        }
Пример #12
0
        public static Picture ConvertToPicture(PictureDto picture)
        {
            Picture newPicture = new Picture();

            newPicture.Id      = picture.Id;
            newPicture.Name    = picture.Name;
            newPicture.EventId = picture.EventId;
            newPicture.Image   = picture.Image;
            return(newPicture);
        }
Пример #13
0
        public ActionResult Edit(int id)
        {
            OpPictureBase editView = new OpPictureBase();

            editView.criteria.Id = id;
            OperationResult rez = _manager.executeOperation(editView);
            PictureDto      dto = rez.Items[0] as PictureDto;

            return(View(dto));
        }
Пример #14
0
 public UpdateUserCommand(Guid userId, bool serviceActive, int announcementPreferenceLimit,
                          AnnouncementSendingFrequencyEnumeration announcementSendingFrequency, PictureDto picture)
 {
     UserId        = userId;
     ServiceActive = serviceActive;
     AnnouncementPreferenceLimit  = announcementPreferenceLimit;
     AnnouncementSendingFrequency = announcementSendingFrequency;
     Picture       = picture;
     CorrelationId = Guid.NewGuid();
 }
Пример #15
0
        public async Task <IActionResult> OnPostAsync(ICollection <IFormFile> file, string groups)
        {
            string yyyymm = DateTime.Now.ToyyyyMM();
            var    config = await _configService.GetAsync();

            string oppositePath = $"pictures/{User.GetUserIdOrZero()}/{yyyymm}/";
            var    folder       = _env.WebRootPath + "/upload/" + oppositePath;

            if (config != null && !string.IsNullOrEmpty(config.PictureSavePath))
            {
                folder = Path.Combine(config.PictureSavePath, oppositePath);
            }
            if (!Directory.Exists(folder))
            {
                Directory.CreateDirectory(folder);
            }

            long[] groupIds = groups.SplitToInt64();
            //检查素材分组与用户关系
            foreach (var id in groupIds)
            {
                var group = await _groupService.GetByIdAsync(id);

                if (group == null || group.Type != Domain.Enum.MaterialCenter.EmUserMaterialGroupType.Picture ||
                    group.UserId != User.GetUserIdOrZero())
                {
                    throw new KuException("选择的素材分组不正确!");
                }
            }
            foreach (var item in file)
            {
                PictureDto model = new PictureDto();
                model.Id = ID.NewID();

                string suffix   = item.FileName.Split('.').Last().ToLower();
                var    saveName = model.Id + "_original." + suffix;

                using (var fileStream = new FileStream(Path.Combine(folder, saveName), FileMode.Create))
                {
                    await item.CopyToAsync(fileStream);

                    await fileStream.FlushAsync();
                }

                model.Title        = item.FileName;
                model.FileName     = saveName;
                model.Folder       = oppositePath;
                model.FilePath     = oppositePath + saveName;
                model.FileSize     = item.Length;
                model.FileType     = suffix;
                model.UploadUserId = User.GetUserIdOrZero();
                await _service.AddAsync(model, groupIds);
            }
            return(Json(true));
        }
Пример #16
0
 public static Picture ToDbEntity(this PictureDto picture)
 {
     return(new Picture()
     {
         Challenge_ID = picture.ChallengeId,
         Milestone_ID = picture.MilestoneId,
         Objective_ID = picture.ObjectiveId,
         Picture_ID = picture.Id,
         Picture1 = picture.Picture
     });
 }
Пример #17
0
        /// <summary>
        /// Optimisation of mapping when mapping is slow
        /// </summary>
        private static void MapEntityToDto_Optimsised()
        {
            Mapper.CreateMap <Picture, PictureDto>().ConvertUsing(src =>
            {
                var dto = new PictureDto()
                {
                    Id              = src.Id,
                    Creation        = src.Creation,
                    IsImported      = src.IsImported,
                    LastUpdate      = src.LastUpdate,
                    Notes           = src.Notes,
                    Tag             = Mapper.Map <Tag, TagDto>(src.Tag),
                    ThumbnailBitmap = src.ThumbnailBitmap,
                    Bitmap          = src.Bitmap,
                };
                Clean(dto);
                return(dto);
            });

            Mapper.CreateMap <Picture, LightPictureDto>().ConvertUsing(src =>
            {
                var dto = new LightPictureDto()
                {
                    Id              = src.Id,
                    IsImported      = src.IsImported,
                    Tag             = Mapper.Map <Tag, TagDto>(src.Tag),
                    ThumbnailBitmap = src.ThumbnailBitmap,
                };
                Clean(dto);
                return(dto);
            });

            Mapper.CreateMap <Patient, LightPatientDto>().ConvertUsing(src =>
            {
                var dto = new LightPatientDto()
                {
                    Birthdate       = src.BirthDate,
                    FirstName       = src.FirstName,
                    Gender          = src.Gender,
                    Height          = (int)src.Height,
                    Id              = src.Id,
                    IsImported      = src.IsImported,
                    LastName        = src.LastName,
                    IsDeactivated   = src.IsDeactivated,
                    Profession      = Mapper.Map <ProfessionDto>(src.Profession),
                    InscriptionDate = src.InscriptionDate,
                    LastUpdate      = src.LastUpdate,
                    Address         = Mapper.Map <Address, AddressDto>(src.Address),
                    Reason          = src.Reason,
                };
                Clean(dto);
                return(dto);
            });
        }
Пример #18
0
 public HttpResponseMessage AddPicture(PictureDto picture)
 {
     try
     {
         _pictureService.AddPicture(picture);
         return(Request.CreateResponse(HttpStatusCode.Created, "Successfully added a picture!"));
     }
     catch (Exception ex)
     {
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, ex.Message));
     }
 }
Пример #19
0
        public static async Task <PictureDto> InsertPicture(byte[] binary)
        {
            var picture = new PictureDto();

            picture.PictureBinary = binary;
            picture.MimeType      = "image/jpeg";
            picture.SeoFilename   = "";
            picture.IsNew         = true;
            picture.Id            = "";
            container.AddToPicture(picture);
            container.SaveChangesAsync().Wait();
            return(picture);
        }
Пример #20
0
        public void Execute(PictureDto request)
        {
            _validator.ValidateAndThrow(request);
            var picture = new Picture
            {
                Id     = request.Id,
                IdPost = request.PostId,
                Name   = request.Name
            };

            _context.Pictures.Add(picture);
            _context.SaveChanges();
        }
Пример #21
0
        public IActionResult Post([FromBody] PictureDto model)
        {
            if (!_permissionService.Authorize(PermissionSystemName.Files))
            {
                return(Forbid());
            }

            if (ModelState.IsValid)
            {
                model = _commonApiService.InsertPicture(model);
                return(Created(model));
            }
            return(BadRequest(ModelState));
        }
Пример #22
0
 public void AddPicture(PictureDto picture)
 {
     try
     {
         _unitOfWork.PictureRepository.Create(picture.ToDbEntity());
         _unitOfWork.PictureRepository.Save();
         _unitOfWork.Commit();
     }
     catch (Exception)
     {
         _unitOfWork.RollBack();
         throw;
     }
 }
Пример #23
0
        /// <summary>
        /// Updates the specified picture.
        /// </summary>
        /// <param name="picture">The picture.</param>
        public void Update(PictureDto item)
        {
            var entity = this.Session.Get <Picture>(item.Id);

            if (entity == null)
            {
                throw new EntityNotFoundException(typeof(Picture));
            }

            Mapper.Map <PictureDto, Picture>(item, entity);

            entity.Tag = this.Session.Get <Tag>(item.Tag.Id);

            this.Session.Merge(entity);
        }
Пример #24
0
        public ActionResult Edit(PictureDto dto)
        {
            try
            {
                OpPictureUpdate update = new OpPictureUpdate();
                update.Slika = dto;
                OperationResult result = _manager.executeOperation(update);

                return(RedirectToAction("Index"));
            }
            catch
            {
                return(View());
            }
        }
Пример #25
0
        public int Update(PictureDto picture)
        {
            int result;

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                SqlCommand command = new SqlCommand("PicturesUpdate", conn);
                command.CommandType = System.Data.CommandType.StoredProcedure;
                command.Parameters.AddWithValue("Id", picture.Id);
                command.Parameters.AddWithValue("Data", picture.Data);
                command.Parameters.AddWithValue("Thumbnail", picture.Thumbnail);
                command.Parameters.AddWithValue("Comment", picture.Comment);
                conn.Open();
                result = command.ExecuteNonQuery();
            }
            return(result);
        }
Пример #26
0
        public async Task <IActionResult> Post([FromBody] PictureDto model)
        {
            if (!await _permissionService.Authorize(PermissionSystemName.Files))
            {
                return(Forbid());
            }

            if (ModelState.IsValid)
            {
                model = await _mediator.Send(new AddPictureCommand()
                {
                    PictureDto = model
                });

                return(Created(model));
            }
            return(BadRequest(ModelState));
        }
Пример #27
0
        private IActionResult CreateImg(List <IFormFile> pic, string name, List <PictureDto> picturePathList)
        {
            string applicationPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            var    picturePath     = $"{applicationPath}/wwwroot/pictures";

            //var picturePathList = new List<PictureDto>();
            if (pic == null)
            {
                return(BadRequest());
            }
            foreach (var image in pic)
            {
                var picName  = $"{name}-{Guid.NewGuid()}.png";
                var fullPath = $"{picturePath}/{picName}";

                if (!image.ContentType.Contains("image"))
                {
                    return(BadRequest("Please attach a image file"));
                }
                //  Image images = Image.FromStream(image.OpenReadStream(), true, true);
                using (MemoryStream ms = new MemoryStream(100))
                {
                    image.OpenReadStream().CopyTo(ms);

                    System.Drawing.Image images = System.Drawing.Image.FromStream(ms);

                    //if (images.Width < 700 || images.Height < 1400)
                    //{
                    //    return BadRequest("Attach a better photo");

                    //}



                    images.Save(fullPath, ImageFormat.Png);
                    var pictureDto = new PictureDto()
                    {
                        Path = "pictures/" + picName
                    };
                    picturePathList.Add(pictureDto);
                }
            }
            return(Ok());
        }
Пример #28
0
        public async Task <IActionResult> FileUpload([FromForm] PictureDto picture)
        {
            if (picture.File.Length == 0 || picture.File == null)
            {
                return(BadRequest());
            }
            var thumb  = _hostingEnvironment.SubFilderPath(@"Thums\");
            var upload = _hostingEnvironment.UploadPath();

            if (!_hostingEnvironment.DirectoryExist(upload) || !_hostingEnvironment.DirectoryExist(thumb))
            {
                return(BadRequest());
            }
            var url = await _fileService.CreateThumbnail(picture.File, 250, 250, thumb, picture.Title);

            await _fileService.SaveImage(picture.File, 450, 450, upload, picture.Title);

            return(Ok(url.Remove(0, _hostingEnvironment.WebRootPath.Length).Replace(@"\", "/").Insert(0, "~")));
        }
Пример #29
0
        public void Execute(PictureDto request)
        {
            validator.ValidateAndThrow(request);

            var guid        = Guid.NewGuid();
            var extension   = Path.GetExtension(request.PictureSrc.FileName);
            var newFileName = guid + extension;
            var path        = Path.Combine("wwwroot", "images", newFileName);

            using (var fileStream = new FileStream(path, FileMode.Create))
            {
                request.PictureSrc.CopyTo(fileStream);
            }

            var slika = mapper.Map <Picture>(request);

            slika.PictureName = newFileName;
            context.Pictures.Add(slika);
            context.SaveChanges();
        }
Пример #30
0
        /// <summary>
        /// Creates the specified picture for the specified patient.
        /// </summary>
        /// <param name="picture">The picture.</param>
        /// <param name="patient">The patient.</param>
        public void Create(PictureDto picture, LightPatientDto forPatient)
        {
            Assert.IsNotNull(picture, "item");

            var foundPatient = (from p in this.Session.Query <Patient>()
                                where p.Id == forPatient.Id
                                select p).FirstOrDefault();

            if (foundPatient == null)
            {
                throw new ExistingItemException();
            }

            var newItem = Mapper.Map <PictureDto, Picture>(picture);

            newItem.Refresh(picture, this.Session);

            foundPatient.Pictures.Add(newItem);
            new ImageHelper().TryCreateThumbnail(foundPatient.Pictures);
            this.Session.Update(foundPatient);
        }
Пример #31
0
 protected override void Because_of()
 {
     _source = new Picture { ImageData = new byte[100] };
     _dest = Mapper.Map<Picture, PictureDto>(_source);
 }
Пример #32
0
 public GameQuestion(IList<string> answerOptions, PictureDto picture, string rightAnswer)
 {
     this.answerOptions = answerOptions;
     this.Picture = picture;
     this.rightAnswer = rightAnswer;
 }