Beispiel #1
0
        ///// <summary>
        ///// Creates an excel file containing data provided in the dataparts.
        ///// Each IDatapart will match with an ExportPart of the same PartId
        ///// and will use this information to output the data in the desired format.
        ///// </summary>
        ///// <param name="open">true to open, false to not</param>
        ///// <param name="title">The title.</param>
        ///// <param name="dataParts">The data parts to output</param>
        ///// <param name="metadata">The metadata.</param>
        ///// <param name="exportParameters">Optional export parameters.</param>
        ///// <returns>The full path of the created file</returns>
        //public string ExportToExcel(bool open, string title, IEnumerable<IDataPart> dataParts, ExportMetadata metadata, ExcelTemplatePackage templatePackage, ExportParameters exportParameters = null)
        //{
        //    if (string.IsNullOrEmpty(title))
        //    {
        //        throw new ArgumentNullException("targetFilePath");
        //    }
        //    if (dataParts == null)
        //    {
        //        throw new ArgumentNullException("dataParts");
        //    }
        //    if (metadata == null)
        //    {
        //        throw new ArgumentNullException("metadata");
        //    }
        //    if (templatePackage == null)
        //    {
        //        throw new ArgumentNullException("templatePackage");
        //    }

        //    // Adds the parameters as a data part (creates a hidden sheet)
        //    dataParts = AddDebugPart(dataParts, metadata, exportParameters);

        //    // build our sets of DataParts, ExportParts, ExportTemplates
        //    List<ExportTripleSet> sets = this.BuildSets(dataParts, metadata, templatePackage);
        //    if (sets.Count == 0)
        //    {
        //        throw new ExportException("Nothing to export, no matching DataParts, ExportParts, ExportTemplates found");
        //    }

        //    var stream = this.ExcelExportInternal(exportParameters, metadata, sets, dataParts, templatePackage);

        //    if (!title.EndsWith(".xls") && !title.EndsWith(".xlsx"))
        //    {
        //        title = string.Concat(title, ".xlsx");
        //    }

        //    return SaveAndOpen(open, title, stream);
        //}

        /// <summary>
        /// Exports to excel memory stream.
        /// </summary>
        /// <param name="dataParts">The data parts.</param>
        /// <param name="metadata">The metadata.</param>
        /// <param name="templatePackage">The template package.</param>
        /// <param name="exportParameters">The export parameters.</param>
        /// <returns></returns>
        public ExportToMemoryStreamResult ExportToExcelMemoryStream(
            IEnumerable <IDataPart> dataParts,
            Book metadata,
            ExcelTemplatePackage resourcePackage,
            ExportParameters exportParameters = null)
        {
            Guard.IsNotNull(dataParts, "dataParts");
            Guard.IsNotNull(metadata, "metadata");
            Guard.IsNotNull(resourcePackage, "resourcePackage");

            var result = new ExportToMemoryStreamResult();

            dataParts = AddDebugPart(dataParts, metadata, exportParameters);

            // build our sets of DataParts, ExportParts, ExportTemplates
            List <ExportTripleSet> sets = this.BuildSets(dataParts, metadata, resourcePackage);

            if (sets.Count == 0)
            {
                throw new ExportException("Nothing to export, no matching DataParts, ExportParts, ExportTemplates found");
            }

            try
            {
                result.MemoryStream = this.ExcelExportInternal(exportParameters, metadata, sets, dataParts, resourcePackage);
            }
            catch (Exception ex)
            {
                result.Error = ex;
            }

            return(result);
        }
Beispiel #2
0
        /// <summary>
        /// The generate export metadata report.
        /// </summary>
        private MemoryStreamResult GenerateExportMetadataBasedReport()
        {
            this.logger.Log(LogType.Trace, this.GetAssemblyName(), "{0}.GenerateExportMetadataReport", this.GetType().Name);
            var resourcesPackage = ExcelTemplatePackage.Open(Path.Combine(this.sourceFolder, this.templatePackageName));
            var exportMetadata   = ExportMetadataPackage.Open(Path.Combine(this.sourceFolder, this.metadataPackageName)).ExportMetadata;
            var generator        = new ExportGenerator();
            var exportParams     = new ExportParameters();

            ExportToMemoryStreamResult result = generator.ExportToExcelMemoryStream(this.dataParts,
                                                                                    exportMetadata,
                                                                                    resourcesPackage,
                                                                                    exportParams);

            if (result.Error != null)
            {
                this.logger.Log(LogType.Fatal, this.GetAssemblyName(), "{0}.GenerateExportMetadataReport", result.Error);
            }

            return(new MemoryStreamResult
            {
                MemoryStream = result.MemoryStream,
                Status = result.Error == null ? MemoryStreamResultStatus.Success : MemoryStreamResultStatus.Failure,
                ErrorMessage = result.Error == null ? null : result.Error.Message,
            });
        }
