コード例 #1
0
        public HttpResponseMessage SaveFile(EditDocumentRequest postedData)
        {
            try
            {
                string htmlContent = postedData.getContent(); // Initialize with HTML markup of the edited document

                string saveFilePath = Path.Combine(globalConfiguration.GetEditorConfiguration().GetFilesDirectory(), postedData.GetGuid());
                if (File.Exists(saveFilePath))
                {
                    File.Delete(saveFilePath);
                }
                using (OutputHtmlDocument editedHtmlDoc = new OutputHtmlDocument(htmlContent, null))
                {
                    dynamic options = GetSaveOptions(saveFilePath);
                    if (options.GetType().Equals(typeof(WordProcessingSaveOptions)))
                    {
                        options.EnablePagination = true;
                    }
                    options.Password     = postedData.getPassword();
                    options.OutputFormat = GetSaveFormat(saveFilePath);
                    using (System.IO.FileStream outputStream = System.IO.File.Create(saveFilePath))
                    {
                        EditorHandler.ToDocument(editedHtmlDoc, outputStream, options);
                    }
                }
                LoadDocumentEntity loadDocumentEntity = LoadDocument(saveFilePath, postedData.getPassword());
                // return document description
                return(Request.CreateResponse(HttpStatusCode.OK, loadDocumentEntity));
            }
            catch (System.Exception ex)
            {
                // set exception message
                return(Request.CreateResponse(HttpStatusCode.Forbidden, new Resources().GenerateException(ex, postedData.getPassword())));
            }
        }
        private static LoadDocumentEntity GetLoadDocumentEntity(bool loadAllPages, string documentGuid, string fileCacheSubFolder, ICustomViewer customViewer, bool printVersion)
        {
            if (loadAllPages)
            {
                customViewer.CreateCache();
            }

            dynamic            viewInfo           = customViewer.GetViewer().GetViewInfo(ViewInfoOptions.ForHtmlView());
            LoadDocumentEntity loadDocumentEntity = new LoadDocumentEntity();

            if (!Directory.Exists(cachePath))
            {
                Directory.CreateDirectory(cachePath);
            }

            string pagesInfoPath;

            TryCreatePagesInfoXml(fileCacheSubFolder, viewInfo, out pagesInfoPath);

            foreach (Page page in viewInfo.Pages)
            {
                PageDescriptionEntity pageData = GetPageInfo(page, pagesInfoPath);
                if (loadAllPages)
                {
                    pageData.SetData(GetPageContent(page.Number, documentGuid, cachePath, printVersion));
                }

                loadDocumentEntity.SetPages(pageData);
            }

            loadDocumentEntity.SetGuid(documentGuid);
            return(loadDocumentEntity);
        }
        public HttpResponseMessage SaveFile(EditDocumentRequest postedData)
        {
            try
            {
                string htmlContent  = postedData.getContent(); // Initialize with HTML markup of the edited document
                string guid         = postedData.GetGuid();
                string password     = postedData.getPassword();
                string saveFilePath = Path.Combine(globalConfiguration.GetEditorConfiguration().GetFilesDirectory(), guid);
                string tempFilename = Path.GetFileNameWithoutExtension(saveFilePath) + "_tmp";
                string tempPath     = Path.Combine(Path.GetDirectoryName(saveFilePath), tempFilename + Path.GetExtension(saveFilePath));

                ILoadOptions loadOptions = GetLoadOptions(guid);
                if (loadOptions != null)
                {
                    loadOptions.Password = password;
                }

                // Instantiate Editor object by loading the input file
                using (GroupDocs.Editor.Editor editor = new GroupDocs.Editor.Editor(guid, delegate { return(loadOptions); }))
                {
                    EditableDocument htmlContentDoc = EditableDocument.FromMarkup(htmlContent, null);
                    dynamic          saveOptions    = GetSaveOptions(guid);

                    if (!(saveOptions is TextSaveOptions))
                    {
                        saveOptions.Password = password;
                    }

                    if (saveOptions is WordProcessingSaveOptions)
                    {
                        saveOptions.EnablePagination = true;
                    }

                    using (FileStream outputStream = File.Create(tempPath))
                    {
                        editor.Save(htmlContentDoc, outputStream, saveOptions);
                    }
                }

                if (File.Exists(saveFilePath))
                {
                    File.Delete(saveFilePath);
                }

                File.Move(tempPath, saveFilePath);

                LoadDocumentEntity loadDocumentEntity = LoadDocument(saveFilePath, password);

                // return document description
                return(Request.CreateResponse(HttpStatusCode.OK, loadDocumentEntity));
            }
            catch (Exception ex)
            {
                // set exception message
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new Resources().GenerateException(ex, postedData.getPassword())));
            }
        }
        public LoadDocumentEntity LoadDocument(PostedDataDto postedData)
        {
            // get/set parameters
            string             filePath           = metadataConfiguration.GetAbsolutePath(postedData.guid);
            string             password           = string.IsNullOrEmpty(postedData.password) ? null : postedData.password;
            LoadDocumentEntity loadDocumentEntity = new LoadDocumentEntity();

            // set password for protected document
            var loadOptions = new LoadOptions
            {
                Password = password
            };

            using (GroupDocs.Metadata.Metadata metadata = new GroupDocs.Metadata.Metadata(filePath, loadOptions))
            {
                GroupDocs.Metadata.Common.IReadOnlyList <PageInfo> pages = metadata.GetDocumentInfo().Pages;

                using (MemoryStream stream = new MemoryStream())
                {
                    PreviewOptions previewOptions = new PreviewOptions(pageNumber => stream, (pageNumber, pageStream) => { });
                    previewOptions.PreviewFormat = PreviewOptions.PreviewFormats.PNG;

                    int pageCount = pages.Count;
                    if (metadataConfiguration.GetPreloadPageCount() > 0)
                    {
                        pageCount = metadataConfiguration.GetPreloadPageCount();
                    }
                    for (int i = 0; i < pageCount; i++)
                    {
                        previewOptions.PageNumbers = new[] { i + 1 };
                        try
                        {
                            metadata.GeneratePreview(previewOptions);
                        }
                        catch (NotSupportedException)
                        {
                            continue;
                        }

                        PageDescriptionEntity pageData = GetPageDescriptionEntities(pages[i]);
                        string encodedImage            = Convert.ToBase64String(stream.ToArray());
                        pageData.SetData(encodedImage);
                        loadDocumentEntity.SetPages(pageData);
                        stream.SetLength(0);
                    }
                }
            }

            loadDocumentEntity.SetGuid(postedData.guid);

            // return document description
            return(loadDocumentEntity);
        }
