예제 #1
0
    private static void ValidateTitle(WordTemplateEntity template, List <TemplateError> errors, string title)
    {
        var titleFirstLine = title.Lines().FirstOrDefault();
        var prefix         = titleFirstLine?.TryBefore(":");

        if (prefix != null)
        {
            var provider = WordTemplateLogic.ToDataTableProviders.TryGetC(prefix);
            if (provider != null)
            {
                var error = provider.Validate(titleFirstLine !.After(":"), template);
                if (error != null)
                {
                    errors.Add(new TemplateError(false, error));
                }


                var pivotStr = title.TryAfter('\n')?.Trim();
                if (pivotStr.HasText())
                {
                    var pivot = UserChartDataTableProvider.ParsePivot(pivotStr);
                    if (pivot == null)
                    {
                        errors.Add(new TemplateError(false, "Unexpected Alternative Text '" + title + "'\nDid you wanted to use 'Pivot(colX, colY, colValue)'?"));
                    }
                }
            }
        }
    }
예제 #2
0
    public string?Validate(string suffix, WordTemplateEntity template)
    {
        if (!Guid.TryParse((suffix.TryBefore("\n") ?? suffix).Trim(), out Guid guid))
        {
            return("Impossible to convert '{0}' in a GUID for a UserChart".FormatWith(suffix));
        }

        var uc = Database.Query <UserChartEntity>().Where(a => a.Guid == guid).Select(a => new { UC = a.ToLite(), a.EntityType }).SingleOrDefaultEx();

        if (uc == null)
        {
            return("No UserChart with GUID={0} found".FormatWith(guid));
        }

        if (uc.EntityType != null)
        {
            var imp = QueryLogic.Queries.GetEntityImplementations(template.Query.ToQueryName());

            var type = TypeLogic.GetType(uc.EntityType.Retrieve().CleanName);

            if (!imp.Types.Contains(type))
            {
                return("No UserChart {0} (GUID={1}) is not compatible with ".FormatWith(uc.UC, guid, imp));
            }
        }

        return(null);
    }
예제 #3
0
 public WordTemplateParser(OpenXmlPackage document, QueryDescription queryDescription, Type?modelType, WordTemplateEntity template)
 {
     this.QueryDescription = queryDescription;
     this.ModelType        = modelType;
     this.document         = document;
     this.template         = template;
 }
예제 #4
0
 public TemplateParser(OpenXmlPackage document, QueryDescription queryDescription, Type systemWordTemplateType, WordTemplateEntity template)
 {
     this.queryDescription       = queryDescription;
     this.SystemWordTemplateType = systemWordTemplateType;
     this.document = document;
     this.template = template;
 }
예제 #5
0
        internal static void ValidateTables(OpenXmlPart part, WordTemplateEntity template, List <TemplateError> errors)
        {
            var graphicFrames = part.RootElement.Descendants().Where(a => a.LocalName == "graphicFrame").ToList();

            foreach (var item in graphicFrames)
            {
                var nonVisualProps = item.Descendants().SingleOrDefaultEx(a => a.LocalName == "cNvPr");
                var title          = GetTitle(nonVisualProps);

                if (title != null)
                {
                    var prefix = title.TryBefore(":");
                    if (prefix != null)
                    {
                        var provider = WordTemplateLogic.ToDataTableProviders.TryGetC(prefix);
                        if (provider == null)
                        {
                            errors.Add(new TemplateError(false, "No DataTableProvider '{0}' found (Possibilieties {1})".FormatWith(prefix, WordTemplateLogic.ToDataTableProviders.Keys.CommaOr())));
                        }
                        else
                        {
                            var error = provider.Validate(title.After(":"), template);
                            if (error != null)
                            {
                                errors.Add(new TemplateError(false, error));
                            }
                        }
                    }
                }
            }
        }
