public void RegisterHelperSample()
 {
     var helperjs =
         @"function() {
     return new Handlebars.SafeString(""<a href='"" + this.url + ""'>"" + this.body + ""</a>"");
     }";
     var source = @"
     <ul>
     {{#posts}}
     <li>{{link_to}}</li>
     {{/posts}}
     </ul>";
     var context = new
     {
         posts = new[]
         {
             new
             {
                 url = "/hello-world",
                 body = "Hello World!"
             }
         }
     };
     using (var handleBars = new Handlebars())
     {
         handleBars.RegisterHelper("link_to", helperjs);
         handleBars.RegisterTemplate("myTemplate", source);
         Approvals.Verify(handleBars.Transform("myTemplate", context));
     }
 }
 public void load()
 {
     Handlebars.RegisterHelper("randomRange", RandomRange());
 }
        public override async Task PerformTask(ISkraprWorker worker)
        {
            Handlebars.RegisterHelper("kebaberize", (writer, context, parameters) =>
            {
                if (parameters.Length != 1)
                {
                    throw new HandlebarsException("kebaberize expects exactly one parameter.");
                }

                writer.WriteSafeString(
                    parameters[0].ToString()
                    .Underscore()
                    .Dasherize()
                    );
            });

            //Compile the task templates
            var template = Handlebars.Compile(TaskTemplates.ToString());

            //Get the matching selectors
            var documentNode = await worker.Session.DOM.GetDocument(1);

            var selectorResponse = await worker.Session.DOM.QuerySelectorAll(new ChromeDevTools.DOM.QuerySelectorAllCommand
            {
                NodeId   = documentNode.NodeId,
                Selector = Selector
            });

            var nodeTasks = new List <Tuple <long, IList <ISkraprTask> > >();

            var jsonSerializerSettings = new JsonSerializerSettings();

            jsonSerializerSettings.Converters.Add(new TaskConverter());

            //For each selector, bind the data to the template, get the tasks for each node.
            int currentIndex = 0;

            foreach (var nodeId in selectorResponse.NodeIds)
            {
                if (!worker.DevTools.ChildNodes.ContainsKey(nodeId))
                {
                    worker.Logger.LogError("{taskName} Expected that a node with an id of {id} would be in the child node dictionary.", Name, nodeId);
                    continue;
                }

                var frameState = await worker.DevTools.GetCurrentFrameState();

                var node       = worker.DevTools.ChildNodes[nodeId];
                var attributes = node.GetAttributes();

                //Add some additional metadata that templates can use.
                attributes.Add("$index", currentIndex.ToString());
                attributes.Add("$oneBasedindex", (currentIndex + 1).ToString());
                attributes.Add("$zeroBasedindex", (currentIndex).ToString());
                attributes.Add("$title", frameState.Title);
                attributes.Add("$url", frameState.Url);

                var subTasksString = template(attributes);

                try
                {
                    var subTasks = JsonConvert.DeserializeObject <IList <ISkraprTask> >(subTasksString, jsonSerializerSettings);
                    nodeTasks.Add(new Tuple <long, IList <ISkraprTask> >(nodeId, subTasks));
                }
                catch (JsonSerializationException ex)
                {
                    worker.Logger.LogError("{taskName} Encountered an error when deserializing tasks for nodeId {nodeId}: {ex}", Name, nodeId, ex);
                    throw;
                }
                currentIndex++;
            }

            if (Shuffle)
            {
                nodeTasks.Shuffle();
            }

            ActionBlock <Tuple <long, IList <ISkraprTask> > > subTaskFlow = null;

            subTaskFlow = new ActionBlock <Tuple <long, IList <ISkraprTask> > >(async(nodeTask) => await ProcessNodeTask(nodeTask, worker, subTaskFlow), new ExecutionDataflowBlockOptions
            {
                CancellationToken      = worker.CancellationToken,
                EnsureOrdered          = true,
                MaxDegreeOfParallelism = 1
            });

            //Execute tasks for each node.
            foreach (var nodeTask in nodeTasks)
            {
                subTaskFlow.Post(nodeTask);
            }

            worker.Logger.LogDebug("{taskName} Processing {0} nodes in subflow", Name, subTaskFlow.InputCount);

            await subTaskFlow.Completion;

            worker.Logger.LogDebug("{taskName} Completed processing all nodes in subflow.", Name);
        }
Beispiel #4
0
        public override void Run(Context context)
        {
            var entitiesArgument = context.Argument("Entities", "");

            context.Verbose($"Parsing `-Entities` argument: \"{entitiesArgument}\"");

            // Selects all valid items out of those that are specified, discarding invalid items.
            var specifiedEntities = entitiesArgument
                                    .Split(',')
                                    .Select((s) => Enum.TryParse <CodeGenEntities>(s.Trim(), out var e) ? e as CodeGenEntities? : null)
                                    .Where((e) => e != null && e != CodeGenEntities.None)
                                    .Cast <CodeGenEntities>()
                                    .ToHashSet();

            if (specifiedEntities.Contains(CodeGenEntities.All))
            {
                specifiedEntities = Enum.GetValues(typeof(CodeGenEntities))
                                    .Cast <CodeGenEntities>()
                                    .Except(new[] { CodeGenEntities.None, CodeGenEntities.All })
                                    .ToHashSet();
            }

            if (specifiedEntities.Any())
            {
                context.Verbose($"Entities specified to be generated are: {String.Join(", ", specifiedEntities)}");

                var dictionary = new Dictionary <CodeGenEntities, SolutionProject>
                {
                    [CodeGenEntities.Enums]               = context.MainProject,
                    [CodeGenEntities.Classes]             = context.MainProject,
                    [CodeGenEntities.Methods]             = context.MainProject,
                    [CodeGenEntities.EnumConversionTests] = context.TestProject,
                };

                Outputs = dictionary
                          .Where((kvp) => specifiedEntities.Contains(kvp.Key))
                          .ToDictionary
                          (
                    (kvp) => kvp.Key,
                    (kvp) => kvp.Value.Path.GetDirectory().Combine(CodeGenHelpers.CodeGenFolderName).Combine(kvp.Key.ToString())
                          );

                // Handlebars configuration.

                Handlebars.Configuration.TextEncoder = new PlainTextEncoder();

                Handlebars.RegisterHelper("ifIsInt", (writer, options, handlebarsContext, arguments) =>
                {
                    if (arguments.Length == 1)
                    {
                        (arguments[0] is int?options.Template: options.Inverse)(writer, (object)handlebarsContext);
                    }
                    else
                    {
                        throw new ArgumentException("The ifIsInt helper takes exactly one argument.");
                    }
                });

                Handlebars.RegisterHelper("newline", (writer, handlebarsContext, arguments) =>
                {
                    writer.WriteLine("");
                });
            }
            else
            {
                var validValues = Enum.GetValues(typeof(CodeGenEntities))
                                  .Cast <CodeGenEntities>()
                                  .Except(new[] { CodeGenEntities.None });

                throw new Exception($"Please specify the entities to be generated via the `-Entities` argument. Valid values are {String.Join(", ", validValues)} (individually, or as a comma-delimited list)");
            }
        }
Beispiel #5
0
        public static void RegisterHelpers(CMSDataContext db)
        {
            Handlebars.RegisterHelper("BottomBorder", (writer, context, args) => { writer.Write(CssStyle.BottomBorder); });
            Handlebars.RegisterHelper("AlignTop", (writer, context, args) => { writer.Write(CssStyle.AlignTop); });
            Handlebars.RegisterHelper("AlignRight", (writer, context, args) => { writer.Write(CssStyle.AlignRight); });
            Handlebars.RegisterHelper("DataLabelStyle", (writer, context, args) => { writer.Write(CssStyle.DataLabelStyle); });
            Handlebars.RegisterHelper("LabelStyle", (writer, context, args) => { writer.Write(CssStyle.LabelStyle); });
            Handlebars.RegisterHelper("DataStyle", (writer, context, args) => { writer.Write(CssStyle.DataStyle); });

            Handlebars.RegisterHelper("ServerLink", (writer, context, args) => { writer.Write(db.ServerLink().TrimEnd('/')); });
            Handlebars.RegisterHelper("FmtZip", (writer, context, args) => { writer.Write(args[0].ToString().FmtZip()); });
            Handlebars.RegisterHelper("IfEqual", (writer, options, context, args) =>
            {
                if (IsEqual(args))
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("IfNotEqual", (writer, options, context, args) =>
            {
                if (!IsEqual(args))
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("IfCond", (writer, options, context, args) =>
            {
                var op = HttpUtility.HtmlDecode(args[1].ToString());
                bool b = false;
                switch (op)
                {
                case "==":
                    b = Compare(args) == 0;
                    break;

                case "!=":
                    b = Compare(args) != 0;
                    break;

                case "<":
                    b = Compare(args) < 0;
                    break;

                case ">":
                    b = Compare(args) > 0;
                    break;

                case ">=":
                    b = Compare(args) >= 0;
                    break;

                case "<=":
                    b = Compare(args) <= 0;
                    break;

                case "&&":
                    b = NumTrue(args) == 2;
                    break;

                case "||":
                    b = NumTrue(args) >= 1;
                    break;
                }
                if (b)
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("GetToken", (writer, context, args) =>
            {
                var s     = args[0].ToString();
                var n     = args[1].ToInt();
                var ntoks = args.Length > 2 ? args[2].ToInt() : 2;
                var sep   = args.Length > 3 ? args[3].ToString() : " ";
                var a     = s.SplitStr(sep, ntoks);
                writer.Write(a[n].trim());
            });

            // Format helper in form of:  {{Fmt value "fmt"}}
            // ex. {{Fmt Total "C"}}
            // fmt is required. Uses standard/custom dotnet format strings
            Handlebars.RegisterHelper("Fmt", (writer, context, args) =>
            {
                var fmt = $"{{0:{args[1]}}}";
                writer.Write(fmt, args[0]);
            });

            // FmtPhone helper in form of:  {{FmtPhone phone# "prefix"}}
            Handlebars.RegisterHelper("FmtPhone", (writer, context, args) => { writer.Write(args[0].ToString().FmtFone($"{args[1]}")); });

            Handlebars.RegisterHelper("ReplaceCode", (writer, context, args) =>
            {
                EmailReplacements r = context.Replacements as EmailReplacements
                                      ?? (context.Replacements = new EmailReplacements(db));
                var code = args[0].ToString();
                var p    = db.LoadPersonById(args[1].ToInt());
                int?oid  = null;
                if (args.Length == 3)
                {
                    oid = args[2].ToInt2();
                }
                writer.Write(r.RenderCode(code, p, oid));
            });
        }
        public override void Init()
        {
            _bucket = Config["bucket"];
            var theme = Config["theme"];

            _postsPerPage = int.Parse(Config["postsPerPage"]);

            if (string.IsNullOrEmpty(theme))
            {
                throw new ArgumentException("No theme was specified");
            }

            Handlebars.RegisterHelper("tz_created",
                                      (writer, context, parameters) =>
            {
                var date = (DateTime)context.Created;
                var tz   = Config["tz"];
                if (!string.IsNullOrEmpty(tz))
                {
                    var tzinfo = TimeZoneInfo.FindSystemTimeZoneById(tz);
                    if (tzinfo != null)
                    {
                        date = TimeZoneInfo.ConvertTimeFromUtc(date, tzinfo);
                    }
                }
                writer.WriteSafeString(date);
            });

            Handlebars.RegisterHelper("xml_created",
                                      (writer, context, parameters) =>
            {
                var date = (DateTime)context.Created;
                writer.WriteSafeString(date.ToString("o"));
            });

            Handlebars.RegisterHelper("encode",
                                      (writer, context, parameters) =>
            {
                if (parameters.Length != 1)
                {
                    throw new ArgumentException("escape helper must have exactly one argument");
                }

                writer.WriteSafeString(WebUtility.HtmlEncode((string)parameters[0]));
            });

            var themePath = Path.Combine(_basePath, theme);

            _assetPath = Path.Combine(themePath, "assets");

            var header = Path.Combine(themePath, "header.hbs");

            if (File.Exists(header))
            {
                using (var reader = new StreamReader(File.OpenRead(header)))
                {
                    var template = Handlebars.Compile(reader);
                    Handlebars.RegisterTemplate("header", template);
                }
            }

            var footer = Path.Combine(themePath, "footer.hbs");

            if (File.Exists(footer))
            {
                using (var reader = new StreamReader(File.OpenRead(footer)))
                {
                    var template = Handlebars.Compile(reader);
                    Handlebars.RegisterTemplate("footer", template);
                }
            }

            var index = Path.Combine(themePath, "index.hbs");

            if (!File.Exists(index))
            {
                throw new FileNotFoundException("Could not find index template", index);
            }
            _index = Handlebars.Compile(File.ReadAllText(index));

            var post = Path.Combine(themePath, "post.hbs");

            if (File.Exists(post))
            {
                _post = Handlebars.Compile(File.ReadAllText(post));
            }
            else
            {
                Log.Info("Post template not found, post pages will not be generated.");
            }

            var feed = Path.Combine(themePath, "feed.hbs");

            if (File.Exists(feed))
            {
                _feed = Handlebars.Compile(File.ReadAllText(feed));
            }
            else
            {
                Log.Info("Feed template not found, rss feed will not be generated.");
            }

            _client = new S3Util(Config["awsKey"], Config["awsSecret"], Config["awsRegion"])
            {
                Log = Log
            };
        }
        public static bool GenerateWebsite(Website website)
        {
            var assembly  = typeof(Generators.CoreApiGenerator).GetTypeInfo().Assembly;
            var resources = assembly.GetManifestResourceNames();

            using (ZipFile zipFile = ZipFile.Read(assembly.GetManifestResourceStream("site_generator_lib.Templates.dotnetcoreangular.WebApplication.zip")))
            {
                FileInfo fileInfo   = new FileInfo(assembly.Location);
                string   serverPath = Path.Combine(fileInfo.DirectoryName, $"output{DateTime.Now.ToString("_ddMMyyyy_HHmmss")}", "server");
                zipFile.ExtractAll(serverPath, ExtractExistingFileAction.OverwriteSilently);

                var fullModel = new { Entities = website.Entities };

                ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcoreangular.startup.t", $"{Path.Combine(serverPath, "WebApplication")}\\Startup.cs", fullModel);

                //Cient Generation
                ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcoreangular.client.nav-menu.t", $"{Path.Combine(serverPath, "WebApplication", "ClientApp", "src", "app", "nav-menu")}\\nav-menu.component.html", fullModel);
                ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcoreangular.client.module.t", $"{Path.Combine(serverPath, "WebApplication", "ClientApp", "src", "app")}\\app.module.ts", fullModel);


                foreach (var entityModel in website.Entities)
                {
                    var model = new { Name = entityModel.Name, Fields = entityModel.Fields.Select(field => new { Type = Shared.TypeConverter.PostgresToCsharp(field.Type), Name = field.Name }).ToArray() };

                    HandlebarsBlockHelper _propertyList = (TextWriter output, HelperOptions options, dynamic context, object[] arguments) => {
                        var enumList = arguments[0] as object[];
                        for (int i = 0; i < enumList.Length; i++)
                        {
                            string text = $"{((dynamic)(enumList[i])).Type} _{((dynamic)(enumList[i])).Name}";
                            if (i < enumList.Length - 1)
                            {
                                text += ",";
                            }
                            output.WriteLine(text);
                        }
                    };
                    Handlebars.RegisterHelper("prop_list", _propertyList);

                    HandlebarsBlockHelper _addModelList = (TextWriter output, HelperOptions options, dynamic context, object[] arguments) => {
                        var enumList = arguments[0] as object[];
                        for (int i = 0; i < enumList.Length; i++)
                        {
                            string text = $"addModel.{((dynamic)(enumList[i])).Name}";
                            if (i < enumList.Length - 1)
                            {
                                text += ",";
                            }
                            output.WriteLine(text);
                        }
                    };
                    Handlebars.RegisterHelper("addmodel_list", _addModelList);

                    // Build Database Layer
                    Directory.CreateDirectory(Path.Combine(serverPath, "WebApplication", "Database", entityModel.Name));
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcoreangular.dbentitycontext.t", $"{Path.Combine(serverPath, "WebApplication", "Database")}\\{entityModel.Name}DbContext.cs", model);

                    // Build Model Layer
                    Directory.CreateDirectory(Path.Combine(serverPath, "WebApplication", "Model", "Models", $"{entityModel.Name}Model"));
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcoreangular.model.t", $"{Path.Combine(serverPath, "WebApplication", "Model", "Models")}\\{entityModel.Name}.cs", model);

                    // Build Web Controller Layer
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcoreangular.controller.t", $"{Path.Combine(serverPath, "WebApplication", "Controllers")}\\{entityModel.Name}Controller.cs", model);


                    // Client //////////////////
                    Directory.CreateDirectory(Path.Combine(serverPath, "WebApplication", "ClientApp", "src", "app", entityModel.Name));
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcoreangular.client.component-ts.t", $"{Path.Combine(serverPath, "WebApplication", "ClientApp", "src", "app", entityModel.Name)}\\{entityModel.Name}.component.ts", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcoreangular.client.component-html.t", $"{Path.Combine(serverPath, "WebApplication", "ClientApp", "src", "app", entityModel.Name)}\\{entityModel.Name}.component.html", model);
                }
            }

            return(true);
        }
Beispiel #8
0
        /// <summary>
        /// Registers all of the required Handlebars helpers.
        /// </summary>
        public static void RegisterHelpers()
        {
            if (_areRegiestered)
            {
                return;
            }

            _areRegiestered = true;

            // Will check that the first argument equals at least one of the subsequent arguments.
            Handlebars.RegisterHelper("ifeq", (writer, context, parameters, args) =>
            {
                if (!CheckArgs("ifeq", writer, args))
                {
                    return;
                }

                if (IfEq(args))
                {
                    context.Template(writer, parameters);
                }
                else
                {
                    context.Inverse(writer, parameters);
                }
            });

            // Will check that the first argument does not equal any of the subsequent arguments.
            Handlebars.RegisterHelper("ifne", (writer, context, parameters, args) =>
            {
                if (!CheckArgs("ifne", writer, args))
                {
                    return;
                }

                if (IfEq(args))
                {
                    context.Inverse(writer, parameters);
                }
                else
                {
                    context.Template(writer, parameters);
                }
            });

            // Will check that all of the arguments have a non-<c>null</c> value.
            Handlebars.RegisterHelper("ifval", (writer, context, parameters, args) =>
            {
                if (!CheckArgs("ifval", writer, args))
                {
                    return;
                }

                foreach (var arg in args)
                {
                    if (arg == null)
                    {
                        context.Inverse(writer, parameters);
                        return;
                    }
                }

                context.Template(writer, parameters);
            });

            // Will check that all of the arguments have a <c>null</c> value.
            Handlebars.RegisterHelper("ifnull", (writer, context, parameters, args) =>
            {
                if (!CheckArgs("ifnull", writer, args))
                {
                    return;
                }

                foreach (var arg in args)
                {
                    if (arg != null)
                    {
                        context.Inverse(writer, parameters);
                        return;
                    }
                }

                context.Template(writer, parameters);
            });

            // Will check that all of the arguments have a <c>true</c> value where bool; otherwise, non-null.
            Handlebars.RegisterHelper("ifor", (writer, context, parameters, args) =>
            {
                if (!CheckArgs("ifor", writer, args))
                {
                    return;
                }

                foreach (var arg in args)
                {
                    if (arg is bool opt)
                    {
                        if (opt)
                        {
                            context.Template(writer, parameters);
                            return;
                        }
                    }
                    else if (arg != null)
                    {
                        context.Template(writer, parameters);
                        return;
                    }
                }

                context.Inverse(writer, parameters);
            });


            // Converts a value to lowercase.
#pragma warning disable CA1308 // Normalize strings to uppercase; this is an explicit and required call to lowercase.
            Handlebars.RegisterHelper("lower", (writer, context, parameters) => writer.WriteSafeString(parameters.FirstOrDefault()?.ToString()?.ToLowerInvariant() ?? ""));
#pragma warning restore CA1308

            // Converts a value to camelcase.
            Handlebars.RegisterHelper("camel", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToCamelCase(parameters.FirstOrDefault()?.ToString()) ?? ""));

            // Converts a value to pascalcase.
            Handlebars.RegisterHelper("pascal", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPascalCase(parameters.FirstOrDefault()?.ToString()) ?? ""));

            // Converts a value to the c# '<see cref="value"/>' comments equivalent.
            Handlebars.RegisterHelper("seecomments", (writer, context, parameters) => writer.WriteSafeString(Beef.CodeGen.CodeGenerator.ToSeeComments(parameters.FirstOrDefault()?.ToString())));

            // Adds a value to a value.
            Handlebars.RegisterHelper("add", (writer, context, parameters) =>
            {
                int sum = 0;
                foreach (var p in parameters)
                {
                    if (p is int pi)
                    {
                        sum += pi;
                    }
                    else if (p is string ps)
                    {
                        sum += int.Parse(ps, NumberStyles.Integer, CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        writer.WriteSafeString("!!! add with invalid integer !!!");
                    }
                }

                writer.WriteSafeString(sum);
            });
        }
        public void Generate()
        {
            const string          setFileName     = "set.hbs";
            const string          contextFileName = "context.hbs";
            Func <object, string> templateSet;
            Func <object, string> templateContext;
            var fksPresetList                      = new List <FkPresetDefinition>();
            var tablesColumnsSettingsList          = new List <ObjectColumnsSettingModel>();
            var viewsColumnsSettingsList           = new List <ObjectColumnsSettingModel>();
            var fkPropertyDisplayNamesSettingsList = new List <FkPropertyDisplayNameDefinition>();
            var entityPluralizeNameSettingsList    = new List <EntityPluralizeNameDefinition>();

            Handlebars.RegisterHelper("TableContainsAllColumns", HBSHelper.TableContainsAllColumns);

            try
            {
                var setTemplate = File.ReadAllText(Path.Combine(_options.TemplatesDirectory, setFileName));
                templateSet = Handlebars.Compile(setTemplate);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error compiling Handlebars template {setFileName}: {ex.Message}");
                return;
            }
            try
            {
                var tableContext = File.ReadAllText(Path.Combine(_options.TemplatesDirectory, contextFileName));
                templateContext = Handlebars.Compile(tableContext);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error compiling Handlebars template {contextFileName}: {ex.Message}");
                return;
            }
            if (!string.IsNullOrEmpty(_options.CustomSettingsJsonPath))
            {
                try
                {
                    var customSettingsJsonString = Path.Combine(_options.CustomSettingsJsonPath);
                    var customSettingsJsonObject = JObject.Parse(File.ReadAllText(customSettingsJsonString));
                    var foreignKeys                    = (JObject)customSettingsJsonObject.GetValue("ForeignKeys");
                    var tablesColumnsSettings          = (JObject)customSettingsJsonObject.GetValue("TablesColumns");
                    var viewsColumnsSettings           = (JObject)customSettingsJsonObject.GetValue("ViewsColumns");
                    var foreignKeyPropertyDisplayNames = (JArray)customSettingsJsonObject.GetValue("FKPropertyNames");
                    var entityPluralizeNameSettings    = (JArray)customSettingsJsonObject.GetValue("EntityPluralizedNames");

                    fksPresetList                      = GetForeignKeysPresetList(foreignKeys);
                    tablesColumnsSettingsList          = GetObjectsColumnsSettingsList(tablesColumnsSettings);
                    viewsColumnsSettingsList           = GetObjectsColumnsSettingsList(viewsColumnsSettings);
                    fkPropertyDisplayNamesSettingsList = GetFkPropertyDisplayNamesSettingsList(foreignKeyPropertyDisplayNames);
                    entityPluralizeNameSettingsList    = GetEntityPluralizedNameSettingsList(entityPluralizeNameSettings);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error loading CustomSettings json file: {ex.Message}");
                    return;
                }
            }

            WriteLine("Templates are ready");

            var fkNamesSkipList = fksPresetList.Where(x => x.FkPropertyNames == null).Select(x => x.ForeignKeyName).ToList();


            using (var connection = new SqlConnection(_options.ConnectionString))
            {
                connection.Open();
                WriteLine("Connected to the database");

                var fkDefinitionsSource = connection.ReadObjects <FkDefinitionSource>(SchemaSql.ForeignKeysSql);
                var fkDefinitions       =
                    (from s in fkDefinitionsSource.Where(x => !fkNamesSkipList.Contains(x.FkName))
                     group s by new { s.PkSchema, s.FkSchema, s.FkTable, s.PkTable, s.FkName, s.PkName, s.MatchOption, s.UpdateRule, s.DeleteRule }
                     into sGroup
                     select new FkDefinition
                {
                    PkSchema = sGroup.Key.PkSchema,
                    FkSchema = sGroup.Key.FkSchema,
                    PkTable = sGroup.Key.PkTable,
                    FkTable = sGroup.Key.FkTable,
                    PkName = sGroup.Key.PkName,
                    FkName = sGroup.Key.FkName,
                    MatchOption = sGroup.Key.MatchOption,
                    DeleteRule = sGroup.Key.DeleteRule,
                    UpdateRule = sGroup.Key.UpdateRule,
                    PkColumns = sGroup.OrderBy(x => x.PkOrdinalPosition).Select(x => x.PkColumn).ToList(),
                    PkColumnDisplayNames = sGroup.OrderBy(x => x.PkOrdinalPosition).Select(x => PropertyHelper.GetColumnNameToDisplay(x.PkColumn, sGroup.Key.PkTable, tablesColumnsSettingsList)).ToList(),
                    FkColumns = sGroup.OrderBy(x => x.FkOrdinalPosition).Select(x => x.FkColumn).ToList(),
                    FkColumnDisplayNames = sGroup.OrderBy(x => x.FkOrdinalPosition).Select(x => PropertyHelper.GetColumnNameToDisplay(x.FkColumn, sGroup.Key.FkTable, tablesColumnsSettingsList)).ToList()
                }).ToList();

                WriteLine("Foreign keys information received");

                var keyColumns = connection.ReadObjects <KeyColumnDefinition>(SchemaSql.KeyColumnsSql);
                WriteLine("Primary keys information received");

                var tables = connection.ReadObjects <EntityDefinition>(SchemaSql.TablesSql);
                WriteLine("Tables information received");

                var views = connection.ReadObjects <EntityDefinition>(SchemaSql.ViewsSql);
                WriteLine("Views information received");

                var tablesColumns = connection.ReadObjects <ColumnDefinition>(string.Format(SchemaSql.TableColumnsSql, _options.ExtendedPropertyTypeName));
                WriteLine("Tables columns information received");

                var viewsColumns = connection.ReadObjects <ColumnDefinition>(string.Format(SchemaSql.ViewColumnsSql, _options.ExtendedPropertyTypeName));
                WriteLine("Views columns information received");

                var spDefinitions = new List <StoredObjectDefinition>();
                if (_options.GenerateStoredProcedures)
                {
                    spDefinitions = GetStoredObjectsDefinition(connection, SchemaSql.StoredProcedureParametersSql, false, _options.IgnoreStoredProcedure);
                    WriteLine("Stored procedures parameters information received");

                    foreach (var sp in spDefinitions)
                    {
                        WriteLine($"Reading schema for {sp.Schema}.{sp.Name}");
                        var spSetDefinition = string.Format(SchemaSql.StoredProcedureSetSql, sp.Schema, sp.Name);
                        var columns         = connection.ReadObjects <StoredObjectSetColumn>(spSetDefinition);
                        sp.Columns = columns.Where(x => !string.IsNullOrEmpty(x.Name) && ColumnValidRegex.IsMatch(x.Name)).ToList();
                    }
                }

                var tvfDefinitions = new List <StoredObjectDefinition>();

                if (_options.GenerateTableValuedFunctions)
                {
                    tvfDefinitions = GetStoredObjectsDefinition(connection, SchemaSql.TableValueFunctionParametersSql, true, _options.IgnoreTableValuedFunctions);
                    WriteLine("Table valued functions parameters information received");

                    var tvfColumns = connection.ReadObjects <TableValuedColumn>(SchemaSql.TableValueFunctionColumnsSql);
                    WriteLine("Table valued functions parameters information received");
                    foreach (var tvf in tvfDefinitions)
                    {
                        tvf.Columns = tvfColumns
                                      .Where(c => c.Schema == tvf.Schema && c.FunctionName == tvf.Name)
                                      .Cast <StoredObjectSetColumn>().ToList();
                    }
                }

                var defaultSchemaName = connection.ReadObjects <SchemaDefinition>(SchemaSql.DefaultSchemaSql).First().SchemaName;

                var entityViewModels = new List <EntityViewModel>();

                ScaffoldEntities(entityViewModels, tables, tablesColumns, keyColumns, fkDefinitions, _options.IgnoreTables, _options.AllowedTables, tablesColumnsSettingsList, entityPluralizeNameSettingsList, defaultSchemaName);

                ScaffoldEntities(entityViewModels, views, viewsColumns, null, null, _options.IgnoreViews, null, viewsColumnsSettingsList, entityPluralizeNameSettingsList, defaultSchemaName);

                var pKeys =
                    (from pk in keyColumns
                     group pk by new { pk.TableSchema, pk.TableName, pk.KeyName }
                     into pkGroup
                     select new
                {
                    pkGroup.Key.TableSchema,
                    pkGroup.Key.TableName,
                    Columns = pkGroup.OrderBy(x => x.KeyOrder).Select(x => x.ColumnName).ToList()
                }).ToDictionary(x => $"{x.TableSchema}.{x.TableName}", x => x.Columns);

                foreach (var foreignKey in fkDefinitions)
                {
                    var originTable = entityViewModels.SingleOrDefault(x =>
                                                                       x.SchemaName == foreignKey.PkSchema && x.EntityName == foreignKey.PkTable);

                    var foreignTable = entityViewModels.SingleOrDefault(x =>
                                                                        x.SchemaName == foreignKey.FkSchema && x.EntityName == foreignKey.FkTable);

                    var isOneToOne = false;
                    //Check one-2-one in case matched columns names and theirs orders
                    var originTableFullName  = $"{foreignKey.PkSchema}.{foreignKey.PkTable}";
                    var foreignTableFullName = $"{foreignKey.FkSchema}.{foreignKey.FkTable}";
                    if (pKeys.ContainsKey(originTableFullName) && pKeys.ContainsKey(foreignTableFullName))
                    {
                        var pKeyOrigin  = pKeys[originTableFullName];
                        var pKeyForeign = pKeys[foreignTableFullName];
                        if (foreignKey.PkColumns.Count == foreignKey.FkColumns.Count && foreignKey.PkColumns.Count == pKeyOrigin.Count && foreignKey.PkColumns.Count == pKeyForeign.Count)
                        {
                            isOneToOne = true;
                            for (var i = 0; i < pKeyOrigin.Count; i++)
                            {
                                if (pKeyOrigin[i] == foreignKey.PkColumns[i] && pKeyForeign[i] == foreignKey.FkColumns[i])
                                {
                                    continue;
                                }
                                isOneToOne = false;
                                break;
                            }
                        }
                    }

                    if (originTable != null && foreignTable != null)
                    {
                        var propertyName        = string.Empty;
                        var inversePropertyName = string.Empty;

                        var fkPreset    = fksPresetList.FirstOrDefault(x => x.ForeignKeyName == foreignKey.FkName && x.FkPropertyNames != null);
                        var hasFKPreset = fkPreset != null && fkPreset.FkPropertyNames != null;

                        if (hasFKPreset)
                        {
                            propertyName        = fkPreset.FkPropertyNames.PropertyName;
                            inversePropertyName = fkPreset.FkPropertyNames.InversePropertyName;
                        }

                        if (string.IsNullOrEmpty(propertyName))
                        {
                            foreach (var fkColumn in foreignKey.FkColumns)
                            {
                                propertyName = RemoveIdRegex.Replace(fkColumn, m => m.Groups["content"].Value).TrimEnd('_');
                            }

                            if (_options.ForeignPropertyRegex != null)
                            {
                                propertyName = Regex.Match(foreignKey.FkName, _options.ForeignPropertyRegex, RegexOptions.Singleline).Groups["PropertyName"].Value;
                                propertyName = propertyName.Replace("_", string.Empty);
                                if (propertyName.EndsWith("Id") || propertyName.EndsWith("ID"))
                                {
                                    propertyName = propertyName.Substring(0, propertyName.Length - 2);
                                }
                            }
                        }

                        if (fkPropertyDisplayNamesSettingsList != null && fkPropertyDisplayNamesSettingsList.Count > 0 && !hasFKPreset)
                        {
                            var fkPropertyDisplayNameSetting = fkPropertyDisplayNamesSettingsList.Find(x => x.Name == propertyName);
                            if (fkPropertyDisplayNameSetting != null && !string.IsNullOrEmpty(fkPropertyDisplayNameSetting.DisplayName))
                            {
                                propertyName        = fkPropertyDisplayNameSetting.DisplayName;
                                inversePropertyName = propertyName.ReplaceFirstOccurrance(originTable.EntityName, foreignTable.EntityName, true);
                            }
                        }

                        propertyName = PropertyHelper.GetColumnNameToDisplay(propertyName, originTable.EntityName, tablesColumnsSettingsList);

                        if (string.IsNullOrEmpty(inversePropertyName))
                        {
                            inversePropertyName = propertyName.ReplaceFirstOccurrance(originTable.EntityName, foreignTable.EntityName);
                        }

                        if (!isOneToOne)
                        {
                            if (!hasFKPreset || !string.Equals(fkPreset.FkPropertyNames.InversePropertyName, inversePropertyName, StringComparison.OrdinalIgnoreCase))
                            {
                                inversePropertyName = StringHelper.Pluralize(inversePropertyName);
                            }
                        }

                        if (originTable == foreignTable)
                        {
                            inversePropertyName = "Inverse" + propertyName;
                        }

                        var keyCount        = originTable.InverseKeys.Count(x => x.PropertyName == inversePropertyName);
                        var propName        = keyCount == 0 ? propertyName : $"{propertyName}_{keyCount}";
                        var inversePropName = keyCount == 0 ? inversePropertyName : $"{inversePropertyName}_{keyCount}";

                        var foreignKeyViewModel = foreignKey.CloneCopy <FkDefinition, ForeignKeyViewModel>();
                        foreignKeyViewModel.IsOptional          = foreignTable.Columns.Where(c => foreignKey.FkColumns.Contains(c.Name)).All(c => c.IsNullable);
                        foreignKeyViewModel.PropertyName        = propName;
                        foreignKeyViewModel.InversePropertyName = inversePropName;
                        foreignKeyViewModel.InverseEntityName   = originTable.EntityName;
                        foreignKeyViewModel.IsOneToOne          = isOneToOne;
                        foreignTable.ForeignKeys.Add(foreignKeyViewModel);

                        var inverseKeyViewModel = foreignKey.CloneCopy <FkDefinition, ForeignKeyViewModel>();
                        inverseKeyViewModel.PropertyName        = inversePropName;
                        inverseKeyViewModel.InversePropertyName = propName;
                        foreignKeyViewModel.InverseEntityName   = foreignTable.EntityName;
                        inverseKeyViewModel.IsOneToOne          = isOneToOne;
                        originTable.InverseKeys.Add(inverseKeyViewModel);
                    }
                }

                if (_options.AllowManyToMany)
                {
                    foreach (var model in entityViewModels)
                    {
                        var isManyToMany = model.Columns.Count == 2 && model.HasForeignKeys && model.Keys.Count == 2 && model.ForeignKeys.Count == 2;
                        if (isManyToMany && !_options.IgnoreObjectsForManyToMany.Contains($"[{model.SchemaName}].[{model.EntityName}]"))
                        {
                            var leftFk  = model.ForeignKeys.Single(f => f.FkColumns[0] == model.ColumnsEfPropertyOrder.First().Name);
                            var rightFk = model.ForeignKeys.Single(f => f.FkColumns[0] == model.ColumnsEfPropertyOrder.Last().Name);

                            var leftTable  = entityViewModels.SingleOrDefault(x => x.SchemaName == leftFk.PkSchema && x.EntityName == leftFk.PkTable);
                            var rightTable = entityViewModels.SingleOrDefault(x => x.SchemaName == rightFk.PkSchema && x.EntityName == rightFk.PkTable);

                            if (leftTable != null && rightTable != null)
                            {
                                model.IsManyToMany = true;

                                model.ManyToManyLeftTable  = leftTable.EntityName;
                                model.ManyToManyRightTable = rightTable.EntityName;

                                var leftTableInverseKey = leftTable.InverseKeys.SingleOrDefault(k => k.FkName == leftFk.FkName);
                                leftTableInverseKey.FkTable      = model.ManyToManyRightTable;
                                leftTableInverseKey.PropertyName = fksPresetList.Find(f => f.ForeignKeyName == leftTableInverseKey.FkName)?.FkPropertyNames.PropertyName ?? StringHelper.Pluralize(leftTableInverseKey.FkTable);
                                leftTableInverseKey.IsManyToMany = true;

                                var rightTableInverseKey = rightTable.InverseKeys.SingleOrDefault(k => k.FkName == rightFk.FkName);
                                rightTableInverseKey.FkTable      = model.ManyToManyLeftTable;
                                rightTableInverseKey.PropertyName = fksPresetList.Find(f => f.ForeignKeyName == rightTableInverseKey.FkName)?.FkPropertyNames.PropertyName ?? StringHelper.Pluralize(rightTableInverseKey.FkTable);
                                rightTableInverseKey.IsManyToMany = true;

                                model.ManyToManyLeftInversePropertyName  = leftTableInverseKey.PropertyName;
                                model.ManyToManyRightInversePropertyName = rightTableInverseKey.PropertyName;
                            }
                        }
                    }
                }

                var fileNames       = new List <string>();
                var modelsDirectory = Path.Combine(_options.Directory, _options.ModelsPath);
                Directory.CreateDirectory(modelsDirectory);

                foreach (var tableViewModel in entityViewModels.Where(e => !e.IsManyToMany))
                {
                    var setResult         = templateSet(tableViewModel);
                    var setResultFileName = Path.Combine(modelsDirectory, tableViewModel.EntityName + ".cs");
                    File.WriteAllText(setResultFileName, setResult);

                    fileNames.Add(setResultFileName);
                }

                if (_options.GenerateStoredProcedures)
                {
                    WriteObjectSets(spDefinitions, modelsDirectory, templateSet, fileNames, tablesColumnsSettingsList, entityPluralizeNameSettingsList);
                }

                if (_options.GenerateTableValuedFunctions)
                {
                    WriteObjectSets(tvfDefinitions, modelsDirectory, templateSet, fileNames, tablesColumnsSettingsList, entityPluralizeNameSettingsList);
                }

                var contextViewModel = new ContextViewModel
                {
                    ContextName          = _options.ContextName,
                    Namespace            = _options.Namespace,
                    Entities             = entityViewModels,
                    StoredProcedures     = spDefinitions,
                    TableValuedFunctions = tvfDefinitions
                };
                var contextResult         = templateContext(contextViewModel);
                var contextResultFileName = Path.Combine(modelsDirectory, contextViewModel.ContextName + ".cs");
                File.WriteAllText(contextResultFileName, contextResult);

                fileNames.Add(contextResultFileName);

                if (_options.CleanUp)
                {
                    var directoryFiles = Directory.GetFiles(modelsDirectory, "*.cs");

                    var filesToCleanUp = directoryFiles.Except(fileNames);

                    foreach (var s in filesToCleanUp)
                    {
                        File.Delete(s);
                    }
                }
            }
        }
        public static void RegisterHelpers()
        {
            Handlebars.RegisterHelper("POCOModelPropertyAttributesV0", (writer, context, parameters) => {
                var PROC_NAME  = "Handlebars.RegisterHelper('POCOModelPropertyAttributesV0')";
                var entityName = "";
                try
                {
                    var prefix            = parameters.AsString(0);
                    var property          = (IProperty)context.Value;
                    var entity            = property.Parent;
                    entityName            = entity.Schema + "." + entity.Name;
                    var decimalAttribute  = "";
                    var keyAttribute      = "";
                    var fkAttributes      = "";
                    var identityAttribute = "";

                    if ((entityName.Contains("dbo.AreaTargetFormations")) && (property.Name.Contains("AreaTypeId")))
                    {
                        entityName = (entityName + " ").Trim();
                    }
                    if (entityName.Contains("dbo.Scenarios")) //&& (property.Name.Contains("")))
                    {
                        entityName = (entityName + " ").Trim();
                    }
                    if (property.Type == "decimal")
                    {
                        decimalAttribute = "[DecimalPrecision(" + property.Precision + ", " + property.Scale + ")]";
                    }
                    if ((!property.IsIdentity) && (entity.Type == "TABLE"))
                    {
                        identityAttribute = ", DatabaseGenerated(DatabaseGeneratedOption.None)";
                    }
                    if (property.IsKey)
                    {
                        if (entity.PrimaryKeys.Count > 1)
                        {
                            keyAttribute = @"[Key, Column(Order=" + property.KeyOrder + ")" + identityAttribute + "]";
                        }
                        else
                        {
                            keyAttribute = "[Key" + identityAttribute + "]";
                        }
                    }
                    if (property.RelatedTo.Count > 0)
                    {
                        foreach (var FKKeyValue in property.RelatedTo.GroupByFKName())
                        {
                            if (FKKeyValue.Key.Equals("FK_FracFleets_FracFleets"))
                            {
                                entityName = (entityName + " ").Trim();
                            }
                            var relGroupSummary = entity.RelationshipGroups[FKKeyValue.Key].AsSummary();
                            int SameTableCount  = 0;
                            foreach (var rg in entity.RelationshipGroups.Values)
                            {
                                if (rg.AsSummary().ToTableName.Equals(relGroupSummary.ToTableName))
                                {
                                    SameTableCount++;
                                }
                            }

                            var FieldName = entity.GenerateObjectName(FKKeyValue.Key, ObjectNameGeneratedFrom.JoinFromColumnName);
                            //We only will write the ForeignKey if we compound FKs or multiple columns with references to the same table
                            //if ((SameTableCount>1) || (relGroupSummary.ToColumnName.Count>1))
                            if (((relGroupSummary.ToColumnName.Count > 1) && (!relGroupSummary.FromTableName.Equals(relGroupSummary.ToTableName))) || (relGroupSummary.MultiplicityType == RelationshipMultiplicityType.OneToOne) || (relGroupSummary.MultiplicityType == RelationshipMultiplicityType.ZeroOrOneToOne))
                            {
                                var ColumnOrder = "";
                                if (relGroupSummary.ToColumnName.Count > 1)
                                {
                                    ColumnOrder   = string.Format(", Column(Order = {0})", relGroupSummary.ToColumnProperties.Where(p => p.Name.Equals(property.Name)).Select(p => p.KeyOrder).FirstOrDefault());
                                    fkAttributes += string.Format("[ForeignKey(\"{0}\"){1}]", (FieldName.Replace(" ", "") + Internal.AppSettings.Instance.Configuration.Database.InverseFKTargetNameCollisionSuffix).Trim(), ColumnOrder);
                                }
                            }
                            if (fkAttributes.Length > 0)
                            {
                                break;
                            }
                        }
                    }

                    if (keyAttribute.Length > 0)
                    {
                        writer.WriteSafeString(keyAttribute);
                    }
                    if (fkAttributes.Length > 0)
                    {
                        writer.WriteSafeString(fkAttributes);
                    }
                    if ((property.Name == "SysStartTime") || (property.Name == "SysEndTime"))
                    {
                        writer.WriteSafeString("[DatabaseGenerated(DatabaseGeneratedOption.Computed)]\n");
                    }
                    if (decimalAttribute.Length > 0)
                    {
                        writer.WriteSafeString(decimalAttribute);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });

            Handlebars.RegisterHelper("POCOModelFKConstructorInitV0", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('POCOModelFKConstructorInitV0')";
                try
                {
                    var prefix = parameters.AsString(0);
                    var entity = (IEntity)context.Value;
                    var PreviousOneToManyFields = new List <string>();

                    var FKToUse = entity.Relationships.Fetch(RelationshipMultiplicityType.ZeroOrOneToMany).Select(s => s.Name).ToList();
                    foreach (var fkNameKV in entity.RelationshipGroups)
                    {
                        var fkName = fkNameKV.Key;
                        if (FKToUse.Contains(fkName))
                        {
                            var relationship    = fkNameKV.Value;
                            var relGroupSummary = relationship.AsSummary();
                            string ToTableName  = entity.Parent.Entities[relGroupSummary.ToTableName].Alias.ToSingular();
                            //string ToObjectFieldName = relGroupSummary.AsObjectPropertyName();
                            string ToObjectFieldName = string.Format("{0}_{1}", relGroupSummary.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", ""), relGroupSummary.ToColumnName.First());

                            writer.WriteSafeString(string.Format(
                                                       "\n{0}this.{1} = new HashSet<{2}>(); //{3} 0|1->*"
                                                       , prefix, ToObjectFieldName, ToTableName, relGroupSummary.Name));
                            PreviousOneToManyFields.Add(relGroupSummary.ToTableName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });

            Handlebars.RegisterHelper("POCOModelFKPropertiesV0", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('POCOModelFKPropertiesV0')";
                try
                {
                    var prefix = parameters.AsString(0);
                    var entity = (IEntity)context.Value;
                    List <string> PreviousOneToManyFields = new List <string>();
                    PreviousOneToManyFields.Clear();

                    var FKToUse = entity.Relationships.Fetch(RelationshipMultiplicityType.ZeroOrOneToMany).Select(s => s.Name).ToList();
                    foreach (var fkNameKV in entity.RelationshipGroups)
                    {
                        var fkName = fkNameKV.Key;
                        if (fkName.Equals("FK_Wells_PIGAreaId_DELETE"))
                        {
                            fkName = (fkName + " ").Trim();
                        }
                        if (FKToUse.Contains(fkName))
                        {
                            var relationship    = fkNameKV.Value;
                            var relGroupSummary = relationship.AsSummary();
                            string ToTableName  = entity.Parent.Entities[relGroupSummary.ToTableName].Alias.ToSingular();
                            //string ToObjectFieldName = relGroupSummary.AsObjectPropertyName();
                            string ToObjectFieldName = string.Format("{0}_{1}", relGroupSummary.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", ""), relGroupSummary.ToColumnName.First());

                            //Check and see we have multiple declarations of the same table,  if we do, we will need an inverse
                            // property annotation figure out how to property find the correct object property target
                            var inversePropertyAttribute = "";
                            int SameTableCount           = 0;
                            foreach (var rg in entity.RelationshipGroups.Values)
                            {
                                if (rg.AsSummary().ToTableName.Equals(relGroupSummary.ToTableName))
                                {
                                    SameTableCount++;
                                }
                            }
                            if (SameTableCount > 1)
                            {
                                var toGroupRelationshipList = entity.Parent[relGroupSummary.ToTableName].Relationships.GroupByFKName();
                                if (!toGroupRelationshipList.ContainsKey(fkName))
                                {
                                    throw new Exception(string.Format("The inverse of FK {0} ({1}->{2})", fkName, relGroupSummary.FromTableName, relGroupSummary.ToTableName));
                                }
                                var inverseOfThisFK              = toGroupRelationshipList[fkName];
                                var relGroupSummaryInverse       = inverseOfThisFK.AsSummary();
                                var InversePropertyNamePotential = relGroupSummaryInverse.EndAsObjectPropertyName();
                                if (InversePropertyNamePotential.Length > 0)
                                {
                                    inversePropertyAttribute = string.Format("[InverseProperty(\"{0}\")]", InversePropertyNamePotential);
                                }
                            }

                            writer.WriteSafeString(string.Format("\n\n{0}//<summary>{1} {2}</summary>", prefix, relGroupSummary.Name, relGroupSummary.MultiplicityType.AsString()));
                            writer.WriteSafeString(string.Format("\n{0}[System.Diagnostics.CodeAnalysis.SuppressMessage(\"Microsoft.Usage\", \"CA2227: CollectionPropertiesShouldBeReadOnly\")]", prefix));
                            if (inversePropertyAttribute.Length > 0)
                            {
                                writer.WriteSafeString(string.Format("\n{0}{1}", prefix, inversePropertyAttribute));
                            }
                            writer.WriteSafeString(string.Format("\n{0}public virtual ICollection<{1}> {2} {{ get; set; }}", prefix, ToTableName, ToObjectFieldName));

                            PreviousOneToManyFields.Add(relGroupSummary.ToTableName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });


            Handlebars.RegisterHelper("POCOModelFKManyToZeroToOneV0", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('POCOModelFKManyToZeroToOneV0')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (IEntity)context.Value;
                    var entityName = entity.Schema + "." + entity.Name;

                    List <string> PreviousManyToOneFields = new List <string>();

                    var FKToUse = entity.Relationships.Fetch(RelationshipMultiplicityType.ManyToZeroOrOne).Select(s => s.Name).ToList();
                    foreach (var fkNameKV in entity.RelationshipGroups)
                    {
                        var fkName = fkNameKV.Key;
                        if ((fkName.Equals("FK_AreaTargetFormations_AreaTypes")) || (fkName.Equals("FK_AreaTargetFormations_TargetFormations1")))
                        {
                            fkName = fkName + "";
                        }
                        if (FKToUse.Contains(fkName))
                        {
                            var relationship    = fkNameKV.Value;
                            var relGroupSummary = relationship.AsSummary();

                            int SameTableCount = 0;
                            foreach (var rg in entity.RelationshipGroups.Values)
                            {
                                if (rg.AsSummary().ToTableName.Equals(relGroupSummary.ToTableName))
                                {
                                    SameTableCount++;
                                }
                            }
                            string ToTableNameSingular = relGroupSummary.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", "").ToSingular();
                            string _FieldName          = ((PreviousManyToOneFields.Contains(ToTableNameSingular) ||
                                                           (entity.Properties.ContainsKey(ToTableNameSingular)) ||
                                                           (entityName == relGroupSummary.ToTableName) ||
                                                           (SameTableCount > 1))
                                                    ? string.Join(", ", relGroupSummary.FromColumnName) : ToTableNameSingular);

                            string FieldName = entity.GenerateObjectName(fkName, ObjectNameGeneratedFrom.JoinFromColumnName);

                            writer.WriteSafeString(string.Format("\n{0}/// <summary>{1}  *->0|1</summary>", prefix, fkName));
                            writer.WriteSafeString(string.Format("\n{0}[ForeignKey(\"{1}\")]", prefix, relGroupSummary.FromFieldName));
                            writer.WriteSafeString(string.Format("\n{0}public virtual {1} {2} {{ get; set; }}", prefix, relGroupSummary.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", "").ToSingular(), FieldName));
                            PreviousManyToOneFields.Add(FieldName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });

            Handlebars.RegisterHelper("POCOModelFKOneToOneV0", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('POCOModelFKOneToOneV0')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (IEntity)context.Value;
                    var entityName = entity.Schema + "." + entity.Name;

                    var PreviousOneToOneFields = new List <string>();

                    var FKToUse = entity.Relationships.Fetch(RelationshipMultiplicityType.OneToOne).Select(s => s.Name).ToList();
                    foreach (var fkNameKV in entity.RelationshipGroups)
                    {
                        var fkName = fkNameKV.Key;
                        if ((fkName.Equals("FK_AreaTargetFormations_AreaTypes")) || (fkName.Equals("FK_Wells_WellStickSurveys")))
                        {
                            fkName += fkName + "";
                        }
                        if (FKToUse.Contains(fkName))
                        {
                            var relationship    = fkNameKV.Value;
                            var relGroupSummary = relationship.AsSummary();

                            int SameTableCount = 0;
                            foreach (var rg in entity.RelationshipGroups.Values)
                            {
                                if (rg.AsSummary().ToTableName.Equals(relGroupSummary.ToTableName))
                                {
                                    SameTableCount++;
                                }
                            }
                            string ToTableNameSingular = relGroupSummary.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", "").ToSingular();
                            string FieldName           = ((PreviousOneToOneFields.Contains(ToTableNameSingular) ||
                                                           (entity.Properties.ContainsKey(ToTableNameSingular)) ||
                                                           (entityName == relGroupSummary.ToTableName) ||
                                                           (SameTableCount > 1))
                                                    ?  string.Format(",", relGroupSummary.FromColumnName) : ToTableNameSingular);
                            writer.WriteSafeString(string.Format("\n{0}/// <summary>{1} 1->1</summary>", prefix, relGroupSummary.Name));
                            writer.WriteSafeString(string.Format("\n{0}public virtual {1} {2} {{ get; set; }}", prefix, relGroupSummary.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", "").ToSingular(), FieldName));
                            PreviousOneToOneFields.Add(FieldName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });


            Handlebars.RegisterHelper("POCOModelFKZeroOrOneToOneV0", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('POCOModelFKZeroOrOneToOneV0')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (IEntity)context.Value;
                    var entityName = entity.Schema + "." + entity.Name;


                    if (entityName.Equals("dbo.Areas"))
                    {
                        entityName = (entityName + " ").Trim();
                    }
                    var PreviousOneToOneFields = new List <string>();
                    //Search for all foreign keys that contain a Zero or one to one...
                    var FKToUse = entity.Relationships.Fetch(RelationshipMultiplicityType.ZeroOrOneToOne).Select(s => s.Name).ToList();
                    foreach (var rg in entity.RelationshipGroups.Values)
                    {
                        if (rg.AsSummary().ToColumnName.Count > 1)
                        {
                            FKToUse.Add(rg.AsSummary().Name);
                        }
                    }

                    foreach (var fkNameKV in entity.RelationshipGroups)
                    {
                        var fkName = fkNameKV.Key;
                        if (fkName.Contains("FK_AreaTargetFormations_AreaTypes"))
                        {
                            entityName = (entityName + " ").Trim();
                        }
                        if (FKToUse.Contains(fkName))
                        {
                            var relationship   = fkNameKV.Value.AsSummary();
                            int SameTableCount = 0;
                            foreach (var rg in entity.RelationshipGroups.Values)
                            {
                                if (rg.AsSummary().ToTableName.Equals(relationship.ToTableName))
                                {
                                    SameTableCount++;
                                }
                            }
                            string ToTableNameSingular = relationship.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", "").ToSingular();
                            string _FieldName          = ((PreviousOneToOneFields.Contains(ToTableNameSingular) ||
                                                           (entity.Properties.ContainsKey(ToTableNameSingular)) ||
                                                           (entityName == relationship.ToTableName) ||
                                                           (SameTableCount > 1))
                                                    ? relationship.ToUniqueColumnName() : ToTableNameSingular);
                            string FieldName  = entity.GenerateObjectName(fkName, ObjectNameGeneratedFrom.ToUniqueColumnName);
                            string ForeignKey = ((entityName == relationship.ToTableName) ? relationship.FromFieldName[relationship.FromFieldName.Count - 1] : string.Join(", ", relationship.FromFieldName));

                            writer.WriteSafeString(string.Format("\n{0}/// <summary>{1} {2}</summary>", prefix, relationship.Name, relationship.MultiplicityType.AsString()));

                            /* New work based on using EF docs to figure out fk attributes - https://www.entityframeworktutorial.net/code-first/foreignkey-dataannotations-attribute-in-code-first.aspx
                             * Specifically - [ForeignKey] on the navigation property in the dependent entity */
                            var fkList           = new List <string>();
                            var WriteFKAttribute = false;
                            var IsRequired       = false;
                            var AttributeText    = new StringBuilder();
                            foreach (Relationship fk in fkNameKV.Value)
                            {
                                //If this is a one to one relationship,  then we will apply the ForiegnKey Attribute to Primary Key of this object
                                if ((fk.MultiplicityType == RelationshipMultiplicityType.ZeroOrOneToOne) || (fk.MultiplicityType == RelationshipMultiplicityType.OneToOne))
                                {
                                    if (fk.ToTableName.Equals(fk.FromTableName))
                                    {
                                        fk.FromFieldName += "";
                                    }
                                    //We want to grab the field that does not equal the current table, but in those case swhere the reference points to itself,  then we need to assume the From End of the Relationship data
                                    var TargetFieldName               = (entityName.Equals(fk.FromTableName)) && (!fk.ToTableName.Equals(fk.FromTableName)) ? fk.ToFieldName : fk.FromFieldName;
                                    var SourceFieldName               = (entityName.Equals(fk.FromTableName)) && (!fk.ToTableName.Equals(fk.FromTableName)) ? fk.FromFieldName : fk.ToFieldName;
                                    var TargetEntityPrimaryKeys       = (entityName.Equals(fk.FromTableName) && (!fk.ToTableName.Equals(fk.FromTableName))) ? fk.ToEntity.PrimaryKeys : fk.FromEntity.PrimaryKeys;
                                    var FKFieldExistsOnTargetTablePKs = TargetEntityPrimaryKeys.Any(c => c.Name.Equals(TargetEntityPrimaryKeys));
                                    if (!IsRequired)
                                    {
                                        IsRequired = ((entityName.Equals(fk.FromTableName)) && (!fk.ToTableName.Equals(fk.FromTableName))) ? !((Property)fk.FromProperty).IsNullable : !((Property)fk.ToProperty).IsNullable;
                                    }
                                    //Because this field exists in the target entity primary keys, then convvention should automatically know to resolve the foriegn key, but if
                                    // it DOES NOT exist,  then we will need to write the key attribute.. however
                                    /// if this is a one to one relationship to the same table, we will apply the ForiegnKey atttribute to the primary key to the object
                                    if (!FKFieldExistsOnTargetTablePKs)
                                    {
                                        WriteFKAttribute = true;
                                    }
                                    fkList.Add(SourceFieldName);
                                }
                                //Determine wich end of the relationship to use, since we need the target, choose the end that does not equal this entities table name (schame.table)
                            }
                            if (!relationship.MultiplicityType.EndsAsOne())
                            {
                                writer.WriteSafeString(string.Format("\n{0}////WARNING:  There are multiple relationship groups with the same name but different multiplicities.. skipping this one...", prefix));
                            }
                            else
                            {
                                if (WriteFKAttribute)
                                {
                                    AttributeText.Append(string.Format("[ForeignKey(\"{0}\")]", string.Join(", ", fkList.ToList())));
                                }
                                if (IsRequired)
                                {
                                    AttributeText.Append("[Required]");
                                }
                                if (AttributeText.Length > 0)
                                {
                                    writer.WriteSafeString(string.Format("\n{0}{1}", prefix, AttributeText.ToString()));
                                }
                                writer.WriteSafeString(string.Format("\n{0}public virtual {1} {2} {{ get; set; }}", prefix, relationship.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", "").ToSingular(), FieldName));
                            }
                            PreviousOneToOneFields.Add(FieldName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });
            Handlebars.RegisterHelper("UnitTestsRenderExtendedEndpointsV0", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('UnitTestsRenderExtendedEndpointsV0')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (IEntity)context.Value;
                    var entityName = entity.Schema + "." + entity.Name;

                    var PreviousManyToOneFields = new List <string>();
                    var FKToUse = entity.Relationships.Fetch(RelationshipMultiplicityType.ManyToZeroOrOne).Select(s => s.Name).ToList();
                    foreach (var fkNameKV in entity.RelationshipGroups)
                    {
                        var fkName = fkNameKV.Key;
                        if (FKToUse.Contains(fkName))
                        {
                            var relationship = fkNameKV.Value;
                        }
                    }


                    var RelationshipsManyToOne = entity.Relationships.Fetch(RelationshipMultiplicityType.ManyToZeroOrOne);
                    foreach (IRelationship relationship in RelationshipsManyToOne)
                    {
                        int SameTableCount         = RelationshipsManyToOne.CountItems(RelationSearchField.ToTableName, relationship.ToTableName);
                        string ToTableNameSingular = relationship.ToTableName.Replace(Internal.AppSettings.Instance.Configuration.Database.DefaultSchema + ".", "").ToSingular();
                        string ExpandColumnName    = ((PreviousManyToOneFields.Contains(ToTableNameSingular) || (entity.Properties.ContainsKey(ToTableNameSingular)) || (entityName == relationship.ToTableName) || (SameTableCount > 1)) ? relationship.FromColumnName : ToTableNameSingular);
                        writer.WriteSafeString(string.Format("\n{0}using (var response = await HttpClient.GetAsync(\"http://testserver/api/{1}?%24expand={2}<t/>&%24top=10\")) ", prefix, entityName, ExpandColumnName));
                        writer.WriteSafeString(string.Format("\n{0}{{ ", prefix));
                        writer.WriteSafeString(string.Format("\n{0}    var result = await response.Content.ReadAsStringAsync(); ", prefix));
                        writer.WriteSafeString(string.Format("\n{0}    Assert.IsTrue(response.StatusCode == HttpStatusCode.OK, \"Return Get 10 or less {1} with Expand of {2}. \" + result); ", prefix, entityName, ExpandColumnName));
                        writer.WriteSafeString(string.Format("\n{0}}} ", prefix));
                        PreviousManyToOneFields.Add(ExpandColumnName);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });
        }
Beispiel #11
0
        public SummaryInfo(CMSDataContext db)
        {
            this.db = db;
            Handlebars.RegisterHelper("YesNo", (writer, options, context, args) =>
            {
                var tf = (bool?)(args[0]);
                writer.Write(tf == true ? "Yes" : tf == false ? "No" : "");
            });
            Handlebars.RegisterHelper("SubGroupChoice", (writer, options, context, args) =>
            {
                var ask = (AskDropdown)(args[0]);
                writer.Write(ask.SmallGroupChoice(p.option).Description);
            });
            Handlebars.RegisterHelper("YesNoAnswer", (writer, options, context, args) =>
            {
                var SubGroup = args[0].ToString();
                writer.Write(p.YesNoQuestion[SubGroup] == true ? "Yes" : "No");
            });
            Handlebars.RegisterHelper("SetMenu", (writer, options, context, args) =>
            {
                var menu = args[0] as AskMenu;
                if (menu == null)
                {
                    return;
                }
                mlist = menu.MenuItemsChosen(p.MenuItem[menu.UniqueId]).ToList();
                if (mlist.Any())
                {
                    lastidesc = mlist.Last().desc;
                }
            });
            Handlebars.RegisterHelper("SetCheckbox", (writer, options, context, args) =>
            {
                var cb = args[0] as AskCheckboxes;
                if (cb == null)
                {
                    return;
                }
                cblist = cb.CheckboxItemsChosen(p.Checkbox).ToList();
                ilabel = cb.Label;
                if (cblist.Any())
                {
                    lastidesc = cblist.Last().Description;
                }
            });
            Handlebars.RegisterHelper("SetYesNoQuestions", (writer, options, context, args) =>
            {
                var yn = args[0] as AskYesNoQuestions;
                if (yn == null)
                {
                    return;
                }
                ynlist = yn.list.Where(a => p.YesNoQuestion.ContainsKey(a.SmallGroup)).ToList();
                if (ynlist.Any())
                {
                    lastidesc = ynlist.Last().Question;
                }
            });
            Handlebars.RegisterHelper("SetExtraQuestions", (writer, options, context, args) =>
            {
                var eq = args[0] as AskExtraQuestions;
                if (eq == null)
                {
                    return;
                }
                eqlist = p.ExtraQuestion[eq.UniqueId].Where(a => a.Value.HasValue()).ToList();
                if (eqlist.Any())
                {
                    lastidesc = eqlist.Last().Key;
                }
            });
            Handlebars.RegisterHelper("SetTextQuestions", (writer, options, context, args) =>
            {
                var tx = args[0] as AskText;
                if (tx == null)
                {
                    return;
                }
                txlist = p.Text[tx.UniqueId].Where(a => a.Value.HasValue()).ToList();
                if (txlist.Any())
                {
                    lastidesc = txlist.Last().Key;
                }
            });
            Handlebars.RegisterHelper("GradeOption", (writer, options, context, args) =>
            {
                var go = (AskGradeOptions)(args[0]);
                if (go == null)
                {
                    return;
                }
                writer.Write(p.GradeOptions(go).SingleOrDefault(s => s.Value == (p.gradeoption ?? "00"))?.Text);
            });
            Handlebars.RegisterHelper("SetLabel", (writer, options, context, args) =>
                                      ilabel = args[0] as string);
            Handlebars.RegisterHelper("SetRowStyle", (writer, options, context, args) =>
                                      rs = lastidesc == args[0].ToString() ? args[1].ToString() : args[2].ToString());

            var template = Handlebars.Compile(CmsData.Properties.Resources.Details2);
        }
Beispiel #12
0
        /// <summary>
        /// Registers all of the required Handlebars helpers.
        /// </summary>
        public static void RegisterHelpers()
        {
            if (_areRegistered)
            {
                return;
            }

            _areRegistered = true;

            // Will check that the first argument equals at least one of the subsequent arguments.
            Handlebars.RegisterHelper("ifeq", (writer, context, parameters, args) =>
            {
                if (IfEq(args))
                {
                    context.Template(writer, parameters);
                }
                else
                {
                    context.Inverse(writer, parameters);
                }
            });

            // Will check that the first argument does not equal any of the subsequent arguments.
            Handlebars.RegisterHelper("ifne", (writer, context, parameters, args) =>
            {
                if (IfEq(args))
                {
                    context.Inverse(writer, parameters);
                }
                else
                {
                    context.Template(writer, parameters);
                }
            });

            // Will check that the first argument is less than or equal to the subsequent arguments.
            Handlebars.RegisterHelper("ifle", (writer, context, parameters, args) =>
            {
                if (IfLe(args))
                {
                    context.Template(writer, parameters);
                }
                else
                {
                    context.Inverse(writer, parameters);
                }
            });

            // Will check that the first argument is greater than or equal to the subsequent arguments.
            Handlebars.RegisterHelper("ifge", (writer, context, parameters, args) =>
            {
                if (IfGe(args))
                {
                    context.Template(writer, parameters);
                }
                else
                {
                    context.Inverse(writer, parameters);
                }
            });

            // Will check that all of the arguments have a non-<c>null</c> value.
            Handlebars.RegisterHelper("ifval", (writer, context, parameters, args) =>
            {
                foreach (var arg in args)
                {
                    if (arg == null)
                    {
                        context.Inverse(writer, parameters);
                        return;
                    }
                }

                context.Template(writer, parameters);
            });

            // Will check that all of the arguments have a <c>null</c> value.
            Handlebars.RegisterHelper("ifnull", (writer, context, parameters, args) =>
            {
                foreach (var arg in args)
                {
                    if (arg != null)
                    {
                        context.Inverse(writer, parameters);
                        return;
                    }
                }

                context.Template(writer, parameters);
            });

            // Will check that any of the arguments have a <c>true</c> value where bool; otherwise, non-null.
            Handlebars.RegisterHelper("ifor", (writer, context, parameters, args) =>
            {
                foreach (var arg in args)
                {
                    if (arg is bool opt)
                    {
                        if (opt)
                        {
                            context.Template(writer, parameters);
                            return;
                        }
                    }
                    else if (arg != null)
                    {
                        var opt2 = arg as bool?;
                        if (opt2 != null && !opt2.Value)
                        {
                            continue;
                        }

                        context.Template(writer, parameters);
                        return;
                    }
                }

                context.Inverse(writer, parameters);
            });

            // Converts a value to lowercase.
            Handlebars.RegisterHelper("lower", (writer, context, parameters) => writer.WriteSafeString(parameters.FirstOrDefault()?.ToString()?.ToLowerInvariant() ?? ""));

            // NOTE: Any ending in 'x' are to explicitly ignore special names!!!

            // Converts a value to camelcase.
            Handlebars.RegisterHelper("camel", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToCamelCase(parameters.FirstOrDefault()?.ToString()) ?? ""));
            Handlebars.RegisterHelper("camelx", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToCamelCase(parameters.FirstOrDefault()?.ToString(), true) ?? ""));

            // Converts a value to pascalcase.
            Handlebars.RegisterHelper("pascal", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPascalCase(parameters.FirstOrDefault()?.ToString()) ?? ""));
            Handlebars.RegisterHelper("pascalx", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPascalCase(parameters.FirstOrDefault()?.ToString(), true) ?? ""));

            // Converts a value to private case.
            Handlebars.RegisterHelper("private", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPrivateCase(parameters.FirstOrDefault()?.ToString()) ?? ""));
            Handlebars.RegisterHelper("privatex", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToPrivateCase(parameters.FirstOrDefault()?.ToString(), true) ?? ""));

            Handlebars.RegisterHelper("sentence", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToSentenceCase(parameters.FirstOrDefault()?.ToString()) ?? ""));
            Handlebars.RegisterHelper("sentencex", (writer, context, parameters) => writer.WriteSafeString(StringConversion.ToSentenceCase(parameters.FirstOrDefault()?.ToString(), true) ?? ""));

            // Converts a value to the c# '<see cref="value"/>' comments equivalent.
            Handlebars.RegisterHelper("seecomments", (writer, context, parameters) => writer.WriteSafeString(ConfigBase.ToSeeComments(parameters.FirstOrDefault()?.ToString())));

            // Inserts indent spaces based on the passed index value.
            Handlebars.RegisterHelper("indent", (writer, context, parameters) => writer.WriteSafeString(new string(' ', 4 * (int)(parameters.FirstOrDefault() ?? 0))));

            // Adds a value to a value.
            Handlebars.RegisterHelper("add", (writer, context, parameters) =>
            {
                int sum = 0;
                foreach (var p in parameters)
                {
                    if (p is int pi)
                    {
                        sum += pi;
                    }
                    else if (p is string ps)
                    {
                        sum += int.Parse(ps, NumberStyles.Integer, CultureInfo.InvariantCulture);
                    }
                    else
                    {
                        writer.WriteSafeString("!!! add with invalid integer !!!");
                    }
                }

                writer.WriteSafeString(sum);
            });
        }
        public static void RegisterHelpers()
        {
            Handlebars.RegisterHelper("AsTSContructorProperty", (writer, context, parameters) => {
                var property = (Property)context.Value;
                var prefix   = parameters.AsString(0);
                if (property.Type.ToJsType(false) == "Date")
                {
                    writer.WriteSafeString(string.Format("\n{0}this.{1} = item.{1} ? new Date(item.{1}) : null;", prefix, property.Name));
                }
                else
                {
                    writer.WriteSafeString(string.Format("\n{0}this.{1} = item.{1};", prefix, property.Name));
                }
            });

            Handlebars.RegisterHelper("TSModelBaseImportDeclarations", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('TSModelBaseImportDeclarations')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (IEntity)context.Value;
                    var entityName = entity.Name;

                    List <string> PreviousManyToOneFields = new List <string>();
                    var RelationshipsManyToOne            = entity.Relationships.Fetch(RelationshipMultiplicityType.ManyToZeroOrOne);
                    foreach (Relationship relationship in RelationshipsManyToOne)
                    {
                        if (!PreviousManyToOneFields.Contains(relationship.ToTableName))
                        {
                            writer.WriteSafeString(string.Format("\n{0}import {{ {1} }} from '../{2}';", prefix, relationship.ToTableName.ToSingular(), relationship.ToTableName.ToSingular().ToSnakeCase()));
                            PreviousManyToOneFields.Add(relationship.ToTableName);
                        }
                    }
                    var RelationshipsOneToMany = entity.Relationships.Fetch(RelationshipMultiplicityType.ZeroOrOneToMany);
                    foreach (Relationship relationship in RelationshipsOneToMany)
                    {
                        if (!PreviousManyToOneFields.Contains(relationship.ToTableName))
                        {
                            writer.WriteSafeString(string.Format("\n{0}import {{ {1} }} from '../{2}';", prefix, relationship.ToTableName.ToSingular(), relationship.ToTableName.ToSingular().ToSnakeCase()));
                            PreviousManyToOneFields.Add(relationship.ToTableName);
                        }
                    }
                    var RelationshipsOneToOne = entity.Relationships.Fetch(RelationshipMultiplicityType.OneToOne);
                    foreach (Relationship relationship in RelationshipsOneToOne)
                    {
                        if (!PreviousManyToOneFields.Contains(relationship.ToTableName))
                        {
                            writer.WriteSafeString(string.Format("\n{0}import {{ {1} }} from '../{2}';", prefix, relationship.ToTableName.ToSingular(), relationship.ToTableName.ToSingular().ToSnakeCase()));
                            PreviousManyToOneFields.Add(relationship.ToTableName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });

            Handlebars.RegisterHelper("TSModelBaseRelatedProperties", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('TSModelBaseRelatedProperties')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (Entity)context.Value;
                    var entityName = entity.Name;

                    List <string> PreviousManyToOneFields = new List <string>();
                    var RelationshipsOneToMany            = entity.Relationships.Fetch(RelationshipMultiplicityType.ZeroOrOneToMany);
                    foreach (Relationship relationship in RelationshipsOneToMany.ToList())
                    {
                        writer.WriteSafeString(string.Format("\n{0}{1}?: Array<{2}> | null;", prefix, (relationship.ToTableName + "_" + relationship.ToColumnName), relationship.ToTableName.ToSingular()));
                    }

                    PreviousManyToOneFields.Clear();
                    var RelationshipsManyToOne = entity.Relationships.Fetch(RelationshipMultiplicityType.ManyToZeroOrOne);
                    foreach (Relationship relationship in RelationshipsManyToOne.ToList())
                    {
                        int SameTableCount         = RelationshipsManyToOne.CountItems(RelationSearchField.ToTableName, relationship.ToTableName);
                        string ToTableNameSingular = relationship.ToTableName.ToSingular();
                        string FieldName           = ((PreviousManyToOneFields.Contains(ToTableNameSingular) || (entity.Properties.ContainsKey(ToTableNameSingular)) || (entityName == relationship.ToTableName) || (SameTableCount > 1)) ? relationship.FromColumnName : ToTableNameSingular);
                        writer.WriteSafeString(string.Format("\n{0}{1}?: {2};", prefix, FieldName, relationship.ToTableName.ToSingular()));
                        PreviousManyToOneFields.Add(FieldName);
                    }

                    PreviousManyToOneFields.Clear();
                    var RelationshipsOneToOne = entity.Relationships.Fetch(RelationshipMultiplicityType.OneToOne);
                    foreach (Relationship relationship in RelationshipsOneToOne.ToList())
                    {
                        int SameTableCount         = RelationshipsOneToOne.CountItems(RelationSearchField.ToTableName, relationship.ToTableName);
                        string ToTableNameSingular = relationship.ToTableName.ToSingular();
                        string FieldName           = ((PreviousManyToOneFields.Contains(ToTableNameSingular) || (entity.Properties.ContainsKey(ToTableNameSingular)) || (entityName == relationship.ToTableName) || (SameTableCount > 1)) ? relationship.FromColumnName : ToTableNameSingular);
                        writer.WriteSafeString(string.Format("\n{0}{1}?: {2};", prefix, FieldName, relationship.ToTableName.ToSingular()));
                        PreviousManyToOneFields.Add(FieldName);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });

            Handlebars.RegisterHelper("TSModelBaseConstructorRelatedDefs", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('TSModelBaseConstructorRelatedDefs')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (IEntity)context.Value;
                    var entityName = entity.Name;

                    List <string> PreviousFieldCheck = new List <string>();
                    var RelationshipsOneToMany       = entity.Relationships.Fetch(RelationshipMultiplicityType.ZeroOrOneToMany);
                    foreach (Relationship relationship in RelationshipsOneToMany.ToList())
                    {
                        writer.WriteSafeString(string.Format("\n{0}this.{1} = Helpers.createClassArray({2}, item.{3});",
                                                             prefix,
                                                             (relationship.ToTableName + "_" + relationship.ToColumnName),
                                                             relationship.ToTableName.ToSingular(),
                                                             relationship.ToTableName + "_" + relationship.ToColumnName
                                                             ));
                        PreviousFieldCheck.Add(relationship.ToTableName);
                    }

                    PreviousFieldCheck.Clear();
                    var RelationshipsManyToOne = entity.Relationships.Fetch(RelationshipMultiplicityType.ManyToZeroOrOne);
                    foreach (Relationship relationship in RelationshipsManyToOne.ToList())
                    {
                        int SameTableCount         = RelationshipsManyToOne.CountItems(RelationSearchField.ToTableName, relationship.ToTableName);
                        string ToTableNameSingular = relationship.ToTableName.ToSingular();
                        string FieldName           = ((PreviousFieldCheck.Contains(ToTableNameSingular) || (entity.Properties.ContainsKey(ToTableNameSingular)) || (entityName == relationship.ToTableName) || (SameTableCount > 1)) ? relationship.FromColumnName : ToTableNameSingular);
                        writer.WriteSafeString(string.Format("\n{0}this.{1} = new {2}(item.{3});", prefix, FieldName, relationship.ToTableName.ToSingular(), FieldName));
                        PreviousFieldCheck.Add(FieldName);
                    }

                    PreviousFieldCheck.Clear();
                    var RelationshipsOneToOne2 = entity.Relationships.Fetch(RelationshipMultiplicityType.OneToOne);
                    foreach (Relationship relationship in RelationshipsOneToOne2.ToList())
                    {
                        int SameTableCount         = RelationshipsOneToOne2.CountItems(RelationSearchField.ToTableName, relationship.ToTableName);
                        string ToTableNameSingular = relationship.ToTableName.ToSingular();
                        string FieldName           = ((PreviousFieldCheck.Contains(ToTableNameSingular) || (entity.Properties.ContainsKey(ToTableNameSingular)) || (entityName == relationship.ToTableName) || (SameTableCount > 1)) ? relationship.FromColumnName : ToTableNameSingular);
                        writer.WriteSafeString(string.Format("\n{0}this.{1} = new {2}(item.{3});", prefix, FieldName, relationship.ToTableName.ToSingular(), FieldName));
                        PreviousFieldCheck.Add(FieldName);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });


            Handlebars.RegisterHelper("TSModelInterfaceImports", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('TSModelInterfaceImports')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (IEntity)context.Value;
                    var entityName = entity.Name;

                    List <string> PreviousManyToOneFields = new List <string>();
                    var RelationshipsManyToOne            = entity.Relationships.Fetch(RelationshipMultiplicityType.ManyToZeroOrOne);

                    writer.WriteSafeString(string.Format("\n{0}// MANY TO ZERO OR ONE", prefix));
                    foreach (Relationship relationship in RelationshipsManyToOne)
                    {
                        if (!PreviousManyToOneFields.Contains(relationship.ToTableName))
                        {
                            writer.WriteSafeString(string.Format("\n{0}import {{ I{1} }} from './i{2}';", prefix, relationship.ToTableName.ToSingular(), relationship.ToTableName.ToSingular().ToSnakeCase()));
                            PreviousManyToOneFields.Add(relationship.ToTableName);
                        }
                    }

                    writer.WriteSafeString(string.Format("\n{0}// ZERO OR ONE TO MANY", prefix));
                    var RelationshipsOneToMany = entity.Relationships.Fetch(RelationshipMultiplicityType.ZeroOrOneToMany);
                    foreach (Relationship relationship in RelationshipsOneToMany)
                    {
                        if (!PreviousManyToOneFields.Contains(relationship.ToTableName))
                        {
                            writer.WriteSafeString(string.Format("\n{0}import {{ I{1} }} from './i{2}';", prefix, relationship.ToTableName.ToSingular(), relationship.ToTableName.ToSingular().ToSnakeCase()));
                            PreviousManyToOneFields.Add(relationship.ToTableName);
                        }
                    }
                    writer.WriteSafeString(string.Format("\n{0}// ONE TO ZERO OR ONE", prefix));

                    var RelationshipsOneOne = entity.Relationships.Fetch(RelationshipMultiplicityType.OneToOne);
                    foreach (Relationship relationship in RelationshipsOneOne)
                    {
                        if (!PreviousManyToOneFields.Contains(relationship.ToTableName))
                        {
                            writer.WriteSafeString(string.Format("\n{0}import {{ I{1} }} from './i{2}';", prefix, relationship.ToTableName.ToSingular(), relationship.ToTableName.ToSingular().ToSnakeCase()));
                            PreviousManyToOneFields.Add(relationship.ToTableName);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });

            Handlebars.RegisterHelper("TSModelInterfaceRelatedProperties", (writer, context, parameters) => {
                var PROC_NAME = "Handlebars.RegisterHelper('TSModelInterfaceRelatedProperties')";
                try
                {
                    var prefix     = parameters.AsString(0);
                    var entity     = (IEntity)context.Value;
                    var entityName = entity.Name;

                    var RelationshipsOneToMany       = entity.Relationships.Fetch(RelationshipMultiplicityType.ZeroOrOneToMany);
                    List <string> PreviousFieldCheck = new List <string>();
                    PreviousFieldCheck.Clear();
                    foreach (Relationship relationship in RelationshipsOneToMany)
                    {
                        writer.WriteSafeString(string.Format("\n{0}{1}<t/>?: I{2}[] | null;", prefix, (relationship.ToTableName + "_" + relationship.ToColumnName), relationship.ToTableName.ToSingular()));
                        PreviousFieldCheck.Add(relationship.ToTableName);
                    }


                    PreviousFieldCheck.Clear();
                    var RelationshipsManyToOne = entity.Relationships.Fetch(RelationshipMultiplicityType.ManyToZeroOrOne);
                    foreach (Relationship relationship in RelationshipsManyToOne)
                    {
                        int SameTableCount         = RelationshipsManyToOne.CountItems(RelationSearchField.ToTableName, relationship.ToTableName);
                        string ToTableNameSingular = relationship.ToTableName.ToSingular();
                        string FieldName           = ((PreviousFieldCheck.Contains(ToTableNameSingular) || (entity.Properties.ContainsKey(ToTableNameSingular)) || (entityName == relationship.ToTableName) || (SameTableCount > 1)) ? relationship.FromColumnName : ToTableNameSingular);
                        writer.WriteSafeString(string.Format("\n{0}{1}?: I{2};", prefix, FieldName, relationship.ToTableName.ToSingular()));
                        PreviousFieldCheck.Add(FieldName);
                    }

                    List <string> PreviousOneToOneFields2 = new List <string>();
                    var RelationshipsOneToOne2            = entity.Relationships.Fetch(RelationshipMultiplicityType.OneToOne);
                    foreach (Relationship relationship in RelationshipsOneToOne2)
                    {
                        int SameTableCount         = RelationshipsOneToOne2.CountItems(RelationSearchField.ToTableName, relationship.ToTableName);
                        string ToTableNameSingular = relationship.ToTableName.ToSingular();
                        string FieldName           = ((PreviousOneToOneFields2.Contains(ToTableNameSingular) || (entity.Properties.ContainsKey(ToTableNameSingular)) || (entityName == relationship.ToTableName) || (SameTableCount > 1)) ? relationship.FromColumnName : ToTableNameSingular);
                        writer.WriteSafeString(string.Format("\n{0}{1}?: I{2};", prefix, FieldName, relationship.ToTableName.ToSingular()));
                        PreviousOneToOneFields2.Add(FieldName);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(PROC_NAME + "- Error! " + ex.Message);
                    writer.WriteSafeString("**** ERROR RENDERING " + PROC_NAME + ".  " + ex.Message);
                }
            });
        }
        protected override void WriteFile(GeneratorContext ctx, FileDescriptorProto obj)
        {
            var file = ctx.File;

            var ast = new ProtoFile
            {
                Filename    = file.Name,
                PackageName = file.Package,
                CsNamespace = file.Options?.CsharpNamespace ?? file.Package,
                Messages    = file
                              .MessageTypes
                              .ToArray()
                              .Select(mt => new ProtoMessage
                {
                    Name   = mt.Name,
                    Fields = mt.Fields.Select(f => new ProtoField()
                    {
                        TypeName   = f.TypeName,
                        Name       = f.Name,
                        Number     = f.Number,
                        IsRepeated = f.label == FieldDescriptorProto.Label.LabelRepeated,
                        OneOfIndex = f.OneofIndex,
                        Type       = f.type,
                        Object     = ctx.TryFind <DescriptorProto>(f.TypeName),
                    }).ToArray()
                })
                              .ToArray(),
                Services = file
                           .Services
                           .ToArray()
                           .Select(
                    s => new ProtoService
                {
                    Name    = s.Name,
                    Methods = s.Methods.ToArray()
                              .Select(
                        (m, i) => new ProtoMethod
                    {
                        Index         = i,
                        Name          = m.Name,
                        InputNameRaw  = RemovePackageName(m.InputType),
                        OutputNameRaw = RemovePackageName(m.OutputType),
                        InputObject   = ctx.TryFind <DescriptorProto>(m.InputType),
                        OutputObject  = ctx.TryFind <DescriptorProto>(m.OutputType),
                    }
                        )
                              .ToArray()
                }
                    )
                           .ToArray()
            };

            Handlebars.RegisterHelper("StringEquality", (output, options, context, arguments) =>
            {
                if (arguments.Length != 2)
                {
                    throw new HandlebarsException("{{#StringEquality}} helper must have exactly two arguments");
                }

                var left  = arguments.At <string>(0);
                var right = arguments[1] as string;
                if (left == right)
                {
                    options.Template(output, context);
                }
                else
                {
                    options.Inverse(output, context);
                }
            });

            var f = Handlebars.Compile(_template);

            var result = f(ast);

            ctx.WriteLine(result);
        /// <summary>
        /// Set Application Template Main
        /// </summary>
        /// <param name="application"></param>
        /// <param name="handlebarsTemplate"></param>
        /// <returns></returns>
        public static string PopulateHtmlTemplateWithApplicationData(ApplicationSubmission application, string handlebarsTemplate)
        {
            Handlebars.RegisterHelper("boolOrString", (writer, context, parameters) =>
            {
                string value = parameters[0].ToString();
                switch (value.ToLower())
                {
                case "true":
                    value = "Yes";
                    break;

                case "false":
                    value = "No";
                    break;

                case "":
                    value = "NOT PROVIDED";
                    break;
                }
                writer.WriteSafeString(value);
            });

            Handlebars.RegisterHelper("formatAddress", (writer, context, parameters) =>
            {
                if (parameters[0].GetType() == typeof(Address))
                {
                    Address value = (Address)parameters[0];
                    writer.WriteSafeString($"{value.StreetAddress}<div>{value.City}, {value.State} {value.ZipCode}</div><div>{value.County}</div>");
                }
            });

            Handlebars.RegisterHelper("formatAttachment", (writer, context, parameters) =>
            {
                if (parameters[0].GetType() == typeof(Attachment))
                {
                    Attachment value = (Attachment)parameters[0];
                    writer.WriteSafeString($"<div>{value.OriginalFileName}</div>");
                }
            });

            Handlebars.RegisterHelper("formatDateTime", (writer, context, parameters) =>
            {
                if (parameters[0].GetType() == typeof(DateTime))
                {
                    DateTime dateTime = (DateTime)parameters[0];
                    writer.WriteSafeString(dateTime.ToString("d"));
                }
            });

            Handlebars.RegisterHelper("if_eq", (writer, options, context, parameters) =>
            {
                if (parameters.Length == 5)
                {
                    switch (parameters[2].ToString())
                    {
                    case "||":
                        if (parameters[0].ToString() == parameters[1].ToString() || parameters[3].ToString() == parameters[4].ToString())
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;

                    case "&&":
                        if (parameters[0].ToString() == parameters[1].ToString() && parameters[3].ToString() == parameters[4].ToString())
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;
                    }
                }
                else
                {
                    if (parameters[0].ToString() == parameters[1].ToString())
                    {
                        options.Template(writer, (object)context);
                    }
                    else
                    {
                        options.Inverse(writer, (object)context);
                    }
                }
            });

            var template = Handlebars.Compile(handlebarsTemplate);

            return(template(application));
        }
        public static void RegisterHandleBarsHelpers()
        {
            // Normal helper
            Handlebars.RegisterHelper("TenOrMore", (output, options, context, data) =>
            {
                //if (data.Length > 10)
                //    output.Write("More than 10!");
                //else
                //    output.Write("Something else! "+data[0]);

                if (data[0].ToString() == data[1].ToString())
                {
                    output.Write("It's the same: " + (object)context);
                }
                else
                {
                    output.Write("Something else! " + data[0]);
                }
            });

            // Block helper
            Handlebars.RegisterHelper("TenOrMore", (output, options, context, data) =>
            {
                if (data[0].ToString() == data[1].ToString())
                {
                    options.Template(output, (object)context);
                }
            });

            // BLOCK HELPER
            //_handlebars.RegisterHelper("if_kpi", (writer, options, context, parameters) =>
            //{
            //    string group = Convert.ToString(parameters[0]);

            //    if (group == Enum.GetName(typeof(KPICategoryGroupEnum), KPICategoryGroupEnum.KPI))
            //    {
            //        options.Template(writer, (object)context);
            //    }
            //    else
            //    {
            //        options.Inverse(writer, (object)context);
            //    }
            //});

            //{
            //    {#if_equal x "my_string"}}
            //        x is "my_string"
            //        { {else} }
            //        x isn't "my_string"
            //        { {/ if_equal} }

            //public void RegisterHandleBarsHelperEvaluateClassificationType()
            //{
            //    Handlebars.RegisterHelper("ShowContactList", (output, context, parameters) =>
            //    {
            //        var contacts = string.Empty;
            //        for (var i = 0; i < context.Buyers.Length; i++)
            //        {
            //            contacts += context.Buyers[i].FirstName + " " + context.Buyers[i].LastName + ",";
            //        }

            //        output.WriteSafeString("Contacts: " + contacts);
            //    });
            //}


            //Handlebars.registerHelper('if_equal', function(a, b, opts) {
            //    if (a == b)
            //    {
            //        return opts.fn(this)
            //    }
            //    else
            //    {
            //        return opts.inverse(this)
            //    }
            //})
        }
Beispiel #17
0
 public static void Register()
 {
     Handlebars.RegisterHelper("outputTriggerJson", (writer, context, parameters) => HelperFunction(writer, context));
 }
Beispiel #18
0
        public void Setup()
        {
            var helpers = new IfLteBlockHelper();

            Handlebars.RegisterHelper(helpers.HelperName, helpers.HelperFunction);
        }
Beispiel #19
0
 public static void Register()
 {
     Handlebars.RegisterHelper("parameterOutputBinding", (writer, context, parameters) => HelperFunction(writer, context));
 }
        public static bool GenerateWebsiteFull(Website website)
        {
            var assembly  = typeof(Generators.CoreApiGenerator).GetTypeInfo().Assembly;
            var resources = assembly.GetManifestResourceNames();

            using (ZipFile zipFile = ZipFile.Read(assembly.GetManifestResourceStream("site_generator_lib.Templates.dotnetcore.dotnetcore_template.zip")))
            {
                FileInfo fileInfo   = new FileInfo(assembly.Location);
                string   serverPath = Path.Combine(fileInfo.DirectoryName, $"output{DateTime.Now.ToString("_ddMMyyyy_HHmmss")}", "server");
                zipFile.ExtractAll(serverPath, ExtractExistingFileAction.OverwriteSilently);

                foreach (var entityModel in website.Entities)
                {
                    var model = new { Name = entityModel.Name, Fields = entityModel.Fields.Select(field => new { Type = Shared.TypeConverter.PostgresToCsharp(field.Type), Name = field.Name }).ToArray() };

                    HandlebarsBlockHelper _propertyList = (TextWriter output, HelperOptions options, dynamic context, object[] arguments) => {
                        var enumList = arguments[0] as object[];
                        for (int i = 0; i < enumList.Length; i++)
                        {
                            string text = $"{((dynamic)(enumList[i])).Type} _{((dynamic)(enumList[i])).Name}";
                            if (i < enumList.Length - 1)
                            {
                                text += ",";
                            }
                            output.WriteLine(text);
                        }
                    };
                    Handlebars.RegisterHelper("prop_list", _propertyList);

                    HandlebarsBlockHelper _addModelList = (TextWriter output, HelperOptions options, dynamic context, object[] arguments) => {
                        var enumList = arguments[0] as object[];
                        for (int i = 0; i < enumList.Length; i++)
                        {
                            string text = $"addModel.{((dynamic)(enumList[i])).Name}";
                            if (i < enumList.Length - 1)
                            {
                                text += ",";
                            }
                            output.WriteLine(text);
                        }
                    };
                    Handlebars.RegisterHelper("addmodel_list", _addModelList);


                    // Build Domain Layer
                    Directory.CreateDirectory(Path.Combine(serverPath, "source", "Domain", entityModel.Name));
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.domainentity.t", $"{Path.Combine(serverPath, "source", "Domain", $"{entityModel.Name}")}\\{entityModel.Name}Entity.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.domainentityfactory.t", $"{Path.Combine(serverPath, "source", "Domain", $"{entityModel.Name}")}\\{entityModel.Name}EntityFactory.cs", model);


                    // Build Database Layer
                    Directory.CreateDirectory(Path.Combine(serverPath, "source", "Database", entityModel.Name));
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.dbirepository.t", $"{Path.Combine(serverPath, "source", "Database", $"{entityModel.Name}")}\\I{entityModel.Name}Repository.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.dbrepository.t", $"{Path.Combine(serverPath, "source", "Database", $"{entityModel.Name}")}\\{entityModel.Name}Repository.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.dbentityconfiguration.t", $"{Path.Combine(serverPath, "source", "Database", $"{entityModel.Name}")}\\{entityModel.Name}EntityConfiguration.cs", model);


                    // Build Model Layer
                    Directory.CreateDirectory(Path.Combine(serverPath, "source", "Model", "Models", $"{entityModel.Name}Model"));
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.model.t", $"{Path.Combine(serverPath, "source", "Model", "Models", $"{entityModel.Name}Model")}\\{entityModel.Name}Model.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.modelvalidator.t", $"{Path.Combine(serverPath, "source", "Model", "Models", $"{entityModel.Name}Model")}\\{entityModel.Name}ModelValidator.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.addmodel.t", $"{Path.Combine(serverPath, "source", "Model", "Models", $"{entityModel.Name}Model")}\\Add{entityModel.Name}Model.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.addmodelvalidator.t", $"{Path.Combine(serverPath, "source", "Model", "Models", $"{entityModel.Name}Model")}\\Add{entityModel.Name}ModelValidator.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.updatemodel.t", $"{Path.Combine(serverPath, "source", "Model", "Models", $"{entityModel.Name}Model")}\\Update{entityModel.Name}Model.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.updatemodelvalidator.t", $"{Path.Combine(serverPath, "source", "Model", "Models", $"{entityModel.Name}Model")}\\Update{entityModel.Name}ModelValidator.cs", model);


                    // Build Application Layer
                    Directory.CreateDirectory(Path.Combine(serverPath, "source", "Application", entityModel.Name));
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.iapplicationservice.t", $"{Path.Combine(serverPath, "source", "Application", entityModel.Name)}\\I{entityModel.Name}ApplicationService.cs", model);
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.applicationservice.t", $"{Path.Combine(serverPath, "source", "Application", entityModel.Name)}\\{entityModel.Name}ApplicationService.cs", model);

                    // Build Web Controller Layer
                    ParseGenerateFileTemplate("site_generator_lib.Templates.dotnetcore.controller.t", $"{Path.Combine(serverPath, "source", "Web", "Controllers")}\\{entityModel.Name}Controller.cs", model);
                }
            }

            return(true);
        }
Beispiel #21
0
        public static void RegisterHandleBarsHelpers()
        {
            // Generation Date/Time functional helper
            Handlebars.RegisterHelper("now", (writer, context, parameters) => { writer.WriteSafeString(DateTime.Now); });

            // Normal helper
            Handlebars.RegisterHelper("samecheck", (output, options, context, data) =>
            {
                //if (data.Length > 10)
                //    output.Write("More than 10!");
                //else
                //    output.Write("Something else! "+data[0]);

                if (data[0].ToString() == data[1].ToString())
                {
                    output.Write("It's the same: " + (object)context);
                }
                else
                {
                    output.Write("Something else! " + data[0]);
                }
            });

            // Block helper
            Handlebars.RegisterHelper("TenOrMore", (output, options, context, data) =>
            {
                if (data[0].ToString() == data[1].ToString())
                {
                    options.Template(output, (object)context);
                }
            });

            // Character spacing not satisfactory? Do not panic, help is near! Make sure the character spacing is righteous using this Handlebars helper.
            // Usage {{space sourceDataObject.name}} will space out (!?) the name of the source to 30 characters and a few tabs for lots of white spaces.
            Handlebars.RegisterHelper("space", (writer, context, args) =>
            {
                string outputString = args[0].ToString();
                if (outputString.Length < 30)
                {
                    outputString = outputString.PadRight(30);
                }
                writer.WriteSafeString(outputString + "\t\t\t\t");
            });

            Handlebars.RegisterHelper("StringReplace", (writer, context, args) =>
            {
                if (args.Length < 3)
                {
                    throw new HandlebarsException("The {{StringReplace}} function requires at least three arguments.");
                }

                string expression = args[0] as string;

                if (args[0] is Newtonsoft.Json.Linq.JValue)
                {
                    expression = ((Newtonsoft.Json.Linq.JValue)args[0]).Value.ToString();
                }

                string pattern     = args[1] as string;
                string replacement = args[2] as string;

                expression = expression.Replace(pattern, replacement);
                writer.WriteSafeString(expression);
            });


            // BLOCK HELPER
            //_handlebars.RegisterHelper("if_kpi", (writer, options, context, parameters) =>
            //{
            //    string group = Convert.ToString(parameters[0]);

            //    if (group == Enum.GetName(typeof(KPICategoryGroupEnum), KPICategoryGroupEnum.KPI))
            //    {
            //        options.Template(writer, (object)context);
            //    }
            //    else
            //    {
            //        options.Inverse(writer, (object)context);
            //    }
            //});

            //{
            //    {#if_equal x "my_string"}}
            //        x is "my_string"
            //        { {else} }
            //        x isn't "my_string"
            //        { {/ if_equal} }

            //public void RegisterHandleBarsHelperEvaluateClassificationType()
            //{
            //    Handlebars.RegisterHelper("ShowContactList", (output, context, parameters) =>
            //    {
            //        var contacts = string.Empty;
            //        for (var i = 0; i < context.Buyers.Length; i++)
            //        {
            //            contacts += context.Buyers[i].FirstName + " " + context.Buyers[i].LastName + ",";
            //        }

            //        output.WriteSafeString("Contacts: " + contacts);
            //    });
            //}


            //Handlebars.registerHelper('if_equal', function(a, b, opts) {
            //    if (a == b)
            //    {
            //        return opts.fn(this)
            //    }
            //    else
            //    {
            //        return opts.inverse(this)
            //    }
            //})


            // Accept two values, and see if they are the same, use as block helper.
            // Usage {{#stringcompare string1 string2}} do something {{else}} do something else {{/stringcompare}}
            // Usage {{#stringcompare string1 string2}} do something {{/stringcompare}}
            Handlebars.RegisterHelper("stringequal", (output, options, context, arguments) =>
            {
                if (arguments.Length != 2)
                {
                    throw new HandlebarsException("The {{stringcompare}} functions requires exactly two arguments.");
                }

                var leftString  = arguments[0] == null ? "" : arguments[0].ToString();
                var rightString = arguments[1] == null ? "" : arguments[1].ToString();

                if (leftString == rightString)
                {
                    options.Template(output, (object)context);
                }
                else
                {
                    options.Inverse(output, (object)context);
                }
            });

            // Accept two values, and do something if they are the different.
            // Usage {{#stringdiff string1 string2}} do something {{else}} do something else {{/stringdiff}}
            // Usage {{#stringdiff string1 string2}} do something {{/strinstringdiffgcompare}}
            Handlebars.RegisterHelper("stringdiff", (output, options, context, arguments) =>
            {
                if (arguments.Length != 2)
                {
                    throw new HandlebarsException("The {{stringdiff}} functions requires exactly two arguments.");
                }

                var leftString  = arguments[0] == null ? "" : arguments[0].ToString();
                var rightString = arguments[1] == null ? "" : arguments[1].ToString();

                if (leftString != rightString)
                {
                    options.Template(output, (object)context);
                }
                else
                {
                    options.Inverse(output, (object)context);
                }
            });
        }
Beispiel #22
0
 public static void Register()
 {
     Handlebars.RegisterHelper("httpVerbs", (writer, context, parameters) => HelperFunction(writer, context, false, parameters));
     Handlebars.RegisterHelper("lowerHttpVerbs", (writer, context, parameters) => HelperFunction(writer, context, true, parameters));
 }
Beispiel #23
0
        public void Run()
        {
            string template_string = File.ReadAllText(GetFullPath(this.template_name), Encoding.UTF8);

            Handlebars.RegisterHelper("normalize",
                                      (writer, context, parameters) =>
                                      writer.WriteSafeString(NormalizePythonIdentifier(parameters[0] as string))
                                      );
            Handlebars.RegisterHelper("D2",
                                      (writer, context, parameters) =>
                                      writer.Write(((double)parameters[0]).ToString("N2",
                                                                                    System.Globalization.CultureInfo.InvariantCulture))
                                      );
            Handlebars.RegisterHelper("D4",
                                      (writer, context, parameters) =>
                                      writer.Write(((double)parameters[0]).ToString("N4",
                                                                                    System.Globalization.CultureInfo.InvariantCulture))
                                      );

            string[] color_names = new string[] { "blue", "red", "green", "black", "magenta", "cyan", "brown", "yellow" };
            Handlebars.RegisterHelper("color",
                                      (writer, context, parameters) =>
                                      writer.Write(color_names[((int)parameters[0]) % color_names.Length])
                                      );

            Handlebars.Configuration.UnresolvedBindingFormatter = "???";

            var template = Handlebars.Compile(template_string);

            Dictionary <string, object> dict = new Dictionary <string, object>();

            dict["CurrentDate"] = DateTime.Now;

            List <object> models = new List <object>();

            dict["Models"] = models;
            int temp_variable_id = 1;
            int rule_id          = 1;

            foreach (FuzzyModel fmodel in BoardProvider.Board.Models)
            {
                if (!fmodel.IsValid)
                {
                    models.Add(new
                    {
                        IsValid          = false,
                        ModelName        = fmodel.Name,
                        ModelDescription = fmodel.Description,
                    });
                    continue;
                }

                FuzzyValue[] all_values = fmodel.Rules
                                          .SelectMany(rule => rule.Premise)
                                          .Union(
                    fmodel.Rules
                    .SelectMany(rule => rule.Conclusion)
                    ).Select(expr => expr.Variable)
                                          .Distinct()
                                          .SelectMany(@var => var.Values).ToArray();

                FuzzyVariable[] input_variables = fmodel.Rules
                                                  .SelectMany(rule => rule.Premise)
                                                  .Select(expr => expr.Variable)
                                                  .Distinct()
                                                  .ToArray();

                FuzzyVariable[] output_variables = fmodel.Rules
                                                   .SelectMany(rule => rule.Conclusion)
                                                   .Select(x => x.Variable)
                                                   .Distinct()
                                                   .ToArray();

                List <object> rule_value_connection = new List <object>();
                List <object> compiled_rules        = new List <object>();
                Dictionary <FuzzyValue, List <object> > value2rule = new Dictionary <FuzzyValue, List <object> >();

                foreach (FuzzyRule fr in fmodel.Rules)
                {
                    // Generuj regułe w postaci strumienia tokenów
                    List <Token> tokens = new List <Token>();
                    foreach (FuzzySubexpression expr in fr.Premise)
                    {
                        if (expr.ConnectiveType == FuzzyConnectiveType.And)
                        {
                            tokens.Add(new Token()
                            {
                                Type = TokenType.Connective, Connective = FuzzyConnectiveType.And
                            });
                        }
                        if (expr.ConnectiveType == FuzzyConnectiveType.Or)
                        {
                            tokens.Add(new Token()
                            {
                                Type = TokenType.Connective, Connective = FuzzyConnectiveType.Or
                            });
                        }

                        tokens.Add(new Token()
                        {
                            Type = TokenType.FuzzyValue, FuzzyValue = expr.Value
                        });
                    }

                    List <Token> t = new List <Token>();
                    t.AddRange(tokens);
                    t.Add(new Token()
                    {
                        Type = TokenType.Connective, Connective = FuzzyConnectiveType.Or
                    });
                    t.AddRange(tokens);
                    t.Add(new Token()
                    {
                        Type = TokenType.Connective, Connective = FuzzyConnectiveType.And
                    });
                    t.AddRange(tokens);
                    tokens = t;


                    List <Operation> ops = new List <Operation>();
                    // Generuj składowe wyrażenia (baardzo uproszczone)

                    bool substitution_occured;
                    do // AND
                    {
                        substitution_occured = false;
                        for (int i = 1; i < tokens.Count - 1; i++)
                        {
                            if (tokens[i].Type == TokenType.Connective && tokens[i].Connective == FuzzyConnectiveType.And)
                            {
                                Token temp = new Token()
                                {
                                    Type = TokenType.NamedVariable, Name = $"temp{temp_variable_id++}"
                                };
                                Operation op = new Operation(temp, tokens[i - 1], tokens[i], tokens[i + 1]);
                                ops.Add(op);
                                tokens[i] = temp;
                                tokens.RemoveAt(i + 1);
                                tokens.RemoveAt(i - 1);
                                substitution_occured = true;
                                i--;
                            }
                        }
                    } while (substitution_occured);

                    do // OR
                    {
                        substitution_occured = false;
                        for (int i = 1; i < tokens.Count - 1; i++)
                        {
                            if (tokens[i].Type == TokenType.Connective && tokens[i].Connective == FuzzyConnectiveType.Or)
                            {
                                Token temp = new Token()
                                {
                                    Type = TokenType.NamedVariable, Name = $"temp{temp_variable_id++}"
                                };
                                Operation op = new Operation(temp, tokens[i - 1], tokens[i], tokens[i + 1]);
                                ops.Add(op);
                                tokens[i] = temp;
                                tokens.RemoveAt(i + 1);
                                tokens.RemoveAt(i - 1);
                                substitution_occured = true;
                                i--;
                            }
                        }
                    } while (substitution_occured);
                    Debug.Assert(tokens.Count == 1);

                    var compiled_rule = new
                    {
                        Rule        = fr,
                        RuleID      = rule_id++,
                        Operations  = ops.ToArray(),
                        Comment     = fr.ToString(),
                        FinalToken  = tokens[0],
                        Conclusions = fr.Conclusion.Select(x => x.Value)
                    };
                    compiled_rules.Add(compiled_rule);


                    foreach (FuzzyValue conclusion_value in fr.Conclusion.Select(c => c.Value))
                    {
                        if (!value2rule.ContainsKey(conclusion_value))
                        {
                            value2rule[conclusion_value] = new List <object>();
                        }

                        var conn = new
                        {
                            Rule           = compiled_rule.Rule,
                            RuleID         = compiled_rule.RuleID,
                            ConcludedValue = conclusion_value
                        };
                        value2rule[conclusion_value].Add(conn);
                    }
                }

                models.Add(new
                {
                    IsValid          = fmodel.IsValid,
                    ModelName        = fmodel.Name,
                    ModelDescription = fmodel.Description,
                    AllValues        = all_values,
                    InputVariables   = input_variables,
                    OutputVariables  = output_variables,
                    CompiledRules    = compiled_rules,

                    OutputValueToRuleAssociation = value2rule
                });
            }


            this.code = template(dict);
            Debug.Write(code);

            //
        }
Beispiel #24
0
        public static void RegisterHelpers(CMSDataContext db, PythonModel pm = null)
        {
            Handlebars.RegisterHelper("BottomBorder", (writer, context, args) => { writer.Write(CssStyle.BottomBorder); });
            Handlebars.RegisterHelper("AlignTop", (writer, context, args) => { writer.Write(CssStyle.AlignTop); });
            Handlebars.RegisterHelper("AlignRight", (writer, context, args) => { writer.Write(CssStyle.AlignRight); });
            Handlebars.RegisterHelper("DataLabelStyle", (writer, context, args) => { writer.Write(CssStyle.DataLabelStyle); });
            Handlebars.RegisterHelper("LabelStyle", (writer, context, args) => { writer.Write(CssStyle.LabelStyle); });
            Handlebars.RegisterHelper("DataStyle", (writer, context, args) => { writer.Write(CssStyle.DataStyle); });

            Handlebars.RegisterHelper("ServerLink", (writer, context, args) => { writer.Write(db.ServerLink().TrimEnd('/')); });
            Handlebars.RegisterHelper("FmtZip", (writer, context, args) => { writer.Write(args[0].ToString().FmtZip()); });
            Handlebars.RegisterHelper("HtmlComment", (writer, context, args) =>
            {
#if DEBUG
                writer.Write($"<h6>{args[0].ToString()} {args[1].ToString()}</h6>");
#else
                writer.Write($"<!--{args[0].ToString()} {args[1].ToString()}-->");
#endif
            });
            Handlebars.RegisterHelper("IfEqual", (writer, options, context, args) =>
            {
                if (IsEqual(args))
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("IfNotEqual", (writer, options, context, args) =>
            {
                if (!IsEqual(args))
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("IfCond", (writer, options, context, args) =>
            {
                var op = HttpUtility.HtmlDecode(args[1].ToString());
                bool b = false;
                switch (op)
                {
                case "==":
                    b = Compare(args) == 0;
                    break;

                case "!=":
                    b = Compare(args) != 0;
                    break;

                case "<":
                    b = Compare(args) < 0;
                    break;

                case ">":
                    b = Compare(args) > 0;
                    break;

                case ">=":
                    b = Compare(args) >= 0;
                    break;

                case "<=":
                    b = Compare(args) <= 0;
                    break;

                case "&&":
                    b = NumTrue(args) == 2;
                    break;

                case "||":
                    b = NumTrue(args) >= 1;
                    break;
                }
                if (b)
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("IfGT", (writer, options, context, args) =>
            {
                if (Compare2(args) > 0)
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("IfLT", (writer, options, context, args) =>
            {
                if (Compare2(args) < 0)
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("IfGE", (writer, options, context, args) =>
            {
                if (Compare2(args) <= 0)
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("IfLE", (writer, options, context, args) =>
            {
                if (Compare2(args) <= 0)
                {
                    options.Template(writer, (object)context);
                }
                else
                {
                    options.Inverse(writer, (object)context);
                }
            });
            Handlebars.RegisterHelper("GetToken", (writer, context, args) =>
            {
                var s     = args[0].ToString();
                var n     = args[1].ToInt();
                var ntoks = args.Length > 2 ? args[2].ToInt() : 2;
                var sep   = args.Length > 3 ? args[3].ToString() : " ";
                var a     = s.SplitStr(sep, ntoks);
                writer.Write(a[n]?.Trim() ?? "");
            });

            Handlebars.RegisterHelper("FmtMDY", (writer, context, args) =>
            {
                DateTime dt;
                var s = args[0].ToString();
                if (DateTime.TryParse(s, out dt))
                {
                    writer.Write(dt.ToShortDateString());
                }
            });
            Handlebars.RegisterHelper("FmtDate", (writer, context, args) =>
            {
                DateTime dt;
                var s = args[0].ToString();
                if (DateTime.TryParse(s, out dt))
                {
                    writer.Write(dt.ToShortDateString());
                }
            });
            Handlebars.RegisterHelper("FmtMoney", (writer, context, args) =>
            {
                decimal d;
                var s = args[0].ToString();
                if (decimal.TryParse(s, out d))
                {
                    writer.Write(d.ToString("C"));
                }
            });

            // Format helper in form of:  {{Fmt value "fmt"}}
            // ex. {{Fmt Total "C"}}
            // fmt is required. Uses standard/custom dotnet format strings
            Handlebars.RegisterHelper("Fmt", (writer, context, args) =>
            {
                var fmt = $"{{0:{args[1]}}}";
                writer.Write(fmt, args[0]);
            });

            // FmtPhone helper in form of:  {{FmtPhone phone# "prefix"}}
            Handlebars.RegisterHelper("FmtPhone", (writer, context, args) => { writer.Write(args[0].ToString().FmtFone($"{args[1]}")); });

            Handlebars.RegisterHelper("ReplaceCode", (writer, context, args) =>
            {
                EmailReplacements r = context.Replacements as EmailReplacements
                                      ?? (context.Replacements = new EmailReplacements(db));
                var code = args[0].ToString();
                var p    = db.LoadPersonById(args[1].ToInt());
                int?oid  = null;
                if (args.Length == 3)
                {
                    oid = args[2].ToInt2();
                }
                writer.Write(r.RenderCode(code, p, oid));
            });
            Handlebars.RegisterHelper("Json", (writer, options, context, args) =>
            {
                dynamic a = JsonDeserialize2(args[0].ToString());
                foreach (var item in a)
                {
                    options.Template(writer, item);
                }
            });

            Handlebars.RegisterHelper("Calc", (writer, context, args) =>
            {
                var calcAmt    = args[0].ToDouble() - args[1].ToDouble();
                var calcAmtfmt = $"{{0:{'c'}}}";
                writer.Write(calcAmtfmt, calcAmt);
            });

            Handlebars.RegisterHelper("ThrowError", (writer, context, args) =>
            {
                throw new Exception("ThrowError called in Handlebars Helper");
            });
        }
        private void CreateHandlebarsHelpers()
        {
            Handlebars.RegisterHelper("#DisplayAddress", (writer, context, parameters) =>
            {
                var jaddress = parameters[0] as JObject;
                if (jaddress != null)
                {
                    var address = jaddress.ToObject <Address>();
                    if (address.IsAutomaticallyFound)
                    {
                        writer.WriteSafeString("<b>" + address.SelectedAddress + "</b>");
                    }
                    else
                    {
                        writer.WriteSafeString("<p>Address line 1: <b>" + address.AddressLine1 + "</b></p>");
                        writer.WriteSafeString("<p>Address line 2: <b>" + address.AddressLine2 + "</b></p>");
                        writer.WriteSafeString("<p>Town: <b>" + address.Town + "</b></p>");
                    }
                    writer.WriteSafeString("<p>Postcode: <b>" + address.Postcode + "</b></p>");
                }
            });

            Handlebars.RegisterHelper("ShouldDisplayAddress", (writer, options, context, args) =>
            {
                if (args[0] is JObject jaddress)
                {
                    var address = jaddress.ToObject <Address>();
                    if (address.IsAutomaticallyFound || !string.IsNullOrEmpty(address.AddressLine1))
                    {
                        options.Template(writer, (object)context);
                    }
                }
            });

            Handlebars.RegisterHelper("#FormatDate", (writer, context, parameters) =>
            {
                if (!string.IsNullOrEmpty(parameters[0].ToString()))
                {
                    string newDate = parameters[0].ToString().Substring(0, 10);
                    writer.WriteSafeString(newDate);
                }
            });

            Handlebars.RegisterHelper("#FormatBoolean", (writer, context, parameters) =>
            {
                if (parameters[0].ToString().ToLower().Equals("true"))
                {
                    writer.WriteSafeString("Yes");
                }
                else
                {
                    writer.WriteSafeString("No");
                }
            });

            Handlebars.RegisterHelper("math", (output, context, parameters) =>
            {
                Expression e = new Expression(string.Format("{0}{1}{2}", parameters[0], parameters[1], parameters[2]));
                output.WriteSafeString(e.Evaluate().ToString());
            });

            Handlebars.RegisterHelper("#Capital", (output, context, parameters) =>
            {
                char[] a = parameters[0].ToString().ToCharArray();
                a[0]     = char.ToUpper(a[0]);
                string s = new string(a);
                output.WriteSafeString(s);
            });

            Handlebars.RegisterHelper("HasValue", (writer, options, context, args) =>
            {
                if (!string.IsNullOrEmpty(args[0].ToString().Trim()) && args[0].ToString() != "[]" && args[0].ToString() != "01/01/0001 00:01:15")
                {
                    options.Template(writer, (object)context);
                }
            });
        }
Beispiel #26
0
        public void BlockHelperWithArbitraryInversionAndComplexOperator()
        {
            Handlebars.RegisterHelper("ifCond", (writer, options, context, args) => {
                if (args.Length != 3)
                {
                    writer.Write("ifCond:Wrong number of arguments");
                    return;
                }
                if (args[0] == null || args[0].GetType().Name == "UndefinedBindingResult")
                {
                    writer.Write("ifCond:args[0] undefined");
                    return;
                }
                if (args[1] == null || args[1].GetType().Name == "UndefinedBindingResult")
                {
                    writer.Write("ifCond:args[1] undefined");
                    return;
                }
                if (args[2] == null || args[2].GetType().Name == "UndefinedBindingResult")
                {
                    writer.Write("ifCond:args[2] undefined");
                    return;
                }
                if (args[0].GetType().Name == "String" || args[0].GetType().Name == "JValue")
                {
                    var val1 = args[0].ToString();
                    var val2 = args[2].ToString();

                    switch (args[1].ToString())
                    {
                    case ">":
                        if (val1.Length > val2.Length)
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;

                    case "=":
                    case "==":
                        if (val1 == val2)
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;

                    case "<":
                        if (val1.Length < val2.Length)
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;

                    case "!=":
                    case "<>":
                        if (val1 != val2)
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;
                    }
                }
                else
                {
                    var val1 = float.Parse(args[0].ToString());
                    var val2 = float.Parse(args[2].ToString());

                    switch (args[1].ToString())
                    {
                    case ">":
                        if (val1 > val2)
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;

                    case "=":
                    case "==":
                        if (val1 == val2)
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;

                    case "<":
                        if (val1 < val2)
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;

                    case "!=":
                    case "<>":
                        if (val1 != val2)
                        {
                            options.Template(writer, (object)context);
                        }
                        else
                        {
                            options.Inverse(writer, (object)context);
                        }
                        break;
                    }
                }
            });

            var template = Handlebars.Compile(@"{{#ifCond arg1 '>' arg2}}{{arg1}} is greater than {{arg2}}{{else}}{{arg1}} is less than {{arg2}}{{/ifCond}}");
            var data     = new { arg1 = 2, arg2 = 1 };
            var result   = template(data);

            Assert.Equal("2 is greater than 1", result);

            data   = new { arg1 = 1, arg2 = 2 };
            result = template(data);
            Assert.Equal("1 is less than 2", result);

            template = Handlebars.Compile(@"{{#ifCond arg1 '<' arg2}}{{arg1}} is less than {{arg2}}{{else}}{{arg1}} is greater than {{arg2}}{{/ifCond}}");
            data     = new { arg1 = 2, arg2 = 1 };
            result   = template(data);
            Assert.Equal("2 is greater than 1", result);

            data   = new { arg1 = 1, arg2 = 2 };
            result = template(data);
            Assert.Equal("1 is less than 2", result);

            template = Handlebars.Compile(@"{{#ifCond arg1 '=' arg2}}{{arg1}} is eq to {{arg2}}{{else}}{{arg1}} is not eq to {{arg2}}{{/ifCond}}");
            data     = new { arg1 = 1, arg2 = 1 };
            result   = template(data);
            Assert.Equal("1 is eq to 1", result);

            data   = new { arg1 = 2, arg2 = 1 };
            result = template(data);
            Assert.Equal("2 is not eq to 1", result);

            template = Handlebars.Compile(@"{{#ifCond arg1 '!=' arg2}}{{arg1}} is not eq to {{arg2}}{{else}}{{arg1}} is eq to {{arg2}}{{/ifCond}}");
            data     = new { arg1 = 2, arg2 = 1 };
            result   = template(data);
            Assert.Equal("2 is not eq to 1", result);

            template = Handlebars.Compile(@"{{#ifCond str '!=' ''}}not empty{{else}}empty{{/ifCond}}");
            var datastr = new { str = "abc" };

            result = template(datastr);
            Assert.Equal("not empty", result);

            template = Handlebars.Compile(@"{{#ifCond str '==' ''}}empty{{else}}not empty{{/ifCond}}");
            datastr  = new { str = "" };
            result   = template(datastr);
            Assert.Equal("empty", result);
        }
        public static async Task <bool> GenerateSendDataItemFrom(SendDataViewModel customFormDataModel, SendDataItem sendDataItem)
        {
            try
            {
                Handlebars.RegisterHelper("formatDateTime", (writer, context, parameters) =>
                {
                    // parameters : datetime iso string, format, culture
                    try
                    {
                        var firstPrm = parameters[0].ToString();

                        if (firstPrm.ToLower() == "now")
                        {
                            firstPrm = DateTime.Now.ToString();
                        }

                        string res;
                        DateTime datetime = DateTime.Parse(firstPrm, null, System.Globalization.DateTimeStyles.RoundtripKind);
                        string format     = "dd/MM/yyyy";
                        if (parameters.Count() > 1)
                        {
                            format = parameters[1].ToString();
                        }
                        if (parameters.Count() > 2 && !string.IsNullOrWhiteSpace(parameters[2].ToString()))
                        {
                            string provider = parameters[2].ToString();
                            IFormatProvider formatprovider = null;
                            if (provider.ToLower() == "invariant")
                            {
                                formatprovider = CultureInfo.InvariantCulture;
                            }
                            else
                            {
                                formatprovider = CultureInfo.CreateSpecificCulture(provider);
                            }
                            res = datetime.ToString(format, formatprovider);
                        }
                        else
                        {
                            res = datetime.ToString(format);
                        }

                        writer.WriteSafeString(res);
                    }
                    catch (Exception e)
                    {
                        writer.WriteSafeString("");
                    }
                });

                #region Get CustomFormDataModel Props
                var toData      = customFormDataModel.To;
                var ccData      = customFormDataModel.Cc;
                var bccData     = customFormDataModel.Bcc;
                var replyToData = customFormDataModel.ReplyTo;

                var subjectData = customFormDataModel.DetailSubject;//Konu
                var sqlQueryConnectionString = customFormDataModel.SqlQueryConStr;
                var sqlqueryData             = customFormDataModel.SqlQuery;
                var sqlqueryToFieldData      = customFormDataModel.SqlQueryToField;
                var sqlqueryReplyToFieldData = customFormDataModel.SqlQueryReplyToField;
                var sqlqueryCcFieldData      = customFormDataModel.SqlQueryCcField;
                var sqlqueryBccFieldData     = customFormDataModel.SqlQueryBccField;
                var headerData = customFormDataModel.DetailHeader;//Başlık
                var footerData = customFormDataModel.DetailFooter;
                var detailSqlQueryConnectionString        = customFormDataModel.DetailSqlQueryConStr;
                var detailSqlqueryData                    = customFormDataModel.DetailSqlQuery;
                var useSendDataDetailQueryForTemplateData = customFormDataModel.DetailQueryForTemplate;
                var bodyData = customFormDataModel.DetailContent;
                var useDetailForEveryoneData = customFormDataModel.DetailBodyForAll == false; //TODO: UI'da ayrı ayrı gönder olarak gösterildigi icin ters kalıyor
                #endregion

                #region Subject Compile
                try
                {
                    var template = Handlebars.Compile(subjectData);

                    subjectData = template(new { });
                }
                catch (Exception ex)
                {
                }
                #endregion

                var bodyContent = bodyData;

                var replacedBodyContent = bodyContent.ToString();

                var listTemplateTokens         = new Dictionary <string, string>();
                var templateTokenRegexMatchRes = Regex.Matches(bodyContent, @"""\[(.*?)]""");
                if (templateTokenRegexMatchRes.Count > 0)
                {
                    foreach (Match item in templateTokenRegexMatchRes)
                    {
                        if (item.Success)
                        {
                            var value = item.Value.Replace("\"[", "").Replace("]\"", "").Trim();

                            if (listTemplateTokens.ContainsKey(value) == false)
                            {
                                listTemplateTokens.Add(value, item.Value);
                            }
                        }
                    }
                }

                sendDataItem.Bcc     = bccData;
                sendDataItem.Cc      = ccData;
                sendDataItem.ReplyTo = replyToData;

                sendDataItem.Type = 1; //TODO:Static - Email/Sms

                var sendDataMailAccounts = await SendDataMailAccountManager.GetMailAccounts();

                var sendDataMailAccount = sendDataMailAccounts.FirstOrDefault();

                if (sendDataMailAccount == null)
                {
                    LoggerService.GetLogger(ConstantHelper.JobLog).Log(new LogItem()
                    {
                        LoggerName        = ConstantHelper.JobLog,
                        Title             = "GenerateSendDataItemFrom GetMailAccounts Not Found",
                        Message           = "GetMailAccounts Not Found",
                        LogItemProperties = new List <LogItemProperty>()
                        {
                            new LogItemProperty("ServiceName", ConstantHelper.JobLog),
                            new LogItemProperty("ActionName", "GenerateSendDataItemFrom"),
                            new LogItemProperty("FormData", new { CustomFormDataModel = customFormDataModel, SendDataItem = sendDataItem })
                        },
                        LogLevel  = LogLevel.Error,
                        Exception = new ArgumentException("GetMailAccounts Not Found")
                    });
                    return(false);
                }

                var toDataSource     = new DataTable();
                var detailDataSource = new DataTable();

                var recipients = toData.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries).ToList();

                /*TODO:
                 * - Validsyon1 => To ve Detail Sql var ama detail sql sonuç dönmüyorsa ?
                 */

                Action <List <string>, string, List <KeyValuePair <string, object> >, string> invokeDetailQuery = async(to, changedBodyContent, columnNames, subject) =>
                {
                    #region Invoke
                    #region Initialize Detail Sqlect Query
                    var detailQuery = detailSqlqueryData.Replace("@[", "@").Replace("]@", "@");
                    List <SqlParameter> parameterList = new List <SqlParameter>();

                    if (columnNames?.Count > 0)
                    {
                        foreach (var col in columnNames)
                        {
                            if (detailQuery.Contains($"@{col.Key.ToLower(new System.Globalization.CultureInfo("en-US"))}@") ||
                                detailQuery.Contains($"@{col.Key}@"))
                            {
                                parameterList.Add(new SqlParameter($"@{col.Key}@", col.Value));
                            }
                        }

                        foreach (var col in columnNames)
                        {
                            if (listTemplateTokens.ContainsKey(col.Key))
                            {
                                var oldToken = listTemplateTokens[col.Key];
                                var newValue = col.Value?.ToString();
                                changedBodyContent = changedBodyContent.Replace(oldToken, newValue);
                            }
                        }
                    }

                    #endregion

                    detailDataSource = await SendDataSqlQueryManager.GetQueryData(detailSqlQueryConnectionString, detailQuery, parameterList);

                    string[] detailDataSourceColumnNames = detailDataSource.Columns.Cast <DataColumn>()
                                                           .Select(x => x.ColumnName)
                                                           .ToArray();

                    var newSendDataItem = JsonConvert.DeserializeObject <SendDataItem>(JsonConvert.SerializeObject(sendDataItem));

                    //detay sorgunun her bir satırı için bir mail mi yoksa detay sorguyu template içinde kullanmak mı ?
                    if (useSendDataDetailQueryForTemplateData)
                    {
                        changedBodyContent = changedBodyContent.Replace("\"[", "{{{").Replace("]\"", "}}}");

                        var jsonDataSource        = JsonConvert.SerializeObject(detailDataSource);
                        var jsonDataSourceExpando = JsonConvert.DeserializeObject <List <ExpandoObject> >(jsonDataSource);
                        var template = Handlebars.Compile(changedBodyContent);

                        changedBodyContent   = template(new { DataSource = jsonDataSourceExpando });
                        newSendDataItem.Body = changedBodyContent;
                        newSendDataItem.From = sendDataMailAccount.FromMailAddress;

                        //var to = toDataSource.Rows[i][sqlqueryToFieldData.Value]?.ToString().Trim().Replace("[", "").Replace("]", "");

                        await SendDataBy(sendDataMailAccount, newSendDataItem, subject, changedBodyContent, to, useDetailForEveryoneData);
                    }
                    else
                    {
                        foreach (DataRow item in detailDataSource.Rows)
                        {
                            foreach (var col in detailDataSourceColumnNames)
                            {
                                if (listTemplateTokens.ContainsKey(col))
                                {
                                    var oldToken = listTemplateTokens[col];
                                    var newValue = item[col]?.ToString();
                                    changedBodyContent = changedBodyContent.Replace(oldToken, newValue);
                                }
                                //var val = item[col]?.ToString();
                            }

                            var template = Handlebars.Compile(changedBodyContent);

                            changedBodyContent   = template(new { Item = item });
                            newSendDataItem.Body = changedBodyContent;
                            newSendDataItem.From = sendDataMailAccount.FromMailAddress;

                            //var to = toDataSource.Rows[i][sqlqueryToFieldData.Value]?.ToString();

                            await SendDataBy(sendDataMailAccount, newSendDataItem, subject, changedBodyContent, to, useDetailForEveryoneData);
                        }
                    }
                    #endregion
                };

                //string[] toDataSourceColumns
                if (string.IsNullOrEmpty(sqlqueryData) == false)
                {
                    toDataSource = await SendDataSqlQueryManager.GetQueryData(sqlQueryConnectionString, sqlqueryData);

                    if (toDataSource.Rows.Count > 0)
                    {
                        var toFormField      = sqlqueryToFieldData?.Trim().Replace("[", "").Replace("]", "");
                        var ccFormField      = sqlqueryCcFieldData?.Trim().Replace("[", "").Replace("]", "");
                        var bccFormField     = sqlqueryBccFieldData?.Trim().Replace("[", "").Replace("]", "");
                        var replyToFormField = sqlqueryReplyToFieldData?.Trim().Replace("[", "").Replace("]", "");

                        recipients = new List <string>();

                        var toDataSourceColumnNames = toDataSource.Columns.Cast <DataColumn>()
                                                      .Select(x => x.ColumnName)
                                                      .ToList();

                        if (string.IsNullOrEmpty(toFormField) == false && toDataSourceColumnNames.Contains(toFormField) == false)
                        {
                            throw new ArgumentException("TO Field Select row'a ait değil !");
                        }

                        Func <string, string, string, string> replaceStringFromToQuery = (sourceString, key, newData) =>
                        {
                            var changedStr = sourceString.ToString();

                            var contentColumn = "";

                            if (sourceString.Contains(key))
                            {
                                contentColumn = key;
                            }

                            if (string.IsNullOrEmpty(contentColumn) == false)
                            {
                                changedStr = sourceString.Replace(contentColumn, newData);
                            }

                            return(changedStr);
                        };

                        for (int i = 0; i < toDataSource.Rows.Count; i++)
                        {
                            try
                            {
                                var to           = "";
                                var ccField      = "";
                                var bccField     = "";
                                var replyToField = "";

                                if (string.IsNullOrEmpty(toFormField))
                                {
                                    to = toData;
                                }
                                else
                                {
                                    to = toDataSource.Rows[i][toFormField.Replace("[", "").Replace("]", "")]?.ToString().Trim().Replace("[", "").Replace("]", "");
                                }

                                if (string.IsNullOrEmpty(ccFormField) == false)
                                {
                                    ccField         = toDataSource.Rows[i][ccFormField.Replace("[", "").Replace("]", "")]?.ToString().Trim().Replace("[", "").Replace("]", "");
                                    sendDataItem.Cc = ccField;
                                }

                                if (string.IsNullOrEmpty(bccFormField) == false)
                                {
                                    bccField         = toDataSource.Rows[i][bccFormField.Replace("[", "").Replace("]", "")]?.ToString().Trim().Replace("[", "").Replace("]", "");
                                    sendDataItem.Bcc = bccField;
                                }

                                if (string.IsNullOrEmpty(sendDataItem.Cc) && string.IsNullOrEmpty(ccField) == false)
                                {
                                    sendDataItem.Cc = ccField;
                                }

                                if (string.IsNullOrEmpty(sendDataItem.Bcc) && string.IsNullOrEmpty(bccField) == false)
                                {
                                    sendDataItem.Bcc = bccField;
                                }

                                if (string.IsNullOrEmpty(replyToFormField) == false)
                                {
                                    replyToField         = toDataSource.Rows[i][replyToFormField.Replace("[", "").Replace("]", "")]?.ToString().Trim().Replace("[", "").Replace("]", "");
                                    sendDataItem.ReplyTo = replyToField;
                                }

                                var headerContent  = headerData;
                                var footerContent  = footerData;
                                var subjectContent = subjectData;

                                var changedBodyContent = replacedBodyContent.ToString();

                                #region Initialize Tokens From To Select Query
                                foreach (var col in toDataSourceColumnNames)
                                {
                                    var newValue = toDataSource.Rows[i][col]?.ToString();

                                    var lowerColumn = $"@{col.ToLower(new System.Globalization.CultureInfo("en-US"))}@";
                                    var column      = $"@{col}@";

                                    changedBodyContent = replaceStringFromToQuery(changedBodyContent, lowerColumn, newValue);

                                    changedBodyContent = replaceStringFromToQuery(changedBodyContent, column, newValue);

                                    headerContent = replaceStringFromToQuery(headerContent, lowerColumn, newValue);

                                    footerContent = replaceStringFromToQuery(footerContent, column, newValue);

                                    subjectContent = replaceStringFromToQuery(subjectContent, column, newValue);
                                }
                                #endregion

                                if (string.IsNullOrEmpty(detailSqlqueryData) == false)
                                {
                                    changedBodyContent = changedBodyContent.Replace("\"[HEADER]\"", headerContent);

                                    changedBodyContent = changedBodyContent.Replace("\"[FOOTER]\"", footerContent);

                                    var columnDatas = toDataSourceColumnNames.Select(colName => new KeyValuePair <string, object>(colName, toDataSource.Rows[i][colName])).ToList();

                                    invokeDetailQuery(new List <string>()
                                    {
                                        to
                                    }, changedBodyContent, columnDatas, subjectContent);
                                }
                                else
                                {
                                    if (string.IsNullOrEmpty(to) == false)
                                    {
                                        changedBodyContent = changedBodyContent.Replace("\"[HEADER]\"", headerContent);

                                        changedBodyContent = changedBodyContent.Replace("\"[FOOTER]\"", footerContent);

                                        var newSendDataItem = JsonConvert.DeserializeObject <SendDataItem>(JsonConvert.SerializeObject(sendDataItem));

                                        newSendDataItem.Body = changedBodyContent;
                                        newSendDataItem.From = sendDataMailAccount.FromMailAddress;

                                        await SendDataBy(sendDataMailAccount, newSendDataItem, subjectContent, changedBodyContent, new List <string>() { to }, useDetailForEveryoneData);
                                    }
                                }
                            }
                            catch (Exception exFor)
                            {
                                var rowData = "";

                                try
                                {
                                    rowData = JsonConvert.SerializeObject(toDataSource.Rows);
                                }
                                catch (Exception)
                                {
                                }

                                LoggerService.GetLogger(ConstantHelper.JobLog).Log(new LogItem()
                                {
                                    LoggerName        = ConstantHelper.JobLog,
                                    Title             = "GenerateSendDataItemFrom SqlqueryData Loop Error",
                                    Message           = exFor.Message,
                                    LogItemProperties = new List <LogItemProperty>()
                                    {
                                        new LogItemProperty("ServiceName", ConstantHelper.JobLog),
                                        new LogItemProperty("ActionName", "GenerateSendDataItemFrom"),
                                        new LogItemProperty("FormData", new { CustomFormDataModel = customFormDataModel, SendDataItem = sendDataItem, RowData = rowData, ToDataSourceColumnNames = toDataSourceColumnNames }),
                                    },
                                    LogLevel  = LogLevel.Error,
                                    Exception = exFor
                                });
                            }
                        }
                    }
                    else
                    {
                        LoggerService.GetLogger(ConstantHelper.JobLog).Log(new LogItem()
                        {
                            LoggerName        = ConstantHelper.JobLog,
                            Title             = "GenerateSendDataItemFrom SqlqueryData Row Count = 0",
                            Message           = "SqlqueryData Row Count = 0",
                            LogItemProperties = new List <LogItemProperty>()
                            {
                                new LogItemProperty("ServiceName", ConstantHelper.JobLog),
                                new LogItemProperty("ActionName", "GenerateSendDataItemFrom"),
                                new LogItemProperty("FormData", new { CustomFormDataModel = customFormDataModel, SendDataItem = sendDataItem }),
                            },
                            LogLevel  = LogLevel.Error,
                            Exception = new ArgumentException("SqlqueryData Row Count = 0")
                        });
                    }
                }
                else if (string.IsNullOrEmpty(detailSqlqueryData) == false)
                {
                    invokeDetailQuery(recipients, bodyContent, null, subjectData);
                }
                else if (recipients.Count > 0)
                {
                    var newSendDataItem = JsonConvert.DeserializeObject <SendDataItem>(JsonConvert.SerializeObject(sendDataItem));
                    await SendDataBy(sendDataMailAccount, newSendDataItem, subjectData, bodyContent, recipients, useDetailForEveryoneData);
                }

                return(true);
            }
            catch (Exception ex)
            {
                LoggerService.GetLogger(ConstantHelper.JobLog).Log(new LogItem()
                {
                    LoggerName        = ConstantHelper.JobLog,
                    Title             = "GenerateSendDataItemFrom Error",
                    Message           = ex.Message,
                    LogItemProperties = new List <LogItemProperty>()
                    {
                        new LogItemProperty("ServiceName", ConstantHelper.JobLog),
                        new LogItemProperty("ActionName", "GenerateSendDataItemFrom"),
                        new LogItemProperty("FormData", new { CustomFormDataModel = customFormDataModel, SendDataItem = sendDataItem }),
                    },
                    LogLevel  = LogLevel.Error,
                    Exception = ex
                });

                return(false);
            }
        }
Beispiel #28
0
 private void RegisterHelper()
 {
     Handlebars.RegisterHelper(helperName, this.ExpandTemplate);
 }
Beispiel #29
0
        private void RegisterHelpers()
        {
            Handlebars.RegisterHelper("#list", (writer, context, parameters) =>
            {
                var items = parameters[0] as IList <Item>;
                var limit = int.Parse(parameters[1].ToString());
                items     = items.Take(5).ToList();
                foreach (var item in items)
                {
                    writer.WriteSafeString("<li>" + item.Name + "</li>");
                }
            });

            Handlebars.RegisterHelper("Compare", (writer, options, context, parameters) =>
            {
                if (parameters.Count() < 3)
                {
                    throw new InvalidOperationException("Handlerbars Helper 'Compare' needs 3 parameters");
                }

                string oprt = parameters[1].ToString();
                bool result = false;
                if (oprt == "==")
                {
                    result = parameters[0] == parameters[2];
                }
                if (oprt == "!=")
                {
                    result = parameters[0] != parameters[2];
                }
                if (oprt == ">")
                {
                    result = decimal.Parse(parameters[0].ToString()) > decimal.Parse(parameters[2].ToString());
                }
                if (oprt == "<")
                {
                    result = decimal.Parse(parameters[0].ToString()) < decimal.Parse(parameters[2].ToString());
                }
                if (oprt == ">=")
                {
                    result = decimal.Parse(parameters[0].ToString()) >= decimal.Parse(parameters[2].ToString());
                }
                if (oprt == "<=")
                {
                    result = decimal.Parse(parameters[0].ToString()) <= decimal.Parse(parameters[2].ToString());
                }
                if (oprt == "&&")
                {
                    result = bool.Parse(parameters[0].ToString()) && bool.Parse(parameters[2].ToString());
                }
                if (oprt == "||")
                {
                    result = bool.Parse(parameters[0].ToString()) || bool.Parse(parameters[2].ToString());
                }

                if (result)
                {
                    options.Template(writer, context);
                }
                else
                {
                    options.Inverse(writer, context);
                }
            });

            Handlebars.RegisterHelper("xif", (writer, options, context, parameters) =>
            {
                string expression = parameters[0].ToString();

                var interpreter = new Interpreter().SetVariable("x", context);
                var isTrue      = interpreter.Eval <bool>(expression);

                if (isTrue)
                {
                    options.Template(writer, context);
                }
                else
                {
                    options.Inverse(writer, context);
                }
            });
        }
        private async Task RegisterHelpersAndPartialsAsync()
        {
            if (_registeredHelpersAndPartials)
            {
                return;
            }
            _registeredHelpersAndPartials = true;

            var basicHtmlLayoutSource = await ReadSourceAsync("Layouts.Basic.html");

            Handlebars.RegisterTemplate("BasicHtmlLayout", basicHtmlLayoutSource);
            var basicTextLayoutSource = await ReadSourceAsync("Layouts.Basic.text");

            Handlebars.RegisterTemplate("BasicTextLayout", basicTextLayoutSource);
            var fullHtmlLayoutSource = await ReadSourceAsync("Layouts.Full.html");

            Handlebars.RegisterTemplate("FullHtmlLayout", fullHtmlLayoutSource);
            var fullTextLayoutSource = await ReadSourceAsync("Layouts.Full.text");

            Handlebars.RegisterTemplate("FullTextLayout", fullTextLayoutSource);

            Handlebars.RegisterHelper("date", (writer, context, parameters) =>
            {
                if (parameters.Length == 0 || !(parameters[0] is DateTime))
                {
                    writer.WriteSafeString(string.Empty);
                    return;
                }
                if (parameters.Length > 0 && parameters[1] is string)
                {
                    writer.WriteSafeString(((DateTime)parameters[0]).ToString(parameters[1].ToString()));
                }
                else
                {
                    writer.WriteSafeString(((DateTime)parameters[0]).ToString());
                }
            });

            Handlebars.RegisterHelper("usd", (writer, context, parameters) =>
            {
                if (parameters.Length == 0 || !(parameters[0] is decimal))
                {
                    writer.WriteSafeString(string.Empty);
                    return;
                }
                writer.WriteSafeString(((decimal)parameters[0]).ToString("C"));
            });

            Handlebars.RegisterHelper("link", (writer, context, parameters) =>
            {
                if (parameters.Length == 0)
                {
                    writer.WriteSafeString(string.Empty);
                    return;
                }

                var text             = parameters[0].ToString();
                var href             = text;
                var clickTrackingOff = false;
                if (parameters.Length == 2)
                {
                    if (parameters[1] is string)
                    {
                        var p1 = parameters[1].ToString();
                        if (p1 == "true" || p1 == "false")
                        {
                            clickTrackingOff = p1 == "true";
                        }
                        else
                        {
                            href = p1;
                        }
                    }
                    else if (parameters[1] is bool)
                    {
                        clickTrackingOff = (bool)parameters[1];
                    }
                }
                else if (parameters.Length > 2)
                {
                    if (parameters[1] is string)
                    {
                        href = parameters[1].ToString();
                    }
                    if (parameters[2] is string)
                    {
                        var p2 = parameters[2].ToString();
                        if (p2 == "true" || p2 == "false")
                        {
                            clickTrackingOff = p2 == "true";
                        }
                    }
                    else if (parameters[2] is bool)
                    {
                        clickTrackingOff = (bool)parameters[2];
                    }
                }

                var clickTrackingText = (clickTrackingOff ? "clicktracking=off" : string.Empty);
                writer.WriteSafeString($"<a href=\"{href}\" target=\"_blank\" {clickTrackingText}>{text}</a>");
            });
        }
Beispiel #31
0
        /// <summary>
        /// Returns a generator singleton for the specified template path.
        /// </summary>
        /// <param name="templatePath"></param>
        /// <returns></returns>
        public Func <object, string> GetGeneratorForTemplate(CodeGenerationTemplateSettings templateSettings)
        {
            var templatePath = templateSettings.TemplatePath;

            if (m_templateGenerators.ContainsKey(templatePath))
            {
                return(m_templateGenerators[templatePath]);
            }

            var targetTemplate = templatePath;

            if (!Path.IsPathRooted(targetTemplate))
            {
                targetTemplate = Path.Combine(Settings.TemplatesPath, targetTemplate);
            }

            if (!File.Exists(targetTemplate))
            {
                throw new FileNotFoundException($"Unable to locate a template at {targetTemplate} - please ensure that a template file exists at this location.");
            }

            var templateContents = File.ReadAllText(targetTemplate);

            Handlebars.RegisterHelper("dehumanize", (writer, context, arguments) =>
            {
                if (arguments.Length != 1)
                {
                    throw new HandlebarsException("{{humanize}} helper must have exactly one argument");
                }

                var str = arguments[0].ToString();

                //Some overrides for values that start with '-' -- this fixes two instances in Runtime.UnserializableValue
                if (str.StartsWith("-"))
                {
                    str = $"Negative{str.Dehumanize()}";
                }
                else
                {
                    str = str.Dehumanize();
                }

                writer.WriteSafeString(str.Dehumanize());
            });

            Handlebars.RegisterHelper("xml-code-comment", (writer, context, arguments) =>
            {
                if (arguments.Length < 1)
                {
                    throw new HandlebarsException("{{code-comment}} helper must have at least one argument");
                }

                var str = arguments[0] == null ? "" : arguments[0].ToString();

                if (String.IsNullOrWhiteSpace(str))
                {
                    switch (context)
                    {
                    case ProtocolDefinitionItem pdi:
                        str = $"{pdi.Name}";
                        break;

                    default:
                        str = context.className;
                        break;
                    }
                }

                var frontPaddingObj = arguments.ElementAtOrDefault(1);
                var frontPadding    = 1;
                if (frontPaddingObj != null)
                {
                    int.TryParse(frontPaddingObj.ToString(), out frontPadding);
                }

                str = Utility.ReplaceLineEndings(str, Environment.NewLine + new StringBuilder(4 * frontPadding).Insert(0, "    ", frontPadding) + "/// ");

                writer.WriteSafeString(str);
            });

            Handlebars.RegisterHelper("typemap", (writer, context, arguments) =>
            {
                var typeDefinition = context as TypeDefinition;
                if (typeDefinition == null)
                {
                    throw new HandlebarsException("{{typemap}} helper expects to be in the context of a TypeDefinition.");
                }

                if (arguments.Length != 1)
                {
                    throw new HandlebarsException("{{typemap}} helper expects exactly one argument - the CodeGeneratorContext.");
                }

                var codeGenContext = arguments[0] as CodeGeneratorContext;
                if (codeGenContext == null)
                {
                    throw new InvalidOperationException("Expected context argument to be non-null.");
                }

                var mappedType = Utility.GetTypeMappingForType(typeDefinition, codeGenContext.Domain, codeGenContext.KnownTypes);
                writer.WriteSafeString(mappedType);
            });

            Handlebars.Configuration.TextEncoder = null;
            return(Handlebars.Compile(templateContents));
        }