コード例 #5
0
 public HttpResponseMessage LoadDocumentDescription(PostedDataEntity postedData)
 {
     try
     {
         LoadDocumentEntity loadDocumentEntity = LoadDocument(postedData.guid, postedData.password);
         // return document description
         return(Request.CreateResponse(HttpStatusCode.OK, loadDocumentEntity));
     }
     catch (System.Exception ex)
     {
         // set exception message
         return(Request.CreateResponse(HttpStatusCode.Forbidden, new Resources().GenerateException(ex, postedData.password)));
     }
 }
        public HttpResponseMessage GetPrintVersion(PostedDataEntity loadDocumentRequest)
        {
            try
            {
                LoadDocumentEntity loadPrintDocument = GetDocumentPages(loadDocumentRequest, true, true);

                // return document description
                return(this.Request.CreateResponse(HttpStatusCode.OK, loadPrintDocument));
            }
            catch (Exception ex)
            {
                // set exception message
                return(this.Request.CreateResponse(HttpStatusCode.InternalServerError, new Resources().GenerateException(ex, loadDocumentRequest.password)));
            }
        }
        public HttpResponseMessage CreateFile(EditDocumentRequest postedData)
        {
            try
            {
                string htmlContent  = postedData.getContent();
                string guid         = postedData.GetGuid();
                string saveFilePath = Path.Combine(globalConfiguration.GetEditorConfiguration().GetFilesDirectory(), guid);
                string tempFilename = Path.GetFileNameWithoutExtension(saveFilePath) + "_tmp";
                string tempPath     = Path.Combine(Path.GetDirectoryName(saveFilePath), tempFilename + Path.GetExtension(saveFilePath));

                File.Create(saveFilePath).Dispose();

                using (EditableDocument newFile = EditableDocument.FromMarkup(htmlContent, null))
                {
                    using (GroupDocs.Editor.Editor editor = new GroupDocs.Editor.Editor(saveFilePath))
                    {
                        dynamic saveOptions = this.GetSaveOptions(saveFilePath);
                        if (saveOptions is WordProcessingSaveOptions)
                        {
                            // TODO: saveOptions.EnablePagination = true here leads to exception
                        }

                        using (FileStream outputStream = File.Create(tempPath))
                        {
                            editor.Save(newFile, outputStream, saveOptions);
                        }
                    }
                }

                if (File.Exists(saveFilePath))
                {
                    File.Delete(saveFilePath);
                }

                File.Move(tempPath, saveFilePath);

                LoadDocumentEntity loadDocumentEntity = LoadDocument(saveFilePath, "");

                // return document description
                return(Request.CreateResponse(HttpStatusCode.OK, loadDocumentEntity));
            }
            catch (Exception ex)
            {
                // set exception message
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new Resources().GenerateException(ex, postedData.getPassword())));
            }
        }