예제 #6
0
    internal static void ValidateTables(OpenXmlPart part, WordTemplateEntity template, List <TemplateError> errors)
    {
        //Powerpoint container
        var graphicFrames = part.RootElement !.Descendants <Presentation.GraphicFrame>().ToList();

        foreach (var item in graphicFrames)
        {
            var nonVisualProps = item.Descendants <Presentation.NonVisualDrawingProperties>().SingleOrDefaultEx();
            var title          = GetTitle(nonVisualProps);

            if (title != null)
            {
                ValidateTitle(template, errors, title);
            }
        }

        //Word container
        var drawings = part.RootElement !.Descendants <Wordprocessing.Drawing>().ToList();

        foreach (var item in drawings)
        {
            var docProps = item.Descendants <WPDrawing.DocProperties>().SingleOrDefaultEx();
            var title    = GetTitle(docProps);

            if (title != null)
            {
                ValidateTitle(template, errors, title);
            }
        }
    }
예제 #7
0
        static string ValidateTemplate(WordTemplateEntity template, PropertyInfo pi)
        {
            if (template.Template == null)
            {
                return(null);
            }

            using (template.DisableAuthorization ? ExecutionMode.Global() : null)
            {
                QueryDescription qd = DynamicQueryManager.Current.QueryDescription(template.Query.ToQueryName());

                string error = null;
                template.ProcessOpenXmlPackage(document =>
                {
                    Dump(document, "0.Original.txt");

                    var parser = new TemplateParser(document, qd, template.SystemWordTemplate.ToType(), template);
                    parser.ParseDocument(); Dump(document, "1.Match.txt");
                    parser.CreateNodes(); Dump(document, "2.BaseNode.txt");
                    parser.AssertClean();

                    error = parser.Errors.IsEmpty() ? null :
                            parser.Errors.ToString(e => e.Message, "\r\n");
                });

                return(error);
            }
        }
예제 #8
0
 public WordTemplateParameters(IEntity?entity, CultureInfo culture, Dictionary <QueryToken, ResultColumn> columns,
                               IEnumerable <ResultRow> rows, WordTemplateEntity template, IWordModel?wordModel) :
     base(entity, culture, columns, rows)
 {
     this.Template = template;
     this.Model    = wordModel;
 }
예제 #9
0
 public TemplateRenderer(OpenXmlPackage document, QueryDescription queryDescription, Entity entity, CultureInfo culture, ISystemWordTemplate systemWordTemplate, WordTemplateEntity template)
 {
     this.document           = document;
     this.entity             = entity;
     this.culture            = culture;
     this.systemWordTemplate = systemWordTemplate;
     this.queryDescription   = queryDescription;
     this.template           = template;
 }
예제 #10
0
 public WordTemplateRenderer(OpenXmlPackage document, QueryDescription queryDescription, CultureInfo culture, WordTemplateEntity template, IWordModel?model, Entity?entity, TextTemplateParser.BlockNode?fileNameBlock)
 {
     this.document         = document;
     this.culture          = culture;
     this.queryDescription = queryDescription;
     this.template         = template;
     this.entity           = entity;
     this.model            = model;
     this.fileNameBlock    = fileNameBlock;
 }
예제 #11
0
        public static void Start(SchemaBuilder sb, DynamicQueryManager dqm)
        {
            sb.Include <WordAttachmentEntity>()
            .WithQuery(dqm, () => s => new
            {
                Entity = s,
                s.Id,
                s.FileName,
                s.WordTemplate,
                s.OverrideModel,
            });

            EmailTemplateLogic.FillAttachmentTokens.Register((WordAttachmentEntity wa, EmailTemplateLogic.FillAttachmentTokenContext ctx) =>
            {
                if (wa.FileName != null)
                {
                    EmailTemplateParser.Parse(wa.FileName, ctx.QueryDescription, ctx.ModelType).FillQueryTokens(ctx.QueryTokens);
                }
            });

            Validator.PropertyValidator((WordAttachmentEntity e) => e.FileName).StaticPropertyValidation = WordAttachmentFileName_StaticPropertyValidation;

            EmailTemplateLogic.GenerateAttachment.Register((WordAttachmentEntity wa, EmailTemplateLogic.GenerateAttachmentContext ctx) =>
            {
                var entity = wa.OverrideModel?.Retrieve() ?? (Entity)ctx.Entity ?? ctx.SystemEmail.UntypedEntity;

                if (wa.ModelConverter != null)
                {
                    entity = wa.ModelConverter.Convert(entity);
                }

                using (CultureInfoUtils.ChangeBothCultures(ctx.Culture))
                {
                    WordTemplateEntity template = WordTemplateLogic.GetFromCache(wa.WordTemplate);

                    var fileName = GetTemplateString(wa.FileName, ref wa.FileNameNode, ctx);

                    var systemWordTemplate = template.SystemWordTemplate != null && !SystemWordTemplateLogic.RequiresExtraParameters(template.SystemWordTemplate) ?
                                             SystemWordTemplateLogic.CreateDefaultSystemWordTemplate(template.SystemWordTemplate, entity) : null;

                    var bytes = WordTemplateLogic.CreateReport(template, entity, systemWordTemplate);

                    return(new List <EmailAttachmentEmbedded>
                    {
                        new EmailAttachmentEmbedded
                        {
                            File = Files.FilePathEmbeddedLogic.SaveFile(new Entities.Files.FilePathEmbedded(EmailFileType.Attachment, fileName, bytes)),
                            Type = EmailAttachmentType.Attachment,
                        }
                    });
                }
            });
        }
