public ActionResult Edit(AttachmentDto input, HttpPostedFileBase newFile, int courseId)
        {
            var fileName = input.AttachmentFileName;

            if (newFile != null && newFile.ContentLength > 0)
            {
                fileName = $"{input.Title.Replace(" ", string.Empty)}_{input.EmployeeId}_{DateTime.Now.ToString("ddMMyyyyhhmmsstt")}.{newFile.FileName.Split('.')[1].Trim()}";

                string root = @"C:\Attachments";

                if (!Directory.Exists(root))
                {
                    Directory.CreateDirectory(root);
                }

                root = root + "\\" + fileName;

                newFile.SaveAs(root);
            }
            input.AttachmentFileName = fileName;

            var updatedSubject = _repository.Edit(input.Id, input);

            return(RedirectToAction("Index", "Attachments", new { employeeId = input.EmployeeId, courseId = courseId }));
        }
Пример #2
0
        /// <summary>
        /// Saves the attachment to disk and updates the location <paramref name="dto"/>
        /// </summary>
        private async Task SaveAttachment(IFormFile file, long tenantId, AttachmentDto dto)
        {
            string extension       = Path.GetExtension(file.FileName);
            string actualStorePath = $"{_assetSettings.AssetStorePath}/{tenantId}";

            string assetName;
            string assetStorePath;

            do
            {
                assetName      = $"{Guid.NewGuid()}{extension}";
                assetStorePath = $"{actualStorePath}/{assetName}";
            }while (System.IO.File.Exists(assetStorePath)); // there's a chance that the same Guid was generated before

            if (!Directory.Exists(actualStorePath))
            {
                Directory.CreateDirectory(actualStorePath);
            }

            if (file.Length > 0)
            {
                using (var stream = new FileStream(assetStorePath, FileMode.Create))
                    await file.CopyToAsync(stream);
            }

            dto.Location = assetStorePath;
        }
Пример #3
0
        public AttachmentDto Insert(AttachmentInsertDto dto)
        {
            AttachmentDto attachmentDto = null;

            try
            {
                var attachment = Mapper.Map <AttachmentInsertDto, Attachment>(dto);
                attachment.CreatedBy = _appSession.GetUserName();
                attachment.IsEnabled = true;
                _unitOfWork.CreateTransaction();

                _unitOfWork.GenericRepository <Attachment>().Insert(attachment);
                _unitOfWork.Save();

                _unitOfWork.Commit();

                attachmentDto = Mapper.Map <Attachment, AttachmentDto>(attachment);
            }
            catch (Exception ex)
            {
                Tracing.SaveException(ex);
                _unitOfWork.Rollback();
            }
            return(attachmentDto);
        }
        public async Task RemoveAttachmentAsync(AttachmentDto attachmentDto)
        {
            var attachment = _mapper.Map <Attachment>(attachmentDto);
            await _uploadService.DeleteAttachment(attachment);

            await _transactionManager.SaveAllAsync();
        }
        public async Task <ResultListDto> GetAllAttachmentsAsync(AttachmentFilterDto attachmentDto)
        {
            var attachmentFilter = _mapper.Map <AttachmentFilter>(attachmentDto);

            var fileList = await _uploadService.GetFilesAsync(attachmentFilter);

            List <Attachment> attachments = (List <Attachment>)fileList.Results;

            List <AttachmentDto> attachmentDtos = new List <AttachmentDto>();

            attachments?.ForEach(x =>
            {
                AttachmentDto dto = new AttachmentDto();
                dto = _mapper.Map <AttachmentDto>(x);
                dto.AttachmentType = _mapper.Map <KeyValueDto>(x.AttachmentType);
                attachmentDtos.Add(dto);
            });

            ResultListDto finalResult = new ResultListDto()
            {
                MaxPageRows = fileList.MaxPageRows,
                TotalRows   = fileList.TotalRows,
                Results     = attachmentDtos,
            };

            return(finalResult);
        }
Пример #6
0
 private static Attachment GetAttachment(AttachmentDto attachment, long messageId) => new Attachment
 {
     Hash      = attachment.Hash,
     Payload   = attachment.Payload,
     Type      = (short)attachment.Type,
     MessageId = messageId
 };
