コード例 #1
0
ファイル: ProjectModule.cs プロジェクト: iwikimon/diplom
 public void AddFile(UserCache cache, FolderDto parentFolder ,FileDto file)
 {
     Project p = null;
     cache.CurrentProject.CopyTo(p);
     var folder = p.Folders.Where(x => x.Path == parentFolder.Path && x.Name == parentFolder.Name).First();
     folder.Files.Add(new File() {Name = file.Name, Path = file.Path});
     System.IO.File.Create(file.Path + "\\" + file.Name);
     SaveContext();
     var log = new Userlog() { Date = DateTime.Now, Message = "Создание файла " + file.Name };
     cache.Client.Userlogs.Add(log);
     cache.LogMessages.Add(log.AsDto());
     cache.StructureChanges.Add(new StructureChange(Action.Added, file));
 }
コード例 #2
0
        public IActionResult UploadFile(long?id)
        {
            try
            {
                if (HttpContext.Request.Form.Files != null &&
                    HttpContext.Request.Form.Files.Count > 0 &&
                    HttpContext.Request.Form.Files[0].Length > 0)
                {
                    var uploadFile = HttpContext.Request.Form.Files[0];
                    var file       = new FileDto
                    {
                        Filename    = Path.GetFileName(uploadFile.FileName),
                        ContentType = uploadFile.ContentType,
                        IdFolder    = id,
                        IsPublic    = Convert.ToBoolean(HttpContext.Request.Form["IsPublic"])
                    };
                    long idGroup;
                    if (long.TryParse(HttpContext.Request.Form["IdGroup"], out idGroup) &&
                        idGroup > 0)
                    {
                        file.IdGroup = idGroup;
                    }

                    byte[] content;
                    using (var fileStream = uploadFile.OpenReadStream())
                        using (var ms = new MemoryStream())
                        {
                            fileStream.CopyTo(ms);
                            content = ms.ToArray();
                        }
                    using (var srv = ServicesFactory.File)
                        srv.Create(SecurityToken, file, content);
                }
            }
            catch (FileSharingException e)
            {
                _logger.LogError(e.Message);
                return(BadRequest(_localizer[e.Code].Value));
            }
            return(Ok());
        }
コード例 #3
0
        public async Task <PreparedFileVm> PrepareFileUpload(UploadFilesVm files)
        {
            var preparedFiles = new List <FileVm>();

            foreach (var file in files.Files)
            {
                // create file dto
                var fileId       = Guid.NewGuid();
                var fileMetadata = new FileDto
                {
                    Id         = fileId,
                    ItemId     = files.ItemId,
                    Name       = file.Name,
                    Size       = file.Size,
                    Status     = FileStatus.Uploading,
                    Type       = file.Type,
                    UploadedBy = files.UploadedBy,
                    UploadedOn = DateTime.Now,
                    UploaderId = files.UploaderId
                };

                preparedFiles.Add(new FileVm
                {
                    Id   = fileId,
                    Name = file.Name,
                    Size = file.Size,
                    Type = file.Type
                });

                await _context.Attachments.AddAsync(fileMetadata);
            }
            await _context.SaveChangesAsync();

            var sas = await _blobStorageService.GetContainerSasUri("sas");

            return(new PreparedFileVm
            {
                Files = preparedFiles,
                SasToken = sas
            });
        }
