private static Document CreateAttachment(IEntity incidentEntity, string fileName, string docExt, string content)
        {
            //todo - work out how to get the right doc type, although I can't see what to use for images
            //todo - at the moment this assumes the content is base64... does that make sense??

            var    docType = ReadiNow.Model.Entity.Get <DocumentType>(new EntityRef("textDocumentDocumentType"));
            string hash;

            using (var stream = new MemoryStream(Convert.FromBase64String(content)))
            {
                hash = FileRepositoryHelper.AddTemporaryFile(stream);
            }

            var doc = ReadiNow.Model.Entity.Create <Document>();

            doc.FileDataHash     = hash;
            doc.Name             = fileName;
            doc.FileExtension    = docExt;
            doc.DocumentFileType = docType;
            doc.SetRelationships("readidesk:attachmentIncident", new EntityRelationshipCollection <IEntity> {
                incidentEntity
            }, Direction.Reverse);
            doc.Save();

            return(doc);
        }
        public static ImportRun RunTest(EntityType entityType, string fileName, ImportFormat importFormat, string sheetName = null)
        {
            string fileToken;

            using (Stream stream = SheetTestHelper.GetStream(fileName))
            {
                fileToken = FileRepositoryHelper.AddTemporaryFile(stream);
            }


            EntityType   type         = entityType;
            ImportConfig importConfig = CreateImportConfig(type, importFormat, sheetName);

            ImportRun importRun = CreateImportRun(importConfig, fileToken);

            ISpreadsheetInspector inspector = Factory.Current.Resolve <ISpreadsheetInspector>( );
            SpreadsheetInfo       info      = inspector.GetSpreadsheetInfo(fileToken, importFormat);
            SampleTable           sample    = inspector.GetSampleTable(fileToken, importFormat, sheetName, 1, 2, null);

            AddAllFields(importConfig, sample);

            // Run import
            IImportRunWorker worker = Factory.Current.Resolve <IImportRunWorker>( );

            worker.StartImport(importRun.Id);

            return(importRun);
        }
Example #3
0
        /// <summary>
        ///     Get spreadsheet Information from the imported file.
        /// </summary>
        /// <param name="fileUploadId">
        ///     File upload Id.
        /// </param>
        /// <param name="fileFormat">
        ///     Imported file fileFormat ( Excel or CSV)
        /// </param>
        /// <returns>Spreadsheet info
        /// </returns>
        public SpreadsheetInfo GetSpreadsheetInfo(string fileUploadId, ImportFormat fileFormat)
        {
            // Get service
            IDataFileReaderService service = _readerActivator(fileFormat);

            // Load info about sheets
            IReadOnlyList <SheetInfo> sheets;

            using (Stream stream = FileRepositoryHelper.GetTemporaryFileDataStream(fileUploadId))
            {
                // Settings
                DataFileReaderSettings settings = new DataFileReaderSettings
                {
                    ImportFormat = fileFormat
                };

                IDataFile dataFile = service.OpenDataFile(stream, settings);
                sheets = dataFile.GetSheets( );
            }

            var spreadsheetInfo = new SpreadsheetInfo
            {
                ImportFileFormat = fileFormat,
                SheetCollection  = sheets
            };

            return(spreadsheetInfo);
        }