Пример #7
0
        public static AttachmentDto GetAttachment(AttachmentVm attachment)
        {
            if (attachment.Payload == null)
            {
                return(null);
            }

            object        payload       = attachment.Payload;
            AttachmentDto attachmentDto = new AttachmentDto
            {
                Type = attachment.Type,
                Hash = attachment.Hash ?? Array.Empty <byte>()
            };

            if (payload is string strPayload)
            {
                attachmentDto.Payload = strPayload;
            }
            else if (payload is PollVm pollPayload)
            {
                attachmentDto.Payload = ObjectSerializer.ObjectToJson(new PollAttachmentInformation
                {
                    ConversationId   = pollPayload.ConversationId.GetValueOrDefault(),
                    ConversationType = pollPayload.ConversationType.GetValueOrDefault(),
                    PollId           = pollPayload.PollId.GetValueOrDefault()
                });
            }
            else
            {
                attachmentDto.Payload = ObjectSerializer.ObjectToJson(attachment.Payload);
            }
            return(attachmentDto);
        }
Пример #8
0
 private static void AddToAttachments(ICollection <AttachmentDto> result, AttachmentDto insertingAttachment)
 {
     if (insertingAttachment.Fields.Count != 0)
     {
         result.Add(insertingAttachment);
     }
 }
        public async Task <ResultListDto> GetAllFilesAsync(ICollection <IFormFile> filess)
        {
            string dtoName       = Request.Form["attachmentTypeCategoryID"];
            string attachmentDto = Request.Form["attachmentDto"];
            string filterDto     = Request.Form["filterDto"];

            AttachmentFilterDto filter = Newtonsoft.Json.JsonConvert.DeserializeObject <AttachmentFilterDto>(filterDto);
            AttachmentDto       attDto = Newtonsoft.Json.JsonConvert.DeserializeObject <AttachmentDto>(attachmentDto);


            if (dtoName == ConstAttachmentTypeCategory.Customer.ToString())
            {
                var entity = Newtonsoft.Json.JsonConvert.DeserializeObject <CustomerHeadDto>(attDto.entity.ToString());
                filter.CustomerID = entity.ID;
            }

            if (dtoName == ConstAttachmentTypeCategory.User.ToString())
            {
                var entity = Newtonsoft.Json.JsonConvert.DeserializeObject <UserDto>(attDto.entity.ToString());
                filter.UserID = entity.ID;
            }

            if (dtoName == ConstAttachmentTypeCategory.Session.ToString())
            {
                var entity = Newtonsoft.Json.JsonConvert.DeserializeObject <SessionDto>(attDto.entity.ToString());
                filter.SessionID = entity.ID;
            }

            var result = await _uploadAppService.GetAllAttachmentsAsync(filter);

            return(result);
        }
        public async Task <ResultObject> UploadUserImage([FromForm] ICollection <IFormFile> filess)
        {
            var resultobject = new ResultObject();

            var           files         = Request.Form.Files;
            string        attachmentDto = Request.Form["attachmentDto"];
            AttachmentDto attDto        = Newtonsoft.Json.JsonConvert.DeserializeObject <AttachmentDto>(attachmentDto);

            if (files.Any(f => f.Length == 0))
            {
                return(new ResultObject {
                    Result = attDto, ServerErrors = null                       /*new List<ServerErr>().Add(new ServerErr() { Hint = "هیچ فایلی فرستاده نشده است" })*/
                });
            }
            attDto.Path = await _uploadAppService.CreateDirectoryAndFile(attDto.UserID.Value, "UserDto", files[0]);

            await _uploadAppService.RemoveAllPersonImages(attDto.UserID.Value);

            attDto.AttachmentTypeID = ConstAttachmentTypes.PersonImage;
            await _uploadAppService.CreateAttachmentAsync(attDto);

            resultobject.Result       = attDto;
            resultobject.ServerErrors = null;
            return(resultobject);
        }
