コード例 #1
0
        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());
        }
コード例 #2
0
        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));
        }
コード例 #3
0
        void df_Click(object sender, EventArgs e)
        {
            DocumentFile df  = (DocumentFile)sender;
            frmShowInfo  frm = new frmShowInfo(df.name);

            frm.ShowDialog();
        }
コード例 #4
0
        public DocumentFileModel(DocumentFile documentFile, IDialogService dialogService)
        {
            this.documentFile  = documentFile;
            this.dialogService = dialogService;

            documentFile.Changed += DocumentFile_Changed;
        }
コード例 #5
0
 public DynamicRenderDocument(DocumentFile document, LayoutFile layout, Site site)
     : base(document.SourceRelativePath)
 {
     _document = document;
     _layout = layout;
     _site = site;
 }
コード例 #6
0
 public DynamicLayoutFile(DocumentFile activeDocument, LayoutFile layout, Site site)
     : base(layout.SourceRelativePath)
 {
     this.ActiveDocument = activeDocument;
     this.Layout = layout;
     this.Site = site;
 }
コード例 #7
0
 private string GetFirstFieldValue(DocumentFile documentFile, string fieldName)
 {
     return(documentFile.DocumentFieldList
            .Where(x => x.FieldName == fieldName)
            .Select(x => x.FieldValueList.First())
            .First());
 }
コード例 #8
0
 public DynamicPaginator(DocumentFile activeDocument, Paginator Paginator, Site site)
     : base(null)
 {
     this.ActiveDocument = activeDocument;
     this.Paginator = Paginator;
     this.Site = site;
 }
コード例 #9
0
        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 });
            }
        }
コード例 #10
0
            /// <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);
            }
コード例 #11
0
        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);
            }
        }
コード例 #12
0
            /// <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);
            }
コード例 #13
0
            /// <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);
            }
コード例 #14
0
            /// <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);
            }
コード例 #15
0
        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);
        }
コード例 #16
0
        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);
        }
コード例 #17
0
 public IActionResult AddDocumentFile(DocumentFile df)
 {
     df.numberOf_document = 0;
     dbContext.documentFiles.Add(df);
     dbContext.SaveChanges();
     return(RedirectToAction("Index"));
 }
コード例 #18
0
        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;
            }
        }
コード例 #19
0
        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);
            }
        }
コード例 #20
0
 public DynamicDataFile(DocumentFile activeDocument, DataFile dataFile, Site site)
     : base(dataFile, dataFile.Metadata)
 {
     this.ActiveDocument = activeDocument;
     this.DataFile = dataFile;
     this.Site = site;
 }
コード例 #21
0
ファイル: DynamicBook.cs プロジェクト: fearthecowboy/tinysite
 public DynamicBook(DocumentFile activeDocument, Book book, Site site)
     : base(null)
 {
     this.ActiveDocument = activeDocument;
     this.Book = book;
     this.Site = site;
 }
コード例 #22
0
        /// <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);
            }
        }
コード例 #23
0
        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);
            }
        }
コード例 #24
0
 public void AppendErrorText(DocumentFile document, string text)
 {
     outputParagraphs[document].Inlines.Add(new Run(text)
     {
         Foreground = (Brush)FindResource("ErrorForeground")
     });
 }
コード例 #25
0
 private void ResetBuildResult(DocumentFile documentFile)
 {
     if (lastBuildResult != null && lastBuildResult.Item1 == documentFile)
     {
         lastBuildResult = null;
     }
 }
コード例 #26
0
        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)));
        }
コード例 #27
0
        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();
        }
コード例 #28
0
        private CodeEditorViewModel CreateDocumentViewModel(DocumentFile document)
        {
            var viewModel = codeEditorViewModelFactory.CreateExport().Value;

            viewModel.DocumentFile = document;
            return(viewModel);
        }
コード例 #29
0
        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));
        }
コード例 #30
0
 public DynamicBookPage(DocumentFile activeDocument, BookPage bookPage, Site site)
     : base(null)
 {
     this.ActiveDocument = activeDocument;
     this.BookPage = bookPage;
     this.Site = site;
 }
コード例 #31
0
        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);
                }
            }
        }
コード例 #32
0
        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));
        }
コード例 #33
0
        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);
            }
        }
コード例 #34
0
        void df_Click(object sender, EventArgs e)
        {
            DocumentFile df = (DocumentFile)sender;

            //播放语音
            backgroundWorker1.RunWorkerAsync(df.name);
        }
コード例 #35
0
        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);
        }
コード例 #36
0
 public DynamicDocumentFile(DocumentFile activeDocument, DocumentFile document, Site site)
     : base(document)
 {
     this.ActiveDocument = activeDocument;
     this.Document = document;
     this.Site = site;
 }
コード例 #37
0
        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);
        }
コード例 #38
0
 public DynamicPagination(DocumentFile activeDocument, Pagination Pagination)
     : base(null)
 {
     this.ActiveDocument = activeDocument;
     this.Pagination = Pagination;
 }
コード例 #39
0
ファイル: DynamicPage.cs プロジェクト: fearthecowboy/tinysite
 public DynamicPage(DocumentFile activeDocument, Page Page)
     : base(null)
 {
     this.ActiveDocument = activeDocument;
     this.Page = Page;
 }
コード例 #40
0
ファイル: BodyController.cs プロジェクト: webitpro/WolfWeb
        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());
        }
コード例 #41
0
ファイル: BodyController.cs プロジェクト: webitpro/WolfWeb
        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();
        }
コード例 #42
0
 public DynamicStaticFile(DocumentFile activeDocument, StaticFile file)
     : base(file)
 {
 }
コード例 #43
0
ファイル: DynamicSite.cs プロジェクト: fearthecowboy/tinysite
 public DynamicSite(DocumentFile activeDocument, Site site)
     : base(site.SitePath)
 {
     this.ActiveDocument = activeDocument;
     this.Site = site;
 }