コード例 #4
0
        public FileDto DownloadWebLogs()
        {
            //Create temporary copy of logs
            var tempLogDirectory = CopyAllLogFilesToTempDirectory();
            var logFiles         = new DirectoryInfo(tempLogDirectory).GetFiles("*.txt", SearchOption.TopDirectoryOnly).ToList();

            //Create the zip file
            var zipFileDto        = new FileDto("WebSiteLogs.zip", MimeTypeNames.ApplicationZip);
            var outputZipFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, zipFileDto.FileToken);

            using (var outputZipFileStream = File.Create(outputZipFilePath))
            {
                using (var zipStream = new ZipOutputStream(outputZipFileStream))
                {
                    zipStream.IsStreamOwner = true; // Makes the Close also Close the underlying stream

                    foreach (var logFile in logFiles)
                    {
                        var logZipEntry = new ZipEntry(logFile.Name)
                        {
                            DateTime = logFile.LastWriteTime,
                            Size     = logFile.Length
                        };

                        zipStream.PutNextEntry(logZipEntry);

                        using (var fs = new FileStream(logFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan))
                        {
                            StreamUtils.Copy(fs, zipStream, new byte[4096]);
                        }

                        zipStream.CloseEntry();
                    }
                }
            }

            //Delete temporary copied logs
            Directory.Delete(tempLogDirectory, true);

            return(zipFileDto);
        }
コード例 #5
0
        // POST api/<controller>
        public HttpResponseMessage Post(FileDto fileDto)
        {
            if (fileDto != null)
            {
                try
                {
                    FileVO fileVO = null;
                    //檢查是否有ServerId 有的話把狀態改成刪除, 重新建立一筆
                    if (fileDto.ServerId != 0)
                    {
                        FileVO oldFileVO = m_PostFileService.GetFileById(fileDto.ServerId);
                        if (oldFileVO != null)
                        {
                            oldFileVO.NeedUpdate = false;
                            oldFileVO.Flag       = 0;
                            oldFileVO.UpdateId   = "系統API";
                            m_PostFileService.UpdateFile(oldFileVO);
                        }
                    }

                    fileVO            = new FileVO(fileDto);
                    fileVO.FileId     = 0;
                    fileVO.ServerId   = 0;
                    fileVO.NeedUpdate = false;
                    fileVO.UpdateId   = "系統API";
                    FixTimeZone(fileVO);
                    fileVO          = m_PostFileService.CreateFile(fileVO);
                    fileVO.ServerId = fileVO.FileId;

                    return(Request.CreateResponse <FileDto>(HttpStatusCode.Created, new FileDto(fileVO)));
                }
                catch (Exception ex)
                {
                    return(Request.CreateResponse(HttpStatusCode.NoContent, ex.ToString()));
                }
            }
            else
            {
                return(Request.CreateResponse(HttpStatusCode.NoContent));
            }
        }
コード例 #6
0
ファイル: FilesController.cs プロジェクト: lexog26/Explora
        public async Task <IActionResult> Create(string scientificName, IFormFile androidFile, IFormFile iosFile, string description,
                                                 IFormFile image, string collection)
        {
            try
            {
                int?collectionId = null;
                if (!string.IsNullOrEmpty(collection))
                {
                    collectionId = (await _collectionService.GetCollectionsByNameAsync(collection)).First().Id;

                    //Create Android dto
                    var androidDto = new FileDto
                    {
                        Name           = androidFile != null ? androidFile.FileName : "",
                        ScientificName = scientificName,
                        Description    = description,
                        CollectionId   = collectionId,
                        Platform       = Platform.Android
                    };

                    //Create IOs dto
                    var iosDto = new FileDto
                    {
                        Name           = iosFile != null ? iosFile.FileName : "",
                        ScientificName = scientificName,
                        Description    = description,
                        CollectionId   = collectionId,
                        Platform       = Platform.IOs
                    };

                    await CreateFileAsync(androidDto, image, androidFile);
                    await CreateFileAsync(iosDto, image, iosFile);
                }

                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception e)
            {
                throw e;
            }
        }
コード例 #7
0
        public async Task <IActionResult> GetLicensePicture()
        {
            var driverId = User.Claims.FirstOrDefault(c => c.Type == Helpers.Constants.Strings.JwtClaimIdentifiers.DriverId)?.Value;

            var driver = _usersRepository.GetDriverById(Guid.Parse(driverId));

            if (driver?.DriverLicense == null)
            {
                return(NotFound());
            }

            FileDto res = await _uploadService.GetObjectAsync(driver.DriverLicense.ImageId);

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

            res.Stream.Seek(0, SeekOrigin.Begin);
            return(File(res.Stream, res.ContentType));
        }