Пример #11
0
 /// <summary>
 /// 转换为附件实体
 /// </summary>
 /// <param name="dto">附件数据传输对象</param>
 public static Attachment ToEntity3(this AttachmentDto dto)
 {
     if (dto == null)
     {
         return(new Attachment());
     }
     return(AttachmentFactory.Create(
                attachmentId: dto.Id.ToGuid(),
                fileName: dto.FileName,
                fileType: dto.FileType,
                size: dto.Size,
                remoteUrl: dto.RemoteUrl,
                localUrl: dto.LocalUrl,
                width: dto.Width,
                height: dto.Height,
                merchantId: dto.MerchantId,
                module: dto.Module,
                creationTime: dto.CreationTime,
                creatorId: dto.CreatorId,
                lastModificationTime: dto.LastModificationTime,
                lastModifierId: dto.LastModifierId,
                isDeleted: dto.IsDeleted,
                version: dto.Version
                ));
 }
Пример #12
0
 /// <summary>
 /// 转换为附件实体
 /// </summary>
 /// <param name="dto">附件数据传输对象</param>
 public static Attachment ToEntity2(this AttachmentDto dto)
 {
     if (dto == null)
     {
         return(new Attachment());
     }
     return(new Attachment(dto.Id.ToGuid())
     {
         FileName = dto.FileName,
         FileType = dto.FileType,
         Size = dto.Size,
         RemoteUrl = dto.RemoteUrl,
         LocalUrl = dto.LocalUrl,
         Width = dto.Width,
         Height = dto.Height,
         MerchantId = dto.MerchantId,
         Module = dto.Module,
         CreationTime = dto.CreationTime,
         CreatorId = dto.CreatorId,
         LastModificationTime = dto.LastModificationTime,
         LastModifierId = dto.LastModifierId,
         IsDeleted = dto.IsDeleted,
         Version = dto.Version,
     });
 }
 public static AttachmentViewModel MapToViewModel(this AttachmentDto att)
 {
     return(new AttachmentViewModel
     {
         Name = att.Name,
         Size = Math.Round(att.SizeMb, 2)
     });
 }
Пример #14
0
 /// <summary>
 /// 转换为附件实体
 /// </summary>
 /// <param name="dto">附件数据传输对象</param>
 public static Attachment ToEntity(this AttachmentDto dto)
 {
     if (dto == null)
     {
         return(new Attachment());
     }
     return(dto.MapTo(new Attachment(dto.Id.ToGuid())));
 }
Пример #15
0
        public async Task Handle_CorrectParams_ShouldUpdateRankAndSendAnwer()
        {
            // Arrange

            var attachment = new AttachmentDto()
            {
                Actions = new List <AttachmentActionDto> {
                    new AttachmentActionDto("test", "test")
                },
            };

            var originalMessage = new OriginalMessageDto()
            {
                Text        = "testText",
                Attachments = new List <AttachmentDto> {
                    attachment
                },
                TimeStamp = It.IsAny <string>()
            };

            var actionParams = new HelpedSlackActionParams()
            {
                User = new ItemInfo
                {
                    Id   = "id",
                    Name = "Bob"
                },
                OriginalMessage = originalMessage,
                Channel         = new ItemInfo {
                    Id = "channelId", Name = "channelName"
                },
                ButtonParams = new HelpedAnswerActionButtonParams
                {
                    AnswerId   = "1234",
                    QuestionId = "1234"
                }
            };


            _questionService
            .Setup(m => m.AnswerRankUpAsync(It.IsAny <string>(), It.IsAny <string>()))
            .Returns(Task.CompletedTask);

            _slackClient
            .Setup(m => m.UpdateMessageAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <List <AttachmentDto> >()))
            .Returns(Task.CompletedTask);

            // Act
            await _handler.Handle(actionParams);

            // Assert
            _questionService.Verify(
                m => m.AnswerRankUpAsync(actionParams.ButtonParams.QuestionId, actionParams.ButtonParams.AnswerId), Times.Once);
            _questionService.VerifyNoOtherCalls();
            _slackClient.Verify(m => m.UpdateMessageAsync(actionParams.OriginalMessage.TimeStamp, actionParams.Channel.Id,
                                                          It.IsAny <string>(), It.IsAny <IList <AttachmentDto> >()));
            _slackClient.VerifyNoOtherCalls();
        }