예제 #12
0
 public string Validate(string suffix, WordTemplateEntity template)
 {
     try
     {
         GetMethod(template, suffix);
         return(null);
     }
     catch (Exception e)
     {
         return(e.Message);
     }
 }
예제 #13
0
        public static bool Regenerate(WordTemplateEntity template)
        {
            var result = Regenerate(template, null);

            if (result == null)
            {
                return(false);
            }

            result.ExecuteLeaves();
            return(true);
        }
예제 #14
0
        public string Validate(string suffix, WordTemplateEntity template)
        {
            if (!Guid.TryParse(suffix, out Guid guid))
            {
                return("Impossible to convert '{0}' in a GUID for a UserChart".FormatWith(suffix));
            }

            if (!Database.Query <UserChartEntity>().Any(a => a.Guid == guid))
            {
                return("No UserChart with GUID={0} found".FormatWith(guid));
            }

            return(null);
        }
예제 #15
0
        private static MethodInfo GetMethod(WordTemplateEntity template, string method)
        {
            if (template.SystemWordTemplate == null)
            {
                throw new InvalidOperationException($"No SystemWordTemplate found in template '{template}' to call '{method}'");
            }

            var type = template.SystemWordTemplate.ToType();
            var mi   = type.GetMethod(method);

            if (mi == null)
            {
                throw new InvalidOperationException($"No Method with name '{method}' found in type '{type.Name}'");
            }


            return(mi);
        }
예제 #16
0
        private static SqlPreCommand Regenerate(WordTemplateEntity template, Replacements replacements)
        {
            var newTemplate = SystemWordTemplateLogic.CreateDefaultTemplate(template.SystemWordTemplate);

            if (newTemplate == null)
            {
                return(null);
            }

            var file = template.Template.Retrieve();

            using (file.AllowChanges())
            {
                file.BinaryFile = newTemplate.Template.Entity.BinaryFile;
                file.FileName   = newTemplate.Template.Entity.FileName;

                return(Schema.Current.Table <FileEntity>().UpdateSqlSync(file, comment: "WordTemplate Regenerated: " + template.Name));
            }
        }
예제 #17
0
        internal static WordTemplateEntity CreateDefaultTemplate(SystemWordTemplateEntity systemWordReport)
        {
            SystemWordTemplateInfo info = systemWordReports.GetOrThrow(systemWordReport.ToType());

            if (info.DefaultTemplateConstructor == null)
            {
                return(null);
            }

            WordTemplateEntity template = info.DefaultTemplateConstructor();

            if (template.Name == null)
            {
                template.Name = systemWordReport.FullClassName;
            }

            template.SystemWordTemplate = systemWordReport;
            template.Query = QueryLogic.GetQueryEntity(info.QueryName);

            return(template);
        }
예제 #18
0
        public static bool IsVisible(WordTemplateEntity wt, WordTemplateVisibleOn visibleOn)
        {
            if (wt.SystemWordTemplate == null)
            {
                return(visibleOn == WordTemplateVisibleOn.Single);
            }

            if (SystemWordTemplateLogic.HasDefaultTemplateConstructor(wt.SystemWordTemplate))
            {
                return(false);
            }

            var entityType = SystemWordTemplateLogic.GetEntityType(wt.SystemWordTemplate.ToType());

            if (entityType.IsEntity())
            {
                return(visibleOn == WordTemplateVisibleOn.Single);
            }

            var should = VisibleOnDictionary.TryGet(entityType, WordTemplateVisibleOn.Single);

            return((should & visibleOn) != 0);
        }
