/// <summary> /// Creates the specified file. /// </summary> /// <param name="file">The file.</param> /// <param name="data">The data.</param> /// <returns></returns> public Entities.File Create(Entities.File file, byte[] data) { var id = Guid.NewGuid(); var subFolder = (file.FileType.ToLower() == "image" ? "img/" : "doc/") + (file.AccountId.HasValue ? file.AccountId.ToString() : "common"); var fullFolder = Path.Combine(_path, subFolder); var extName = Path.GetExtension(file.FileName)?.ToLower(); var filePath = Path.Combine(subFolder, id + extName); var fullFilePath = Path.Combine(fullFolder, id + extName); if (!Directory.Exists(fullFolder)) { Directory.CreateDirectory(fullFolder); } using (var stream = File.Create(fullFilePath)) { stream.Write(data, 0, data.Length); stream.Flush(); stream.Close(); } // Data access component declarations. var fileDAC = new FileDAC(); // Step 1 - Calling Create on FileDAC. file.Id = id; file.FilePath = filePath; file.MimeType = FileContentType.GetMimeType(extName); fileDAC.Create(file); return(file); }
private void UploadBTN_Click(object sender, EventArgs e) { DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { // // The user selected a folder and pressed the OK button. // We print the number of files found. // List <Entities.File> addedFiles = new List <Entities.File>(); Entities.Peer peerType = new Entities.Peer(); Entities.File FileType = new Entities.File(); FileInfo fInfo = new FileInfo(openFileDialog1.FileName); FileType.FileName = openFileDialog1.FileName; FileType.FileSize = (int)fInfo.Length; FileType.FileType = Path.GetExtension(openFileDialog1.FileName); FileType.PeerHostName = Config.LocalHostyName; peerType.PeerID = FileType.PeerID = Guid.NewGuid(); addedFiles.Add(FileType); peerType.PeerHostName = Config.LocalHostyName; fileTransferManager.AddFiles(addedFiles, peerType); MessageBox.Show("Files Added!"); } }
public async Task <IActionResult> UploadFile(FileUploadViewModel model) { if (model.File == null || model.File.Length == 0) { return(BadRequest()); } if (!ModelState.IsValid) { return(BadRequest()); } ; var guId = GetFileName(); var targetFile = GetTargetFile(guId); using (var stream = new FileStream(targetFile, FileMode.Create)) { await model.File.CopyToAsync(stream); model.File.OpenReadStream(); } var file = new Entities.File { CourseId = model.CourseId, Name = model.File.FileName, DirName = "${uploadPath}", UIdFileName = guId }; _fileService.Create(file); return(Ok(file)); }
public JsonResult SaveFile(Entities.File item) { if (Request.Files == null || Request.Files.Count < 1) { throw new Exception("Выберите файл для загрузки"); } try { //сохраняем на диск HttpPostedFileBase upload = Request.Files[0]; string filename = Guid.NewGuid().ToString() + Path.GetExtension(upload.FileName); string path = Path.Combine(ConfiguraionProvider.FileStorageFolder, filename); upload.SaveAs(path); //дозаполняем данными item.AttachmentDate = DateTime.Now; item.UserID = CurrentUser.Id; item.FileName = Request.Files[0].FileName; //оригинальное название файла item.FIleUrl = Path.Combine(filename); //имя, как мы его сохраняем //сохраняем в БД List <Entities.File> files = new List <Entities.File>() { item }; var result = statementBusinessLogic.File_Save(files); return(Json(result)); } catch (Exception ex) { Response.StatusCode = (int)HttpStatusCode.InternalServerError; var exceptionDetails = new ExceptionDetails(ex, "Ошибка при сохранении файла(-ов)."); return(Json(exceptionDetails)); } }
public void Delete(Entities.File file) { try { System.IO.File.Delete(Path.Combine(StoragePath, file.Id)); } catch { } }
public async Task TestInsertFile() { var fileEntity = new Entities.File { Content = System.Text.Encoding.UTF8.GetBytes("Test") }; await _fixture.Db.SetEntity <Entities.File>().InsertAsync(fileEntity); }
public async Task <Entities.File> UploadFile(Entities.File File) { FileInfo fileInfo = new FileInfo(File.Name); string path = $"/company/{StaticParams.DateTimeNow.ToString("yyyyMMdd")}/{Guid.NewGuid()}{fileInfo.Extension}"; string thumbnailPath = $"/company/{StaticParams.DateTimeNow.ToString("yyyyMMdd")}/{Guid.NewGuid()}{fileInfo.Extension}"; File = await FileService.Create(File, path); return(File); }
public async Task <Entities.File> Get(long Id) { Entities.File File = await UOW.FileRepository.Get(Id); if (File == null) { return(null); } return(File); }
public async Task <IHttpActionResult> GetFile(Guid id) { Entities.File file = await db.Files.FindAsync(id); if (file == null) { return(NotFound()); } return(Ok(file)); }
public void Download(Entities.File fileSearchResult) { //var action =new Action<object>(searchForSameFileBaseOnHash); //Task searchForSameFileBaseOnHashTask = new Task(action, fileSearchResult); //searchForSameFileBaseOnHashTask.Start(); var downloadAction = new Action <object>(StartDownload); Task downloadActionTask = new Task(downloadAction, fileSearchResult); downloadActionTask.Start(); }
private void InsertMetaOf(Entities.File inputFile, List <Folder> folders, ref Section section) { var parentFolderName = (from folder in folders where folder.Id == inputFile.ParenFolderId select folder.Name).FirstOrDefault() ?? "ROOT"; section.AddParagraph("Name: " + inputFile.Name + inputFile.FileExt); section.AddParagraph("Type: FILE"); section.AddParagraph("Size: " + inputFile.FileSizeInKB + " KB"); section.AddParagraph("Parent: " + parentFolderName); section.AddParagraph(); }
public Object UploadFile(int userId, int parentFolderId) { if (HttpContext.Current.Request.Files.Count > 0) { try { foreach (var filename in HttpContext.Current.Request.Files.AllKeys) { HttpPostedFile postedFile = HttpContext.Current.Request.Files[filename]; if (postedFile != null) { var uniqueName = Guid.NewGuid().ToString().Substring(0, 4); Entities.File file = new Entities.File(); file.Name = uniqueName + "-" + Path.GetFileNameWithoutExtension(postedFile.FileName); file.FileExt = Path.GetExtension(postedFile.FileName); file.IsActive = true; file.FileSizeInKB = (postedFile.ContentLength) / 1024; file.UploadedOn = DateTime.Now; file.CreatedBy = userId; file.ParenFolderId = parentFolderId; var rootPath = HttpContext.Current.Server.MapPath("~/UploadedFiles"); var fileSavePath = Path.Combine(rootPath, file.Name + file.FileExt); postedFile.SaveAs(fileSavePath); ShellFile shellFile = ShellFile.FromFilePath(fileSavePath); Bitmap shellThumb = shellFile.Thumbnail.ExtraLargeBitmap; shellThumb.MakeTransparent(Color.Black); var thumbFilePath = Path.Combine(rootPath, file.Name) + "-thumb.png"; shellThumb.Save(thumbFilePath, ImageFormat.Png); file.Save(); } } } catch (Exception) { return(new HttpResponseMessage(HttpStatusCode.InternalServerError));; } } else { return(new HttpResponseMessage(HttpStatusCode.BadRequest)); } return(new HttpResponseMessage(HttpStatusCode.OK)); }
public async Task <bool> SaveListFile(Entities.File File) { try { await SaveReference(File); return(true); } catch (Exception e) { throw new MessageException(e); } }
FileSystemObject MapToDto(Entities.File file) { return(new FileDto() { ContentType = _mimeTypeMapping.GetValueOrDefault(Path.GetExtension(file.Name)), Name = file.Name, Path = _pathHelper.PathToUrl(file.Path), ApiPath = _pathHelper.PathToUrl(_pathHelper.GetApiPath(file.Path)), Height = file.Height, Width = file.Width, ThumbnailPath = _pathHelper.PathToUrl(file.ThumbnailPath) }); }
private CatalogImage ImageFromData(FileData fileData, int?catalogId = null) { var newImage = new CatalogImage() { CatalogId = catalogId ?? default, File = new Entities.File { FileName = fileData.FileName, ContentType = fileData.ContentType } }; return(newImage); }
public async Task <IHttpActionResult> PutFile(Guid id, Entities.File file) { Entities.File existedFile = await db.Files.FindAsync(id); if (existedFile == null) { return(NotFound()); } db.Entry(existedFile).CurrentValues.SetValues(file); await db.SaveChangesAsync(); await db.Entry(existedFile).GetDatabaseValuesAsync(); return(Ok(existedFile)); }
protected void SaveButton_Click(object sender, EventArgs e) { if (file.HasFile) { if (!string.IsNullOrEmpty(FileDescription.Text)) { if (NewFileClient.SelectedItem != null) { try { DBUserConnection dBUserConnection = new DBUserConnection(); User FileUser = dBUserConnection.GetUser(Convert.ToInt32(NewFileClient.SelectedValue)); bool DirExists = System.IO.Directory.Exists(Server.MapPath("/Files/" + FileUser.UniqueUserID + "/")); if (!DirExists) { System.IO.Directory.CreateDirectory(Server.MapPath("/Files/" + FileUser.UniqueUserID + "/")); } file.SaveAs(Server.MapPath("/Files/" + FileUser.UniqueUserID + "/" + file.FileName)); DBFileConnection dBFileConnection = new DBFileConnection(); Entities.File NewFile = new Entities.File(); NewFile.Description = FileDescription.Text; NewFile.FileName = file.FileName; NewFile.FilePath = "/Files/" + FileUser.UniqueUserID + "/" + file.FileName; dBFileConnection.Save(LoggedInUser, NewFile, FileUser.ID); Message.Text = "Bestand is opgeslagen"; } catch (Exception ex) { Message.Text = "Er is een uitzondering opgetreden bij het opslaan van " + file.FileName + "<br/>" + ex.Message; } } else { Message.Text = "Er is geen gebruiker geselecteerd"; } } else { Message.Text = "Er is geen beschrijving ingevuld"; } } else { Message.Text = "Er is geen bestand gekozen"; } }
public async Task <IActionResult> Upload(IFormFile file) { //files are stored on the server, database stores only file info //create file object in database storing real name of the file, id and employeeId int myId = int.Parse(User.Identity.Name); Entities.File fileParam = new Entities.File() { Employee_Id = myId, File_Name = file.FileName, Storage_Name = "tmp" }; _fileContext.File.Add(fileParam); _fileContext.SaveChanges(); // create the storage file name string newFileName = DateTime.Now + "_" + fileParam.File_Id; newFileName = newFileName.Replace(".", "-"); newFileName = newFileName.Replace(":", "-"); newFileName = newFileName + "." + file.FileName.Split(".")[1]; //insert storage name into database fileParam.Storage_Name = newFileName; _fileContext.File.Update(fileParam); _fileContext.SaveChanges(); // create directory for employee string dirName = _employeeContext.Employee.Find(myId).First_Name + "_" + _employeeContext.Employee.Find(myId).Last_Name; string dirPath = Path.Combine(storagePath, dirName); Directory.CreateDirectory(dirPath); // create filepath var filePath = Path.Combine(dirPath, newFileName); // Create a new file in employee directory using (var stream = new FileStream(filePath, FileMode.Create)) { //copy the contents of the received file to the newly created local file await file.CopyToAsync(stream); } // return the file name for the locally stored file return(Ok(newFileName)); }
private void StartDownload(object state) { Entities.File fileSearchResult = state as Entities.File; //Wee need to aply multiThreading to use multi host to download diferent part of file cuncurently max number of thread could be 5 thread per host in all of the application; long partcount = fileSearchResult.FileSize / FilePartSizeInByte; long mod = fileSearchResult.FileSize % FilePartSizeInByte; if (mod > 0) { partcount++; } for (int i = 1; i <= partcount; i++) { downloadFilePart(new DownloadParameter { FileSearchResult = fileSearchResult, Host = fileSearchResult.PeerHostName, Part = i, AllPartsCount = partcount }); } }
public async Task <FileDto> UploadFile([FromForm] CreateFileDto createFileDto) { CreateFileValidator createfileValidator = new CreateFileValidator(); if (!createfileValidator.Validate(createFileDto.PhFile).IsValid) { throw new Exception("Name Not Valid... "); } //--------------- Upload Physical File ------------------// var path = ""; if (createFileDto.FolderId > 0) { var rootFolder = (await _unitOfWork.FoldersRepository.GetAllIncluded(f => f.FolderId == createFileDto.FolderId)).SingleOrDefault(); if (rootFolder == null) { throw new Exception("Folder not found"); } path = rootFolder.FolderPath + '\\' + createFileDto.PhFile.FileName; } else { path = _fileManager.GetRootPath() + createFileDto.PhFile.FileName; } _fileManager.UploadFile(createFileDto.PhFile, path); //----------------------- Save to Db --------------------// var entityFile = new Entities.File { FileName = Path.GetFileNameWithoutExtension(path), FileExtension = Path.GetExtension(createFileDto.PhFile.FileName), FileSize = int.Parse(createFileDto.PhFile.Length.ToString()), FilePath = Path.GetFullPath(path), FolderId = createFileDto.FolderId > 0 ? createFileDto.FolderId : default(int?) }; var f = new FileInfo(Path.GetFullPath(path)); _unitOfWork.FileRepository.Add(entityFile); await _unitOfWork.CompleteAsync(); return(_mapper.Map <Entities.File, FileDto>(entityFile)); }
private IEnumerable <KeyValuePair <ProductImage, Stream> > ImagesFromData(IEnumerable <FileData> imageDatas, int?productId = null) { var images = new List <KeyValuePair <ProductImage, Stream> >(); foreach (var imageData in imageDatas) { var newImage = new ProductImage() { ProductId = productId ?? default, File = new Entities.File { FileName = imageData.FileName, ContentType = imageData.ContentType } }; images.Add(new KeyValuePair <ProductImage, Stream>(newImage, imageData.Stream)); } return(images); }
public override object VisitScript([NotNull] HtmlParser.ScriptContext context) { foreach (var item in context.htmlAttribute()) { var name = item.htmlAttributeName().TAG_NAME().GetText(); if (name.ToUpper() != "SRC") { continue; } var manager = new HtmlAttributeManager(item); var path = manager.Value; Entities.File searchFile = valueProvider.GetFile(path); if (searchFile != null) { if (searchFile.IsExternal) { manager.Value = searchFile.FileName; } return(null); } try { HttpWebRequest req = WebRequest.CreateHttp(path); req.Method = "GET"; var result = req.GetResponse(); var fileName = Path.GetRandomFileName() + ".js"; Entities.File file = new ParseFile().ToParse(fileName, result.GetResponseStream(), Entities.FileType.Js); valueProvider.AddFile(file); file = new Entities.File { Type = file.Type, FileName = file.FileName, SearchName = path, IsExternal = true, }; valueProvider.AddFile(file); manager.Value = fileName; } catch { return(null); } } return(null); }
/* * /// <summary> * /// 新增【圖片】 * /// </summary> * [MimeMultipart] * [ResponseType(typeof(Entities.File))] * public async Task<IHttpActionResult> PostFile2() * { * DirectoryInfo directoryInfo; * var tempsAzurePath = "D:/home/site/wwwroot/Temps"; * if (!Directory.Exists(tempsAzurePath)) * { * directoryInfo = Directory.CreateDirectory(tempsAzurePath); * * } * UploadMultipartFormProvider uploadMultipartFormProvider = new UploadMultipartFormProvider(tempsAzurePath);//HttpContext.Current.Server.MapPath("~/Temps") * await Request.Content.ReadAsMultipartAsync(uploadMultipartFormProvider); * string path = uploadMultipartFormProvider.Contents.FirstOrDefault().Headers.ContentDisposition.Name.Replace("\"", ""); * * var filesAzurePath = "D:/home/site/wwwroot/Files"; * DirectoryInfo directoryInfo2; * if (!Directory.Exists(filesAzurePath)) * { * directoryInfo2 = Directory.CreateDirectory(filesAzurePath); * * } * string folderPath = "D:/home/site/wwwroot/Files/" + path; //HttpContext.Current.Server.MapPath("~/Files/" + path) * Guid folderId = new Guid(path.Substring(path.Length - 36, 36)); * Folder folder = await db.Folders.FindAsync(folderId); * DirectoryInfo directoryInfo3; * if (!Directory.Exists(folderPath)) * { * directoryInfo3 = Directory.CreateDirectory(folderPath); * * } * if (folder == null) * { * folder = new Folder * { * Id = folderId * }; * db.Folders.Add(folder); * await db.SaveChangesAsync(); * } * * ICollection<FolderFile> folderFiles = new List<FolderFile>(); * foreach (var fileData in uploadMultipartFormProvider.FileData) * { * * string fileName = Path.GetFileName(fileData.LocalFileName); * Guid fileId = new Guid(fileName.Substring(0, 36)); * string targetPath = folderPath + "/" + fileName; * * // (HttpContext.Current.Server.MapPath("~/Files/" + path) + "\\" + fileName).Replace(HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath, ""); * * * if (System.IO.File.Exists(targetPath)) * { * string duplicateId = fileId.ToString(); * fileId = Guid.NewGuid(); * targetPath = targetPath.Replace(duplicateId, fileId.ToString()); * fileName = fileName.Replace(duplicateId, fileId.ToString()); * } * * //System.IO.File.Move(HttpContext.Current.Server.MapPath("~/Temps/") + fileName, targetPath); * System.IO.File.Move("D:/home/site/wwwroot/Temps/" + fileName, targetPath); * Entities.File file = await db.Files.FirstOrDefaultAsync(x => x.Value == fileName); * if (file == null) * { * FolderFile newFolderFile = new FolderFile * { * StartDate = DateTime.Now, * OwnerId = folder.Id, * Target = new Entities.File * { * Id = fileId, * Path = path, * Value = fileName * } * }; * db.FolderFiles.Add(newFolderFile); * await db.SaveChangesAsync(); * * folderFiles.Add(newFolderFile); * } * } * return Ok(new FileSave * { * Folder = folder, * Photos = folderFiles * }); * } */ /// <summary> /// 刪除【檔案】 /// </summary> /// <param name="id">檔案序號</param> public async Task <IHttpActionResult> DeleteFile(Guid id) { Entities.File existedFile = await db.Files.FindAsync(id); if (existedFile == null) { return(NotFound()); } else { foreach (FolderFile existedFolderFile in db.FolderFiles.Where(x => x.TargetId == existedFile.Id).ToArray()) { db.FolderFiles.Remove(existedFolderFile); } db.Files.Remove(existedFile); } await db.SaveChangesAsync(); return(Ok()); }
public static Domain.File ToQueries(this Entities.File model) { return(new Domain.File() { FileId = model.FileId, Source = model.Source, Destination = model.Destination, DownloadStartedDate = model.DownloadStartedDate, DownloadEndedDate = model.DownloadEndedDate, IsLargeData = Convert.ToString(model.IsLargeData), IsSlow = Convert.ToString(model.IsSlow), PercentageOfFailure = model.PercentageOfFailure, DownloadSpeed = model.DownloadSpeed, ElapsedTime = model.ElapsedTime, ProtocolId = model.ProtocolId, StatusId = model.StatusId, Protocol = model.Protocol.Name, Status = model.Status.Name }); }
public Guid Create(string nameWithExtension, Stream fileContents) { var newStorageName = Guid.NewGuid().ToString() + ".dat"; var storagePath = BuildPath(newStorageName); using (Stream s = System.IO.File.OpenWrite(storagePath)) { fileContents.CopyTo(s); } var file = new Entities.File() { Name = nameWithExtension, StorageFileName = newStorageName }; context.Files.Add(file); context.SaveChanges(); return file.FileId; }
public Guid Create(string nameWithExtension, Stream fileContents) { var newStorageName = Guid.NewGuid().ToString() + ".dat"; var storagePath = BuildPath(newStorageName); using (Stream s = System.IO.File.OpenWrite(storagePath)) { fileContents.CopyTo(s); } var file = new Entities.File() { Name = nameWithExtension, StorageFileName = newStorageName }; context.Files.Add(file); context.SaveChanges(); return(file.FileId); }
public async Task <bool> ProcessRVAsync(string fileBase64, int offset, string username) { string filename = this.GetRandomFilename("txt"); // Status 1: File entity created Entities.File file = new Entities.File { Name = filename, IdFileType = 1, CreationDate = System.DateTimeOffset.Now, Status = 0 }; Context.File.Add(file); await Context.SaveChangesAsync(); // Status 2: File saved on disk byte[] fileBytes = this.GetBytesFromBase64(fileBase64); await this.SaveFileOnDisk(fileBytes, filename); file.Status = 2; Context.File.Update(file); Context.SaveChanges(); // Status 3: File processed into Database this.LoadFileInDatabase(fileBytes, file.Id, offset); file.Status = 3; Context.File.Update(file); Context.SaveChanges(); // Status 4: Ticketed created await this.ProcessTickets(username, file.Id); file.Status = 4; Context.File.Update(file); Context.SaveChanges(); return(true); }
public async Task <ActionResult> GetFile(long?fileId) { Entities.File file = statementBusinessLogic.File_Get(fileId.Value); try { var filePath = Path.Combine(ConfiguraionProvider.FileStorageFolder, file.FIleUrl); byte[] fileContents; using (var fs = System.IO.File.OpenRead(filePath)) { fileContents = new byte[fs.Length]; await fs.ReadAsync(fileContents, 0, fileContents.Length); } return(File(fileContents, System.Net.Mime.MediaTypeNames.Application.Octet, file.FileName)); } catch (Exception ex) { var exceptionDetails = new ExceptionDetails(ex, "Ошибка при получении файла."); var model = new StatementList(exceptionDetails); return(View("Statement", model)); } }
private void Initialize(Entities.File file) { _syncpointId = file.SyncpointId; _latestVersionId = file.LatestVersionId; var syncpoint = SyncPointsService.GetSyncpoint(_syncpointId); if (syncpoint == null) { throw new ArgumentException("Invalid Syncpoint Id"); } var storageEndpoint = StorageEndpointsService.GetStorageEndpoint(syncpoint.StorageEndpointId); if (storageEndpoint.Urls == null || storageEndpoint.Urls.Length == 0) { throw new ArgumentException("Invalid StorageEndpoint Urls"); } _downloadUrl = string.Format(DownloadUlrFormat, storageEndpoint.Urls[0].Url); if (ConfigurationHelper.UseSecureSessionToken) { _sessionKey = string.Format(SessionKeyFormat, ApiGateway.CreateSst(storageEndpoint.Id)); } else { _sessionKey = string.Format(SessionKeyFormat, ConfigurationHelper.SyncplicityMachineTokenAuthenticationEnabled ? ApiContext.MachineToken : ApiContext.AccessToken); } Debug.WriteLine($"Download Url: {_downloadUrl}"); Debug.WriteLine($"Session Key: {_sessionKey}"); Console.WriteLine($"Download Url: {_downloadUrl}"); Console.WriteLine($"Session Key: {_sessionKey}"); }
public async Task <Entities.File> Create(Entities.File File, string path) { RestClient restClient = new RestClient(InternalServices.UTILS); RestRequest restRequest = new RestRequest("/rpc/utils/file/upload"); restRequest.RequestFormat = DataFormat.Json; restRequest.Method = Method.POST; restRequest.AddCookie("Token", CurrentContext.Token); restRequest.AddCookie("X-Language", CurrentContext.Language); restRequest.AddHeader("Content-Type", "multipart/form-data"); restRequest.AddFile("file", File.Content, File.Name); restRequest.AddParameter("path", path); try { var response = restClient.Execute <Entities.File>(restRequest); if (response.StatusCode == System.Net.HttpStatusCode.OK) { File.Id = response.Data.Id; File.Url = "/rpc/utils/file/download" + response.Data.Path; File.AppUserId = File.AppUserId; File.RowId = response.Data.RowId; await UOW.Begin(); await UOW.FileRepository.Create(File); File = await UOW.FileRepository.Get(File.Id); await UOW.Commit(); return(File); } return(null); } catch (Exception e) { return(null); } }
public void DownloadFileSimple(Entities.File file, string downloadFolder) { var combinedFileName = Path.Combine(downloadFolder, file.Filename); PrepareDownloadFolder(downloadFolder, combinedFileName); Initialize(file); using (var fileStream = OpenFileForDownload(combinedFileName)) { try { DownloadChunk(fileStream); } catch { fileStream.Close(); File.Delete(combinedFileName); throw; } } }
private void UploadBTN_Click(object sender, EventArgs e) { DialogResult result = openFileDialog1.ShowDialog(); if (result == DialogResult.OK) { // // The user selected a folder and pressed the OK button. // We print the number of files found. // List<Entities.File> addedFiles = new List<Entities.File>(); Entities.Peer peerType = new Entities.Peer(); Entities.File FileType = new Entities.File(); FileInfo fInfo = new FileInfo(openFileDialog1.FileName); FileType.FileName = openFileDialog1.FileName; FileType.FileSize = (int)fInfo.Length; FileType.FileType = Path.GetExtension(openFileDialog1.FileName); FileType.PeerHostName = Config.LocalHostyName; peerType.PeerID=FileType.PeerID = Guid.NewGuid(); addedFiles.Add(FileType); peerType.PeerHostName = Config.LocalHostyName; fileTransferManager.AddFiles(addedFiles,peerType); MessageBox.Show("Files Added!"); } }
public ActionResult Upload(int Id) { // Comprobamos si habia un archivo ya asociado y lo elminamos var file = this.DataService.FileRepository.CreateQuery(Proyection.Basic).Where(FileFields.EntityId, Id).ToList().FirstOrDefault(); if (file != null) this.Repository.Delete(file); HttpPostedFileBase fileBase = Request.Files[0]; this.DataService.BeginTransaction(); byte[] fileData = GetFileByteArray(fileBase.InputStream); Entities.File doc = new Entities.File(); doc.FileContent = fileData; doc.FileName = fileBase.FileName; doc.EntityId = Id; doc.CreatedDate = DateTime.Now; SaveEntity(doc); var car = this.DataService.CarRepository.CreateQuery(Proyection.Detailed).Get(Id); car.CarITVName = doc.FileName; car.CarITVId = doc.FileId; SaveEntity(car); this.DataService.Commit(); return View(); }