public async Task <IActionResult> Edit(int id, [Bind("Id,ApplicationUserId,PublicationType,ArTitle,EnTitle,ArAuthors,EnAuthors,ArAbstract,EnAbstract,PublicationDate,Publisher,VolumeNo,IssueNo,ISSN,DOI,Pages,FileLink,ExternalLink,DownloadHits,Keywords")] Publication publication, IFormFile myfile) { if (id != publication.Id) { return(NotFound()); } if (ModelState.IsValid) { try { publication.FileLink = await UserFile.UploadeNewFileAsync( _context.Publications.Where(m => m.Id == id).Select(c => c.FileLink).First(), myfile, _environment.WebRootPath, Properties.Resources.PublicationFiles); _context.Update(publication); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PublicationExists(publication.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } return(View(publication)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,CategoryId,Subject,Body,AuthorName,ImageUrl")] Post post, IFormFile myfile) { if (id != post.Id) { return(NotFound()); } if (ModelState.IsValid) { try { post.ImageUrl = await UserFile.UploadeNewImageAsync(post.ImageUrl, myfile, _environment.WebRootPath, Properties.Resources.ImgFolder, 100, 100); _context.Update(post); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PostExists(post.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["CategoryId"] = new SelectList(_context.Categories, "Id", "Name", post.CategoryId); ViewData["UserId"] = new SelectList(_context.ApplicationUser, "Id", "Id", post.UserId); return(View(post)); }
public static List <UserFile> FileGetByComplexUserId() { Guid ComplexID = new Guid(userGuid); List <UserFile> list = null; DataProvider.ExecuteCmd(GetConnection, "dbo.File_GetByComplexUserId", inputParamMapper : delegate(SqlParameterCollection paramCollection) { paramCollection.AddWithValue("@ComplexID", ComplexID); }, map : delegate(IDataReader reader, short set) { UserFile f = new UserFile(); int startingIndex = 0; f.ID = reader.GetSafeInt32(startingIndex++); f.PersonID = reader.GetSafeInt32(startingIndex++); f.FileUrl = reader.GetSafeString(startingIndex++); f.FileTitle = reader.GetSafeString(startingIndex++); f.FileType = reader.GetSafeInt32(startingIndex++); if (list == null) { list = new List <UserFile>(); } list.Add(f); }); return(list); }
public async Task <IActionResult> EditResubFile(int id, [Bind("Id,SubmissionId,JournalFileTypeId,FileName,Description")] SubmissionFile submissionFile, IFormFile myfile) { if (id != submissionFile.Id) { return(NotFound()); } if (ModelState.IsValid) { try { submissionFile.FileName = await UserFile.UploadeNewFileAsync(submissionFile.FileName, myfile, _environment.WebRootPath, Properties.Resources.Secured); _context.Update(submissionFile); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SubmissionFileExists(submissionFile.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction("ResubmissionFiles", "SubmissionFiles", new { /* routeValues, for example: */ sid = submissionFile.SubmissionId })); } ViewData["JournalFileTypeId"] = new SelectList(_context.JournalFileTypes, "Id", "Id", submissionFile.JournalFileTypeId); ViewData["SubmissionId"] = new SelectList(_context.Submissions, "Id", "CoverLetter", submissionFile.SubmissionId); return(View(submissionFile)); }
public virtual void SaveUserFile() { Result result = fileService.SaveFile(ctx.GetFileSingle(), ctx.Ip, ctx.viewer.obj as User, ctx.owner.obj); Dictionary <String, String> dic = new Dictionary <String, String>(); if (result.HasErrors) { dic.Add("FileName", ""); dic.Add("DeleteLink", ""); dic.Add("Msg", result.ErrorsText); echoJson(dic); } else { UserFile att = result.Info as UserFile; updateDataInfo(att); String deleteLink = to(DeleteUserFile, att.Id); dic.Add("FileName", att.Name); dic.Add("DeleteLink", deleteLink); dic.Add("Id", att.Id.ToString()); echoJson(dic); } }
public void UnPickPicOne( UserFile x ) { BlogPicPick pick = BlogPicPick.find( "FileId=" + x.Id ).first(); if (pick != null) { pick.delete(); } }
//-------------------------------------------------------------------------- //Read/Write Para. public void fn_Load(bool IsLoad) { //Local Var. string m_strPath, sPath; m_strPath = UserFile.fn_GetExePath(); //File Path sPath = m_strPath + "SYSTEM\\Actuator.ini"; if (IsLoad) { if (!UserFile.fn_CheckFileExist(sPath)) { return; } } for (int i = 0; i < m_iNumOfACT; i++) { Actuator[i].Load(IsLoad, i, sPath); } //JUNG/201012 fn_SetRetryCnt((int)EN_ACTR_LIST.aSpdl_LensCovr, 2); fn_SetRetryCnt((int)EN_ACTR_LIST.aspdl_IR, 2); }
public virtual void SaveEditorFile() { Result result = fileService.SaveFile(ctx.GetFileSingle(), ctx.Ip, ctx.viewer.obj as User, ctx.owner.obj); Dictionary <String, String> dic = new Dictionary <String, String>(); if (result.HasErrors) { dic.Add("state", result.ErrorsText); echoJson(dic); } else { UserFile att = result.Info as UserFile; updateDataInfo(att); dic.Add("state", "SUCCESS"); dic.Add("url", att.PathFull); dic.Add("fileType", att.Ext); dic.Add("original", att.FileName); echoJson(dic); } }
public void AddUserFile(User user, UserFile file) { using (var db = GetConnect(_mf.ConnectionString)) { SHA256 sha = new SHA256Managed(); file.Hash = Convert.ToBase64String(sha.ComputeHash(file.Bin)); var newUserFile = new DbUserfile { Userid = user.Id, Hash = file.Hash, Filename = file.Filename, Contenttype = file.ContentType, }; if (db.Files.Any(o => o.Hash == file.Hash)) { db.Userfiles.Add(newUserFile); db.SaveChanges(); } else { DbFile newFile = new DbFile { Hash = file.Hash, Bin = file.Bin, }; db.Files.Add(newFile); db.Userfiles.Add(newUserFile); db.SaveChanges(); } } }
public UserFile GetUser(string UserName) { UserFile model = new UserFile(); model = ConstDB.UserFile.Where(o => o.DcdUserID == UserName).FirstOrDefault(); return(model); }
public async Task <IHttpActionResult> PostUpdateUserPic(UpdateUserPicBinndingModel model) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } UserFile file = await dataRepo.UserFiles.Where(f => f.UserFileId == model.UserFileId).FirstOrDefaultAsync(); if (file == null) { return(BadRequest("File with supplied id not found.")); } file.State = UserFileState.Assigned; Photo photo = new Photo { AlbumId = 0, UserId = CurrentUser.UserId, EntityId = CurrentUser.UserId, EntityType = PhotoEntityTypes.User, UserFileId = file.UserFileId }; (dataRepo.Photos as DbSet <Photo>).Add(photo); await dataRepo.SaveChangesAsync(); ApplicationUser user = await dataRepo.Users.Where(u => u.Id == CurrentUser.UserId).FirstAsync(); user.PhotoId = photo.PhotoId; await dataRepo.SaveChangesAsync(); return(Ok()); }
//[RequestSizeLimit(50 * 1024 * 1024)] public IActionResult AddFiles(IFormFileCollection uploads) { var user = db.MRUserManager.GetUser(User.Identity.Name); foreach (var file in uploads) { if (file.Length > (50 * 1024 * 1024)) { return(new BadRequestObjectResult(string.Format("{0} слишком большой", file.Name))); } UserFile newFile = new UserFile { Filename = file.FileName, UserId = user.Id, ContentType = file.ContentType }; using (var binaryReader = new BinaryReader(file.OpenReadStream())) { newFile.Bin = binaryReader.ReadBytes((int)file.Length); } db.MRFilesManager.AddUserFile(user, newFile); } return(RedirectToAction("Index")); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Name,Indx,CourseId,Logo,Link")] CourseSponsor courseSponsor, IFormFile myfile) { if (id != courseSponsor.Id) { return(NotFound()); } if (ModelState.IsValid) { courseSponsor.Logo = await UserFile.UploadeNewImageAsync(courseSponsor.Logo, myfile, _environment.WebRootPath, Properties.Resources.ScientificEvent, 500, 500); try { _context.Update(courseSponsor); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CourseSponsorExists(courseSponsor.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(Index))); } ViewData["CourseId"] = new SelectList(_context.Courses, "Id", "ArName", courseSponsor.CourseId); return(View(courseSponsor)); }
public ActionResult Product_Read([DataSourceRequest] DataSourceRequest request) { try { // should be true not false var result = db.Products.Where(x => x.adminToPublic); var productList = new List <ProductViewModel>(); foreach (var item in result) { var product = new ProductViewModel { productID = item.productID, productDescription = item.productDescription, EAN = item.EAN, categoryID = item.Category.categoryID, CountryID = item.countryID // articleId = item.articleID }; var fileListName = db.UserFiles .Where(file => file.productID == item.productID && file.adminApproved).ToList(); if (fileListName != null) { product.listOfFiles = new List <UserFile>(); foreach (var file in fileListName) { var userFiles = new UserFile { fileName = file.fileName, fileID = file.fileID, SheetType = new SheetType { sheetTypeID = file.SheetType.sheetTypeID, sheetTypeName = file.SheetType.sheetTypeName } }; userFiles.SheetType.sheetTypeName = file.SheetType.sheetTypeName; product.listOfFiles.Add(userFiles); } } productList.Add(product); } return(Json(productList.ToDataSourceResult(request), JsonRequestBehavior.AllowGet)); } catch (Exception e) { Console.WriteLine(e); throw; } }
public ActionResult InputCode(CodeInputModel model) { if (model != null && this.ModelState.IsValid) { if (CheckIfFileExists() == true) { string currUser = currentUserId(); var fileToDelete = db.UserFiles.FirstOrDefault(f => f.FileOwner == currUser); db.UserFiles.Remove(fileToDelete); } var file = new UserFile() { FileName = model.CodeTitle, FileDate = DateTime.Now, FileOwner = User.Identity.GetUserId(), FileContent = ConvertStringToByte(model.CodeContent) }; db.UserFiles.Add(file); db.SaveChanges(); this.AddNotification("SUCCESS! Code has been submitted.", NotificationType.SUCCESS); return(RedirectToAction("Scanning", "Scan")); } return(View(model)); }
public ActionResult UploadFile(FileInputModel fileInput) { if (fileInput != null && ModelState.IsValid && fileInput.UsrFile.ContentLength > 0 && fileInput.UsrFile.ContentLength <= 5000000 && fileInput.UsrFile.ContentType.Contains("text")) { if (CheckIfFileExists() == true) { string currUser = currentUserId(); var fileToDelete = db.UserFiles.FirstOrDefault(f => f.FileOwner == currUser); db.UserFiles.Remove(fileToDelete); } var file = new UserFile() { FileName = Path.GetFileName(fileInput.UsrFile.FileName), FileDate = DateTime.Now, FileOwner = currentUserId(), FileContent = ConvertStreamToByte(fileInput.UsrFile.InputStream) }; db.UserFiles.Add(file); db.SaveChanges(); this.AddNotification("File has been uploaded.", NotificationType.SUCCESS); return(RedirectToAction("Scanning", "Scan")); } else if (fileInput != null && ModelState.IsValid && fileInput.UsrFile.ContentLength > 5000000 || !fileInput.UsrFile.ContentType.Contains("text")) { this.AddNotification("File must be a .txt and less than 5Mb.", NotificationType.ERROR); return(RedirectToAction("UploadFile", "File")); } return(View()); }
public async Task <IActionResult> Create([Bind("Id,Title,MOOCProviderId,Description,SpecialityId,IsFree,IsReported,Language,Certificate,Duration,UniversityId,Link,YouTubeLink,Tags,Instructor,Image,StartDate,ApplicationUserId,DateOfRecord")] MOOCList mOOCList, IFormFile myfile) { if (ModelState.IsValid) { mOOCList.ApplicationUserId = _userManager.GetUserId(User); mOOCList.DateOfRecord = DateTime.Now; mOOCList.Image = await UserFile.UploadeNewImageAsync(mOOCList.Image, myfile, _environment.WebRootPath, Properties.Resources.ScientificEvent, 500, 500); mOOCList.Description = mOOCList.Description.Replace("\n", "<br/>"); mOOCList.Id = Guid.NewGuid(); _context.Add(mOOCList); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ApplicationUserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id", mOOCList.ApplicationUserId); ViewData["MOOCProviderId"] = new SelectList(_context.MOOCProviders, "Id", "Name", mOOCList.MOOCProviderId); ViewData["SpecialityId"] = new SelectList(_context.Specialities, "Id", "Name", mOOCList.SpecialityId); // ViewData["UniversityId"] = new SelectList(_context.Universities, "Id", "ArUniversityName", mOOCList.UniversityId); return(View(mOOCList)); }
public async Task <ActionResult> Update(string fileName, [FromForm] UserFile value) { var userFileDto = GetUserFileDto(value); if (userFileDto != null) { var fileIdFromUri = await _manager.GetFileId(fileName); if (fileIdFromUri > 0) { userFileDto.UserFileId = fileIdFromUri; var fileIdFromValue = await _manager.GetFileId(value.FileName); await this.Update(_manager, fileIdFromUri, fileIdFromValue, userFileDto); } else { await this.Add(_manager, userFileDto); } return(Ok()); } return(NoContent()); }
public static UserFile FileGetById(int id) { UserFile row = null; DataProvider.ExecuteCmd(GetConnection, "dbo.File_SelectById" , inputParamMapper : delegate(SqlParameterCollection paramCollection) { paramCollection.AddWithValue("@ID", id); }, map : delegate(IDataReader reader, short set) { UserFile f = new UserFile(); int startingIndex = 0; f.ID = reader.GetSafeInt32(startingIndex++); f.PersonID = reader.GetSafeInt32(startingIndex++); f.FileUrl = reader.GetSafeString(startingIndex++); f.FileTitle = reader.GetSafeString(startingIndex++); f.FileType = reader.GetSafeInt32(startingIndex++); f.CreatedBy = reader.GetSafeString(startingIndex++); f.ModifiedBy = reader.GetSafeString(startingIndex++); f.ModifiedDate = reader.GetSafeDateTime(startingIndex++); if (row == null) { row = f; } }); return(row); }
public static bool TryCreateUser(string email, string password, string username, string pic = "") { try { UserFile u = new UserFile() { Email = email, Password = password, Username = username }; FileSystem.TryWriteFile(UserFile.UserFolder + username + "/user.userfile", UserFile.Serialise(u)); //Debug.WriteLine($"Create new user at {UserFile.UserFolder}"); UpdateLocalUsers(); OnRegistered?.Invoke(new UserAccount() { Username = username, EmailAddress = email, Password = password }); return(true); } catch (Exception ex) { Debug.LogException(ex); return(false); } }
public static bool TryLogin(string email, string password) { //Step one... //Find local user with those details try { UserFile user = LocalUsers.Single(x => x.Email == email && x.Password == password); //await Task.Delay(2000); CurrentUser = new UserAccount() { EmailAddress = user.Email, Password = user.Password, Username = user.Username }; OnLoggedIn?.Invoke(CurrentUser); return(true); } catch (Exception ex) { Debug.LogException(ex); return(false); } }
public async Task <IActionResult> Edit( int id, [Bind("Id,ArCountryName,EnCountryName,CountryCode,ShortName,Flag")] Country country, IFormFile myfile) { if (id != country.Id) { return(NotFound()); } if (ModelState.IsValid) { try { country.Flag = await UserFile.UploadeNewImageAsync( _context.Countries.Where(m => m.Id == id).Select(c => c.Flag).First(), myfile, _environment.WebRootPath, Properties.Resources.CountryFlagFolder, 100, 100); _context.Update(country); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CountryExists(country.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index")); } return(View(country)); }
public async Task <IActionResult> Create([Bind("Id,ArName,EnName,ArDescription,EnDescription,ShortName,Logo,PISSN,EISSN,Email,ActivationDate,CreatedByUserId,EiCId,JournalStatus,Visitors,ReviewerCertificateBackgroundFile,JournalHeader,AuthorCertificateBackgroundFile,PublisherId")] Journal journal, IFormFile myfile, IFormFile myfile1, IFormFile myfile2, IFormFile myfile3) { if (ModelState.IsValid) { journal.Logo = await UserFile.UploadeNewImageAsync(journal.Logo, myfile, _environment.WebRootPath, Properties.Resources.Images, 500, 500); journal.JournalHeader = await UserFile.UploadeNewImageAsync(journal.JournalHeader, myfile1, _environment.WebRootPath, Properties.Resources.Images, 500, 500); journal.ReviewerCertificateBackgroundFile = await UserFile.UploadeNewFileAsync(journal.ReviewerCertificateBackgroundFile, myfile2, _environment.WebRootPath, Properties.Resources.Images); journal.AuthorCertificateBackgroundFile = await UserFile.UploadeNewFileAsync(journal.AuthorCertificateBackgroundFile, myfile3, _environment.WebRootPath, Properties.Resources.Images); journal.CreatedByUserId = _userManager.GetUserId(User); journal.ArDescription = journal.ArDescription.Replace("\n", "<br/>"); journal.EnDescription = journal.EnDescription.Replace("\n", "<br/>"); journal.ActivationDate = DateTime.Now; journal.JournalStatus = JournalStatus.UnderReview; _context.Add(journal); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ApplicantUserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id", journal.CreatedByUserId); ViewData["EditorinChiefId"] = new SelectList(_context.ApplicationUsers, "Id", "Id", journal.EiCId); ViewData["PublisherId"] = new SelectList(_context.Publishers, "Id", "ArName", journal.PublisherId); return(View(journal)); }
public async Task <IActionResult> Create([Bind("Id,ApplicationUserId,Name,ShortName,BgImage,Logo,Description,CreationDate,CommunityType,SpecialityId,SecurityLevel,IsCommentsAllowed,IsFeatured,IsApproved,IsSuspended,Tags")] Community community, IFormFile myfile, IFormFile myfile1) { if (ModelState.IsValid) { community.ApplicationUserId = _userManager.GetUserId(User); community.BgImage = await UserFile.UploadeNewFileAsync(community.BgImage, myfile, _environment.WebRootPath, Properties.Resources.Community); community.Logo = await UserFile.UploadeNewImageAsync(community.Logo, myfile1, _environment.WebRootPath, Properties.Resources.Community, 50, 50); community.CreationDate = DateTime.Now; community.IsFeatured = false; community.IsSuspended = false; community.IsApproved = false; community.IsCommentsAllowed = true; community.SecurityLevel = SecurityLevel.Open; community.CommunityType = CommunityType.Community; _context.Add(community); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } ViewData["ApplicationUserId"] = new SelectList(_context.ApplicationUsers, "Id", "Id", community.ApplicationUserId); ViewData["SpecialityId"] = new SelectList(_context.Specialities, "Id", "Name", community.SpecialityId); return(View(community)); }
public async Task <IActionResult> Edit(int id, [Bind("Id,Question,CourseChapterId,Indx,IsHidden,Description,Imgurl")] CourseChapterExam courseChapterExam, IFormFile myfile) { if (id != courseChapterExam.Id) { return(NotFound()); } if (ModelState.IsValid) { try { courseChapterExam.Imgurl = await UserFile.UploadeNewImageAsync(courseChapterExam.Imgurl, myfile, _environment.WebRootPath, Properties.Resources.Secured, 500, 500); _context.Update(courseChapterExam); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!CourseChapterExamExists(courseChapterExam.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Edit", "CourseChapters", new { id = courseChapterExam.CourseChapterId })); } return(View(courseChapterExam)); }
private void onUpdate() { ShowUpdate = Visibility.Collapsed; ShowProgress = Visibility.Visible; UserFile.FinishUpdates += UserFile_FinishUpdate; UserFile.Upload(UserFile.FileFolder, childWindow.Dispatcher); }
public async Task <IActionResult> AddFile(IFormFileCollection uploads) { var login = HttpContext.User.Identity.Name; foreach (var uploadedFile in uploads) { var valid = uploadedFile.FileName.Split("."); if (valid[valid.Length - 1] != "txt") { break; } // путь к папке Files string path = "/Files/" + uploadedFile.FileName; // сохраняем файл в папку Files в каталоге wwwroot using (var fileStream = new FileStream(_appEnvironment.WebRootPath + path, FileMode.Create)) { await uploadedFile.CopyToAsync(fileStream); } User user = GetUser(db, HttpContext); UserFile file = new UserFile { Name = uploadedFile.FileName, Path = path, Time = DateTime.Now, UserId = user.Id, Previous = -1 }; db.Files.Add(file); } db.SaveChanges(); return(RedirectToAction("Index")); }
void CreateNewUser(UserFile userFile, string message) { var passwordForm = new FormPassword(); passwordForm.Message = message; passwordForm.ShowDialog(this); if (!passwordForm.Accepted) { return; } var user = userFile.Find(passwordForm.UserName); if (user != null) { MessageBox.Show(this, "This user already exists", App.Name); return; } // Create and save new user user = new User(); user.UserName = passwordForm.UserName; user.ResetPassword(passwordForm.Password); userFile.Users.Add(user); }
public async Task <IActionResult> TechnicalCreate(int sid, [Bind("Id,SubmissionId,JournalFileTypeId,FileName,Description")] SubmissionFile submissionFile, IFormFile myfile) { var sub = _context.Submissions.SingleOrDefault(a => a.Id == submissionFile.SubmissionId); var ManuscriptId = sub.ManuscriptId; var journalfile = _context.JournalFileTypes.SingleOrDefault(a => a.Id == submissionFile.JournalFileTypeId); if (ModelState.IsValid) { if (submissionFile.Description != null) { submissionFile.Description = submissionFile.Description.Replace("\n", "<br/>"); } if (journalfile.FileTypeId == 4) { submissionFile.FileName = await UserFile.UploadeNewFileAsync(submissionFile.FileName, myfile, _environment.WebRootPath, Properties.Resources.PublicationFiles); } else { submissionFile.FileName = await UserFile.UploadeNewFileAsync(submissionFile.FileName, myfile, _environment.WebRootPath, Properties.Resources.Secured); } _context.Add(submissionFile); await _context.SaveChangesAsync(); return(RedirectToAction("TechnicalEditorDetails", "Manuscripts", new { /* routeValues, for example: */ id = ManuscriptId })); } ViewData["JournalFileTypeId"] = new SelectList(_context.JournalFileTypes, "Id", "Id", submissionFile.JournalFileTypeId); ViewData["SubmissionId"] = new SelectList(_context.Submissions, "Id", "CoverLetter", submissionFile.SubmissionId); return(View(submissionFile)); }
private void AddFile(FileInfo file) { if (file.Exists) { string fileName = file.Name; //Create a new UserFile object IUserFile userFile = new UserFile(); userFile.FileName = file.Name; userFile.FileStream = file.OpenRead(); //Check for the file size limit (configurable) if (userFile.FileStream.Length <= Configuration.Instance.MaxFileSize) { //Add to the list _files.Add(userFile); } else { //MessageChildWindow messageWindow = new MessageChildWindow(); //messageWindow.Message = UserMessages.MaxFileSize + (_maxFileSize / 1024).ToString() + "KB."; //messageWindow.Show(); if (MaximumFileSizeReached != null) { MaximumFileSizeReached(this, null); } } } }
public int AddFile(string path) { var file = new UserFile(); file.Path = path; return(this.fileRepository.AddFile(file)); }
public void Id_is_not_null_or_blank_for_new_object() { // arrange // act var file = new UserFile(); // assert Assert.False(String.IsNullOrWhiteSpace(file.Id)); }
private string getPickIcon( List<BlogPost> blogPosts, UserFile x ) { Boolean isPick = pickService.IsPick( x ); if (isPick) { return string.Format( "<img src=\"{0}star.gif\" />", sys.Path.Img ); } else { return ""; } }
public void SimpleDbEntityHelper_reports_primary_key_is_Id() { var guid = Guid.NewGuid().ToString(); var request = new UserFile { Id = guid }; var helper = new SimpleDbEntityHelper(); // act var actual = helper.GetPrimaryKeyValueOfEntity<UserFile>(request); // assert Assert.That(actual, Is.EqualTo(guid)); }
public HttpFileUploader(UserFile file, string httpHandlerName) { _file = file; _dataLength = _file.FileStream.Length; _dataSent = 0; if(string.IsNullOrEmpty(httpHandlerName)) httpHandlerName = "HttpUploadHandler.ashx"; UploadUrl = new CustomUri(httpHandlerName).ToString(); }
public void Default_constructor_sets_UploadDate_to_now() { // arrange var dt = (new DateTime(2008, 3, 4, 2, 1, 3)).ToUniversalTime(); SystemTime.Now = () => dt; var expected = dt.ToTimestamp(); // act var file = new UserFile(); // assert Assert.That(file.UploadTimestamp, Is.EqualTo(expected)); }
public UserModel GetUser(string user) { var res = new UserModel(); var Temp = new UserFile<UserModel>().Read(user); if (Temp != null) { res = Temp; } res.UserID = user; return res; }
public static void RestoreModel(UserFile userFile, ref DataPersistency.BL.UserOptions.LoggingSystemOptions model) { DataPersistency.BL.UserOptions.UserOptions userOptions = new DataPersistency.BL.UserOptions.UserOptions(); if (fileInfo == null) { fileInfo = userOptions.GetFileInfo(userFile); } if (streamWriter == null) { streamWriter = fileInfo.AppendText(); streamWriter.AutoFlush = true; } DataPersistency.BL.UserOptions.LoggingSystemOptions mdl = (DataPersistency.BL.UserOptions.LoggingSystemOptions)model; List<string[]> filtredLines = new List<string[]>(); if (streamWriter != null) { streamWriter.Close(); streamWriter.Dispose(); streamWriter = null; } streamReader = fileInfo.OpenText(); string line = string.Empty; while ((line = streamReader.ReadLine()) != null) { filtredLines.Add(line.Split('\t')); } streamReader.Close(); streamReader.Dispose(); streamReader = null; mdl.LogNumbersNone = filtredLines[0][2].Equals("True") ? true : false; mdl.LogNumbersResults = filtredLines[1][2].Equals("True") ? true : false; mdl.LogNumbersParameters = filtredLines[2][2].Equals("True") ? true : false; mdl.LogNumbersCode = filtredLines[3][2].Equals("True") ? true : false; mdl.LogObjectsNone = filtredLines[4][2].Equals("True") ? true : false; mdl.LogObjectsResults = filtredLines[5][2].Equals("True") ? true : false; mdl.LogObjectsParameters = filtredLines[6][2].Equals("True") ? true : false; mdl.LogObjectsCode = filtredLines[7][2].Equals("True") ? true : false; mdl.LogRelationsNone = filtredLines[8][2].Equals("True") ? true : false; mdl.LogRelationsResults = filtredLines[9][2].Equals("True") ? true : false; mdl.LogRelationsParameters = filtredLines[10][2].Equals("True") ? true : false; mdl.LogRelationsCode = filtredLines[11][2].Equals("True") ? true : false; mdl.LogLogicsNone = filtredLines[12][2].Equals("True") ? true : false; mdl.LogLogicsResults = filtredLines[13][2].Equals("True") ? true : false; mdl.LogLogicsParameters = filtredLines[14][2].Equals("True") ? true : false; mdl.LogLogicsCode = filtredLines[15][2].Equals("True") ? true : false; }
public MainPage(IDictionary<string, string> initParams) { InitializeComponent(); if (initParams.ContainsKey("UploadContainerUrl") && !string.IsNullOrEmpty(initParams["UploadContainerUrl"])) { _uploadContainerUrl = initParams["UploadContainerUrl"]; } _file = new UserFile(); _file.FileFinished += _file_Finished; HtmlPage.RegisterScriptableObject("File", _file); HtmlPage.RegisterScriptableObject("MainPage", this); }
public virtual void PickPicOne( UserFile x ) { BlogPicPick pick = BlogPicPick.find( "FileId=" + x.Id ).first(); if (pick == null) { pick = new BlogPicPick(); } pick.FileId = x.Id; pick.BlogPost = BlogPost.findById( x.DataId ); pick.Title = x.Name; pick.Pic = x.PathRelative; pick.insert(); }
public WcfFileUploader(UserFile file) { #region 传送到服务器的实体 model = new SMT.Saas.Tools.NewFileUploadWS.UserFile(); model.SmtFileListId = file.SmtFileListId;// this.SmtFileListId;//主键ID model.FileName = file.CustomFileName;//文件名 model.FileType = file.FileType;//文件类型(.doc、.xls、.txt、.pdf......) model.FileUrl = file.FileUrl;//文件地址 model.FileSize = file.FileSize; model.CompanyCode = file.CompanyCode;//公司代号 model.CompanyName = file.CompanyName;//公司名字 model.SystemCode = file.SystemCode;//系统代号 model.ModelCode = file.ModelCode;//模块代号 model.ApplicationID = file.ApplicationID;//业务ID model.ThumbnailUrl = file.ThumbnailUrl;//缩略图地址 model.INDEXL = file.Indexl;//排序 model.Remark = file.Remark;//备注 model.CreateTime = file.CreateTime;//创建时间 model.CreateName = file.CreateName;//创建人 model.UpdateTime = file.UpdateTime;//修改时间 model.UpdateName = file.UpdateName;//修改人 model.SavePath = file.SavePath;//文件保存的目录 //model.OWNERCOMPANYID = file.ow #endregion _file = file; UserID = file.UserID; _dataLength = _file.FileStream.Length; _dataSent = 0;//已经上传的大小,如果是续传,这里要得到上传文的已经上的大小 SystemCode = file.SystemCode; ModelCode = file.ModelCode; Md5Name = file.MD5String; ID = file.ID; TempID = file.TempID; _client = new SMT.Saas.Tools.NewFileUploadWS.UploadServiceClient(); _client.SaveUpLoadFileCompleted += new EventHandler<SMT.Saas.Tools.NewFileUploadWS.SaveUpLoadFileCompletedEventArgs>(_client_SaveUpLoadFileCompleted); //新加 // _client.SaveUpLoadFileCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(_client_SaveUpLoadFileCompleted);//原来 _client.CancelUploadCompleted += new EventHandler<System.ComponentModel.AsyncCompletedEventArgs>(_client_CancelUploadCompleted); _client.CheckFileExistsCompleted += new EventHandler<SMT.Saas.Tools.NewFileUploadWS.CheckFileExistsCompletedEventArgs>(_client_CheckFileExistsCompleted); _client.ChannelFactory.Closed += new EventHandler(ChannelFactory_Closed); _client.GetCompanyFileSetInfoCompleted += new EventHandler<SMT.Saas.Tools.NewFileUploadWS.GetCompanyFileSetInfoCompletedEventArgs>(_client_GetCompanyFileSetInfoCompleted); _client.DeleteFileCompleted += new EventHandler<SMT.Saas.Tools.NewFileUploadWS.DeleteFileCompletedEventArgs>(_client_DeleteFileCompleted); _client.SaveUpLoadFileIsExistCompleted += new EventHandler<SMT.Saas.Tools.NewFileUploadWS.SaveUpLoadFileIsExistCompletedEventArgs>(_client_SaveUpLoadFileIsExistCompleted); }
public static void SaveModel(UserFile userFile, object model) { DataPersistency.BL.UserOptions.UserOptions userOptions = new DataPersistency.BL.UserOptions.UserOptions(); if (fileInfo == null) { fileInfo = userOptions.GetFileInfo(userFile); } if (streamWriter == null) { if (streamReader != null) { streamReader.Close(); streamReader.Dispose(); streamReader = null; } streamWriter = fileInfo.CreateText(); streamWriter.AutoFlush = true; } DataPersistency.BL.UserOptions.LoggingSystemOptions mdl = (DataPersistency.BL.UserOptions.LoggingSystemOptions)model; streamWriter.WriteLine("LogNumbersNone" + "\t" + mdl.LogNumbersNone.GetType() + "\t" + mdl.LogNumbersNone); streamWriter.WriteLine("LogNumbersResults" + "\t" + mdl.LogNumbersResults.GetType() + "\t" + mdl.LogNumbersResults); streamWriter.WriteLine("LogNumbersParameters" + "\t" + mdl.LogNumbersParameters.GetType() + "\t" + mdl.LogNumbersParameters); streamWriter.WriteLine("LogNumbersCode" + "\t" + mdl.LogNumbersCode.GetType() + "\t" + mdl.LogNumbersCode); streamWriter.WriteLine("LogObjectsNone" + "\t" + mdl.LogObjectsNone.GetType() + "\t" + mdl.LogObjectsNone); streamWriter.WriteLine("LogObjectsResults" + "\t" + mdl.LogObjectsResults.GetType() + "\t" + mdl.LogObjectsResults); streamWriter.WriteLine("LogObjectsParameters" + "\t" + mdl.LogObjectsParameters.GetType() + "\t" + mdl.LogObjectsParameters); streamWriter.WriteLine("LogObjectsCode" + "\t" + mdl.LogObjectsCode.GetType() + "\t" + mdl.LogObjectsCode); streamWriter.WriteLine("LogRelationsNone" + "\t" + mdl.LogRelationsNone.GetType() + "\t" + mdl.LogRelationsNone); streamWriter.WriteLine("LogRelationsResults" + "\t" + mdl.LogRelationsResults.GetType() + "\t" + mdl.LogRelationsResults); streamWriter.WriteLine("LogRelationsParameters" + "\t" + mdl.LogRelationsParameters.GetType() + "\t" + mdl.LogRelationsParameters); streamWriter.WriteLine("LogRelationsCode" + "\t" + mdl.LogRelationsCode.GetType() + "\t" + mdl.LogRelationsCode); streamWriter.WriteLine("LogLogicsNone" + "\t" + mdl.LogLogicsNone.GetType() + "\t" + mdl.LogLogicsNone); streamWriter.WriteLine("LogLogicsResults" + "\t" + mdl.LogLogicsResults.GetType() + "\t" + mdl.LogLogicsResults); streamWriter.WriteLine("LogLogicsParameters" + "\t" + mdl.LogLogicsParameters.GetType() + "\t" + mdl.LogLogicsParameters); streamWriter.WriteLine("LogLogicsCode" + "\t" + mdl.LogLogicsCode.GetType() + "\t" + mdl.LogLogicsCode); streamWriter.Close(); streamWriter = null; }
public virtual IPortfolioFileParser Create(UserFile userFile) { IPortfolioFileParser parser; var custodian = userFile.Custodian; switch (custodian) { case Custodian.Fidelity: { parser = new FidelityFileParser(); break; } default: { var msg = String.Format("No file parser has been defined for the custodian '{0}'.", custodian); throw new Exception(msg); } } return parser; }
public void CreatePutAttributesRequest_gets_correct_number_of_attributes_for_UserFile() { // arrange var client = AwsClientFactory.CreateSimpleDbClient(); var userFile = new UserFile { ClientFileName = "a", ContentLength = 1, CreateTimestamp = 2, FileSystemType = FileSystemType.S3, Id = "b", Location = "c", ModifyTimestamp = 3, }; const int expectedCount = 13; // act var request = client.CreatePutAttributesRequest<UserFile>(userFile); // assert var actualCount = request.Attribute.Count; Assert.That(actualCount, Is.EqualTo(expectedCount)); }
private void countDataCount( UserFile uFile ) { if (uFile.DataId <= 0 || strUtil.IsNullOrEmpty( uFile.DataType )) return; int fileCount = UserFile.find( "DataId=" + uFile.DataId + " and DataType=:dtype" ) .set( "dtype", uFile.DataType ) .count(); EntityInfo ei = Entity.GetInfo( uFile.DataType ); IEntity post = ndb.findById( ei.Type, uFile.DataId ); if (post != null) { String propertyName = "AttachmentCount"; if (ei.GetProperty( propertyName ) != null) { post.set( propertyName, fileCount ); db.update( post ); } else { logger.Warn( "property 'AttachmentCount' not exist: " + ei.Type.FullName ); } } }
private void updateDataInfo( UserFile uFile ) { long dataId = ctx.PostLong( "dataId" ); String dataType = ctx.Post( "dataType" ); if (dataId <= 0 || strUtil.IsNullOrEmpty( dataType )) return; uFile.DataId = dataId; uFile.DataType = dataType; uFile.update(); fileService.UpdateDataInfo( uFile ); }
public void Get_UserFile_returns_expected_value() { // arrange var guid = Guid.NewGuid().ToString(); var userFile = new UserFile { Id = guid, Location = "foo", FileSystemType = FileSystemType.S3, UserFileType = UserFileType.Test, CreatedBy = "test", RequestId = "foo", Status = UserFileStatus.Unknown, }; var client = AwsClientFactory.CreateSimpleDbClient(); var info = client.SaveEntity<UserFile>(userFile); // act var actual = client.Get<UserFile>(info.PrimaryKey, true); Assert.That(actual.Location, Is.EqualTo("foo")); }
private void LoadImage(UserFile fu) { if (fu != null && fu.DisplayThumbnail && (fu.FileName.ToLower().EndsWith("jpg") || fu.FileName.ToLower().EndsWith("png"))) { if (!imageSet) { BitmapImage imageSource = new BitmapImage(); try { imageSource.SetSource(fu.FileStream); imagePreview.Source = imageSource; imageSet = true; imagePreview.Visibility = Visibility.Visible; } catch (Exception e) { string message = e.Message; } } else imagePreview.Visibility = Visibility.Visible; } else imagePreview.Visibility = Visibility.Collapsed; }
public UploadFileViewModel CreateViewModel(UserFile datamodel) { if (datamodel == null) { throw new ArgumentNullException("datamodel"); } return new UploadFileViewModel() { Id = datamodel.Id, Name = datamodel.Name, ContentType = datamodel.ContentType, ContentSize = datamodel.Content.Length, Global = datamodel.Global, Owner = datamodel.Owner, IsPermanent = !datamodel.IsTemp, Created = datamodel.CreatedUTC, Url = _UrlHelper.Link("GetFileById", new { fileId = datamodel.Id }) }; }
public virtual bool IsPick( UserFile x ) { BlogPicPick pick = BlogPicPick.find( "FileId=" + x.Id ).first(); return pick != null; }
protected internal virtual SaveEntityInfo SaveUserFileRecord(string requestId, PortfolioFileInfo fileInfo) { var nowTimestamp = SystemTime.Now().ToTimestamp(); var file = new UserFile { ClientFileName = fileInfo.ClientFileName, CreatedBy = "system", ModifiedBy = "system", CreateTimestamp = nowTimestamp, ModifyTimestamp = nowTimestamp, FileSystemType = fileInfo.FileSystemType, Location = fileInfo.Uri, RequestId = requestId, Status = UserFileStatus.Pending, UploadTimestamp = fileInfo.UploadTimestamp, UserFileType = UserFileType.Portfolio, }; var info = this.SimpleDbClient.SaveEntity<UserFile>(file); return info; }
/// <summary> /// 增加上传文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void addFilesButton_Click(object sender, RoutedEventArgs e) {//第2步 string files1 = ","; string TempID = ""; OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = Multiselect;//是否可以多选 try { if (!string.IsNullOrEmpty(Filter)) ofd.Filter = Filter; } catch (ArgumentException ex) { throw new Exception("不是正确的上传格式.", ex); } //string StrSpecial = @"~!@#$%^&*()_+- =`;:'\<>;~!@#¥%……&*()——+=-·";//特殊字符串 List<string> StrSpecial = GetSpecialString(); if (ofd.ShowDialog() == true) { foreach (FileInfo file in ofd.Files) { if (file.Length == 0) { MessageBox.Show(file.Name+":文件内容不能为空!"); continue; } string[] StrFrontName = file.Name.Split('.'); //控制文件名不为特殊字符 if (StrFrontName.Count() > 1) { var ents = from ent in StrSpecial where StrFrontName[0].Contains(ent) || StrFrontName[1].Contains(ent) select ent; if (ents.Count() > 0) { MessageBox.Show(file.Name + "文件名存在特殊字符(*&^%$#@!~`?=+|><';:.,)请重新命名!"); continue; } } string fileName = file.Name; UserFile userFile = new UserFile(); #region 用户定义设置 userFile.SavePath = this.SavePath;//文件保存位置目录 userFile.SmtFileListId = Guid.NewGuid().ToString();// this.SmtFileListId;//主键ID userFile.CustomFileName = String.IsNullOrEmpty(this.CustomFileName) ? file.Name : this.CustomFileName;//文件名(用户自定义) userFile.FileName =file.Name;//文件名 userFile.FileType = file.Extension;//文件类型(.doc、.xls、.txt、.pdf......) userFile.FileUrl = this.FileUrl;//文件地址 userFile.FileSize =Convert.ToDouble(file.Length);// userFile.CompanyCode = this.CompanyCode;//公司代号 userFile.CompanyName = this.CompanyName;//公司名字 userFile.SystemCode = this.SystemCode;//系统代号 userFile.ModelCode = this.ModelCode;//模块代号 userFile.ThumbnailUrl = this.ThumbnailUrl;//缩略图地址 int fileCount = _files.Count() + 1; userFile.Indexl = fileCount;//排序 userFile.Remark = this.Remark;//备注 userFile.CreateTime =this.CreateTime;//创建时间 userFile.CreateName = this.CreateName;//创建人 userFile.UpdateTime = this.UpdateTime;//修改时间 userFile.UpdateName = this.UpdateName;//修改人 userFile.ApplicationID = this.ApplicationID;//业务ID userFile.NotShowDeleteButton = this.NotShowDeleteButton;//不显示删除按钮 userFile.ID = this.ApplicationID; userFile.UserID = this.UserID; #endregion //userFile.FileName = file.Name; //userFile.SystemCode = this.SystemCode; //userFile.ModelCode = this.ModelCode; //userFile.FileType = this.FileType; userFile.FileStream = file.OpenRead(); userFile.UIDispatcher = this.Dispatcher; userFile.DisplayThumbnail = (bool)displayThumbailChckBox.IsChecked; userFile.MD5String = MD5FileName(file.Name, file.Length.ToString(), UserID, SystemCode, ModelCode,this.ApplicationID) + file.Extension; userFile.UploadProgressChanged += new ProgressChangedEvent(userFile_UploadProgressChanged); userFile.FileFinished += new UserFile.DelegateFinish(userFile_FileFinished); while (true) { TempID = GetTmpID(); if (files1.IndexOf("," + TempID + ",") == -1) break; } files1 = files1 + TempID + ","; userFile.TempID = TempID; if (userFile.FileStream.Length <= MaxSize) { if (_files.Count > 0) { #region 不加重复 bool bol = false; for (int i = 0; i < _files.Count; i++) { if (_files[i].FileName == userFile.FileName && _files[i].FileSize == userFile.FileSize) {//不加重复 bol = true;//有重复 } } if(!bol) { _files.Add(userFile); } } else { _files.Add(userFile); } #endregion // _files.Add(userFile); } else { MessageChildWindow messageWindow = new MessageChildWindow(); // messageWindow.Message = "Maximum file size is: " + (MaxSize / 1024).ToString() + "KB."; messageWindow.Message = "文件最大限制为: " + ByteConverter.GetSizeName(MaxSize); messageWindow.Show(); } } } }
private string getFileInfo( UserFile x ) { if (x.IsPic == 1) { return string.Format( "<a href='{0}' target='_blank'><img src='{1}' /></a>", x.PicO, x.PicS ); } return string.Format( "<a href='{0}' target='_blank'>{1}</a>", x.PathFull, "下载" ); }
private string getDataLink( List<BlogPost> blogPosts, UserFile x ) { foreach (BlogPost post in blogPosts) { if (post.Id == x.DataId) return alink.ToAppData( post ); } return ""; }
void userFile_FileFinished(UserFile _userfile) { if (FileCompleted != null) { FileCompleted(); } }
/// <summary> /// 增加上传文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void addFilesButton_Click(object sender, RoutedEventArgs e) { string files1=","; string TempID = ""; OpenFileDialog ofd = new OpenFileDialog(); ofd.Multiselect = true; try { if (!string.IsNullOrEmpty(Filter)) ofd.Filter = Filter; } catch (ArgumentException ex) { throw new Exception("不是正确的上传格式.", ex); } if (ofd.ShowDialog() == true) { foreach (FileInfo file in ofd.Files) { string fileName = file.Name; UserFile userFile = new UserFile(); userFile.ID = ApplicationID; userFile.UserID = UserID; userFile.FileName = file.Name; userFile.FileStream = file.OpenRead(); userFile.UIDispatcher = this.Dispatcher; userFile.SystemCode = this.SystemCode; userFile.ModelCode = this.ModelCode; userFile.Indexl = 1; userFile.DisplayThumbnail = (bool)displayThumbailChckBox.IsChecked; userFile.MD5String = MD5FileName(file.Name, file.Length.ToString(), UserID,SystemCode,ModelCode) + file.Extension; userFile.UploadProgressChanged += new ProgressChangedEvent(userFile_UploadProgressChanged); userFile.FileFinished += new UserFile.DelegateFinish(userFile_FileFinished); while (true) { TempID = GetTmpID(); if (files1.IndexOf("," + TempID + ",") == -1) break; } files1 = files1 + TempID + ","; userFile.TempID = TempID; if (userFile.FileStream.Length <= MaxSize) { _files.Add(userFile); } else { MessageChildWindow messageWindow = new MessageChildWindow(); messageWindow.Message = "Maximum file size is: " + (MaxSize / 1024).ToString() + "KB."; messageWindow.Show(); } } } }
public UserFile CreateModel(UploadFileViewModel viewModel, UserFile datamodel) { var result = datamodel; result.Name = viewModel.Name; result.ContentType = viewModel.ContentType; result.Global = viewModel.Global; result.IsTemp = !viewModel.IsPermanent; result.CreatedUTC = viewModel.Created; return result; }
protected void UploadButton_Click(object sender, EventArgs e) { // Specify the path on the server to // save the uploaded file to. String savePath = Path.Combine(Request.PhysicalApplicationPath, "UserFiles"); // Before attempting to perform operations // on the file, verify that the FileUpload // control contains a file. if (FileUpload1.HasFile) { // Get the name of the file to upload. String fileName = FileUpload1.FileName; String savedFileName = String.Empty; int postfix = 0; // Append the name of the file to upload to the path. do { if (postfix == 0) { savedFileName = Path.Combine(new string[] {savePath, fileName}); } else { savedFileName = Path.Combine(new string[] {savePath, Path.GetFileNameWithoutExtension(fileName) + "_" + postfix + Path.GetExtension(fileName)}); } postfix++; } while (File.Exists(savedFileName)); FileUpload1.SaveAs(savedFileName); using (ProductProvider provider = new ProductProvider()) { var userFile = new UserFile() { id = Guid.NewGuid(), pid = GetPID, cid = Guid.Empty, filename = Path.GetFileName(savedFileName), username = Path.GetFileNameWithoutExtension(fileName) }; provider.UserFiles.InsertOnSubmit(userFile); provider.SubmitChanges(); } DataBind(); // Notify the user of the name of the file // was saved under. // UploadStatusLabel.Text = "Your file was saved as " + fileName; } else { // Notify the user that a file was not uploaded. // UploadStatusLabel.Text = "You did not specify a file to upload."; } }
public UserFile CreateModel(CreateUploadFileViewModel viewModel, UserFile datamodel = null) { var fileContent = new byte[viewModel.TempFileInfo.Length]; using (var reader = viewModel.TempFileInfo.OpenRead()) { reader.Read(fileContent, 0, fileContent.Length); } var result = datamodel ?? new UserFile() { Id = Guid.NewGuid() }; result.Name = viewModel.FileName; result.ContentType = viewModel.ContentType; result.Content = fileContent; result.CreatedUTC = viewModel.TempFileInfo.CreationTimeUtc; result.Global = viewModel.Global; result.UserId = viewModel.Owner.ToString(); return result; }
private UserFile ParseImage(string imagePath) { UserFile userFile = new UserFile(); try { System.Drawing.Image imageToConvert = System.Drawing.Image.FromFile(imagePath); using (MemoryStream ms = new MemoryStream()) { imageToConvert.Save(ms, imageToConvert.RawFormat); userFile.FileName = Path.GetFileNameWithoutExtension(imagePath); userFile.Extension = Path.GetExtension(imagePath); userFile.FileContent = ms.ToArray(); userFile.AccountId = Convert.ToInt16(accountId); userFile.TimeStamp = DateTime.Now; } } catch (Exception) { userFile = null; } return userFile; }