Beispiel #3
0
        ///// <summary>
        ///// Saves the memory stream to my documents with the provided title
        ///// </summary>
        ///// <param name="title">The title.</param>
        ///// <param name="stream">The stream.</param>
        ///// <returns>
        ///// The full path of the saved file
        ///// </returns>
        //public static string Save(string title, MemoryStream stream)
        //{
        //    string filePath = FileHelper.GetMyDocumentFilePath(title);
        //    using (FileStream fileStream = File.OpenWrite(filePath))
        //    {
        //        stream.WriteTo(fileStream);
        //    }
        //    return filePath;
        //}

        ///// <summary>
        ///// Saves the stream to the my documents with the title
        ///// Optionally opends
        ///// </summary>
        ///// <param name="open">if set to <c>true</c> [open].</param>
        ///// <param name="title">The title.</param>
        ///// <param name="stream">The stream.</param>
        ///// <returns>
        ///// The full path of the saved file
        ///// </returns>
        //public static string SaveAndOpen(bool open, string title, MemoryStream stream)
        //{
        //    // call save and open
        //    string outputFile = Save(title, stream);
        //    if (open)
        //    {
        //        ThreadPool.QueueUserWorkItem(
        //            (obj) =>
        //            {
        //                Process.Start(outputFile);
        //            });
        //    }
        //    return outputFile;
        //}

        #region Build of export sets

        /// <summary>
        /// Creates a list of export sets matching parts based on the provided data.
        /// For each data part try and find a matching export part.
        /// If any mandatory export parts havent been provided with data an exception will be thrown.
        /// </summary>
        /// <param name="dataParts">The data parts.</param>
        /// <param name="exportMetadata">The export metadata.</param>
        /// <param name="templatePackage">The template package.</param>
        /// <returns></returns>
        /// <exception cref="MetadataException"></exception>
        private List <ExportTripleSet> BuildSets(
            IEnumerable <IDataPart> dataParts,
            Book exportMetadata,
            ExcelTemplatePackage templatePackage)
        {
            // pair up the data with the export part and keep them for use later
            var sets = new List <ExportTripleSet>();

            // for each data part get the matching export part
            foreach (var dataPart in dataParts)
            {
                if (dataPart == null)
                {
                    continue;
                }

                // return the ExportPart(s) that matches with the provided data part
                foreach (var exportPart in SafePartMatch(dataPart, exportMetadata.Parts))
                {
                    // return a new instance of the template
                    var template = templatePackage.GetTemplateByTemplateId(exportPart.TemplateId);

                    // and add the 3 items to the set
                    sets.Add(new ExportTripleSet(dataPart, exportPart, template));
                }
            }

            // get a list of mandatory parts
            var mandatoryExportParts = from p in exportMetadata.Parts
                                       where p.IsMandatory
                                       select p;

            StringBuilder errors = new StringBuilder();

            // and for each of these check that they've been added to the set
            foreach (var mandatory in mandatoryExportParts)
            {
                bool match = (from s in sets
                              where s.Part == mandatory
                              select s).Any();
                // if we cant find one them add to our list of errors
                if (!match)
                {
                    errors.Append("No DataPart supplied for mandatory export part <");
                    errors.Append(mandatory.PartId);
                    errors.Append(">");
                    errors.Append(Environment.NewLine);
                }
            }

            // then throw any missing mandatorys as a metadata exception
            if (errors.Length > 0)
            {
                throw new MetadataException(errors.ToString());
            }

            return(sets);
        }