예제 #19
0
        public static byte[] ProcessOpenXmlPackage(this WordTemplateEntity template, Action <OpenXmlPackage> processPackage)
        {
            var file = template.Template.Retrieve();

            using (var memory = new MemoryStream())
            {
                memory.WriteAllBytes(file.BinaryFile);

                var ext = Path.GetExtension(file.FileName).ToLower();

                var document =
                    ext == ".docx" ? (OpenXmlPackage)WordprocessingDocument.Open(memory, true) :
                    ext == ".pptx" ? (OpenXmlPackage)PresentationDocument.Open(memory, true) :
                    ext == ".xlsx" ? (OpenXmlPackage)SpreadsheetDocument.Open(memory, true) :
                    throw new InvalidOperationException("Extension '{0}' not supported".FormatWith(ext));

                using (document)
                {
                    processPackage(document);
                }

                return(memory.ToArray());
            }
        }
예제 #20
0
 public WordContext(WordTemplateEntity template, Entity?entity, IWordModel?model)
 {
     Template = template;
     Entity   = entity;
     Model    = model;
 }
예제 #21
0
        public static WordTemplateEntity GetFromCache(this Lite <WordTemplateEntity> liteTemplate)
        {
            WordTemplateEntity template = WordTemplatesLazy.Value.GetOrThrow(liteTemplate, "Word report template {0} not in cache".FormatWith(liteTemplate));

            return(template);
        }
예제 #22
0
        public static byte[] CreateReport(this WordTemplateEntity template, ModifiableEntity model = null, ISystemWordTemplate systemWordTemplate = null, bool avoidConversion = false)
        {
            WordTemplatePermission.GenerateReport.AssertAuthorized();

            Entity entity = null;

            if (template.SystemWordTemplate != null)
            {
                if (systemWordTemplate == null)
                {
                    systemWordTemplate = SystemWordTemplateLogic.CreateDefaultSystemWordTemplate(template.SystemWordTemplate, model);
                }
                else if (template.SystemWordTemplate.ToType() != systemWordTemplate.GetType())
                {
                    throw new ArgumentException("systemWordTemplate should be a {0} instead of {1}".FormatWith(template.SystemWordTemplate.FullClassName, systemWordTemplate.GetType().FullName));
                }
            }
            else
            {
                entity = model as Entity ?? throw new InvalidOperationException("Model should be an Entity");
            }

            using (template.DisableAuthorization ? ExecutionMode.Global() : null)
                using (CultureInfoUtils.ChangeBothCultures(template.Culture.ToCultureInfo()))
                {
                    QueryDescription qd = DynamicQueryManager.Current.QueryDescription(template.Query.ToQueryName());

                    var array = template.ProcessOpenXmlPackage(document =>
                    {
                        Dump(document, "0.Original.txt");

                        var parser = new TemplateParser(document, qd, template.SystemWordTemplate.ToType(), template);
                        parser.ParseDocument(); Dump(document, "1.Match.txt");
                        parser.CreateNodes(); Dump(document, "2.BaseNode.txt");
                        parser.AssertClean();

                        if (parser.Errors.Any())
                        {
                            throw new InvalidOperationException("Error in template {0}:\r\n".FormatWith(template) + parser.Errors.ToString(e => e.Message, "\r\n"));
                        }

                        var renderer = new TemplateRenderer(document, qd, entity, template.Culture.ToCultureInfo(), systemWordTemplate, template);
                        renderer.MakeQuery();
                        renderer.RenderNodes(); Dump(document, "3.Replaced.txt");
                        renderer.AssertClean();

                        FixDocument(document); Dump(document, "4.Fixed.txt");

                        if (template.WordTransformer != null)
                        {
                            Transformers.GetOrThrow(template.WordTransformer)(new WordContext
                            {
                                Template           = template,
                                Entity             = entity,
                                SystemWordTemplate = systemWordTemplate
                            }, document);
                        }
                    });

                    if (!avoidConversion && template.WordConverter != null)
                    {
                        array = Converters.GetOrThrow(template.WordConverter)(new WordContext
                        {
                            Template           = template,
                            Entity             = entity,
                            SystemWordTemplate = systemWordTemplate
                        }, array);
                    }

                    return(array);
                }
        }