コード例 #8
0
        public static LoadDocumentEntity LoadDocumentPages(string documentGuid, string password, bool loadAllPages)
        {
            LoadDocumentEntity loadDocumentEntity = new LoadDocumentEntity();

            using (Comparer comparer = new Comparer(documentGuid, GetLoadOptions(password)))
            {
                Dictionary <int, string> pagesContent = new Dictionary <int, string>();
                IDocumentInfo            documentInfo = comparer.Source.GetDocumentInfo();

                if (documentInfo.PagesInfo == null)
                {
                    throw new GroupDocs.Comparison.Common.Exceptions.ComparisonException("File is corrupted.");
                }

                if (loadAllPages)
                {
                    for (int i = 0; i < documentInfo.PageCount; i++)
                    {
                        string encodedImage = GetPageData(i, documentGuid, password);

                        pagesContent.Add(i, encodedImage);
                    }
                }

                for (int i = 0; i < documentInfo.PageCount; i++)
                {
                    PageDescriptionEntity pageData = new PageDescriptionEntity
                    {
                        height = documentInfo.PagesInfo[i].Height,
                        width  = documentInfo.PagesInfo[i].Width,
                        number = i + 1
                    };

                    if (pagesContent.Count > 0)
                    {
                        pageData.SetData(pagesContent[i]);
                    }

                    loadDocumentEntity.SetPages(pageData);
                }

                return(loadDocumentEntity);
            }
        }
