public BaseResponse Add(AudioFile newTrack) { return(DoSuccess(() => { _repo.Add(newTrack); })); }
public async Task <IActionResult> Create([FromBody] File item) { if (item == null) { return(BadRequest()); } var parent = _folderRepository.Find(item.ParentID); if (parent == null) { return(BadRequest()); } var userId = _userManager.GetUserId(HttpContext.User); if (!_permissionServices.HasWriteAccess(parent.ProjectID, userId)) { return(Unauthorized()); } else { _fileRepository.Add(item); await _fileHandler.Add(item.Id, item.Name, item.Content, item.Syntax, item.ParentID, parent.ProjectID); return(CreatedAtAction("GetFile", new { id = item.Id }, item)); } }
public ActionResult Action(tblFile objSubmit) { if (System.IO.File.Exists(Server.MapPath(ConfigWeb.TempPath + objSubmit.FileName))) { objSubmit.Size = new System.IO.FileInfo(Server.MapPath(ConfigWeb.TempPath + objSubmit.FileName)).Length; FileUtility.MoveFile(StaticEnum.FileType.File, objSubmit.FileName); } if (objSubmit.ID == 0) { objSubmit.DateCreated = DateTime.Now; objSubmit.DateUpdated = DateTime.Now; objSubmit.IsDeleted = false; objSubmit.IsShow = true; fileRepository.Add(objSubmit); } else { var obj = fileRepository.GetById <tblFile>(objSubmit.ID); UpdateModel(obj); objSubmit.DateUpdated = DateTime.Now; fileRepository.Update(obj); } return(Json(new { Error = false }, JsonRequestBehavior.AllowGet)); }
public async Task <FileAddResponse> AddFiles(string email, IFormFile file) { var user = await _userService.FindUserByEmailAsync(email); FileRecord fileRecord = new FileRecord(); var filePath = _env.ContentRootPath; var docName = Path.GetFileName(file.FileName); var fileType = Path.GetExtension(file.FileName); if (file != null && file.Length > 0) { fileRecord.Id = Guid.NewGuid(); fileRecord.Name = docName; fileRecord.Type = fileType; fileRecord.Path = Path.Combine(filePath, "Files", fileRecord.Id.ToString() + fileRecord.Type); fileRecord.Owner = user; fileRecord.OwnerID = user.Id; using (var stream = new FileStream(fileRecord.Path, FileMode.Create)) { await file.CopyToAsync(stream); } _fileRepository.Add(fileRecord); return(new FileAddResponse(true, null)); } else { return(new FileAddResponse(false, "Something is wrong with your file")); } }
public Model.FileInfo UploadFile(Model.File file) { var sourceStream = file.Stream; var buffer = new Byte[FileHelper.DefaultBufferSize]; using (var memoryStream = new MemoryStream()) { int read; while ((read = sourceStream.Read(buffer, 0, buffer.Length)) > 0) { memoryStream.Write(buffer, 0, read); } file.Data = memoryStream.ToArray(); memoryStream.Close(); sourceStream.Close(); } _fileRepository.Add(file); _fileRepository.Save(); return(file.Info); }
public ActionResult Add(HttpPostedFileBase upload) { if (upload != null) { string pathFile = "~/Files/" + User.Identity.Name + "/"; string pathIco = "~/Files/Ico/" + User.Identity.Name + "/"; if (!Directory.Exists(Server.MapPath(pathFile))) { Directory.CreateDirectory(Server.MapPath(pathFile)); } if (!Directory.Exists(Server.MapPath(pathIco))) { Directory.CreateDirectory(Server.MapPath(pathIco)); } string filename = Path.GetFileName(upload.FileName); upload.SaveAs(Server.MapPath(pathFile + filename)); Icon extractedIcon = Icon.ExtractAssociatedIcon(Server.MapPath(pathFile + filename)); string icostr = filename; string v = Path.GetExtension(filename); icostr = icostr.Replace(v, "") + ".jpg"; Bitmap bitmap = extractedIcon.ToBitmap(); bitmap.Save(Server.MapPath(pathIco + icostr)); icostr = "Files/Ico/" + User.Identity.Name + "/" + icostr; string path = "Files/" + User.Identity.Name + "/" + filename; DateTime date = DateTime.Now; int author = _authProvider.SearchUser(User.Identity.Name); _fileRepositoty.Add(filename, date, author, icostr, path); } return(RedirectToAction("Index")); }
public void UploadFiles(int userId, int?folderId, IEnumerable <FileUploadDTO> files) { var user = _users.GetById(userId); folderId = folderId.HasValue ? folderId : user.Folder.Id; var folder = _folders.GetById(folderId.Value); foreach (var file in files) { //переделать под automapper File generatedFile = new File() { Folder = folder, CreationTime = DateTime.Now, Name = System.IO.Path.GetFileNameWithoutExtension(file.FileName), Ext = System.IO.Path.GetExtension(file.FileName), Size = file.Data.Length, Visibility = FileAccess.Private }; StringBuilder sb = new StringBuilder(); sb.Append(generatedFile.Name); sb.Append(generatedFile.Size * 31); sb.Append(generatedFile.Ext); //нужно добавить, как закончу, т.к. ну или нет, надо подумать //sb.Append(generatedFile.Folder.Name); sb.Append(generatedFile.CreationTime.ToString()); generatedFile.Hash = _hash.Hash(sb.ToString()); _files.Add(generatedFile); _storage.UploadFile(user, generatedFile, file.Data); _files.SaveChanges(); } }
public int Create(RegisterFileDTO FileDto) { try { var file = new File(); if (FileDto == null) { return(0); } file.Name = FileDto.Name; file.Type = FileDto.Type; file.PublishDate = DateTime.Now; file.IsDelete = false; file.Size = Convert.ToDouble(FileDto.Size); file.Description = FileDto.Description; file.UserId = FileDto.UserId; _fileRepository.Add(file); return(file.Id); } catch (RepositoryException re) { throw new ServiceException("Repository ex: " + re.Message); } catch (Exception ex) { throw new ServiceException(ex.Message); } }
public async Task <long> Upload(FileVm vm) { Throw.IfNull(vm, nameof(vm)); var fileMetadata = _fileProvider.GetMetadata(vm.Content); var entity = _mapper.Map <FileEntity>(vm); entity.CreatedOn = _time.Now; entity.Type = fileMetadata.Type; Func <Task <long> > func = new Func <Task <long> >(async() => { _repository.Add(entity); await _repository.SaveChanges(); foreach (FieldVm f in fileMetadata.Fields) { var fieldEntity = _mapper.Map <FieldEntity>(f); fieldEntity.FileId = entity.Id; _fieldsRepository.Add(fieldEntity); } await _fieldsRepository.SaveChanges(); return(entity.Id); }); return(await ExecuteInTransaction(func)); }
private void AddFilesToDatabase(DvdFolderToImport dvdFolder) { if (!dvdFolder.IsReadyToImport) // throw a NotReadyToImportException or something { } fileRepository.Add(dvdFolder.Files); }
public void SortAllNames(string[] allNames) { var unsortedNames = GetAllNames(allNames); var sortedNames = SortName(unsortedNames); nameRepository.Add(sortedNames.ToArray()); }
public async Task <ICommandResult> Handle(ImageAddCommand mesage) { try { var shard = await _shardingService.GetCurrentWriteShardByYear(ShardGroup); File file = new File(shard.Id); file.Add(mesage.FileName, mesage.Extentsion, File.TypeEnum.Image, mesage.FilePath, mesage.CreatedUid); await _fileRepository.Add(shard.ConnectionString, file); ICommandResult result = new CommandResult() { Message = "", ObjectId = file.Id, Status = CommandResult.StatusEnum.Sucess }; return(result); } catch (Exception e) { e.Data["Param"] = mesage; ICommandResult result = new CommandResult() { Message = e.Message, Status = CommandResult.StatusEnum.Sucess }; return(result); } }
/// <summary> /// Save a file and file history when the user upload a file. /// </summary> /// <param name="file"></param> /// <returns></returns> public void Upload(File file) { fileRepository.Add(file); SaveHistory(file.Id, file.UserId, StatusTypes.Upload); fileRepository.Save(); }
public Post Edit(Post post, IFormFile file) { if (file != null) { bool fileAdded = _fileRepository.Add(file); Image image = new Image { FileName = file.FileName, ContentType = file.ContentType, Timestamp = DateTime.UtcNow }; image = _imageRepository.Add(image); post.ImageId = image.ImageId; } post.Timestamp = DateTime.UtcNow; return(_postRepository.Edit(post)); }
public void UploadFile(IBllFile file, string userName) { file.DateUploaded = DateTime.Now; IDalAppFile dalFile = file.ToDalAppFile(); dalFile.UserId = _userService.GetUserByName(userName).Id; _fileRepository.Add(dalFile); _unitOfWork.Commit(); }
public string AddFile(FileModel model) { var entity = _mapper.Map <File>(model); entity.Id = Guid.NewGuid().ToString(10); _fileRepository.Add(entity); _fileRepository.SaveChanges(); return(entity.Id); }
public FileDto Add(int valueId, FileDto value) { if (value == null) { throw new ArgumentNullException(); } var entity = _mapper.Map <FileDto, File>(value); value = _mapper.Map <File, FileDto>(_fileRepository.Add(valueId, entity)); return(value); }
protected override Result <string> Handle(CreateFileCommand request) { EnsureArg.IsNotNull(request); var fileContent = FileContent.Create(request.Content); var file = Domain.File.Create(request.Name, request.Extensions, fileContent); fileRepository.Add(file); fileRepository.SaveChanges(); return(Result.Ok <string>($"{file.Id}.{file.Extension}")); }
public int Upload(IFormFile file, int applicationId) { string savePath = GetSavePath(); if (!Directory.Exists(savePath)) { Directory.CreateDirectory(savePath); } //string fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"'); if (file?.Length > 0 && !string.IsNullOrEmpty(file.FileName)) { //todo create guid and save with guid name string fullPath = Path.Combine(savePath, file.FileName); using (var stream = new FileStream(fullPath, FileMode.Create)) { file.CopyTo(stream); } if (TryCheckFile(fullPath, out var checkStatus)) { if (checkStatus.IsOk) { var entity = new ConfModel.Model.File() { Name = file.FileName, ApplicationId = applicationId, Size = file.Length }; foreach (var expertId in _fileRepository.GetExpertIds()) { entity.FileNotifications.Add(new FileNotification() { UserId = expertId }); } return(_fileRepository.Add(entity)); } DeleteFile(fullPath); throw new ObjectException(checkStatus); } else { DeleteFile(fullPath); throw new Exception("Exception while checking."); } } throw new Exception("Bad file"); }
public void UploadFile(DTO.Models.File fileUploadModel) { try { fileUploadModel.UploadedAt = DateTime.Now; fileRepository.Add(fileUploadModel); SaveChanges(); } catch (Exception ex) { throw ex; } }
public FileImgResViewModel SaveFileInfo(FileUploadViewModel fileUploadViewModel) { var UploadFile = _IMapper.Map <FileUploadViewModel, UploadFile>(fileUploadViewModel); var result = _IMapper.Map <FileUploadViewModel, FileImgResViewModel>(fileUploadViewModel); _fileRepository.Add(UploadFile); _fileRepository.SaveChanges(); int fileKeyid = _fileRepository.getfileIDByPhy(fileUploadViewModel); result.id = fileKeyid; return(result); }
public async Task <bool> CreateDirectoryAndFile(JobRequest request) { var directory = new File { Directory = request.SessionId }; await fileRepository.Add(directory); if (!string.IsNullOrEmpty(request.FileName)) { var file = new File { Directory = request.SessionId, Name = request.FileName, TextContents = Encoding.UTF8.GetString(request.FileContent) }; await fileRepository.Add(file); } return(true); }
public FileModel Add(FileModel entity) { try { _repo.Add(_mapper.Map <File>(entity)); UoW.Commit(); return(entity); } catch (Exception) { UoW.RollBack(); return(null); } }
public async Task SavingFileDataToDataBase(string filePath) { var fileParseManager = new FileParse(); var fileBarDataModel = new FileBarDataModel(); //parsing file data var resultFileBar = fileParseManager.ProcessFile(filePath); foreach (var item in resultFileBar) { fileBarDataModel.ColourName = item.ColourName; fileBarDataModel.Size = item.Size; var parseFileBarData = mapper.Map <FileBarData>(fileBarDataModel); fileRepository.Add(parseFileBarData); await fileRepository.SaveChangesAsync(); } }
private Flashcards.Entities.File createUploadFile(HttpPostedFileBase file, string userID, FileTypeEnum fileType, string filePath) { var dbFile = new Flashcards.Entities.File() { Filename = Path.GetFileName(filePath), FileTypeID = (int)fileType, OriginalFilename = file.FileName, UploadedByID = userID, UploadTime = DateTime.Now }; fileRepository.Add(dbFile); fileRepository.SaveChanges(); return(dbFile); }
public void Upload() { var file = Request.Form.Files[0]; using (var ms = new MemoryStream()) { file.CopyTo(ms); var fileBytes = ms.ToArray(); _fileRepository.Add(new Models.FileModel() { File = fileBytes, FileName = file.FileName, Extension = file.FileName.Split(".")[1] }); } }
private void TryAdd(Content content) { if (TryCastToFile(content, out File file)) { _fileRepository.Add(file); } else if (TryCastToFolder(content, out Folder folder)) { _folderRepository.Add(folder); } else { throw new ArgumentException($"{nameof(content)} is an unsupported content type."); } AddObject(content); }
public async Task SaveFile(UploadedFileViewModel fileViewModel, Stream contentStream, string pathToSave, string baseUrl) { //TODO: validate var entity = Mapper.Map <UploadedFile>(fileViewModel); var extension = Path.GetExtension(entity.OriginalName); entity.FileName = $"{fileViewModel.Id}{extension}"; entity.Size = contentStream.Length; entity.FtpFileUrl = $"{baseUrl}/uploads/{entity.FileName}"; await _fileRepository.Add(entity); await _fileRepository.SaveChanges(); await _fileRepository.SaveFile(entity, contentStream); }
//public HttpResponseMessage CreateThumbnail(Guid id, ThumbnailType type) //{ // ValidateCreateThumbnailRequest(id); // IFileUploadRepository repo = IoC.Container.Resolve<IFileUploadRepository>(); // FileUpload file = repo.GetById(id.ToString()); // Stream fileStream = GetFileStream(file, type); // StreamContent strContent = new StreamContent(fileStream); // strContent.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse(file.ContentType); // HttpResponseMessage message = new HttpResponseMessage(); // message.Content = strContent; // return message; //} //private Stream GetFileStream(FileUpload file, ThumbnailType type) //{ // Stream stream; // Image img; // switch (file.ContentType) // { // case FileContentType.Jpeg: // case FileContentType.Png: // byte[] contentInByte = Encoding.ASCII.GetBytes(file.Content); // stream= new MemoryStream(contentInByte, 0, contentInByte.Length); // //stream = new MemoryStream(); // //img = PhotoHelper.CreatePngStream(file.Content, type); // //img.Save(stream, System.Drawing.Imaging.ImageFormat.Png); // break; // //stream = new MemoryStream(); // //img = PhotoHelper.CreatePngStream(file.Content, type); // //img.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); // //break; // default: // throw new ValidationException("common.httpError.unsupportedContent"); // } // return stream; //} //private void ValidateCreateThumbnailRequest(Guid id) //{ // IFileUploadRepository repo = IoC.Container.Resolve<IFileUploadRepository>(); // FileUpload file = repo.GetById(id.ToString()); // if (file == null) // { // throw new ValidationException("common.httpError.notFound"); // } //} //public IList<TEntity> GetByParentId<TEntity>(Guid parentId) where TEntity : IMappedFrom<FileUpload> //{ // IFileUploadRepository repo = IoC.Container.Resolve<IFileUploadRepository>(); // return repo.GetByParentId<TEntity>(parentId); //} //public FilesUploadResponse UploadFiles(Guid parentId, HttpFileCollection files) //{ // FilesUploadResponse uploadResponse = new FilesUploadResponse(); // ValidateUploadFilesRequest(parentId); // using (IUnitOfWork uow = new UnitOfWork(new AppDbContext(IOMode.Write))) // { // IFileUploadRepository fileRepo = IoC.Container.Resolve<IFileUploadRepository>(uow); // foreach (string fileKey in files) // { // HttpPostedFile file = files[fileKey]; // FileUpload fileUpload = new FileUpload(file); // fileUpload.ParentId = parentId; // fileRepo.Add(fileUpload); // uploadResponse.File = fileUpload.Id; // } // uow.Commit(); // } // return uploadResponse; //} //private void ValidateUploadFilesRequest(Guid parentId) //{ // if (parentId == null) // { // throw new ValidationException("common.fileUpload.invalidParentId"); // } //} //public FileUpload GetById(Guid id) //{ // IFileUploadRepository repo = IoC.Container.Resolve<IFileUploadRepository>(); // return repo.GetById(id.ToString()); //} //public FilesUploadResponse UploadFiles(Guid parentId, IList<FileUploadInfo> files) //{ // FilesUploadResponse uploadResponse = new FilesUploadResponse(); // ValidateUploadFilesRequest(parentId); // using (IUnitOfWork uow = new UnitOfWork(new AppDbContext(IOMode.Write))) // { // IFileUploadRepository fileRepo = IoC.Container.Resolve<IFileUploadRepository>(uow); // foreach (FileUploadInfo file in files) // { // FileUpload fileUpload = new FileUpload(file); // fileUpload.ParentId = parentId; // fileRepo.Add(fileUpload); // uploadResponse.File = fileUpload.Id; // } // uow.Commit(); // } // return uploadResponse; //} public IList <FileUploadResponse> UploadFiles(List <MultipartFormDataMemoryStreamProvider.FileInfo> files) { ValidateUploadRequest(files); using (IUnitOfWork uow = new UnitOfWork(new AppDbContext(IOMode.Write))) { IFileRepository repo = IoC.Container.Resolve <IFileRepository>(uow); IList <FileUploadResponse> filesUploaded = new List <FileUploadResponse>(); foreach (App.Common.Providers.MultipartFormDataMemoryStreamProvider.FileInfo file in files) { App.Entity.Common.FileUpload fileCreated = new Entity.Common.FileUpload(file.FileName, file.ContentType, file.FileSize, file.Content); repo.Add(fileCreated); filesUploaded.Add(ObjectHelper.Convert <FileUploadResponse>(fileCreated)); } uow.Commit(); return(filesUploaded); } }
public Photo Add(Photo photo, IFormFile file) { if (file != null) { bool fileAdded = _fileRepository.Add(file); Image image = new Image { FileName = file.FileName, ContentType = file.ContentType, Timestamp = DateTime.UtcNow }; image = _imageRepository.Add(image); photo.ImageId = image.ImageId; } photo.Timestamp = DateTime.UtcNow; return(_photoRepository.Add(photo)); }