コード例 #8
0
        public async Task <IActionResult> GetProfilePicture()
        {
            var uid = User.Claims.FirstOrDefault(c => c.Type == Helpers.Constants.Strings.JwtClaimIdentifiers.Id)?.Value;

            var user = await _userManager.Users.Include(o => o.ProfilePicture).FirstOrDefaultAsync(p => p.Id == uid);

            if (user?.ProfilePicture == null)
            {
                return(NotFound());
            }

            FileDto res = await _uploadService.GetObjectAsync(user.ProfilePicture?.Id);

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

            res.Stream.Seek(0, SeekOrigin.Begin);
            return(File(res.Stream, res.ContentType));
        }
コード例 #9
0
        protected FileDto CreateExcelPackage(string templateFile, DataSet dataSet, string reportName)
        {
            //
            var file = new FileDto(reportName, MimeTypeNames.ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet);

            var designer = new WorkbookDesigner {
                Workbook = new Workbook(templateFile)
            };

            //Set data row
            designer.SetDataSource(dataSet);
            designer.Process();

            MemoryStream excelStream = new MemoryStream();

            designer.Workbook.Save(excelStream, SaveFormat.Xlsx);

            _tempFileCacheManager.SetFile(file.FileToken, excelStream.ToArray());

            return(file);
        }
コード例 #10
0
        public async Task <IActionResult> ImagePut(
            string id,
            [FromBody] FileDto model
            )
        {
            var fileName = model.UniqueName;
            var filePath = $"{_hostingEnvironment.WebRootPath}\\Uploads\\{fileName}";

            using (var ms = model.ReadAsStream())
                using (var file = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    await ms.CopyToAsync(file);
                }

            await _userService.PartialUpdate(id, new UserPartialDto
            {
                Image = fileName
            });

            return(NoContent());
        }
コード例 #11
0
        public async Task <FileDto> UploadFileAsync()
        {
            var file = Request.Form.Files.FirstOrDefault();

            if (file == null)
            {
                throw new Exception("No file has been requested");
            }

            FileRequest fileRequest = new FileRequest
            {
                FileName    = file.FileName,
                FileContent = await ReadContent(file)
            };

            File uploadedFile = await fileService.UploadFileAsync(fileRequest);

            FileDto response = FileMapper.MapFileToDto(uploadedFile);

            return(response);
        }
コード例 #12
0
        public IActionResult AddImages([FromForm] FileDto fileDto)
        {
            var file       = fileDto.File;
            var productId  = Convert.ToInt32(fileDto.productId);
            var folderName = Path.Combine("Resources", "Images");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);


            if (file.Length > 0)
            {
                var result = _productService.UploadImage(productId, file, folderName, pathToSave);

                if (result.IsSuccess)
                {
                    return(Ok(new { Message = result.Message }));
                }
                return(BadRequest(new { Message = result.Message }));
            }

            return(BadRequest("Dosya Yok"));
        }
コード例 #13
0
        /// <summary>
        /// 获取文件类型
        /// </summary>
        /// <param name="fileClass"></param>
        /// <returns></returns>
        private FileDto GetFilter(string fileClass)
        {
            FileDto file = new FileDto();

            if (fileClass == FileEnum.JsonFiles)
            {
                file.Filter    = "Json文件|*.json";
                file.Extension = new string[] { ".json" };
            }
            else if (fileClass == FileEnum.XMLFiles)
            {
                file.Filter    = "XML文件|*.xml";
                file.Extension = new string[] { ".xml" };
            }
            else if (fileClass == FileEnum.ExcelFiles)
            {
                file.Filter    = "Excel文件|*.xlsx;*.xls";
                file.Extension = new string[] { ".xlsx", ".xls" };
            }
            return(file);
        }