Example #4
0
        /// <summary>
        ///     Get sheet info from the imported spreadsheet.
        /// </summary>
        /// <param name="fileUploadId">File upload Id.</param>
        /// <param name="sheetId">Selected sheet info.</param>
        /// <param name="headerRowNo">Header row no.</param>
        /// <param name="dataRowNo">Data row number to start reading data.</param>
        /// <param name="lastRowNo">Optional last row number to read.</param>
        /// <param name="fileFormat">Imported file fileFormat ( Excel or CSV)</param>
        /// <returns>
        ///     Sheet Info.
        /// </returns>
        public SampleTable GetSampleTable(string fileUploadId, ImportFormat fileFormat, string sheetId, int headerRowNo, int dataRowNo, int?lastRowNo)
        {
            // Get service
            IDataFileReaderService service = _readerActivator(fileFormat);

            // Settings
            DataFileReaderSettings settings = new DataFileReaderSettings
            {
                ImportFormat       = fileFormat,
                HeadingRowNumber   = headerRowNo,
                FirstDataRowNumber = dataRowNo,
                LastDataRowNumber  = lastRowNo,
                SheetId            = sheetId
            };

            // Open stream
            using (Stream stream = FileRepositoryHelper.GetTemporaryFileDataStream(fileUploadId))
            {
                // Build sample
                SampleDataCreator creator     = new SampleDataCreator( );
                SampleTable       sampleTable = creator.CreateSample(stream, settings, service);

                // Trim titles
                foreach (var col in sampleTable.Columns)
                {
                    col.Name = col.Name?.Trim( ) ?? "";
                }

                return(sampleTable);
            }
        }
Example #5
0
        /// <summary>
        ///     Creates the thumbnail image entity.
        /// </summary>
        /// <param name="stream">The stream.</param>
        /// <param name="originalImageEntity">The original image entity.</param>
        /// <param name="fileExtension">The file extension.</param>
        /// <param name="width">The width.</param>
        /// <param name="height">The height.</param>
        /// <param name="scaleEnum">The scale enum.</param>
        /// <returns></returns>
        private ThumbnailFileType CreateThumbnailImageEntity(Stream stream, ImageFileType originalImageEntity, string fileExtension,
                                                             int width, int height, ImageScaleEnum scaleEnum)
        {
            using (DatabaseContext context = DatabaseContext.GetContext(true))
            {
                stream.Position = 0;

                string dataHash = FileRepositoryHelper.AddTemporaryFile(stream);

                var thumbnailEntity = new ThumbnailFileType( );

                string thumbnailName = originalImageEntity.Name;
                if (string.IsNullOrEmpty(thumbnailName))
                {
                    thumbnailName = "Thumbnail";
                }
                else
                {
                    thumbnailName += " Thumbnail";
                }

                thumbnailEntity.Name                = thumbnailName;
                thumbnailEntity.FileDataHash        = dataHash;
                thumbnailEntity.FileExtension       = fileExtension;
                thumbnailEntity.ImageWidth          = width;
                thumbnailEntity.ImageHeight         = height;
                thumbnailEntity.ThumbnailScaling    = scaleEnum;
                thumbnailEntity.IsThumbnailForImage = originalImageEntity;
                thumbnailEntity.Save( );

                context.CommitTransaction( );

                return(thumbnailEntity);
            }
        }
Example #6
0
        private ReportTemplate CreateTestTemplate(string fileName)
        {
            using (var ctx = DatabaseContext.GetContext(requireTransaction: true))
            {
                var wordDocType = Entity.Get <DocumentType>(new EntityRef("wordDocumentDocumentType"));
                var stream      = GetTestDocStream(fileName);
                //var hash = CryptoHelper.ComputeSha256Hash(stream);
                var tempHash = FileRepositoryHelper.AddTemporaryFile(stream);

                var docRev = Entity.Create <DocumentRevision>();
                docRev.FileDataHash     = tempHash;
                docRev.Name             = fileName;
                docRev.FileExtension    = "docx";
                docRev.DocumentFileType = wordDocType;
                docRev.Save();

                var hash = docRev.FileDataHash;

                var doc = Entity.Create <Document>();
                doc.FileDataHash = hash;
                doc.DocumentHasDocumentRevision.Add(docRev);
                doc.CurrentDocumentRevision = docRev;
                doc.FileDataHash            = hash;
                doc.Name             = fileName;
                doc.FileExtension    = "docx";
                doc.DocumentFileType = wordDocType;

                var template = Entity.Create <ReportTemplate>();
                template.Name = fileName;
                template.ReportTemplateUsesDocument = doc;

                ctx.CommitTransaction();
                return(template);
            }
        }