Пример #16
0
        /// <inheritdoc/>
        public async Task <AttachmentInfoDto> SaveAttachmentAsync(AttachmentDto attachmentDto, CancellationToken cancellationToken)
        {
            var fileName = $"{Guid.NewGuid()}.{MimeTypesMap.GetExtension(attachmentDto.ContentType)}";
            var path     = GetFullFilePath(fileName);
            await File.WriteAllBytesAsync(path, attachmentDto.Data, cancellationToken);

            return(new AttachmentInfoDto()
            {
                FileKey = path
            });
        }
Пример #17
0
        public async Task DownloadFile(AttachmentDto attachment)
        {
            var response = await HttpClient.GetAsync($"{Url}/Attachment/{attachment.Id}");

            var directory = Path.Combine(Android.OS.Environment.ExternalStorageDirectory.AbsolutePath, Android.OS.Environment.DirectoryDownloads);
            var file      = Path.Combine(directory, attachment.FileName);

            var bytes = await response.Content.ReadAsByteArrayAsync();

            File.WriteAllBytes(file, bytes);
        }
Пример #18
0
 public static Attachment ToEntity(this AttachmentDto dto)
 {
     return(new Attachment
     {
         ID = dto.ID,
         Name = dto.Name,
         Description = dto.Description,
         FullPath = dto.FullPath,
         AttachmentTypeID = dto.AttachmentTypeID
     });
 }
Пример #19
0
 private static AttachmentVm GetAttachmentVm(AttachmentDto attachment, long?requestorId)
 {
     return(attachment == null
         ? null
         : new AttachmentVm
     {
         Hash = attachment.Hash,
         Type = attachment.Type,
         Payload = PayloadStringToObject(attachment.Payload, attachment.Type, requestorId).Result
     });
 }
Пример #20
0
 /// <summary>
 /// Saves the specified dto.
 /// </summary>
 /// <param name="dto">The dto.</param>
 /// <returns></returns>
 public AttachmentDto Save(AttachmentDto dto)
 {
     try
     {
         var retVal = this.dal.Save(dto.Id, dto.FileName, dto.Extension, dto.MimeType, dto.Content, dto.Product.Id).ToDto();
         return(retVal);
     }
     catch (Exception)
     {
         throw;
     }
 }
        public async Task <ResultObject> UploadFiles([FromForm] ICollection <IFormFile> filess)
        {
            var resultobject = new ResultObject();

            var           files         = Request.Form.Files;
            string        attachmentDto = Request.Form["attachmentDto"];
            string        dtoName       = Request.Form["dtoName"];
            AttachmentDto attDto        = Newtonsoft.Json.JsonConvert.DeserializeObject <AttachmentDto>(attachmentDto);

            attDto.File = files[0];

            if (files.Any(f => f.Length == 0))
            {
                return(new ResultObject {
                    Result = attDto, ServerErrors = null                       /*new List<ServerErr>().Add(new ServerErr() { Hint = "هیچ فایلی فرستاده نشده است" })*/
                });
            }

            if (attDto.AttachmentTypeID == 0)
            {
                resultobject.ServerErrors.Add(new ServerErr()
                {
                    Hint = "نوع فایل را وارد کنید"
                });
                return(resultobject);
            }

            string entity = attDto.entity.ToString();

            if (dtoName == ConstAttachmentTypeCategory.Customer.ToString())
            {
                CustomerHeadDto customerDto = Newtonsoft.Json.JsonConvert.DeserializeObject <CustomerHeadDto>(entity);
                attDto.CustomerHeadID = customerDto.ID;
                attDto.Path           = await _uploadAppService.CreateDirectoryAndFile(attDto.CustomerHeadID.Value, "CustomerDto", attDto.File);
            }

            else if (dtoName == ConstAttachmentTypeCategory.User.ToString())
            {
                UserDto userDto = Newtonsoft.Json.JsonConvert.DeserializeObject <UserDto>(entity);
                attDto.UserID = userDto.ID;
                attDto.Path   = await _uploadAppService.CreateDirectoryAndFile(attDto.UserID.Value, "UserDto", attDto.File);
            }



            await _uploadAppService.CreateAttachmentAsync(attDto);

            resultobject.Result       = attDto;
            resultobject.ServerErrors = null;

            return(resultobject);
        }