コード例 #9
0
        private LoadDocumentEntity LoadDocument(string guid, string password)
        {
            try
            {
                dynamic options = null;
                //GroupDocs.Editor cannot detect text-based Cells documents formats (like CSV) automatically
                if (guid.EndsWith("csv", StringComparison.OrdinalIgnoreCase))
                {
                    options = new SpreadsheetToHtmlOptions();
                }
                else
                {
                    options = EditorHandler.DetectOptionsFromExtension(guid);
                }

                if (options is SpreadsheetToHtmlOptions)
                {
                    options.TextOptions = options.TextLoadOptions(",");
                }
                else
                {
                    options.Password = password;
                }
                string bodyContent;

                using (System.IO.FileStream inputDoc = System.IO.File.OpenRead(guid))

                    using (InputHtmlDocument htmlDoc = EditorHandler.ToHtml(inputDoc, options))
                    {
                        bodyContent = htmlDoc.GetEmbeddedHtml();
                    }
                LoadDocumentEntity loadDocumentEntity = new LoadDocumentEntity();
                loadDocumentEntity.SetGuid(System.IO.Path.GetFileName(guid));
                PageDescriptionEntity page = new PageDescriptionEntity();
                page.SetData(bodyContent);
                loadDocumentEntity.SetPages(page);
                return(loadDocumentEntity);
            }
            catch
            {
                throw;
            }
        }
 public HttpResponseMessage LoadDocumentDescription(PostedDataEntity loadResultPageRequest)
 {
     try
     {
         LoadDocumentEntity document = ComparisonServiceImpl.LoadDocumentPages(loadResultPageRequest.guid,
                                                                               loadResultPageRequest.password,
                                                                               globalConfiguration.GetComparisonConfiguration().GetPreloadResultPageCount() == 0);
         return(Request.CreateResponse(HttpStatusCode.OK, document));
     }
     catch (PasswordProtectedFileException ex)
     {
         // set exception message
         return(Request.CreateResponse(HttpStatusCode.Forbidden, new Resources().GenerateException(ex, loadResultPageRequest.password)));
     }
     catch (Exception ex)
     {
         // set exception message
         return(Request.CreateResponse(HttpStatusCode.InternalServerError, new Resources().GenerateException(ex, loadResultPageRequest.password)));
     }
 }
        public HttpResponseMessage GetDocumentData(PostedDataEntity postedData)
        {
            try
            {
                LoadDocumentEntity loadDocumentEntity = GetDocumentPages(postedData, globalConfiguration.GetViewerConfiguration().GetPreloadPageCount() == 0);

                // return document description
                return(this.Request.CreateResponse(HttpStatusCode.OK, loadDocumentEntity));
            }
            catch (PasswordRequiredException ex)
            {
                // set exception message
                return(this.Request.CreateResponse(HttpStatusCode.Forbidden, new Resources().GenerateException(ex, postedData.password)));
            }
            catch (Exception ex)
            {
                // set exception message
                return(this.Request.CreateResponse(HttpStatusCode.InternalServerError, new Resources().GenerateException(ex, postedData.password)));
            }
        }
        private LoadDocumentEntity LoadDocument(string guid, string password)
        {
            LoadDocumentEntity loadDocumentEntity = new LoadDocumentEntity();

            loadDocumentEntity.SetGuid(guid);
            ILoadOptions loadOptions = GetLoadOptions(guid);

            if (loadOptions != null)
            {
                loadOptions.Password = password;
            }

            // Instantiate Editor object by loading the input file
            using (GroupDocs.Editor.Editor editor = new GroupDocs.Editor.Editor(guid, delegate { return(loadOptions); }))
            {
                IDocumentInfo documentInfo = editor.GetDocumentInfo(password);

                dynamic editOptions = GetEditOptions(guid);
                if (editOptions is WordProcessingEditOptions)
                {
                    editOptions.EnablePagination = true;

                    // Open input document for edit — obtain an intermediate document, that can be edited
                    EditableDocument      beforeEdit = editor.Edit(editOptions);
                    string                allEmbeddedInsideString = beforeEdit.GetEmbeddedHtml();
                    PageDescriptionEntity page = new PageDescriptionEntity();
                    page.SetData(allEmbeddedInsideString);
                    loadDocumentEntity.SetPages(page);
                    beforeEdit.Dispose();
                }
                else if (editOptions is SpreadsheetEditOptions)
                {
                    for (var i = 0; i < documentInfo.PageCount; i++)
                    {
                        // Let's create an intermediate EditableDocument from the i tab
                        SpreadsheetEditOptions sheetEditOptions = new SpreadsheetEditOptions();
                        sheetEditOptions.WorksheetIndex = i; // index is 0-based
                        EditableDocument tabBeforeEdit = editor.Edit(sheetEditOptions);

                        // Get document as a single base64-encoded string, where all resources (images, fonts, etc)
                        // are embedded inside this string along with main textual content
                        string allEmbeddedInsideString = tabBeforeEdit.GetEmbeddedHtml();
                        PageDescriptionEntity page     = new PageDescriptionEntity();
                        page.SetData(allEmbeddedInsideString);
                        page.number = i + 1;
                        loadDocumentEntity.SetPages(page);
                        tabBeforeEdit.Dispose();
                    }
                }
                else if (editOptions is PresentationEditOptions)
                {
                    for (var i = 0; i < documentInfo.PageCount; i++)
                    {
                        // Create editing options
                        PresentationEditOptions presentationEditOptions = new PresentationEditOptions();
                        // Specify slide index from original document.
                        editOptions.SlideNumber = i; // Because index is 0-based, it is 1st slide
                        EditableDocument slideBeforeEdit = editor.Edit(presentationEditOptions);

                        // Get document as a single base64-encoded string, where all resources (images, fonts, etc)
                        // are embedded inside this string along with main textual content
                        string allEmbeddedInsideString = slideBeforeEdit.GetEmbeddedHtml();
                        PageDescriptionEntity page     = new PageDescriptionEntity();
                        page.SetData(allEmbeddedInsideString);
                        page.number = i + 1;
                        loadDocumentEntity.SetPages(page);
                        slideBeforeEdit.Dispose();
                    }
                }
            }

            return(loadDocumentEntity);
        }