예제 #23
0
        internal static SqlPreCommand SynchronizeWordTemplate(Replacements replacements, WordTemplateEntity template, StringDistance sd)
        {
            try
            {
                if (template.Template == null || !replacements.Interactive)
                {
                    return(null);
                }

                var queryName = QueryLogic.ToQueryName(template.Query.Key);

                QueryDescription qd = DynamicQueryManager.Current.QueryDescription(queryName);

                Console.Clear();

                SafeConsole.WriteLineColor(ConsoleColor.White, "WordTemplate: " + template.Name);
                Console.WriteLine(" Query: " + template.Query.Key);

                var file = template.Template.Retrieve();

                try
                {
                    SyncronizationContext sc = new SyncronizationContext
                    {
                        ModelType        = template.SystemWordTemplate.ToType(),
                        QueryDescription = qd,
                        Replacements     = replacements,
                        StringDistance   = sd,
                        HasChanges       = false,
                        Variables        = new ScopedDictionary <string, ValueProviderBase>(null),
                    };

                    var bytes = template.ProcessOpenXmlPackage(document =>
                    {
                        Dump(document, "0.Original.txt");

                        var parser = new TemplateParser(document, qd, template.SystemWordTemplate.ToType(), template);
                        parser.ParseDocument(); Dump(document, "1.Match.txt");
                        parser.CreateNodes(); Dump(document, "2.BaseNode.txt");
                        parser.AssertClean();

                        foreach (var root in document.AllRootElements())
                        {
                            foreach (var node in root.Descendants <BaseNode>().ToList())
                            {
                                node.Synchronize(sc);
                            }
                        }

                        if (sc.HasChanges)
                        {
                            Dump(document, "3.Synchronized.txt");
                            var variables = new ScopedDictionary <string, ValueProviderBase>(null);
                            foreach (var root in document.AllRootElements())
                            {
                                foreach (var node in root.Descendants <BaseNode>().ToList())
                                {
                                    node.RenderTemplate(variables);
                                }
                            }

                            Dump(document, "4.Rendered.txt");
                        }
                    });

                    if (!sc.HasChanges)
                    {
                        return(null);
                    }

                    file.AllowChange = true;
                    file.BinaryFile  = bytes;

                    using (replacements.WithReplacedDatabaseName())
                        return(Schema.Current.Table <FileEntity>().UpdateSqlSync(file, comment: "WordTemplate: " + template.Name));
                }
                catch (TemplateSyncException ex)
                {
                    if (ex.Result == FixTokenResult.SkipEntity)
                    {
                        return(null);
                    }

                    if (ex.Result == FixTokenResult.DeleteEntity)
                    {
                        return(SqlPreCommandConcat.Combine(Spacing.Simple,
                                                           Schema.Current.Table <WordTemplateEntity>().DeleteSqlSync(template),
                                                           Schema.Current.Table <FileEntity>().DeleteSqlSync(file)));
                    }

                    if (ex.Result == FixTokenResult.ReGenerateEntity)
                    {
                        return(Regenerate(template, replacements));
                    }

                    throw new InvalidOperationException("Unexcpected {0}".FormatWith(ex.Result));
                }
                finally
                {
                    Console.Clear();
                }
            }
            catch (Exception e)
            {
                return(new SqlPreCommandSimple("-- Exception in {0}: \r\n{1}".FormatWith(template.BaseToString(), e.Message.Indent(2, '-'))));
            }
        }
예제 #24
0
        public static byte[] CreateReport(this ISystemWordTemplate systemWordTemplate, out WordTemplateEntity template, bool avoidConversion = false)
        {
            SystemWordTemplateEntity system = GetSystemWordTemplate(systemWordTemplate.GetType());

            template = GetDefaultTemplate(system, systemWordTemplate.UntypedEntity as Entity);

            return(WordTemplateLogic.CreateReport(template.ToLite(), systemWordTemplate: systemWordTemplate, avoidConversion: avoidConversion));
        }