Пример #22
0
        public async Task <VarlikResult <AttachmentDto> > UploadFile(HttpPostedFile file)
        {
            var result = new VarlikResult <AttachmentDto>();

            StorageClient storageClient = StorageClient.Create();

            var createBucketResult = CreateBucket();

            if (!createBucketResult.IsSuccess)
            {
                result.Status = createBucketResult.Status;
                return(result);
            }

            var bucketName = createBucketResult.Data;
            var fileName   = IdentityHelper.Instance.TokenUser.Mail + "_" + Guid.NewGuid().ToString();
            var fileAcl    = PredefinedObjectAcl.BucketOwnerFullControl;

            try
            {
                var fileObject = await storageClient.UploadObjectAsync(
                    bucket : bucketName,
                    objectName : fileName,
                    contentType : file.ContentType,
                    source : file.InputStream,
                    options : new UploadObjectOptions {
                    PredefinedAcl = fileAcl
                }
                    );

                AttachmentDto attachmentDto = new AttachmentDto();
                attachmentDto.BucketName = bucketName;
                attachmentDto.IdFileType = file.ContentType;
                attachmentDto.Path       = fileObject.MediaLink;
                attachmentDto.FileName   = file.FileName;


                var attachmentSaveResult = await SaveAttachment(attachmentDto);

                attachmentDto.Id = attachmentSaveResult.ObjectId;

                result.Data      = attachmentDto;
                result.Data.Path = null;
                result.Status    = attachmentSaveResult.Status;
                result.ObjectId  = attachmentSaveResult.ObjectId;
                return(result);
            }
            catch (Exception e)
            {
            }
            return(result);
        }
Пример #23
0
        public virtual AttachmentDto getAttachment(string attachmentId)
        {
            ensureHistoryEnabled(Status.NOT_FOUND);

            Attachment attachment = engine.TaskService.getTaskAttachment(taskId, attachmentId);

            if (attachment == null)
            {
                throw new InvalidRequestException(Status.NOT_FOUND, "Task attachment with id " + attachmentId + " does not exist for task id '" + taskId + "'.");
            }

            return(AttachmentDto.fromAttachment(attachment));
        }
Пример #24
0
        public async Task <ActionResult <Attachment> > PostAttachment([FromBody] AttachmentDto attachmentDto)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            var attachmentToAdd = _mapper.Map <AttachmentDto, Attachment>(attachmentDto);

            _context.Attachment.Add(attachmentToAdd);
            await _context.SaveChangesAsync();

            return(CreatedAtAction("GetAttachment", new { id = attachmentToAdd.Id }, attachmentToAdd));
        }
        public async Task <JsonResult> ProcessTaskItemAssign(TaskItemAssignModel model)
        {
            SendMessageResponse rs = null;

            try
            {
                TaskItemAssignDto dto = new TaskItemAssignDto();
                //check permission

                dto = _mapper.Map <TaskItemAssignDto>(model);
                dto.IsFullControl = false;
                if (CurrentUser.HavePermission(EnumModulePermission.Task_FullControl))
                {
                    dto.IsFullControl = true;
                }
                dto.ModifiedBy   = CurrentUser.Id;
                dto.ModifiedDate = DateTime.Now;
                dto.Attachments  = new List <AttachmentDto>();
                if (Request.Files.Count > 0)
                {
                    foreach (string file in Request.Files)
                    {
                        var    fileContent = Request.Files[file];
                        byte[] document    = Utility.ReadAllBytes(fileContent);
                        string ext         = Path.GetExtension(fileContent.FileName).Replace(".", "");

                        AttachmentDto attachmentDto = new AttachmentDto()
                        {
                            Id = Guid.NewGuid(),
                            CreateByFullName = CurrentUser.FullName,
                            CreatedBy        = CurrentUser.Id,
                            CreatedDate      = DateTime.Now,
                            FileExt          = ext,
                            FileContent      = document,
                            FileName         = fileContent.FileName,
                            FileSize         = fileContent.ContentLength,
                            ProjectId        = dto.Id,
                            Source           = Entities.Source.TaskItemAssign,
                        };
                        dto.Attachments.Add(attachmentDto);
                    }
                }
                rs = await _taskItemAssignService.UpdateProcessTaskAssign(dto);
            }
            catch (Exception ex)
            {
                _loggerServices.WriteError(ex.ToString());
            }
            return(Json(rs, JsonRequestBehavior.AllowGet));
        }