Example #7
0
        /// <summary>
        /// Send a file to a Ftps address
        /// </summary>
        /// <param name="fileHash"></param>
        /// <param name="url"></param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        public void PutFromTemporaryFile(string fileHash, string uri, string username, string password)
        {
            ConnectAndRun(uri, username, password,

                          // setup
                          request =>
            {
                request.Method = WebRequestMethods.Ftp.UploadFile;

                using (var fileStream = FileRepositoryHelper.GetTemporaryFileDataStream(fileHash))
                {
                    using (var requestStream = request.GetRequestStream())
                    {
                        fileStream.CopyTo(requestStream);
                    }
                }
            },

                          // handle response
                          responseStream =>
            {
                // do nothing
            }
                          );
        }
Example #8
0
        public async Task <HttpResponseMessage <FileList> > PostFormData( )
        {
            //TODO: store the original filename along with the file.

            if (!Request.Content.IsMimeMultipartContent( ))
            {
                throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
            }

            var provider = new LocalCacheStreamProvider( );

            try
            {
                await Request.Content.ReadAsMultipartAsync(provider);
            }
            catch (Exception ex)
            {
                throw new WebArgumentException(string.Format("Invalid file upload request. Request: {0}", Request), ex);
            }

            var idMap = new FileList( );

            try
            {
                string expectedType = Request.RequestUri.ParseQueryString( )["type"];

                foreach (var entry in provider.RemoteToLocalFileNameMap)
                {
                    string remoteFileName = entry.Key;
                    string localFileName  = entry.Value;

                    string token;

                    if (!FileRepositoryHelper.CheckFileExtensionIsValid(remoteFileName, expectedType))
                    {
                        throw new PlatformSecurityException("Disallowed file type.");
                    }

                    using (var source = new FileStream(localFileName, FileMode.Open, FileAccess.Read, FileShare.Read))
                    {
                        token = FileRepositoryHelper.AddTemporaryFile(source);
                    }
                    idMap.Add(new FileListItem
                    {
                        FileName = remoteFileName, Hash = token
                    });
                }
            }
            finally
            {
                // clean up the local files
                foreach (var entry in provider.RemoteToLocalFileNameMap)
                {
                    File.Delete(entry.Value);
                }
            }


            return(new HttpResponseMessage <FileList>(idMap));
        }
Example #9
0
        private static void CreateTempFile(out byte[] buffer, out string fileHash)
        {
            buffer = new Byte[1];
            _rand.NextBytes(buffer);
            var ms = new MemoryStream(buffer);

            fileHash = FileRepositoryHelper.AddTemporaryFile(ms);
        }
Example #10
0
        public HttpResponseMessage GetFileByToken(string token)
        {
            var response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(FileRepositoryHelper.GetTemporaryFileDataStream(token))
            };

            return(response);
        }
Example #11
0
        /// <summary>
        ///     Determines if the image already exists.
        /// </summary>
        /// <param name="imageId">The image identifier.</param>
        /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
        public bool DoesImageFileExist(long imageId)
        {
            var imageFile = Entity.Get <ImageFileType>(imageId);

            if (imageFile == null || string.IsNullOrWhiteSpace(imageFile.FileDataHash))
            {
                return(false);
            }

            return(FileRepositoryHelper.DoesFileExist(Factory.BinaryFileRepository, imageFile.FileDataHash));
        }