コード例 #14
0
        public async Task <IHttpActionResult> CreateFile()
        {
            if (!Request.Content.IsMimeMultipartContent())
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            //Recupero il provider multipart
            //var provider = MultipartHelper.GetFromDataStreamProviderAsync(Path.GetTempPath());
            var provider = MultipartHelper.GetFromDataStreamProviderAsync("~/App_data/temp");

            await Task.Run(async() => await Request.Content.ReadAsMultipartAsync(provider));

            FileDto dto        = new FileDto();
            Guid?   registryId = null;

            if (provider.FormData.Get("registryId") != null)
            {
                registryId = new Guid(provider.FormData.Get("registryId"));
            }
            dto.Name             = provider.FormData.Get("name");
            dto.Size             = provider.FormData.Get("size");
            dto.Type             = provider.FormData.Get("type");
            dto.FilepathBodypart = provider.FileData != null && provider.FileData.Count > 0
                ? provider.FileData[0].LocalFileName
                : string.Empty;

            var oResult = _fileService.CreateFile(dto, registryId);

            if (oResult.HasErrors())
            {
                Log4NetConfig.ApplicationLog.Warn(string.Format("Errore durante l'upload di un File. Id: {0} - Errore: {1}",
                                                                dto?.Id, oResult.GetValidationErrorsInline(" - ")));
                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, oResult)));
            }

            dto = Mapper.Map <FileDto>(oResult.ReturnedValue);

            return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, dto)));
        }
コード例 #15
0
ファイル: LocalStorage.cs プロジェクト: Drekus/TestMovieSite
        public OperationResult <string> TryUploadFile(FileDto fileDto)
        {
            try
            {
                var currentDirectory = Directory.GetCurrentDirectory();
                var storageDirectory = Path.Combine(currentDirectory, "wwwroot", StoragePath);
                if (!Directory.Exists(storageDirectory))
                {
                    Directory.CreateDirectory(storageDirectory);
                }
                var filePath = Path.Combine(storageDirectory, fileDto.UniqueName);
                //код для работы м директориями можно убрать заменив точным путем к хранилищу, но тогда для запуска на новой машине нужно было бы создававть вручную директории

                var i = 1;
                while (File.Exists($"{filePath}.{fileDto.Extension}"))
                {
                    filePath = filePath + i++;
                }

                using var fStream = new FileStream($"{filePath}.{fileDto.Extension}", FileMode.OpenOrCreate);
                fStream.Write(fileDto.FileData, 0, fileDto.FileData.Length);

                var relativePath = Path.Combine("\\", StoragePath, $"{fileDto.UniqueName}.{fileDto.Extension}");
                return(new OperationResult <string>(data: relativePath, isSuccess: true));

                // Что нужно улучшить:
                // Сейчас этот метод возвращает точный путь к файлу на внутри wwwroot.
                // Просто возвратом пути к фалу можно ограничится при использовании облачных хранилищ
                // Для локального хотел еще реализовать возращение относительной ссылки виды "/getfile/{тип хранилиша}/{имя файла}"
                // По этой ссылке отрабатывал бы метод FileController.GetFile, который бы использовал FileService.GetFile, возвращающий byte[]
                // Также можно добавить  сжатие картинок до заданного разрешения и отдельно маленькие превью, которые показывать при отображении списка фильмов
                // Реализовать могу, но потребует еще времени, которого я и так на тестовое достаточно потратил.
                // При этом каких-то ВАУ-штук код бы не содержал
            }
            catch (Exception e)
            {
                _logger.LogError(e, "Failed to upload file.");
                return(new OperationResult <string>(data: null, isSuccess: false));
            }
        }
コード例 #16
0
        public async Task <FileInfo> Execute(FileDto search)
        {
            var containerClient = _blobServiceClient.GetBlobContainerClient("code");
            var blobList        = containerClient
                                  .GetBlobs(BlobTraits.All)
                                  .Where(p => p.Metadata["project"].ToString().ToLower() == search.ProjectName.ToLower())
                                  .OrderByDescending(p => p.Properties.LastModified)
                                  .ToList();

            if (blobList.Count() == 0)
            {
                throw new Exception("not exist");
            }
            var blobClient       = containerClient.GetBlobClient(blobList[0].Name);
            var blobDownloadInfo = await blobClient.DownloadAsync();

            return(new FileInfo
            {
                Content = blobDownloadInfo.Value.Content,
                ContentType = blobDownloadInfo.Value.ContentType
            });
        }