Beispiel #4
0
        /// <summary>
        /// Creates a fully populated <see cref="ResourceStore" /> which contains all resources defined in a <see cref="TemplateCollection" />.
        /// This is for backward compatibility during processing of a <see cref="TemplateCollection" />.
        /// </summary>
        /// <param name="templateCollection">The template collection.</param>
        /// <param name="templatePackage">The template package.</param>
        /// <returns>
        /// A fully populated <see cref="ResourceStore" />
        /// </returns>
        internal static ResourceStore Create(TemplateCollection templateCollection, ExcelTemplatePackage templatePackage)
        {
            if (templateCollection == null || string.IsNullOrEmpty(templateCollection.XamlString))
            {
                return(null);
            }

            ResourceStore resourceStore = new ResourceStore();
            var           document      = XDocument.Parse(templateCollection.XamlString);

            // Add in the defined Styles
            foreach (var resource in templateCollection.StyleResources)
            {
                resourceStore.Add(resource.Key, ResourceTypeNames.StyleBase, resource, null);
            }

            // Add in CellStyleSelectors
            foreach (var resource in templateCollection.CellStyleSelectors)
            {
                resourceStore.Add(resource.Key, ResourceTypeNames.CellStyleSelector, resource, null);
            }

            // Loop over each all elements, adding any that are defined in the Maps collection or identified as being Template resources
            foreach (var element in document.Root.Elements())
            {
                if (element.NodeType != XmlNodeType.Element || element.Name == null)
                {
                    continue;
                }

                if (element.Name.LocalName.CompareTo("TemplateCollection.Maps") == 0)
                {
                    foreach (var mapElement in element.Elements())
                    {
                        AddElementToStore(templateCollection, resourceStore, mapElement);
                    }
                }
                else if (element.Name.LocalName.CompareTo("Template") == 0)
                {
                    var id = element.Attribute("TemplateId").Value;
                    resourceStore.Add(id, element.Name.LocalName, element.ToString(), templateCollection.TemplateFileName, null);
                }
            }

            // Add the TemplateFile as a designer file, which can be used by maps as a resource
            if (!string.IsNullOrEmpty(templateCollection.TemplateFileName))
            {
                var data = templatePackage.TemplateResourceStore.templateDocumentDictionary[templateCollection.TemplateFileName].Data;
                resourceStore.AddDesignerFileData(templateCollection.TemplateFileName, data);
            }

            // Populate chart and shape models from the supplied resource designer files and defined templates,
            // such as ChartTemplate and ShapeTempaltes.
            resourceStore.PopulateModels();

            return(resourceStore);
        }
