/// <summary>
        /// Generate a doucment
        /// </summary>
        /// <param name="templateDoc">The template file to generate from</param>
        /// <param name="sourceResource">The optional resource to use a data for the generation</param>
        /// <param name="newName">The name of the generated file</param>
        /// <param name="newDescription">The name of the generated description</param>
        /// <param name="timezoneName">the timezone the report will be evaluated in</param>
        public static Document GenerateDoc(Document templateDoc, IEntity sourceResource, string newName, string newDescription, string timezoneName)
        {
            var sourceResourceId = sourceResource != null ? sourceResource.Id : 0;
            var templateName     = templateDoc.Name ?? "[Unnamed]";

            var tmpFileName = string.Format("{0:yyyyMMddhhmmssfff}.doc", DateTime.UtcNow);
            var tmpFilePath = Path.Combine(Path.GetTempPath(), tmpFileName);

            try
            {
                // Generate document
                using (var templateStream = FileRepositoryHelper.GetFileDataStreamForEntity(templateDoc))
                {
                    if (templateStream == null)
                    {
                        throw new WorkflowRunException("Unable to find the template file '{0}'", templateName);
                    }

                    using (Stream targetStream = File.Create(tmpFilePath))
                    {
                        var genSettings = new GeneratorSettings
                        {
                            WriteDebugFiles    = false,
                            ThrowOnError       = true,
                            TimeZoneName       = timezoneName,
                            SelectedResourceId = sourceResourceId,
                        };

                        Factory.DocumentGenerator.CreateDocument(templateStream, targetStream, genSettings);        // Any gen failures are handled higher up
                    }
                }


                string tempHash;

                using (var source = new FileStream(tmpFilePath, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    tempHash = FileRepositoryHelper.AddTemporaryFile(source);
                }

                var document = DocHelper.CreateDoc(tempHash, newName, newDescription, templateDoc.FileExtension, templateDoc.DocumentFileType);

                return(document);
            }
            finally
            {
                // clean up
                if (File.Exists(tmpFileName))
                {
                    File.Delete(tmpFilePath);
                }
            }
        }
Example #2
0
        public void TestGenerate()
        {
            var template     = CreateTestTemplate("Single employee.docx");
            var employeeType = Entity.GetByName <EntityType>("Employee").First();
            var employee     = Entity.Create(employeeType);

            var doc = GenerateDocImplementation.GenerateDoc(template.ReportTemplateUsesDocument, employee, "testName" + DateTime.UtcNow.ToString(), "testDescription" + DateTime.UtcNow.ToString(), TimeZoneHelper.SydneyTimeZoneName);

            Assert.That(doc, Is.Not.Null);
            Assert.That(doc.Name, Is.Not.Null);
            Assert.That(doc.CurrentDocumentRevision, Is.Not.Null);
            Assert.That(doc.CurrentDocumentRevision.Name, Is.Not.Null);
            Assert.That(doc.CurrentDocumentRevision.FileDataHash, Is.Not.Null);
            using (var stream = FileRepositoryHelper.GetFileDataStreamForEntity(new EntityRef(doc.Id)))
            {
                Assert.That(stream, Is.Not.Null);
                Assert.That(stream.Length, Is.Not.EqualTo(0));
            }
        }
Example #3
0
        public void TestExportCsv()
        {
            var report      = Entity.Get <Report>(new EntityRef("test", "personReport"));
            var name        = "testName" + DateTime.UtcNow.Ticks.ToString();
            var description = "testDescription" + DateTime.UtcNow.Ticks.ToString();

            var doc = ExportToImplementation.ExportTo(report, name, description, TimeZoneHelper.SydneyTimeZoneName, ExportFormat.Csv);

            Assert.That(doc, Is.Not.Null);
            Assert.That(doc.Name, Is.EqualTo(name));
            Assert.That(doc.Description, Is.EqualTo(description));
            Assert.That(doc.CurrentDocumentRevision, Is.Not.Null);
            Assert.That(doc.CurrentDocumentRevision.Name, Is.Not.Null);
            Assert.That(doc.CurrentDocumentRevision.FileDataHash, Is.Not.Null);
            using (var stream = FileRepositoryHelper.GetFileDataStreamForEntity(new EntityRef(doc.Id)))
            {
                Assert.That(stream, Is.Not.Null);
                Assert.That(stream.Length, Is.Not.EqualTo(0));
            }
        }
Example #4
0
 /// <summary>
 ///     Gets the image data stream.
 /// </summary>
 /// <param name="imageId">The image id.</param>
 /// <returns></returns>
 public Stream GetImageDataStream(EntityRef imageId)
 {
     return(FileRepositoryHelper.GetFileDataStreamForEntity(imageId));
 }
 static Stream GetDocStream(FileType file)
 {
     return(FileRepositoryHelper.GetFileDataStreamForEntity(file));
 }
Example #6
0
        /// <summary>
        ///     Get a file for a request. If the
        /// </summary>
        /// <param name="request">The request.</param>
        /// <param name="imageIdRef">The image identifier reference.</param>
        /// <param name="generateEtagFn">The generate e-tag function.</param>
        /// <returns>
        ///     The file response or a NotModified response if the e-tag matches.
        /// </returns>
        public static HttpResponseMessage GetFileForRequest(HttpRequestMessage request, ERM.EntityRef imageIdRef, Func <ERM.EntityRef, string> generateEtagFn)
        {
            string etag = generateEtagFn(imageIdRef);

            // If the request contains the same e-tag then return a not modified
            if (request.Headers.IfNoneMatch != null &&
                request.Headers.IfNoneMatch.Any(et => et.Tag == etag))
            {
                var notModifiedResponse = new HttpResponseMessage(HttpStatusCode.NotModified);
                notModifiedResponse.Headers.ETag = new EntityTagHeaderValue(etag, false);
                return(notModifiedResponse);
            }

            // Return the image
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(FileRepositoryHelper.GetFileDataStreamForEntity(imageIdRef))
            };

            response.Headers.ETag         = new EntityTagHeaderValue(etag, false);
            response.Headers.CacheControl = new CacheControlHeaderValue
            {
                MustRevalidate = true,
                MaxAge         = new TimeSpan(0)
            };

            // Yuck. You gotta do what you gotta do.
            bool isIosDevice = false;

            if (request.Headers.UserAgent != null)
            {
                isIosDevice = request.Headers.UserAgent.Any(ua => IosMobileRegex.IsMatch(ua.ToString()));
            }

            string contentType = string.Empty;

            // Note: We are not setting the content length because the CompressionHandler will compress the stream.
            // Specifying the length here will cause the browser to hang as the actual data it
            // receives (as it is compressed) will be less than the specified content length.
            FileDetails dbFileType = FileRepositoryHelper.GetStreamContentType(imageIdRef);

            if (dbFileType != null)
            {
                response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                {
                    FileName = dbFileType.Filename
                };

                // Found that specifying specific mime types on IOS mobile
                // causes safari to raise errors.
                // However, found that on Android the download
                // manager requires the mime type so that the downloaded
                // file can be opened by tapping.
                if (!isIosDevice)
                {
                    if (!string.IsNullOrWhiteSpace(dbFileType.ContentType))
                    {
                        contentType = dbFileType.ContentType;
                    }
                    else
                    {
                        // Attempt to get a mime type from the file name
                        if (!string.IsNullOrWhiteSpace(dbFileType.Filename))
                        {
                            contentType = MimeMapping.GetMimeMapping(dbFileType.Filename);
                        }
                    }
                }
            }

            // If we don't have a content type, fallback to the generic one.
            if (string.IsNullOrWhiteSpace(contentType))
            {
                contentType = "application/octet-stream";
            }

            response.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType);

            return(response);
        }