Example #12
0
        /// <summary>
        /// Gets an asset file in the form of an array of bytes
        /// </summary>
        /// <param name="assetFileParameterMessage">Message wrapper for GetAssetFile parameters</param>
        /// <returns>a StreamErrorWrapper with the relevant stream or with a code that specifies that the file is the same as the one on the client side or with error information</returns>
        public StreamErrorWrapper GetAssetFile(AssetFileParameterMessage assetFileParameterMessage)
        {
            StreamErrorWrapper streamErrorWrapper = new StreamErrorWrapper();

            // close returned stream on completion
            OperationContext clientContext = OperationContext.Current;

            clientContext.OperationCompleted += new EventHandler(delegate(object sender, EventArgs args)
            {
                if (streamErrorWrapper.ReturnStream != null)
                {
                    streamErrorWrapper.ReturnStream.Dispose();
                }
            });

            if (assetFileParameterMessage.SystemPassPhrase != _systemPassPhrase)
            {
                streamErrorWrapper.ErrorCode     = "ERR:001";
                streamErrorWrapper.Message       = "Authentication failure";
                streamErrorWrapper.ErrorSeverity = ErrorSeverity.Retriable;
                streamErrorWrapper.ErrorStatus   = ErrorStatus.Failure;
                streamErrorWrapper.ReturnStream  = new MemoryStream(new byte[0]);

                return(streamErrorWrapper);
            }

            // _assetPath/<asset's GUID suffix>/asset filename
            string assetFullPath = FileRepositoryHelper.GetAssetFullPath(assetFileParameterMessage.AssetFileName);

            if (!File.Exists(assetFullPath))
            {
                _applicationLog.Warn(assetFullPath + " does not exist.");
                streamErrorWrapper.ErrorCode     = "ERR:002";
                streamErrorWrapper.Message       = "File not found";
                streamErrorWrapper.ErrorSeverity = ErrorSeverity.Retriable; // search for asset file later
                streamErrorWrapper.ErrorStatus   = ErrorStatus.Failure;
                streamErrorWrapper.ReturnStream  = new MemoryStream(new byte[0]);
                return(streamErrorWrapper);
            }

            string serverSideChecksum = ReadStringFromFile(Path.GetDirectoryName(assetFullPath) + "\\" + Path.GetFileNameWithoutExtension(assetFullPath) + ".chk");

            if (assetFileParameterMessage.Checksum == serverSideChecksum)
            {
                streamErrorWrapper.ErrorStatus  = ErrorStatus.ChecksumEqual;
                streamErrorWrapper.ReturnStream = new MemoryStream(new byte[0]);
                return(streamErrorWrapper);
            }

            TryReadFileWithReadLock(streamErrorWrapper, assetFullPath);

            return(streamErrorWrapper);
        }
        /// <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 #14
0
        public void PutFromTemporaryFile(string fileHash, string url, string username, string password)
        {
            var uri = new Uri(url);

            ConnectAndRun(uri.Host, username, password, (sftp) =>
            {
                var filePath = uri.AbsolutePath;

                using (var ms = FileRepositoryHelper.GetTemporaryFileDataStream(fileHash))
                {
                    sftp.UploadFile(ms, filePath);
                }
            });
        }
        /// <summary>
        ///     Inserts the file to the database.
        /// </summary>
        /// <param name="fileUploadId">The file upload identifier that was created by the file manager service.</param>
        /// <remarks>The file upload ID is used as the primary key for the table that holds the file for the import.</remarks>
        public string InsertFileToRepository(string fileUploadId)
        {
            string token;

            // Write the data to the stream
            string documentFilename = FileManagerService.GetFilenameFromFileId(fileUploadId);

            using (var source = new FileStream(documentFilename, FileMode.Open, FileAccess.Read, FileShare.Read))
            {
                token = FileRepositoryHelper.AddTemporaryFile(source);
            }
            File.Delete(documentFilename);

            return(token);
        }