Beispiel #5
0
        /// <summary>
        /// The pack source templates folder.
        /// </summary>
        /// <param name="subFolderName">The sub folder name.</param>
        /// <returns>The zipped file name</returns>
        private string PackSourceTemplatesFolder(string subFolderName)
        {
            this.logger.Log(LogType.Trace, this.GetAssemblyName(), "{0}.PackSourceTemplatesFolder - Packing {1}", this.GetType().Name, subFolderName);
            string directory = Path.Combine(this.sourceFolder, subFolderName);
            string package   = this.isExcelDocumentMetaBased
                ? ResourcePackage.Pack(directory)
                : ExcelTemplatePackage.Pack(directory);

            // Extract package name from returned
            return(Path.GetFileName(package));
        }
        /// <summary>
        /// Opens the specified file name.
        /// </summary>
        /// <param name="fileName">Name of the file.</param>
        /// <param name="errors">The errors.</param>
        /// <returns></returns>
        public static ExcelTemplatePackage Open(string fileName, out string errors)
        {
            // avoid contention whilst opening file, should be v quick anyway
            lock (padLock)
            {
                try
                {
                    errors      = null;
                    writeOutput = false;

                    if (string.IsNullOrEmpty(fileName))
                    {
                        throw new ArgumentNullException("fileName");
                    }

                    var fi = new FileInfo(fileName);
                    if (!fi.Exists)
                    {
                        throw new MetadataException(string.Format("File not found <{0}>", fileName));
                    }

                    Output(string.Format("Starting open of package <{0}>", fileName));

                    ExcelTemplatePackage package = new ExcelTemplatePackage();

                    List <PackagePart> metadataParts = new List <PackagePart>();
                    List <PackagePart> fileParts     = new List <PackagePart>();

                    using (var zip = ZipPackage.Open(fileName, FileMode.Open, FileAccess.Read))
                    {
                        Output("Zip opened");

                        foreach (var part in zip.GetParts())
                        {
                            string uriString = part.Uri.OriginalString;

                            if (uriString.StartsWith(string.Concat(UriDelim, MetadataPathPart)))
                            {
                                metadataParts.Add(part);

                                Output(string.Format("Found Metadata part: Uri <{0}>", uriString));
                            }
                            else if (uriString.StartsWith(string.Concat(UriDelim, FilesPathPart)))
                            {
                                fileParts.Add(part);

                                Output(string.Format("Found TemplateFile part: Uri <{0}>", uriString));
                            }
                        }

                        // read all the templates files into our internal store
                        foreach (var m in metadataParts)
                        {
                            long   length = m.GetStream().Length;
                            byte[] data   = new byte[length];
                            m.GetStream().Read(data, 0, (int)length);

                            Output(string.Format("Loading Metadata part: Uri <{0}> Size {1}", m.Uri.OriginalString, length));

                            bool hasBomb = false;
                            if (data.Length > 2 && data[0] == 0xEF && data[1] == 0xBB && data[2] == 0xBF)
                            {
                                hasBomb = true;
                                Output("Stripping Byte Order Mark");
                            }

                            string resourceString = System.Text.UTF8Encoding.UTF8.GetString(hasBomb ? data.Skip(3).ToArray() : data);

                            string error = null;
                            if (!package.TryLoadResourceString(m.Uri.OriginalString, resourceString, out error))
                            {
                                if (string.IsNullOrEmpty(errors))
                                {
                                    errors = error;
                                }
                                else
                                {
                                    errors += error;
                                }
                                errors += Environment.NewLine;
                            }
                        }

                        foreach (var f in fileParts)
                        {
                            string name   = f.Uri.OriginalString.Replace(string.Concat(UriDelim, FilesPathPart, UriDelim), null);
                            long   length = f.GetStream().Length;
                            byte[] data   = new byte[length];
                            f.GetStream().Read(data, 0, (int)length);

                            Output(string.Format("Loading TemplateFile part: Uri <{0}> Size {1}", f.Uri.OriginalString, length));

                            package.LoadTemplateFile(name, data);
                        }
                    }

                    package.ValidateInternal();

                    return(package);
                }
                catch (Exception ex)
                {
                    Output(ex.ToString());
                    throw;
                }
                finally
                {
                    writeOutput = false;
                }
            }
        }
        ///// <summary>
        ///// Creates an excel file containing data provided in the dataparts.
        ///// Each IDatapart will match with an ExportPart of the same PartId
        ///// and will use this information to output the data in the desired format.
        ///// </summary>
        ///// <param name="open">true to open, false to not</param>
        ///// <param name="title">The title.</param>
        ///// <param name="dataParts">The data parts to output</param>
        ///// <param name="metadata">The metadata.</param>
        ///// <param name="exportParameters">Optional export parameters.</param>
        ///// <returns>The full path of the created file</returns>
        //public string ExportToExcel(bool open, string title, IEnumerable<IDataPart> dataParts, ExportMetadata metadata, ExcelTemplatePackage templatePackage, ExportParameters exportParameters = null)
        //{
        //    if (string.IsNullOrEmpty(title))
        //    {
        //        throw new ArgumentNullException("targetFilePath");
        //    }
        //    if (dataParts == null)
        //    {
        //        throw new ArgumentNullException("dataParts");
        //    }
        //    if (metadata == null)
        //    {
        //        throw new ArgumentNullException("metadata");
        //    }
        //    if (templatePackage == null)
        //    {
        //        throw new ArgumentNullException("templatePackage");
        //    }

        //    // Adds the parameters as a data part (creates a hidden sheet)
        //    dataParts = AddDebugPart(dataParts, metadata, exportParameters);

        //    // build our sets of DataParts, ExportParts, ExportTemplates
        //    List<ExportTripleSet> sets = this.BuildSets(dataParts, metadata, templatePackage);
        //    if (sets.Count == 0)
        //    {
        //        throw new ExportException("Nothing to export, no matching DataParts, ExportParts, ExportTemplates found");
        //    }

        //    var stream = this.ExcelExportInternal(exportParameters, metadata, sets, dataParts, templatePackage);

        //    if (!title.EndsWith(".xls") && !title.EndsWith(".xlsx"))
        //    {
        //        title = string.Concat(title, ".xlsx");
        //    }

        //    return SaveAndOpen(open, title, stream);
        //}

        /// <summary>
        /// Exports to excel memory stream.
        /// </summary>
        /// <param name="dataParts">The data parts.</param>
        /// <param name="metadata">The metadata.</param>
        /// <param name="templatePackage">The template package.</param>
        /// <param name="exportParameters">The export parameters.</param>
        /// <returns></returns>
        public ExportToMemoryStreamResult ExportToExcelMemoryStream(IEnumerable <IDataPart> dataParts, ExportMetadata metadata, ExcelTemplatePackage templatePackage, ExportParameters exportParameters = null)
        {
            var result = new ExportToMemoryStreamResult();

            if (dataParts == null)
            {
                throw new ArgumentNullException("dataParts");
            }
            if (metadata == null)
            {
                throw new ArgumentNullException("metadata");
            }
            if (templatePackage == null)
            {
                throw new ArgumentNullException("templatePackage");
            }

            dataParts = AddDebugPart(dataParts, metadata, exportParameters);

            // build our sets of DataParts, ExportParts, ExportTemplates
            List <ExportTripleSet> sets = this.BuildSets(dataParts, metadata, templatePackage);

            if (sets.Count == 0)
            {
                throw new ExportException("Nothing to export, no matching DataParts, ExportParts, ExportTemplates found");
            }

            try
            {
                result.MemoryStream = this.ExcelExportInternal(exportParameters, metadata, sets, dataParts, templatePackage);
            }
            catch (Exception ex)
            {
                result.Error = ex;
            }

            return(result);
        }