Пример #26
0
        public static AttachmentDto ToDto(this Attachment e)
        {
            if (e == null)
            {
                return(null);
            }

            var res = new AttachmentDto();

            res.Id         = e.Id;
            res.Name       = e.Name;
            res.Size       = e.Size;
            res.IdResource = e.IdResource;
            return(res);
        }
        public async Task <AttachmentDto> UploadAttachment(IFormFile file, Guid guid, string comment = "")
        {
            Guard.ArgumentNotNull(file, "File cannot be null");
            Guard.ArgumentNotNull(comment, "Comment can not be null but empty");
            Guard.IsGreaterThanZero(file.Length);

            var s3FileInfo = await _awsS3Service.UploadFileAsync(_awsConfig.S3BucketForFiles, guid.ToString(), file);

            var attachmentId  = CreateAttachmentProperties(s3FileInfo, comment);
            var attachmentDto = new AttachmentDto {
                Id = attachmentId, s3File = s3FileInfo
            };

            return(attachmentDto);
        }
Пример #28
0
        public async Task AddAttachment(AttachmentDto attachmentDto, string userId)
        {
            if (attachmentDto != null)
            {
                var newAttachment = mapper.Map <Attachment>(attachmentDto);
                newAttachment.CreatorId = userId;
                await attachmentRepository.SaveAttachment(newAttachment);

                await attachmentRepository.SaveChanges();
            }
            else
            {
                throw new Exception("Error occured while saving, please try later");
            }
        }
Пример #29
0
        /// <summary>
        /// Creates the specified dto.
        /// </summary>
        /// <param name="dto">The dto.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentException">File name, extension and Content must be provided</exception>
        public AttachmentDto Create(AttachmentDto dto)
        {
            try
            {
                if (string.IsNullOrEmpty(dto.FileName) || string.IsNullOrEmpty(dto.Extension) || dto.Content.Length == 0)
                {
                    throw new ArgumentException("File name, extension and Content must be provided");
                }

                var retVal = this.dal.Create(dto.FileName, dto.Extension, dto.MimeType, dto.Content, dto.Product.Id).ToDto();
                return(retVal);
            }
            catch (Exception)
            {
                throw;
            }
        }
Пример #30
0
        private void dgAttachments_SelectionChanged(object sender, EventArgs e)
        {
            DataGridView    dg  = (DataGridView)sender;
            DataGridViewRow row = dg.CurrentRow;

            if (bsAttachments.DataSource != null)
            {
                if (dgAttachments.Rows.Count > 0)
                {
                    AttachmentDto selectedAttachment = (AttachmentDto)row.DataBoundItem;
                    if (selectedAttachment != null)
                    {
                        _selectedAttachmentDTO = selectedAttachment;
                    }
                }
            }
        }
Пример #31
0
 public AttachmentDto getDto(IList<QueryModel> qmlist)
 {
     SqlConnection cn = null;
     AttachmentDto pm = new AttachmentDto();
     try
     {
         cn = DbHelperSQL.getConnection();
         pm = dal.getDto(cn, null, qmlist);
     }
     catch (SqlException sqlex)
     {
         throw new MakeException(ExpSort.普通, sqlex.Message);
     }
     finally
     {
         DbHelperSQL.closeConnection(cn);
     }
     return pm;
 }