Example #16
0
        /// <summary>
        /// Fetch a file via FTP, returning a token to the temporary file in the file repository
        /// </summary>
        /// <param name="url">The file path, must start with either either ftps:// or sftp:// </param>
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>A token to the file repository</returns>
        public string GetToTemporaryFile(string url, string username, string password)
        {
            var uri = new Uri(url);

            string fileToken = null;

            ConnectAndRun(uri.Host, username, password, (sftp) =>
            {
                using (var ms = new MemoryStream())
                {
                    var filePath = uri.AbsolutePath;
                    sftp.DownloadFile(filePath, ms);
                    fileToken = FileRepositoryHelper.AddTemporaryFile(ms);
                }
            });

            return(fileToken);
        }
        /// <summary>
        /// Formats the specified message.
        /// </summary>
        /// <param name="message">The message.</param>
        /// <param name="formattedMessage">The formatted message.</param>
        /// <param name="inbox">The inbox.</param>
        public MailMessageFormatterResult Format(MailMessage message, ReceivedEmailMessage formattedMessage, IEntity inbox)
        {
            if (message == null || formattedMessage == null || inbox == null)
            {
                return(MailMessageFormatterResult.Skip);
            }

            formattedMessage.EmFrom    = message.From?.ToString( );
            formattedMessage.EmTo      = message.To.ToString( );
            formattedMessage.EmSubject = message.Subject;
            formattedMessage.EmCC      = message.CC.ToString( );
            formattedMessage.EmBody    = message.Body;
            var parser = new EmailBodyParser(message.Body);

            formattedMessage.EmReplyFragment = parser.GetReplySectionFromEmailBodyAsText();
            formattedMessage.EmReferences    = message.Headers[EmailHelper.ReferencesHeader];
            formattedMessage.EmIsHtml        = message.IsBodyHtml;
            formattedMessage.EmReceivedDate  = DateTime.UtcNow;
            formattedMessage.FromInbox       = inbox.As <Inbox>( );

            foreach (var emailAttachment in message.Attachments)
            {
                if (emailAttachment.ContentStream.Length > MaxAttachmentSize)
                {
                    EDC.ReadiNow.Diagnostics.EventLog.Application.WriteWarning("Skipping attachment in email from '{0}' to '{1}'. Attachment is greater than maximum allowed size", message.From, message.To);
                    continue;
                }

                var tempHash = FileRepositoryHelper.AddTemporaryFile(emailAttachment.ContentStream);

                var file = Entity.Create <FileType>();
                file.Name          = EnsureValidFileName(emailAttachment.Name);
                file.Description   = "Email Attachment";
                file.FileDataHash  = tempHash;
                file.Size          = (int)emailAttachment.ContentStream.Length;
                file.FileExtension = Path.GetExtension(emailAttachment.Name);
                file.Save();
                formattedMessage.EmAttachments.Add(file);

                EDC.ReadiNow.Diagnostics.EventLog.Application.WriteTrace("Created file '{0}' for attachment in email from '{1}' to {2}.", file.Name, message.From, message.To);
            }

            return(MailMessageFormatterResult.Ok);
        }
        public HttpResponseMessage <ImportResult> ImportXmlGetData([FromUri] string fileId, [FromUri] string fileName = null, [FromUri] bool ignoreDeps = false)
        {
            IEntityXmlImporter importer = Factory.EntityXmlImporter;

            EntityXmlImportResult serviceResult;

            // Decode settings
            var settings = new EntityXmlImportSettings
            {
                IgnoreMissingDependencies = ignoreDeps
            };

            // Import
            using (Stream stream = FileRepositoryHelper.GetTemporaryFileDataStream(fileId))
                using (var xmlReader = XmlReader.Create(stream))
                {
                    serviceResult = importer.ImportXml(xmlReader, settings);
                }

            // Format result
            ImportResult webResult;

            if (serviceResult.ErrorMessage != null)
            {
                webResult = new ImportResult
                {
                    Success = false,
                    Message = serviceResult.ErrorMessage
                };
            }
            else
            {
                IEntityRepository entityRepository = Factory.EntityRepository;
                var entities = entityRepository.Get <Resource>(serviceResult.RootEntities);

                webResult = new ImportResult
                {
                    Success  = true,
                    Entities = entities.Select(FormatEntity).ToList( )
                };
            }

            return(new HttpResponseMessage <ImportResult>(webResult));
        }
