public async Task <IActionResult> PutDocumentFile([FromRoute] int id, [FromBody] DocumentFile documentFile) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != documentFile.DocumentFileId) { return(BadRequest()); } _context.Entry(documentFile).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!DocumentFileExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
private async Task <RestoreResult> RestoreFromDir(Uri destUri) { if (!HasPersistablePermissionsAtUri(destUri)) { throw new InvalidOperationException("No permission at URI"); } var directory = DocumentFile.FromTreeUri(_context, destUri); var files = directory.ListFiles(); var mostRecentBackup = files .Where(f => f.IsFile && f.Type == Backup.MimeType && f.Name.EndsWith(Backup.FileExtension) && f.Length() > 0 && f.CanRead()) .OrderByDescending(f => f.LastModified()) .FirstOrDefault(); if (mostRecentBackup == null || mostRecentBackup.LastModified() <= _preferences.MostRecentBackupModifiedAt) { return(new RestoreResult()); } _preferences.MostRecentBackupModifiedAt = mostRecentBackup.LastModified(); var password = await GetBackupPassword(); if (password == null) { throw new InvalidOperationException("No password defined."); } var data = await FileUtil.ReadFile(_context, mostRecentBackup.Uri); var backup = Backup.FromBytes(data, password); return(await _restoreService.RestoreAndUpdateAsync(backup)); }
void df_Click(object sender, EventArgs e) { DocumentFile df = (DocumentFile)sender; frmShowInfo frm = new frmShowInfo(df.name); frm.ShowDialog(); }
public DocumentFileModel(DocumentFile documentFile, IDialogService dialogService) { this.documentFile = documentFile; this.dialogService = dialogService; documentFile.Changed += DocumentFile_Changed; }
public DynamicRenderDocument(DocumentFile document, LayoutFile layout, Site site) : base(document.SourceRelativePath) { _document = document; _layout = layout; _site = site; }
public DynamicLayoutFile(DocumentFile activeDocument, LayoutFile layout, Site site) : base(layout.SourceRelativePath) { this.ActiveDocument = activeDocument; this.Layout = layout; this.Site = site; }
private string GetFirstFieldValue(DocumentFile documentFile, string fieldName) { return(documentFile.DocumentFieldList .Where(x => x.FieldName == fieldName) .Select(x => x.FieldValueList.First()) .First()); }
public DynamicPaginator(DocumentFile activeDocument, Paginator Paginator, Site site) : base(null) { this.ActiveDocument = activeDocument; this.Paginator = Paginator; this.Site = site; }
public JsonResult DeleteFile(Guid? id) { if (String.IsNullOrEmpty(id.ToString())) { Response.StatusCode = (int)HttpStatusCode.BadRequest; return Json(new { Result = "Error" }); } try { Guid guid = new Guid(id.ToString()); DocumentFile fileDetail = db.DocumentFiles.Find(id); if (fileDetail == null) { Response.StatusCode = (int)HttpStatusCode.NotFound; return Json(new { Result = "Error" }); } //Remove from database db.DocumentFiles.Remove(fileDetail); db.SaveChanges(); //Delete file from the file system var path = Path.Combine(Server.MapPath(_uploadPath), fileDetail.Id + fileDetail.Path); if (System.IO.File.Exists(path)) { System.IO.File.Delete(path); } return Json(new { Result = "OK" }); } catch (Exception ex) { return Json(new { Result = "ERROR", Message = ex.Message }); } }
/// <summary> /// liefert selbst innerhalb des secondary ext. storage bei Oreo eine Exception: "Copy not supported" /// <para>Das scheint eine Exception der abstrakten Klasse DocumentProvider zu sein, d.h. die Copy-Funktion wurd in der konkreten Klasse nicht implemetiert. /// Das Flag FLAG_SUPPORTS_COPY für Dokumente fehlt (deswegen).</para> /// </summary> /// <param name="storagenamesrc"></param> /// <param name="volpathsrc"></param> /// <param name="storagenamenewparent"></param> /// <param name="volpathnewparent"></param> /// <returns></returns> public bool Copy(string storagenamesrc, string volpathsrc, string storagenamenewparent, string volpathnewparent) { DocumentFile srcdoc = GetExistingDocumentFile(storagenamesrc, volpathsrc); DocumentFile dstparentdoc = GetDocumentFile(storagenamenewparent, volpathnewparent, true); // Zielverzeichnis (wird notfalls erzeugt) /* Added in API level 24; Nougat, 7.0, Deprecated in API level Q * * public static Uri copyDocument (ContentResolver content, * Uri sourceDocumentUri, Document mit FLAG_SUPPORTS_COPY * Uri targetParentDocumentUri) * * neu: * ContentProviderClient provclient = Activity.ContentResolver.AcquireUnstableContentProviderClient(srcdoc.Uri.Authority); * DocumentsContract.CopyDocument(provclient, srcdoc.Uri, dstparentdoc.Uri); * * intern: * Bundle inbundle = new Bundle(); * inbundle.PutParcelable(DocumentsContract.EXTRA_URI, srcdoc.Uri); "uri" * inbundle.PutParcelable(DocumentsContract.EXTRA_TARGET_URI, dstparentdoc.Uri); "android.content.extra.TARGET_URI" * Bundle outbundle = provclient.Call(METHOD_COPY_DOCUMENT, null, inbundle); "android:copyDocument" * return outbundle.GetParcelable(DocumentsContract.EXTRA_URI); "uri" */ global::Android.Net.Uri newuri = DocumentsContract.CopyDocument(Activity.ContentResolver, srcdoc.Uri, dstparentdoc.Uri); System.Diagnostics.Debug.WriteLine("AndroidCopy(" + storagenamesrc + ", " + volpathsrc + ", " + storagenamenewparent + ", " + volpathnewparent + ") = " + (newuri != null).ToString()); return(newuri != null); }
public void DeleteFile(string path) { Android.Net.Uri uri; string auth = "com.Linaq.LinaqStorage.Android.fileprovider"; string mimeType = Android.Webkit.MimeTypeMap.Singleton.GetMimeTypeFromExtension(Android.Webkit.MimeTypeMap.GetFileExtensionFromUrl(path.ToLower())); if (mimeType == null) { mimeType = "*/*"; } if (path.StartsWith("content://")) { uri = Android.Net.Uri.Parse(path); DocumentFile pickedDir = DocumentFile.FromSingleUri(Android.App.Application.Context, uri); if (pickedDir.Exists()) { pickedDir.Delete(); } } else { var file = new Java.IO.File(Path.Combine(Android.App.Application.Context.FilesDir.Path, path)); file.Delete(); // uri = FileProvider.GetUriForFile(Android.App.Application.Context, auth, file); } }
/// <summary> /// Die Variante mit File-Uri fkt. nur im primary external storage und der Stream ist genauso eingeschränkt wie bei der Content-Uri. /// </summary> /// <param name="fullpath"></param> /// <param name="mode"></param> /// <returns></returns> //public Stream CreateOpenFile(string fullpath, string mode) { // Android.Net.Uri uri = Android.Net.Uri.FromFile(new Java.IO.File(fullpath)); // return mode == "r" ? // Activity.ContentResolver.OpenInputStream(uri) : // Activity.ContentResolver.OpenOutputStream(uri, mode); //} /// <summary> /// liefert einen Dateistream (erzeugt die Datei bei Bedarf) /// <para>ACHTUNG: Der Stream erfüllt nur primitivste Bedingungen. Er ist nicht "seekable", es wird keine Position oder Länge geliefert. /// Auch ein "rwt"-Stream scheint nur beschreibbar zu sein.</para> /// </summary> /// <param name="storagename">z.B. "primary" oder "19F4-0903"</param> /// <param name="volpath">abs. Pfad im Volume</param> /// <param name="mode">May be "w", "wa", "rw", or "rwt". This value must never be null. Zusatz: "r" verwendet OpenInputStream()</param> /// <returns></returns> public Stream CreateOpenFile(string storagename, string volpath, string mode) { DocumentFile doc = GetDocumentFile(storagename, volpath, false); if (doc != null) { /* * InputStream openInputStream(Uri uri) Open a stream on to the content associated with a content URI. * If there is no data associated with the URI, FileNotFoundException is thrown. * Accepts the following URI schemes: * content(SCHEME_CONTENT) * android.resource (SCHEME_ANDROID_RESOURCE) * A Uri object can be used to reference a resource in an APK file. * z.B.: * Uri uri = Uri.parse("android.resource://com.example.myapp/" + R.raw.my_resource"); * Uri uri = Uri.parse("android.resource://com.example.myapp/raw/my_resource"); * file(SCHEME_FILE) * * OutputStream openOutputStream(Uri uri) Synonym for openOutputStream(uri, "w") * OutputStream openOutputStream(Uri uri, String mode) Open a stream on to the content associated with a content URI. * If there is no data associated with the URI, FileNotFoundException is thrown. * mode: May be "w", "wa", "rw", or "rwt". This value must never be null. * Accepts the following URI schemes: * content(SCHEME_CONTENT) * file(SCHEME_FILE) */ return(mode == "r" ? Activity.ContentResolver.OpenInputStream(doc.Uri) : Activity.ContentResolver.OpenOutputStream(doc.Uri, mode)); } return(null); }
/// <summary> /// Ändert den Objektnamen (API level 14) /// </summary> /// <param name="storagename">z.B. "primary" oder "19F4-0903"</param> /// <param name="volpath">abs. Pfad im Volume</param> /// <param name="newfilename"></param> /// <returns></returns> public bool Rename(string storagename, string volpath, string newfilename) { if (newfilename.Contains('/')) { throw new Exception("Path for newname is not allowed."); } /* * boolean renameTo (String displayName) * * Renames this file to displayName. * Note that this method does not throw IOException on failure. Callers must check the return value. * Some providers may need to create a new document to reflect the rename, potentially with a different MIME type, so getUri() and getType() may change to reflect the rename. * When renaming a directory, children previously enumerated through listFiles() may no longer be valid. * * Parameters * displayName String: the new display name. * * Returns * boolean true on success. */ DocumentFile doc = GetExistingDocumentFile(storagename, volpath); bool ok = doc.RenameTo(newfilename); System.Diagnostics.Debug.WriteLine("AndroidRename(" + storagename + ", " + volpath + ", " + newfilename + ") = " + ok.ToString()); return(ok); }
/// <summary> /// liefert das DocumentFile für eine Datei oder ein Verzeichnis (API level 14) /// <para>Wenn das Objekt noch nicht ex., wird es erzeugt. Auch ein notwendiger Pfad wird vollständig erzeugt.</para> /// </summary> /// <param name="storagename">z.B. "primary" oder "19F4-0903"</param> /// <param name="volpath">abs. Pfad im Volume</param> /// <param name="isDirectory">Pfad bezieht sich auf eine Datei oder ein Verzeichnis</param> /// <returns></returns> public DocumentFile GetDocumentFile(string storagename, string volpath, bool isDirectory) { global::Android.Net.Uri rooturi = GetTreeDocumentUri(storagename); DocumentFile document = DocumentFile.FromTreeUri(Activity.ApplicationContext, rooturi); string[] pathelems = volpath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries); for (int i = 0; document != null && i < pathelems.Length; i++) { DocumentFile nextDocument = document.FindFile(pathelems[i]); if (nextDocument == null) { if ((i < pathelems.Length - 1) || isDirectory) { nextDocument = document.CreateDirectory(pathelems[i]); } else { nextDocument = document.CreateFile("", pathelems[i]); } } document = nextDocument; } System.Diagnostics.Debug.WriteLine("AndroidGetDocumentFile(" + storagename + ", " + volpath + ", " + isDirectory.ToString() + ") = " + (document != null && (isDirectory == document.IsDirectory)).ToString()); return(document != null ? (isDirectory == document.IsDirectory ? document : null) : null); }
public static List <DocumentFile> GetFilesForTutorial(int tutorialId) { DocumentFileDSTableAdapters.FileInfoTableAdapter ta = new DocumentFileDSTableAdapters.FileInfoTableAdapter(); DocumentFileDS.FileInfoDataTable table = ta.GetFilesByTutorial(tutorialId); List <DocumentFile> fileList = new List <DocumentFile>(); if (table.Count > 0) { foreach (DocumentFileDS.FileInfoRow row in table) { fileList.Add(DocumentFile.CreateNewTypedDocumentFileObject( row.fileID, row.uploadedOn, row.fileSize, row.fileName, row.extension, row.title, row.fileStoragePath)); } } return(fileList); }
public static List <DocumentFile> GetFilesByStorageFolder(string folderName) { if (string.IsNullOrEmpty(folderName)) { return(null); } folderName = folderName + "%"; DocumentFileDSTableAdapters.FileInfoTableAdapter ta = new DocumentFileDSTableAdapters.FileInfoTableAdapter(); DocumentFileDS.FileInfoDataTable table = ta.GetFilesByStoragePathName(folderName); List <DocumentFile> fileList = new List <DocumentFile>(); if (table.Count > 0) { foreach (DocumentFileDS.FileInfoRow row in table) { fileList.Add(DocumentFile.CreateNewTypedDocumentFileObject( row.fileID, row.uploadedOn, row.fileSize, row.fileName, row.extension, row.title, row.fileStoragePath)); } } return(fileList); }
public IActionResult AddDocumentFile(DocumentFile df) { df.numberOf_document = 0; dbContext.documentFiles.Add(df); dbContext.SaveChanges(); return(RedirectToAction("Index")); }
private async void BindFileList() { List <DocumentFile> lstDocFiles = new List <DocumentFile>(); string SavedFolderPath = _parentFolderPath; PermissionStatus status = await PermissionUtilities.GetInstance().RequestExtrenalStorageReadPermission(); if (Directory.Exists(SavedFolderPath) && status == PermissionStatus.Granted) { string[] filesList = Directory.GetFiles(SavedFolderPath); int slNo = 1; foreach (string file in filesList) { DocumentFile docFile = new DocumentFile(); docFile.FullFilePath = file; docFile.FileName = Path.GetFileName(file); docFile.FileType = Path.GetExtension(file); docFile.SlNo = slNo; lstDocFiles.Add(docFile); slNo++; } lstDocuments.ItemsSource = lstDocFiles; } }
public async Task <bool> RemoveFileIfExists(ContentType accessType, string filename, string storageLocationBase) { var fileIfExists = GetPathIfFileExists(accessType, filename, storageLocationBase); if (!fileIfExists.Exists) { return(false); } switch (accessType) { case ContentType.DirectAccess: File.Delete(fileIfExists.Path); await Task.Delay(50); return(true); case ContentType.StorageFramework: var doc = DocumentsContract.BuildDocumentUriUsingTree(Uri.Parse(storageLocationBase), fileIfExists.Path); DocumentFile file = DocumentFile.FromTreeUri(Android.App.Application.Context, doc); await Task.Delay(50); return(file.Delete()); default: throw new ArgumentOutOfRangeException(nameof(accessType), accessType, null); } }
public DynamicDataFile(DocumentFile activeDocument, DataFile dataFile, Site site) : base(dataFile, dataFile.Metadata) { this.ActiveDocument = activeDocument; this.DataFile = dataFile; this.Site = site; }
public DynamicBook(DocumentFile activeDocument, Book book, Site site) : base(null) { this.ActiveDocument = activeDocument; this.Book = book; this.Site = site; }
/// <summary> /// Pulishes all relevant documents matching the target folder branch /// </summary> /// <param name="TargetFolderBranch">Filter of the target branch applied to documents that are published.</param> public void Publish(string FilterFolderBranch) { if (FilterFolderBranch == null) { FilterFolderBranch = ""; } // build the target root folder string FilterFolderPath = BuildPath(this.TargetRootFolder, FilterFolderBranch); DocumentFile.AssertFolderExists(FilterFolderPath); // get file info under the target root this.FileInfoStore = GetFileInfoStoreFromPath(FilterFolderPath, true); // get target folders to publish string[] TargetFolderBranches = AppContext.Documents .Where(d => d.IgnoreFlag == Document.FALSE_FLAG_VALUE && d.TargetFolderBranch.StartsWith(FilterFolderBranch)) .Select(b => b.TargetFolderBranch) .Distinct() .ToArray <string>(); string TargetFolderPath = null; // loop through folders foreach (string TargetFolderBranch in TargetFolderBranches) { TargetFolderPath = BuildPath(this.TargetRootFolder, TargetFolderBranch); PublishFolder(TargetFolderPath, TargetFolderBranch); } }
public void Update(string serverUrl, string loginId, string authToken, DbFileJob dbFileJob) { lock (this) { var filePath = dbFileJob.FilePath; if (!File.Exists(filePath)) { return; } var fileReader = this.BuildFileReader(filePath); if (fileReader == null) { return; } var modelId = this.GetDocumentIdByFilePathFromDataBase.Execute(filePath); if (modelId == null) { return; } DateTime fileCreatedAt = File.GetCreationTime(filePath); DateTime fileUpdatedAt = File.GetLastWriteTime(filePath); var fileContent = fileReader.Execute(); var documentFile = new DocumentFile(modelId.Value, Path.GetFileName(filePath), filePath, fileContent, string.Empty, fileCreatedAt, fileUpdatedAt); this.DocumentFileService.UpdateDocumentFile(serverUrl, loginId, authToken, documentFile); this.UpdateFileToDataBase.Execute(filePath, fileCreatedAt, fileUpdatedAt); } }
public void AppendErrorText(DocumentFile document, string text) { outputParagraphs[document].Inlines.Add(new Run(text) { Foreground = (Brush)FindResource("ErrorForeground") }); }
private void ResetBuildResult(DocumentFile documentFile) { if (lastBuildResult != null && lastBuildResult.Item1 == documentFile) { lastBuildResult = null; } }
public async Task <IActionResult> DeleteConfirmed(int id) { var document = await _context.Documents.Include(m => m.File).SingleOrDefaultAsync(m => m.DocumentId == id); var file = await _context.DocumentFiles /*.Include(m => m.PrevVersion)*/.SingleOrDefaultAsync(m => m.DocumentFileId == document.File.DocumentFileId); DocumentFile nextFile = null; do { //if(file.PrevVersion != null) // nextFile = await _context.DocumentFiles.Include(m => m.PrevVersion).SingleOrDefaultAsync(m => m.DocumentFileId == file.PrevVersion.DocumentFileId); _context.DocumentFiles.Remove(file); if (nextFile == null) { break; } else { file = nextFile; } } while (true); _context.Documents.Remove(document); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); }
public void Create(DocumentFile d) { d.DocumentId = d.DocumentId ?? paths.GetIDFromDocumentPath(d.DocumentPath); var fileExists = client.Cypher .WithParams(new { documentId = d.DocumentId }) .Match("(parent:Document { ID: {documentId} })<-[:FILE_FOR]-(f:DocumentFile)") .Return <DocumentFile>("f") .Results .Any(); if (fileExists) { throw new Exception("File already exists for this document."); } // Attach to root folder client.Cypher .WithParams(new { documentId = d.DocumentId, file = new { d.Data, d.MimeType } }) .Match("(parent:Document { ID: {documentId} })") .Create("parent<-[:FILE_FOR]-(:DocumentFile {file})") .ExecuteWithoutResults(); }
private CodeEditorViewModel CreateDocumentViewModel(DocumentFile document) { var viewModel = codeEditorViewModelFactory.CreateExport().Value; viewModel.DocumentFile = document; return(viewModel); }
public JsonResult Post([FromBody] DocumentFileViewModel data) { var response = new DocumentUploadResponse(); if (data.TypeId != 0) { var docType = _unitOfWork.DocumentDataType.Get(data.TypeId); var newitem = new DocumentFile { BuildingFloorId = data.BuildingFloorId, BuildingId = data.BuildingId, Type = docType, Description = data.Description, DocumentId = data.DocumentId, Id = data.Id, Name = data.Name, WebPath = data.WebPath }; _unitOfWork.Documentfiles.Add(newitem); _unitOfWork.SaveChanges(); } else { response.AddError(0, "Моля Изберете Тип на документа"); } return(new JsonResult(response)); }
public DynamicBookPage(DocumentFile activeDocument, BookPage bookPage, Site site) : base(null) { this.ActiveDocument = activeDocument; this.BookPage = bookPage; this.Site = site; }
public void PublishDocument(string SourceFilePath, string TargetFolderPath, string TargetFileName, string DocumentHash) { // rename file in the same directory with Hash DocumentFileInfo dfi = this.FileInfoStore.Where(x => x.DocumentHash.Equals(DocumentHash)).FirstOrDefault(); string TargetFilePath = BuildPath(TargetFolderPath, TargetFileName); // if the document exists under the root folder... if (dfi != null) { // if target path is different // otherwise no action is required: file name and hash are identical if (!dfi.FilePath.Equals(TargetFilePath)) { Console.WriteLine("Moving file to \"{0}\".", TargetFilePath); // move the file and rename it DocumentFile.MoveFile(dfi.FilePath, TargetFilePath); } } else { try { Console.WriteLine("Copying file to \"{0}\".", TargetFilePath); // otherwise copy file from source (outside root folder) DocumentFile.CopyFile(SourceFilePath, TargetFilePath); } catch (Exception ex) { Console.WriteLine("ERROR: Unable to copy the file \"{0}\" to \"{1}\". {2}", SourceFilePath, TargetFilePath, ex.Message); } } }
public async Task <IActionResult> Create(DocumentViewModel documentViewModel) { if (ModelState.IsValid) { var document = new Document(); var project = _context.Projects.Include(p => p.Documents) .FirstOrDefault(p => p.ProjectId == documentViewModel.ProjectId); var file = new DocumentFile(); file.Name = documentViewModel.Name; file.ModifiedTime = DateTime.Now; file.OwnerDocumentId = document.DocumentId; using (var memoryStream = new MemoryStream()) { await documentViewModel.Data.CopyToAsync(memoryStream); file.Data = memoryStream.ToArray(); } _context.Add(file); document.File = file; project.Documents.Add(document); _context.Add(document); await _context.SaveChangesAsync(); file.OwnerDocumentId = document.DocumentId; _context.Update(file); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } return(View(documentViewModel)); }
public void Add(string serverUrl, string loginId, string authToken, DbFileJob dbFileJob) { lock (this) { var filePath = dbFileJob.FilePath; if (!File.Exists(filePath)) { return; } var fileReader = this.BuildFileReader(filePath); if (fileReader == null) { return; } var fileContent = fileReader.Execute(); DateTime fileCreatedAt = File.GetCreationTime(filePath); DateTime fileUpdatedAt = File.GetLastWriteTime(filePath); System.Diagnostics.Debug.WriteLine("*** updated " + fileUpdatedAt.ToString()); var documentFile = new DocumentFile(Path.GetFileName(filePath), filePath, fileContent, string.Empty, fileCreatedAt, fileUpdatedAt); var modelId = this.DocumentFileService.AddDocumentFile(serverUrl, loginId, authToken, documentFile); this.AddFileToDataBase.Execute(filePath, modelId.Value, fileCreatedAt, fileUpdatedAt); } }
void df_Click(object sender, EventArgs e) { DocumentFile df = (DocumentFile)sender; //播放语音 backgroundWorker1.RunWorkerAsync(df.name); }
public DocumentFile GetDocumentFile(int id) { using (SqlConnection connection = new SqlConnection(connectionString)) { using (SqlCommand command = connection.CreateCommand()) { command.CommandText = selectQuery + "WHERE doc.Id = @Id "; command.Parameters.AddWithValue("@Id", id); connection.Open(); var reader = command.ExecuteReader(); if (reader.HasRows) { if (reader.Read()) { DocumentFile folder = Read(reader); return(folder); } } } } return(null); }
public DynamicDocumentFile(DocumentFile activeDocument, DocumentFile document, Site site) : base(document) { this.ActiveDocument = activeDocument; this.Document = document; this.Site = site; }
public static DocumentFileViewModel ConvertToDocumentFileViewModel(this DocumentFile DocumentFile) { DocumentFileViewModel DocumentFileViewModel = new DocumentFileViewModel() { Id = DocumentFile.Id, Identifier = DocumentFile.Identifier, Name = DocumentFile.Name, Path = DocumentFile.Path, Size = DocumentFile.Size, DocumentFolder = DocumentFile?.DocumentFolder?.ConvertToDocumentFolderViewModelLite(), IsActive = DocumentFile.Active, Company = DocumentFile.Company?.ConvertToCompanyViewModelLite(), CreatedBy = DocumentFile.CreatedBy?.ConvertToUserViewModelLite(), UpdatedAt = DocumentFile.UpdatedAt, CreatedAt = DocumentFile.CreatedAt }; return(DocumentFileViewModel); }
public DynamicPagination(DocumentFile activeDocument, Pagination Pagination) : base(null) { this.ActiveDocument = activeDocument; this.Pagination = Pagination; }
public DynamicPage(DocumentFile activeDocument, Page Page) : base(null) { this.ActiveDocument = activeDocument; this.Page = Page; }
public ActionResult ManageDocument(Document doc, DocumentFile file, ImageFile thumb, string category, string name, string webPageId, string tmpl) { string dbPath = "", dbThumbPath = ""; DBDataContext db = Utils.DB.GetContext(); //check for category <> 0 int categoryId = 0; if (!string.IsNullOrEmpty(name)) { //add category to database Category c = new Category() { Name = name }; try { db.Categories.InsertOnSubmit(c); db.SubmitChanges(); categoryId = c.ID; } catch (Exception ex) { ModelState.AddModelError("", "An unknown error occurred while adding category to the database."); ErrorHandler.Report.Exception(ex, "Body/ManageDocument[HTTPPOST]"); } } //no new category, try parsing existing one from dropdown list if (categoryId == 0) { Int32.TryParse(category, out categoryId); } //validate category if (categoryId > 0) { WebPage page = db.WebPages.SingleOrDefault(x => x.ID == Convert.ToInt32(webPageId)); if (page != null) { if (file != null) { file.ValidateForUpload(true); if (ModelState.IsValid) { string documentName = "doc-lib_" + DateTime.Now.Ticks.ToString() + "_" + new Random().Next(1, 100).ToString() + System.IO.Path.GetExtension(file.Name); if (file.Save(documentName)) { dbPath = "/" + file.SavePath; file.Cleanup(); } } } else { ModelState.AddModelError("", "Document file is not recognized"); } if (thumb != null) { thumb.ValidateForUpload(true); if (ModelState.IsValid) { string thumbName = "doc-lib_thumb_" + DateTime.Now.Ticks.ToString() + "_" + new Random().Next(1, 100).ToString(); if (thumb.Save(thumbName, new System.Drawing.Size(Config.DocLib.Thumbnail.Width, Config.DocLib.Thumbnail.Height), false)) { dbThumbPath = "/" + thumb.SavePath; thumb.Cleanup(); } } } else { ModelState.AddModelError("", "Image file is not recognized"); } if (!string.IsNullOrEmpty(dbPath) && !string.IsNullOrEmpty(dbThumbPath)) { Category c = db.Categories.SingleOrDefault(x => x.ID == categoryId); Document d = new Document() { Title = doc.Title, Source = dbPath, Thumb = dbThumbPath }; d.Category = c; page.Documents.Add(d); try { db.SubmitChanges(); return RedirectToAction("DocLib", "Body", new { controller = "Body", action = "DocLib", webpage = webPageId.ToString(), tmpl = tmpl }); } catch (Exception ex) { ModelState.AddModelError("", "An unknown error occurred. Please try again in a few minutes."); ErrorHandler.Report.Exception(ex, "Body/ManageDocument[HTTPPOST]"); } } else { ModelState.AddModelError("", "There has been an issue with uploading your Image file. Please try again in few minutes."); } } else { ModelState.AddModelError("", "Page cannot be found. Please try again in few minutes."); } } else { ModelState.AddModelError("category", "You must either add new or select valid category for this document."); } if (System.IO.File.Exists(HttpContext.Server.MapPath(dbPath))) { System.IO.File.Delete(HttpContext.Server.MapPath(dbPath)); } if (System.IO.File.Exists(HttpContext.Server.MapPath(dbThumbPath))) { System.IO.File.Delete(HttpContext.Server.MapPath(dbThumbPath)); } ViewData["WebPageID"] = webPageId; ViewData["TemplateID"] = tmpl; return View("ManageDocument", new Document()); }
public ActionResult PDFPrev(string webPageId, DocumentFile doc) { string code = ""; if (doc != null) { doc.ValidateForUpload(true); if (ModelState.IsValid) { if (doc.Save(doc.Name.Replace(" ", "").ToLower())) { code = doc.SavedName; doc.Cleanup(); } } } else { ModelState.AddModelError("", "Document File format is not recognized"); } if (!string.IsNullOrEmpty(code)) { DBDataContext db = Utils.DB.GetContext(); WebPage pg = db.WebPages.SingleOrDefault(x => x.ID == Convert.ToInt32(webPageId)); if (pg != null) { Body b = pg.Bodies.FirstOrDefault(); if (b != null) { //delete existing PDF file if (System.IO.File.Exists(HttpContext.Server.MapPath(Url.Data(b.HTML)))) { System.IO.File.Delete(HttpContext.Server.MapPath(Url.Data(b.HTML))); } b.HTML = HttpUtility.HtmlEncode(code); } else { pg.Bodies.Add(new Body() { HTML = HttpUtility.HtmlEncode(code) }); } try { db.SubmitChanges(); return RedirectToAction("Index", "WebPage", new { controller = "WebPage", action = "Index", webpage = webPageId }); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); ErrorHandler.Report.Exception(ex, "Body/PDFPrev [POST]"); } } else { ModelState.AddModelError("", "Web Page does not exist"); } } else { ModelState.AddModelError("", "There has been an issue with uploading your Document file. Please try again in few minutes."); } return View(); }
public DynamicStaticFile(DocumentFile activeDocument, StaticFile file) : base(file) { }
public DynamicSite(DocumentFile activeDocument, Site site) : base(site.SitePath) { this.ActiveDocument = activeDocument; this.Site = site; }