コード例 #17
0
 public BlobDto DownloadBlobsData(FileDto fileDto)
 {
     //var accessToken = GetApiAccessTokenAsync();
     using (var httpClient = new HttpClient())
     {
         //httpClient.SetBearerToken(accessToken);
         httpClient.BaseAddress = new Uri(Configuration.ServerUrl);
         var request  = new HttpRequestMessage(HttpMethod.Get, fileDto.Url);
         var response = httpClient.SendAsync(request).GetAwaiter().GetResult();
         if (response.IsSuccessStatusCode)
         {
             var stream = response.Content.ReadAsStreamAsync().GetAwaiter().GetResult();
             return(new BlobDto
             {
                 Name = fileDto.Name,
                 Extension = fileDto.Extension,
                 Data = stream
             });
         }
         return(null);
     }
 }
コード例 #18
0
        private void importProductsFromFileToolStripMenuItem_Click(object sender, System.EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.Filter = "Excel Files|*.xls;*.xlsx;*.xlsm";

            if (openFileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }

            byte[] array = File.ReadAllBytes(openFileDialog.FileName);

            FileDto fileDto = new FileDto
            {
                FileName       = openFileDialog.SafeFileName,
                FileLength     = array.Length,
                FileByteStream = array
            };

            _productServiceClient.ImportProducts(fileDto);
        }
コード例 #19
0
        public async Task <FileDto> SaveFile(Guid entityId, string fileName, byte[] data)
        {
            var fullPath = Path.Combine(root, entityId.ToString(), fileName);
            var dir      = Path.GetDirectoryName(fullPath);

            if (Directory.Exists(dir) == false)
            {
                Directory.CreateDirectory(dir);
            }
            using (FileStream fs = new FileStream(fullPath, FileMode.Create)) {
                await fs.WriteAsync(data, 0, data.Length);
            }

            var dto = new FileDto()
            {
                ParentId = entityId,
                FileName = fileName,
                Size     = data.Length,
            };

            return(dto);
        }
コード例 #20
0
        public async Task <UploadResponse> Handle(UploadFilesCommand request, CancellationToken cancellationToken)
        {
            // Step 1: Gets parameters from request
            Dictionary <string, StringValues> parameters = request.UploadResponse.FormAccumulator.GetResults();

            // Step 2: Validates request
            if (request.UploadResponse.Files == null)
            {
                return(new UploadResponse());
            }

            // Step 3: Creates upload folder if not existed
            CreateUploadFolderIfNotExisted(GetAssetType(parameters));

            // Step 4: Creates returned object
            var result = new UploadResponse
            {
                Messages = request.UploadResponse.Messages,
                Files    = new List <FileDto>(),
                Status   = true
            };

            // Step 5: Processing for all uploaded files
            foreach (var fileUploadResponse in request.UploadResponse.Files)
            {
                FileDto fileToAdd = await GetFileDto(parameters, fileUploadResponse);

                bool requestStatus = await ValidateAndAddFileAsync(result, fileToAdd);

                if (!requestStatus)
                {
                    request.UploadResponse.Status = requestStatus;
                }
            }

            // Step 6: Sets response status and returns object
            result.Status = request.UploadResponse.Status;
            return(result);
        }