コード例 #13
0
        /// <summary>
        /// Uploads a document to the KBX Document Service and stores metadata in Loadshop
        /// </summary>
        /// <param name="uploadPayload"></param>
        /// <returns></returns>
        public async Task <LoadDocumentMetadata> UploadDocument(LoadDocumentUploadData uploadPayload)
        {
            securityService.GuardAction(SecurityActions.Loadshop_Ui_Carrier_MyLoads_Documents_Attach);

            if (uploadPayload.LoadDocumentType == null || uploadPayload.LoadDocumentType.Id < 1)
            {
                throw new ValidationException("Invalid load document type");
            }

            var load = await context.Loads.AsNoTracking().FirstOrDefaultAsync(x => x.LoadId == uploadPayload.LoadId);

            if (load == null)
            {
                throw new ValidationException("Load not found");
            }

            var billingLoadId = await context.LoadTransactions.AsNoTracking()
                                .Include(x => x.Claim)
                                .Where(x => x.TransactionTypeId == TransactionTypes.Accepted)
                                .Where(x => x.LoadId == load.LoadId)
                                .Select(x => x.Claim.BillingLoadId)
                                .FirstOrDefaultAsync();

            // copy stream to request
            var stream = new FileMemoryStream();
            await uploadPayload.File.CopyToAsync(stream);

            // reset position to ensure http request sends payload
            stream.Position           = 0;
            stream.FileName           = uploadPayload.File.FileName;
            stream.ContentDisposition = uploadPayload.File.ContentDisposition;
            stream.ContentType        = uploadPayload.File.ContentType;

            // we hold all metadata in loadshop; however we will include some fields in case TOPS needs to query anything from there in the future
            var request = new DocumentService.SDK.Version.V1.Model.DocumentCreate()
            {
                Properties = new List <DocPropertyData>()
                {
                    new DocPropertyData()
                    {
                        PropertyValue = load.LoadId.ToString(),
                        PropertyName  = DocumentServiceConstants.Property_Name_LoadshopLoadId
                    },
                    new DocPropertyData()
                    {
                        PropertyValue = load.PlatformPlusLoadId?.ToString(),
                        PropertyName  = DocumentServiceConstants.Property_Name_PlatformPlusLoadId
                    },
                    new DocPropertyData()
                    {
                        PropertyValue = load.ReferenceLoadId?.ToString(),
                        PropertyName  = DocumentServiceConstants.Property_Name_ReferenceLoadId
                    },
                    new DocPropertyData()
                    {
                        PropertyValue = billingLoadId,
                        PropertyName  = DocumentServiceConstants.Property_Name_BillingLoadId
                    }
                },
                DocTypeId       = uploadPayload.LoadDocumentType.Id,
                CreatedBy       = userContext.UserName,
                CreatedDateTime = DateTime.Now,
                DocumentFile    = stream
            };

            try
            {
                // upload file to document API
                var uploadResult = await documentApiClient.CreateDocument(request);

                if (uploadResult.Status.Equals("Error", StringComparison.CurrentCultureIgnoreCase))
                {
                    throw new Exception($"Error while upload document to Document Service: {uploadResult.Result}");
                }

                var entity = new LoadDocumentEntity()
                {
                    LoadDocumentId              = Guid.NewGuid(),
                    DocumentServiceDocHeaderId  = uploadResult.ResultData.DocHeaderId.Value,
                    DocumentServiceDocContentId = uploadResult.ResultData.DocContentId.Value,
                    DocumentServiceDocumentType = uploadPayload.LoadDocumentType.Id,
                    FileName    = uploadPayload.File.FileName,
                    Comment     = uploadPayload.Comment,
                    LoadId      = load.LoadId,
                    CreateBy    = userContext.UserName,
                    CreateDtTm  = DateTime.Now,
                    LastChgBy   = userContext.UserName,
                    LastChgDtTm = DateTime.Now
                };

                // add the new entity and in order for the DB to generate the doc id, use that to pass to the document service
                context.LoadDocuments.Add(entity);
                await context.SaveChangesAsync();

                return(mapper.Map <LoadDocumentMetadata>(entity));
            }
            catch (Exception e)
            {
                // if any errors occured, we dont want to show the record in loadshop, so remove the attachment record and return error
                logger.LogError($"Error while uploading document: {e.Message}", e);
            }
            return(null);
        }