Example #19
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 #20
0
        public async Task <HttpResponseMessage> Upload([FromUri] string tenant, [FromUri] string apiPath)
        {
            try
            {
                using (Profiler.Measure("ConnectorController.Upload"))
                {
                    // Capture file
                    string fileToken;
                    using (Stream fileStream = await Request.Content.ReadAsStreamAsync( ))
                    {
                        fileToken = FileRepositoryHelper.AddTemporaryFile(fileStream);
                    }

                    // Run service
                    // Prepare request
                    ConnectorRequest connectorRequest = new ConnectorRequest
                    {
                        Verb               = ConnectorVerb.Post,
                        ApiPath            = GetApiPath(apiPath),
                        Payload            = null,
                        TenantName         = tenant,
                        QueryString        = GetQueryString( ),
                        ControllerRootPath = GetControllerAddress(UploadPrefix),
                        FileUploadToken    = fileToken
                    };

                    // Run request
                    ConnectorResponse response = _connectorService.HandleRequest(connectorRequest);

                    // Response
                    return(ConvertResponse(response));
                }
            }
            catch (WebArgumentException)
            {
                throw;
            }
            catch (Exception ex)
            {
                return(UnhandledException(ex));
            }
        }
        public HttpResponseMessage ExportApplication(string token, string name)
        {
            Stream stream   = FileRepositoryHelper.GetTemporaryFileDataStream(token);
            var    response = new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StreamContent(stream)
            };

            // Note: We are not setting the content length or the mime type
            // because the CompressionHandler will compress the stream.
            // Specifying a mimetype specified here will cause the browser (Chrome at least) to log a
            // message.
            // 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.
            response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
            {
                FileName = name
            };
            return(response);
        }
Example #22
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 #23
0
        public static void TestPutGet(IRemoteFileFetcher fetcher, string url, string username, string password)
        {
            byte[] buffer;
            string fileHash;

            CreateTempFile(out buffer, out fileHash);

            // Put
            fetcher.PutFromTemporaryFile(fileHash, url, username, password);

            // Get
            var fetchedHash = fetcher.GetToTemporaryFile(url, username, password);

            using (var fetchedMs = FileRepositoryHelper.GetTemporaryFileDataStream(fetchedHash))
            {
                var b = fetchedMs.ReadByte();

                buffer[0].ShouldBeEquivalentTo(b);
            }
            //TODO: Delete the file
        }
Example #24
0
        /// <summary>
        /// Fetch a file via FTPS, returning a token to the temporary file in the file repository
        /// </summary>
        /// <param name="url">The file path,
        /// <param name="username"></param>
        /// <param name="password"></param>
        /// <returns>A token to the file repository</returns>
        public string GetToTemporaryFile(string uri, string username, string password)
        {
            string fileHash = null;

            ConnectAndRun(uri, username, password,

                          // setup
                          request =>
            {
                request.Method = WebRequestMethods.Ftp.DownloadFile;
            },

                          // handle response
                          responseStream =>
            {
                fileHash = FileRepositoryHelper.AddTemporaryFile(responseStream);
            }
                          );

            return(fileHash);
        }
        /// <summary>
        ///     Gets the document stream for the specified entity identifier.
        /// </summary>
        /// <param name="entityId">The entity id.</param>
        /// <returns>The open file stream for the document stored in the file stream table.</returns>
        /// <remarks></remarks>
        private static RevisionData GetDocumentStreamForRevisionId(long entityId)
        {
            Stream stream = null;
            // Get the document revision
            var documentRevision = Entity.Get <DocumentRevision>(entityId);

            if (documentRevision == null)
            {
                EventLog.Application.WriteError("Unable to get the document revision stream, invalid document entityId {0}", entityId);
                return(null);
            }

            stream = FileRepositoryHelper.GetFileDataStreamForToken(Factory.DocumentFileRepository, documentRevision.FileDataHash);

            RevisionData result = new RevisionData
            {
                Stream        = stream,
                FileExtension = (documentRevision.FileExtension ?? "").ToLowerInvariant().Trim()
            };

            return(result);
        }
        /// <summary>
        ///     Exports the application to an sqlite database file and loads it into the document library.
        /// </summary>
        /// <param name="applicationVersionId">The application version id.</param>
        /// <returns>A token used to access the export for download.</returns>
        public string ExportApplication(Guid applicationVersionId)
        {
            string token;

            var appFile = $"{DateTime.Now:yyyyMMddhhmmssfff}.xml";
            var db      = Path.Combine(Path.GetTempPath( ), appFile);

            AppManager.ExportAppPackage(applicationVersionId, db, Format.Undefined);

            try
            {
                using (var source = new FileStream(db, FileMode.Open, FileAccess.Read, FileShare.Read))
                {
                    token = FileRepositoryHelper.AddTemporaryFile(source);
                }
            }
            finally
            {
                File.Delete(db);
            }

            return(token);
        }