コード例 #21
0
        /// <param name="service">Drive API service instance.</param>
        /// <param name="title">Title of the file to insert, including the extension.</param>
        /// <param name="description">Description of the file to insert.</param>
        /// <param name="parentId">Parent folder's ID.</param>
        /// <param name="mimeType">MIME type of the file to insert.</param>
        public List <FileDto> InsertFile(DriveService service, string parentId, IFormFileCollection formFiles)
        {
            List <FileDto> listFileDtoResponse = new List <FileDto>();

            try
            {
                if (formFiles.Count > Constant.Zero)
                {
                    var listFileDto = _objFiles.ToByteArrayAsync(formFiles, parentId).Result;

                    for (int i = Constant.Zero; i < listFileDto.FileListDto.Count; i++)
                    {
                        var objFile  = listFileDto.FileListDto[i];
                        var byteFile = listFileDto.ListByteDto[i];
                        System.IO.MemoryStream          stream  = new System.IO.MemoryStream(byteFile);
                        FilesResource.CreateMediaUpload request = service.Files.Create(objFile, stream, objFile.MimeType);
                        request.Upload();

                        var fileExtension = _objFiles.TransformDocNameIntoStringTypeFile(request.ResponseBody.Name);
                        if (null != fileExtension)
                        {
                            var fileDto = new FileDto()
                            {
                                IdDto       = request.ResponseBody.Id,
                                NameDto     = request.ResponseBody.Name,
                                MimeTypeDto = request.ResponseBody.MimeType,
                                UrlDto      = fileExtension + request.ResponseBody.Id
                            };
                            listFileDtoResponse.Add(fileDto);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.Error(ex.StackTrace);
            }
            return(listFileDtoResponse);
        }
コード例 #22
0
        public IActionResult Post([FromForm] FileDto dto)
        {
            var guid      = Guid.NewGuid();
            var extension = Path.GetExtension(dto.Image.FileName);

            var newFileName = guid + extension;

            try
            {
                var path = Path.Combine("wwwroot", "images", newFileName);

                using (var fileStream = new FileStream(path, FileMode.Create))
                {
                    dto.Image.CopyTo(fileStream);
                }
                return(Ok(path));
            }
            catch (Exception e)
            {
                return(StatusCode(500));
            }
        }
コード例 #23
0
        public async Task UpdateAsync(FileDto file)
        {
            try
            {
                File puttingFile = await _fileRepo.GetAsync(file.ID) ?? throw new EntityNotFoundException(file.ID);

                IO.File.Delete(puttingFile.ToString());
                FileDescriptor fileDesc = new FileDescriptor(file, _env);

                puttingFile.FileName  = fileDesc.Name;
                puttingFile.Path      = fileDesc.Path;
                puttingFile.Extension = fileDesc.Extension;

                await fileDesc.Override(puttingFile);

                await _fileRepo.ModifyAsync(puttingFile, file.ID);
            }
            catch (Exception)
            {
                throw;
            }
        }
コード例 #24
0
        public async Task <FileDto> CreateFileAsync(FileDto fileDto, string token)
        {
            if (fileDto == null)
            {
                throw new ArgumentNullException(nameof(fileDto));
            }

            var ownerId = _factory.GetUserIdClaim(token);

            var entity     = _mapper.Map <FileDto, File>(fileDto);
            var statistics = _mapper.Map <FileDto, FileStatistics>(fileDto);

            entity.UserId = ownerId;

            var result = _unitOfWork.FileRepository.Add(entity);

            _unitOfWork.FileStatisticsRepository.Add(statistics);

            await _unitOfWork.SaveAsync();

            return(_mapper.Map <File, FileDto>(result));
        }
コード例 #25
0
        /// <summary>
        /// 导出文章
        /// </summary>
        public async Task <FileDto> GetArticleInfosToExcel(GetArticleInfosInput input)
        {
            async Task <List <ArticleInfoExportDto> > getListFunc(bool isLoadSoftDeleteData)
            {
                var query   = CreateArticleInfosQuery(input);
                var results = await query
                              .OrderBy(input.Sorting)
                              .ToListAsync();

                var exportListDtos = results.MapTo <List <ArticleInfoExportDto> >();

                if (exportListDtos.Count == 0)
                {
                    throw new UserFriendlyException(L("NoDataToExport"));
                }

                return(exportListDtos);
            }

            List <ArticleInfoExportDto> exportData = null;

            //是否仅加载回收站数据
            if (input.IsOnlyGetRecycleData)
            {
                using (UnitOfWorkManager.Current.DisableFilter(AbpDataFilters.SoftDelete))
                {
                    exportData = await getListFunc(true);
                }
            }

            exportData = await getListFunc(false);

            var fileDto   = new FileDto(L("ArticleInfo") + L("ExportData") + ".xlsx", MimeTypeNames.ApplicationVndOpenxmlformatsOfficedocumentSpreadsheetmlSheet);
            var byteArray = await _excelExporter.ExportAsByteArray(exportData);

            _tempFileCacheManager.SetFile(fileDto.FileToken, byteArray);
            return(fileDto);
        }
コード例 #26
0
        public FileDto DownloadWebLogs()
        {
            var zipFileDto        = new FileDto("WebSiteLogs.zip", MimeTypeNames.ApplicationZip);
            var outputZipFilePath = Path.Combine(_appFolders.TempFileDownloadFolder, zipFileDto.FileToken);

            using (var outputZipFileStream = File.Create(outputZipFilePath))
            {
                using (var zipStream = new ZipOutputStream(outputZipFileStream))
                {
                    var directory = new DirectoryInfo(_appFolders.WebLogsFolder);
                    var logFiles  = directory.GetFiles("*.txt", SearchOption.AllDirectories).ToList();

                    foreach (var logFile in logFiles)
                    {
                        var logFileInfo = new FileInfo(logFile.FullName);
                        var logZipEntry = new ZipEntry(logFile.Name)
                        {
                            DateTime = logFileInfo.LastWriteTime,
                            Size     = logFileInfo.Length
                        };

                        zipStream.PutNextEntry(logZipEntry);

                        using (var fs = new FileStream(logFile.FullName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite, 0x1000, FileOptions.SequentialScan))
                        {
                            StreamUtils.Copy(fs, zipStream, new byte[4096]);
                        }

                        zipStream.CloseEntry();
                    }

                    // Makes the Close also Close the underlying stream
                    zipStream.IsStreamOwner = true;
                }
            }

            return(zipFileDto);
        }
コード例 #27
0
 public void Setup()
 {
     _stubFileDto = new FileDto
     {
         Id         = Guid.Parse("aada6f2a-8854-4a5e-a907-2244f43408a1"),
         ItemId     = Guid.Parse("5eb09b45-9c70-4465-b62d-535e28b16aed"),
         Name       = "Stub file",
         Size       = 25424,
         Status     = Models.ViewModels.FileStatus.Uploading,
         Type       = "Image/PNG",
         UploadedBy = "Stub test",
         UploadedOn = DateTime.Now,
         UploaderId = Guid.Parse("aada6f2a-8854-4a5e-a907-2244f43408a1"),
     };
     _stubFiles = new UploadFilesVm
     {
         Files = new System.Collections.Generic.List <FileMetadataVm>
         {
             new FileMetadataVm
             {
                 Name = "Stub file metadata",
                 Size = 1000,
                 Type = "Image/PNG"
             }
         },
         ItemId     = Guid.Parse("aada6f2a-8854-4a5e-a907-2244f43408a2"),
         UploadedBy = "Stub tester",
         UploaderId = Guid.Parse("aada6f2a-8854-4a5e-a907-2244f43408a3"),
     };
     _stubStatusUpdate = new UpdateStatusVm
     {
         Id     = Guid.Parse("aada6f2a-8854-4a5e-a907-2244f43408a1"),
         Status = FileStatus.Uploaded,
     };
     _mockBlobStorageService = new Mock <IBlobStorageService>();
     _mockLogger             = new Mock <ILogger <AttachmentsRepository> >();
     _attachmentsRepository  = new AttachmentsRepository(GetInMemoryContextWithSeedData(), _mockBlobStorageService.Object, _mockLogger.Object);
 }
コード例 #28
0
        private async Task <IList <FileDto> > FetchFileDtos(IList <MediaDto> mediaDtos, CancellationToken token, [CanBeNull] IProgressListener progressListener)
        {
            var fileManager = IoCManager.Resolve <IMediaFileManager>();
            var files       = new List <FileDto>();

            foreach (var mediaDto in mediaDtos)
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }

                var mediaId        = mediaDto.Id;
                var mediaTimestamp = mediaDto.Timestamp;
                if (await fileManager.ContainsMedia(mediaId, mediaTimestamp))
                {
                    Debug.WriteLine($"Skipped download of already present file with id {mediaId}");
                    continue;
                }

                FileDto file;
                try
                {
                    file = await fileApiAccess.GetFile(mediaId);
                }
                catch (NotFoundException)
                {
                    file = new FileDto {
                        Data = BackupData.BackupImageData, MediaId = mediaId
                    };
                }

                files.Add(file);
                progressListener?.ProgressOneStep();
            }

            return(files);
        }
コード例 #29
0
ファイル: ProfileControllerBase.cs プロジェクト: war-man/GEC
        public bool UploadUserFaceMap(FileDto input)
        {
            try
            {
                var profilePictureFile = Request.Form.Files.First();
                if (profilePictureFile == null)
                {
                    throw new UserFriendlyException(L("ProfilePicture_Change_Error"));
                }

                byte[] fileBytes;
                using (var stream = profilePictureFile.OpenReadStream())
                {
                    fileBytes = stream.GetAllBytes();
                }

                return(true);
            }
            catch (Exception ex)
            {
                return(false);
            }
        }
コード例 #30
0
        public FileDto Export([FromQuery] string buildingId)
        {
            var listFloors = this.floorService.GetByBuildingID(buildingId);

            var floorTable = this.GetFloorTable(listFloors);

            var floorTemplate = Excel.CreateTemplate <Floor_Template>();

            floorTemplate.SetBuildingId(buildingId);
            floorTemplate.SetTableData(floorTable, "DANH SÁCH TẦNG NHÀ");

            this.excel.Serialize(floorTemplate);

            //Stream stream = this.excel.Write();
            string  fileName = $"Floors_{buildingId}.xlsx";
            FileDto file     = new FileDto(fileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            string  path     = Path.Combine(this.appFolders.TempFileDownloadFolder, file.FileToken);

            this.excel.SaveFile(path, out string error);
            this.excel.Close();

            return(file);
        }
コード例 #31
0
ファイル: FileService.cs プロジェクト: adjanybekov/Emlak24
        public List <FileDto> GetProfilePicture(string userId)
        {
            var list = new List <FileDto>();
            var user = _dbContext.Users.Find(userId);

            if (user?.Avatar != null)
            {
                var userAvatar = user.Avatar;
                var picture    = new FileDto
                {
                    Name         = userAvatar.Name,
                    Id           = userAvatar.Id,
                    Length       = userAvatar.ContentLengthInBytes,
                    FileUrl      = userAvatar.RelativePath,
                    ThumbnailUrl = userAvatar.ThumbnailPath,
                    Filetype     = userAvatar.Filetype,
                    Mime         = userAvatar.Mime,
                    Extension    = userAvatar.Extension
                };
                list.Add(picture);
            }
            return(list);
        }
コード例 #32
0
ファイル: ProjectModule.cs プロジェクト: iwikimon/diplom
 public void RemoveFile(UserCache cache, FileDto file)
 {
     Project p = null;
     cache.CurrentProject.CopyTo(p);
     foreach(var folder in p.Folders)
     {
         var f = folder.Files.Where(x => x.Path == file.Path && x.Name == file.Name);
         if(f.Count() > 0)
         {
             folder.Files.Remove(f.First());
             System.IO.File.Delete(file.Path+"\\"+file.Name);
             SaveContext();
             return;
         }
     }
     SaveContext();
     var log = new Userlog() {Date = DateTime.Now, Message = "Удаление файла " + file.Name};
     cache.Client.Userlogs.Add(log);
     cache.LogMessages.Add(log.AsDto());
     cache.StructureChanges.Add(new StructureChange(Action.Removed,file));
 }