Example #27
0
 /// <summary>
 ///     Gets the image data stream.
 /// </summary>
 /// <param name="imageFileDataHash">The image file data hash.</param>
 /// <returns></returns>
 public Stream GetImageDataStream(string imageFileDataHash)
 {
     return(FileRepositoryHelper.GetFileDataStreamForToken(Factory.BinaryFileRepository, imageFileDataHash));
 }
Example #28
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));
 }
Example #29
0
        /// <summary>
        ///     Export Data for given file format.
        /// </summary>
        /// <param name="reportId">Report Id.</param>
        /// <param name="settings">Report settings</param>
        /// <param name="format">File format.</param>
        /// <returns>ExportInfo</returns>
        public ExportInfo ExportData(long reportId, ReportSettings settings, ExportFormat format)
        {
            var exportInfo = new ExportInfo();

            //set the page size to maximum.
            settings.SupportPaging = true;
            settings.InitialRow    = 0;
            settings.PageSize      = 10001; // The maximum number of records can be exported is limited to 10000.

            //to retrive the report object and run the report, dosen't need the writeable permission.
            var          reportingInterface = new ReportingInterface();
            ReportResult reportResult       = reportingInterface.RunReport(reportId, settings);

            // Ensure that the report result contains the report metadata (which is loaded in a security bypass context).
            // This ensures that when processing the grid data the required metadata is available
            // and will not throw security exceptions.
            var metadata = reportResult.Metadata;

            //Remove the last record if the number of records are more then 10000.
            List <DataRow> rows;

            if (reportResult.GridData.Count > 10000)
            {
                exportInfo.ResponseMessage = "There are more than 10,000 records in this report. Only the first 10,000 records will be downloaded.";
                rows = reportResult.GridData.GetRange(0, 10000);
            }
            else
            {
                rows = reportResult.GridData;
            }

            Stream fileStream;

            // Generate content
            switch (format)
            {
            case ExportFormat.Csv:
            {
                byte[] resultText = ExportToCsv.CreateCsvDocument(reportResult, rows);
                fileStream = new MemoryStream(resultText);
                break;
            }

            case ExportFormat.Excel:
            {
                fileStream = ExportToExcel.CreateExcelDocument(reportResult, rows);
                break;
            }

            case ExportFormat.Word:
            {
                string reportName = Entity.GetName(reportId);
                fileStream = ExportToWord.CreateWordDocument(reportResult, rows, reportName);
                break;
            }

            default:
                throw new ArgumentException("fileFormat");
            }

            //save the file to the database.
            string hash;

            using (fileStream)
            {
                hash = FileRepositoryHelper.AddTemporaryFile(fileStream);
            }
            exportInfo.FileHash = hash;
            return(exportInfo);
        }
 static Stream GetDocStream(FileType file)
 {
     return(FileRepositoryHelper.GetFileDataStreamForEntity(file));
 }