Ejemplo n.º 1
0
        public Repository(Project project)
        {
            this.inflector = new Inflector.Inflector(new CultureInfo("en"));

            this.AssemblyByName          = new Dictionary <string, Assembly>();
            this.UnitBySingularName      = new Dictionary <string, Unit>();
            this.InterfaceBySingularName = new Dictionary <string, Interface>();
            this.ClassBySingularName     = new Dictionary <string, Class>();
            this.CompositeByName         = new Dictionary <string, Composite>();
            this.TypeBySingularName      = new Dictionary <string, Type>();

            var projectInfo = new ProjectInfo(project);

            this.CreateUnits();

            this.CreateAssemblies(projectInfo);
            this.CreateAssemblyExtensions(projectInfo);

            this.CreateTypes(projectInfo);
            this.CreateHierarchy(projectInfo);
            this.CreateMembers(projectInfo);

            this.FromReflection(projectInfo);

            this.LinkImplementations();

            this.CreateInheritedProperties();
            this.CreateReverseProperties();
        }
Ejemplo n.º 2
0
 public Pluralizer()
 {
     _inflector = new Inflector.Inflector(CultureInfo.CurrentCulture);
     // This is so a table ending in Alias will not become the enity 'Alia'
     _inflector.CurrentCultureRules.Singulars.Add("(alias)$", "$1");
     // TPPS
     _inflector.CurrentCultureRules.Uncountables.Add("tpps");
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Razorに入力するModelを作成する
        /// 外部ソース用なので、OutListだけ
        /// </summary>
        /// <returns></returns>
        public static dynamic CreateOutModel(Dictionary <string, List <List <string> > > excel)
        {
            var inf    = new Inflector.Inflector(new CultureInfo("en-US"));
            var errors = new List <string>();

            // データ作成順を決める
            var sequence = MakeSequence(excel, errors);

            // 親を持たない各シートのデータ:キーはシート名
            var topDataList = new Dictionary <string, dynamic>();

            // 子情報取得
            var childList = MakeChildData(excel, errors);

            // 子シートデータ
            var childDynamic = new Dictionary <string, Dictionary <string, Dictionary <string, dynamic> > >();

            foreach (var sheetName in sequence)
            {
                if (sheetName.StartsWith(DocumentSheetPrefix))
                {
                    // なにもなし
                    continue;
                }

                // 1つのシート
                var sheet = excel[sheetName];

                // Razorの互換性を持たせるために名前を変更して扱う
                if (sheetName == OutSheet)
                {
                    // OutはRootListとして登録
                    MakeListModel(inf, errors, topDataList, childList, childDynamic, RootListSheet, sheet, string.Empty);
                }
                else if (sheetName.EndsWith(OutListSheetSuffix))
                {
                    // OutListはListとして登録
                    MakeListModel(inf, errors, topDataList, childList, childDynamic, sheetName.Replace(OutListSheetSuffix, ListSheetSuffix), sheet, string.Empty);
                }
            }
            if (errors.Count > 0)
            {
                throw new Exception($"Excelの内容がおかしい:\n{string.Join(",\n", errors)}");
            }

            // 共通変数としてOutGeneral.Index=0を入れる
            var generalData = new Dictionary <string, object>
            {
                { "Index", "0" }
            };

            topDataList.Add("General", generalData.ToDynamic());

            var result = topDataList.ToDynamic();

            return(result);
        }
Ejemplo n.º 4
0
        public Property(Inflector.Inflector inflector, Composite definingType, string name)
        {
            this.AttributeByName  = new Dictionary <string, Attribute>();
            this.AttributesByName = new Dictionary <string, Attribute[]>();

            this.DefiningType = definingType;
            this.inflector    = inflector;
            this.name         = name;
        }
Ejemplo n.º 5
0
        private string BuildResultSetName(string baseIdentifierValue)
        {
            var name = ActionPrefixRemover.Remove(baseIdentifierValue);

            var s = new Inflector.Inflector(CultureInfo.CurrentCulture);

            name = s.Singularize(name);

            return(name + "Dto");;
        }
Ejemplo n.º 6
0
        public static void PluralizeTableName(this ModelBuilder modelBuilder)
        {
            var inflector = new Inflector.Inflector(new System.Globalization.CultureInfo("en-US"));
            var models    = modelBuilder.Model.GetEntityTypes().Where(s => !typeof(ValueObject).IsAssignableFrom(s.ClrType)).ToList();

            foreach (var item in models)
            {
                string tableName = inflector.Pluralize(item.GetTableName()) ?? item.Name;
                item.SetTableName(tableName);
            }
        }
Ejemplo n.º 7
0
 protected Composite(Inflector.Inflector inflector, Guid id, string name)
     : base(id, name)
 {
     this.inflector             = inflector;
     this.AttributeByName       = new Dictionary <string, Attribute>();
     this.AttributesByName      = new Dictionary <string, Attribute[]>();
     this.ImplementedInterfaces = new List <Interface>();
     this.PropertyByRoleName    = new Dictionary <string, Property>();
     this.DefinedReversePropertyByAssociationName   = new Dictionary <string, Property>();
     this.InheritedReversePropertyByAssociationName = new Dictionary <string, Property>();
     this.MethodByName = new Dictionary <string, Method>();
 }
Ejemplo n.º 8
0
        private static string InferTableName(CProtoMessage message)
        {
            var tableName = message.MessageName;

            tableName = tableName.ReplaceAtStart("GetAll", "");

            tableName = tableName.ReplaceAtStart("Get", "");
            tableName = tableName.ReplaceAtStart("Is", "");

            tableName = tableName.ReplaceAtStart("List", "");

            tableName = tableName.ReplaceAtStart("Add", "");
            tableName = tableName.ReplaceAtStart("Save", "");
            tableName = tableName.ReplaceAtStart("Approve", "");

            tableName = tableName.Replace("Find", "");

            tableName = tableName.Replace("Check", "");

            tableName = tableName.Replace("Read", "");

            tableName = tableName.Replace("Create", "");

            tableName = tableName.Replace("Queue", "");

            tableName = tableName.Replace("Dequeue", "");

            tableName = tableName.Replace("Delete", "");

            tableName = tableName.Replace("Response", "");

            tableName = tableName.Replace("Request", "");

            var indexOfBy = tableName.IndexOf("By", StringComparison.CurrentCulture);

            if (indexOfBy > -1)
            {
                tableName = tableName.Substring(0, indexOfBy);
            }

            var s = new Inflector.Inflector(CultureInfo.CurrentCulture);

            tableName = s.Singularize(tableName);
            return(tableName);
        }
Ejemplo n.º 9
0
 public Class(Inflector.Inflector inflector, Guid id, string name)
     : base(inflector, id, name) =>
     this.PartialByDomainName = new Dictionary <string, PartialClass>();
Ejemplo n.º 10
0
 private void SetupInflector()
 {
     Inflector.Inflector.SetDefaultCultureFunc = () => Thread.CurrentThread.CurrentUICulture;
     _inflector = new Inflector.Inflector(new CultureInfo("en"));
 }
 public Pluralizer()
 {
     _inflector = new Inflector.Inflector(CultureInfo.CreateSpecificCulture("en-US"));
 }
Ejemplo n.º 12
0
        static void Main()
        {
            var inf = new Inflector.Inflector(new CultureInfo("en-US"));

            Console.WriteLine(inf.Pluralize("cost"));
            Console.WriteLine(inf.Pluralize("sword"));
            Console.WriteLine(inf.Pluralize("water"));
            Console.WriteLine(inf.Pluralize("data"));
            Console.WriteLine(inf.Pluralize("child"));
            Console.WriteLine(inf.Pluralize("apple"));
            Console.WriteLine(inf.Pluralize("Apple"));
            Console.WriteLine(inf.Pluralize("History"));
            Console.WriteLine("---------------------------------");
            Console.WriteLine(inf.Singularize("oranges"));
            Console.WriteLine(inf.Singularize("Lemons"));
            Console.WriteLine(inf.Singularize("templates"));
            Console.WriteLine(inf.Singularize("children"));
            Console.WriteLine(inf.Singularize("boxes"));
            Console.WriteLine("---------------------------------");
            Console.WriteLine(inf.Pascalize("tryCatchPrecure"));    // できる
            Console.WriteLine(inf.Pascalize("try-catch-precure"));  // できない
            Console.WriteLine(inf.Pascalize("try catch precure"));  // できない
            Console.WriteLine(inf.Camelize("TryCatchPrecure"));     // できる
            Console.WriteLine(inf.Camelize("try_catch_precure"));   // できる
            Console.WriteLine(inf.Dasherize("TryCatchPrecure"));    // TryCatchPrecure  // 未実装っぽい
            Console.WriteLine(inf.Humanize("TryCatchPrecure"));     // Trycatchprecure  // よく分からん変換
            Console.WriteLine(inf.Humanize("try_catch_precure"));   // Try catch precure
            Console.WriteLine(inf.Ordinalize(3));                   // 1st 2nd...
            Console.WriteLine(inf.Ordinalize(54321));               // 54321st
            Console.WriteLine(inf.Titleize("try-catch-precure"));   // Try Catch Precure
            Console.WriteLine(inf.Titleize("try_catch_precure"));   // Try Catch Precure
            Console.WriteLine(inf.Titleize("TryCatchPrecure"));     // Try Catch Precure // 大文字とスペース区切りにする
            Console.WriteLine(inf.Uncapitalize("TryCatchPrecure")); // tryCatchPrecure // わからん
            Console.WriteLine(inf.Underscore("TryCatchPrecure"));   // try_catch_precure // snake caseにする


            //var a = TreeNode<string>.GetDirectoryFileList(@"C:\Users\ginpay\source\repos\DigitalMegaFlare\DigitalMegaFlare\wwwroot\files\razors");

            //foreach (var item in a.Children)
            //{
            //    Console.WriteLine(item.Value);
            //}


            // RazorEngineを使ったシステムの作成
            // TODO:datファイルを読み込んで、テンプレートとして使用する
            // データは最終的にサーバのどこかに置くので、ここでは適当なデータフォルダ作ってアクセス

            // TODO:Modelデータを作成する

            //OKボタンがクリックされたとき、選択されたファイルを読み取り専用で開く
            //Console.WriteLine("--------");
            //using (var reader = new StreamReader("Template/Test.dat"))
            //{
            //    string text = reader.ReadToEnd();
            //    Console.WriteLine(text);

            //    var model1 = new { Name = "World" };
            //    var result1 = Engine.Razor.RunCompile(text, "templateKey", null, model1);
            //    Console.WriteLine(result1);
            //}

            //Console.WriteLine("--------");

            // --------------------------------------------------
            //// スニペットを生成する
            //var sg = new SnippetGenerator();

            //var imports = new List<string>
            //{
            //    "System",
            //    "System.Collections.Generic"
            //};
            //var declarations = new List<Literal>
            //{
            //    new Literal("Id", "通し番号", "0"),
            //    new Literal("Expression", "ここに列挙体を指定する", "switchOn"),
            //    new Literal("Cases", Function.GenerateSwitchCases, "$expression$"),
            //    new Literal("Name", "名前クラス", "ginpay", Function.ClassName),
            //    new Literal("SystemConsole", Function.SimpleTypeName, "global::System.Console")
            //};
            //var data = new SnippetData
            //{
            //    Imports = imports,
            //    Declarations = declarations
            //};
            //var sw = sg.MakeSnippetXml(data);
            //Console.WriteLine(sw.ToString());
            // --------------------------------------------------

            //// パラメータを作って
            //var context = new GenerationContext
            //{
            //    NamespaceName = "Ananan",
            //    TypeSuffix = "TottemoDaisuki",
            //    RepeatCount = 2
            //};

            //// テキストを生成して
            //var text = new MyCodeGenerator(context).TransformText();

            //Console.WriteLine(text);

            //// UTF8(BOMなし)で出力
            //File.WriteAllText(outputPath, text, new UTF8Encoding(false));

            //Console.WriteLine("Success generate:" + outputPath);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// やっつけ
        /// </summary>
        /// <param name="inf"></param>
        /// <param name="errors"></param>
        /// <param name="topDataList"></param>
        /// <param name="childList"></param>
        /// <param name="childDynamic"></param>
        /// <param name="sheetName"></param>
        /// <param name="sheet"></param>
        /// <param name="parentName"></param>
        /// <returns></returns>
        private static string MakeListModel(Inflector.Inflector inf, List <string> errors, Dictionary <string, dynamic> topDataList, Dictionary <string, List <string> > childList, Dictionary <string, Dictionary <string, Dictionary <string, dynamic> > > childDynamic, string sheetName, List <List <string> > sheet, string parentName)
        {
            try
            {
                // キー列取得
                var keyIndex = GetIndex(sheet, KeyCulumn);

                // 親があるか
                var parentIndex = GetIndex(sheet, ParentCulumn);

                // リスト
                if (sheet.Count > 2)
                {
                    // 親があってもなくてもトップからデータアクセス
                    var topData = new List <dynamic>();

                    // 親Key別データ、親が無い場合はシート全体のデータ(親キー、1行データ)
                    var dataByParent = new Dictionary <string, List <dynamic> >();

                    // 2行目まで読まない
                    for (int row = 2; row < sheet.Count; row++)
                    {
                        // 1行読む
                        var parentKeys = new List <string>();   // 対象の親のKey
                        if (parentIndex == -1)
                        {
                            // 親がない場合は-1に格納する
                            parentKeys.Add("-1");
                        }

                        var rowData = new Dictionary <string, object>();
                        for (int col = 0; col < sheet[row].Count; col++)
                        {
                            // 列を読む
                            if (col == parentIndex)
                            {
                                // 親参照はdynamicデータに登録しないが、子dynamicデータリストに保持させるための情報を取得する
                                var split = sheet[row][col].Split('.');
                                parentName = split[0];
                                for (int i = 1; i < split.Length; i++)
                                {
                                    parentKeys.Add(split[i]);
                                }
                            }
                            else if (col == keyIndex)
                            {
                                // キー列の場合、子を追加
                                var key = sheet[row][col];  // 書かれているKeyを取得
                                AddChildDynamic(childList, childDynamic, sheetName, key, rowData);
                            }
                            else if (sheet[0][col].StartsWith(BoolCulumnPrefix))
                            {
                                // Isならば、bool型判定
                                var val = sheet[row][col];
                                try
                                {
                                    rowData.Add(sheet[0][col], ToBool(sheet[row][col]));
                                }
                                catch (Exception)
                                {
                                    errors.Add($"{BoolCulumnPrefix}で始まってる項目なのにboolにできない。sheet:{sheetName} row:{row} column:{col} value:{val}");
                                }
                            }
                            else if (sheet[0][col].EndsWith(InflectCulumn))
                            {
                                // 語尾がNameならば、フィールドを余分に作る
                                var baseName = sheet[0][col].Remove(sheet[0][col].LastIndexOf(InflectCulumn), InflectCulumn.Length);
                                rowData.Add(sheet[0][col], sheet[row][col]);
                                rowData.Add(baseName + Camel, inf.Camelize(sheet[row][col]));
                                rowData.Add(baseName + Pascal, inf.Pascalize(sheet[row][col]));
                                rowData.Add(baseName + Plural, inf.Pluralize(sheet[row][col]));
                                rowData.Add(baseName + CamelPlural, inf.Camelize(inf.Pluralize(sheet[row][col])));
                                rowData.Add(baseName + PascalPlural, inf.Pascalize(inf.Pluralize(sheet[row][col])));
                                rowData.Add(baseName + Snake, inf.Underscore(sheet[row][col]));
                                rowData.Add(baseName + Hyphen, inf.Underscore(sheet[row][col]).Replace('_', '-'));
                            }
                            else
                            {
                                // ParentでもKeyでもない通常の列
                                rowData.Add(sheet[0][col], sheet[row][col]);
                            }
                        }

                        // 行データをdynamic化し、親Key別のリストに追加する。
                        // 親がないシートは必ず1件の同じリストに入る(parentKeyは"-1")
                        foreach (var parentKey in parentKeys)
                        {
                            if (!dataByParent.ContainsKey(parentKey))
                            {
                                dataByParent.Add(parentKey, new List <dynamic>());
                            }
                            dataByParent[parentKey].Add(rowData.ToDynamic());
                        }
                        topData.Add(rowData.ToDynamic());
                    }

                    // 親Key別のリストをどこかに登録する。
                    foreach (var dataByParentKey in dataByParent.Keys)
                    {
                        if (parentIndex >= 0)
                        {
                            // 親がある場合は、データを溜めておく
                            AddChildrenData(childDynamic, parentName, dataByParentKey, sheetName, dataByParent[dataByParentKey]);

                            // 親子でなくてもModelからListにアクセスできるようにするため
                            // 親が無いシートと同様にトップにもデータを入れる
                            if (!topDataList.ContainsKey(sheetName))
                            {
                                topDataList.Add(sheetName, topData);
                            }
                        }
                        else
                        {
                            // 親が無いシートはトップにデータを入れる
                            topDataList.Add(sheetName, dataByParent[dataByParentKey]);
                        }
                    }
                }

                return(parentName);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Ejemplo n.º 14
0
        private string InferDomainModelName(string name)
        {
            if (name.Contains("By"))
            {
                name = name.Substring(0, name.IndexOf("By"));
            }
            if (name.StartsWith("Get"))
            {
                name = name.Substring(3, name.Length - 3);
            }
            if (name.StartsWith("Is"))
            {
                name = name.Substring(2, name.Length - 2);
            }

            if (name.StartsWith("Read"))
            {
                name = name.Substring(4, name.Length - 4);
            }
            if (name.StartsWith("List"))
            {
                name = name.Substring(4, name.Length - 4);
            }

            if (name.StartsWith("Find"))
            {
                name = name.Substring(4, name.Length - 4);
            }

            if (name.StartsWith("Check"))
            {
                name = name.Substring(5, name.Length - 5);
            }

            if (name.StartsWith("Create"))
            {
                name = name.Substring(6, name.Length - 6);
            }
            if (name.StartsWith("Update"))
            {
                //name = name.Substring(6, name.Length - 6);
            }

            if (name.StartsWith("Queue"))
            {
                name = name.Substring(5, name.Length - 5);
            }
            if (name.StartsWith("Dequeue"))
            {
                name = name.Substring(7, name.Length - 7);
            }

            if (name.StartsWith("All"))
            {
                name = name.Substring(3, name.Length - 3);
            }

            if (name.StartsWith("Update"))
            {
                if (name.EndsWith("Response"))
                {
                    name = name.Replace("Response", "Model");
                }
            }
            else
            {
                if (name.EndsWith("Response"))
                {
                    name = name.Substring(0, name.LastIndexOf("Response"));
                }
            }

            var s = new Inflector.Inflector(CultureInfo.CurrentCulture);

            name = s.Singularize(name);
            return($"{name}");
        }
Ejemplo n.º 15
0
 public Interface(Inflector.Inflector inflector, string name)
     : base(inflector, name)
 {
     this.PartialByAssemblyName       = new Dictionary <string, PartialInterface>();
     this.InheritedPropertyByRoleName = new Dictionary <string, Property>();
 }
Ejemplo n.º 16
0
 public Interface(Inflector.Inflector inflector, Guid id, string name)
     : base(inflector, id, name)
 {
     this.PartialByDomainName         = new Dictionary <string, PartialInterface>();
     this.InheritedPropertyByRoleName = new Dictionary <string, Property>();
 }
Ejemplo n.º 17
0
 public Class(Inflector.Inflector inflector, string name)
     : base(inflector, name)
 {
     this.PartialByAssemblyName = new Dictionary <string, PartialClass>();
 }
Ejemplo n.º 18
0
 public Compiler() : base()
 {
     Inflector = new Inflector.Inflector();
 }
Ejemplo n.º 19
0
        public CClass Convert(CTable table, IEnumerable <CTable> allTables, bool convertForeignKeysToObjects)
        {
            var @class = new CClass(table.TableName);

            @class.DerivedFrom = table;
            @class.Namespace   = new CNamespace {
                NamespaceName = table.Schema.SchemaName
            };

            @class.NamespaceRef.Add(new CNamespaceRef()
            {
                ReferenceTo = new CNamespace()
                {
                    NamespaceName = "System"
                }
            });
            @class.NamespaceRef.Add(new CNamespaceRef()
            {
                ReferenceTo = new CNamespace()
                {
                    NamespaceName = "System.Collections.Generic"
                }
            });

            foreach (var column in table.Column)
            {
                if (!convertForeignKeysToObjects || !column.ForeignKeyColumn.Any())
                {
                    var prop = new CProperty();
                    prop.PropertyName = column.ColumnName;
                    prop.Type         = column.ColumnType.ToClrTypeName();
                    @class.Property.Add(prop);
                }
                else
                {
                    //we add foreign keys later, as objects
                }
            }

            if (convertForeignKeysToObjects && allTables != null)
            {
                //add foreign keys as objects
                //todo: put this core logic into extension method
                foreach (var allTable in allTables)
                {
                    foreach (var allTableColumn in allTable.Column)
                    {
                        foreach (var allTableColumnFK in allTableColumn.ForeignKeyColumn)
                        {
                            if (allTableColumnFK.Table.Schema.SchemaName == table.Schema.SchemaName &&
                                allTableColumnFK.Table.TableName == table.TableName) //todo: use a fancy compare method
                            {
                                var prop = new CProperty();
                                var s    = new Inflector.Inflector(CultureInfo.CurrentCulture);

                                prop.PropertyName = s.Pluralize(allTable.TableName);
                                prop.Type         = $"IEnumerable<{allTable.TableName}>"; //todo: how can we determine if is a collection or not? may be able to use DerivedFrom
                                @class.Property.Add(prop);
                            }
                        }
                    }
                }
            }



            return(@class);
        }
Ejemplo n.º 20
0
        /// <summary>
        ///  Updates a project
        /// </summary>
        /// <param name="output">Project root folder</param>
        /// <param name="name">Name (=== namespace)</param>
        /// <param name="xml">XML file what is wanted.</param>
        /// <returns></returns>
        static int DoUpdate(string output, string name, string xml)
        {
            Console.WriteLine($"Updating {output} {name} {xml}");
            var sr = new XmlSerializer(typeof(Model));

            using var stream = File.OpenRead(xml);
            var model = (Model)sr.Deserialize(stream);

            // Templates use Invariant culture so embedded datestamps are mm/dd/yyyy.
            var inflector = new Inflector.Inflector(Thread.CurrentThread.CurrentUICulture);

            // https://docs.microsoft.com/en-us/visualstudio/modeling/run-time-text-generation-with-t4-text-templates?view=vs-2019;

            var appContext = "CrudDbContext";

            var template       = new ClassModelTemplate(model, name);
            var content        = template.TransformText();
            var dataFolder     = Path.Combine(output, "Data");
            var modelDest      = Path.Combine(dataFolder, "Model.cs");
            var servicesFolder = Path.Combine(output, "Services");

            Directory.CreateDirectory(dataFolder);
            Directory.CreateDirectory(servicesFolder);

            // Generate class model
            File.WriteAllText(modelDest, content);
            var dcTemplate = new DataContextTemplate(model, name, appContext);
            var dcContent  = dcTemplate.TransformText();
            var dcDest     = Path.Combine(dataFolder, "CrudDbContext.cs");

            File.WriteAllText(dcDest, dcContent);
            var servicesToRegister = new List <string>();
            var navLinks           = new List <NavLink>();

            // Generate grid services
            foreach (var view in model.Views)
            {
                var m = model.Classes.First(x => x.Name == view.ClassName);

                var references = m.Fields.Where(x => x.IsReference);
                var includes   = string.Join("", references.Select(r => $".Include(x => x.{r.Name})"));

                var query              = $"{m.Name}{includes}"; //context.Invoice.Include(x => x.InvoiceLines).Include(x => x.Customer).ToList();
                var className          = m.Name + "GridService";
                var gridTemplate       = new GridServiceTemplate(name, className, appContext, m.Name, query, m.Name + "Grid", view.Filters);
                var dest               = Path.Combine(servicesFolder, className + ".cs");
                var gridServiceContent = gridTemplate.TransformText();
                File.WriteAllText(dest, gridServiceContent);
                servicesToRegister.Add(className);
            }

            // Generate views
            foreach (var view in model.Views)
            {
                var m = model.Classes.First(x => x.Name == view.ClassName);

                var pageName         = m.Name.ToLower();
                var filterName       = m.Name + "Filter";
                var gridViewTemplate = new GridViewTemplate($"/{pageName}", name, m.Name, m.Name + "GridService", m.Name + "CrudService", m, view.Filters, filterName);

                navLinks.Add(new NavLink {
                    Url = pageName, Text = view.Name
                });

                // add View to avoid class name clash with model in XXX.Data
                var viewClass       = m.Name + "View";
                var dest            = Path.Combine(output, "Pages", viewClass + ".razor");
                var gridViewContent = gridViewTemplate.TransformText();
                File.WriteAllText(dest, gridViewContent);
                var codeBehindPath = Path.Combine(output, "Pages", viewClass + ".razor.cs");
                if (File.Exists(codeBehindPath))
                {
                    Console.WriteLine("Not creating file {0} - already exists", codeBehindPath);
                }
                else
                {
                    var codeBehindTemplate = new GridViewCodeBehindTemplate(name, viewClass, m.Name);
                    File.WriteAllText(codeBehindPath, codeBehindTemplate.TransformText());
                }

                var filterPath = Path.Combine(output, "Shared", filterName + ".razor");
                if (view.Filters != null && view.Filters.Any())
                {
                    // add a selector at the top
                    var filterTemplate = new FilterTemplate(view.Filters);
                    File.WriteAllText(filterPath, filterTemplate.TransformText());
                }
                else
                {
                    if (File.Exists(filterPath))
                    {
                        Console.WriteLine("Please delete unrequired file {0}", filterPath);
                    }
                }
            }
            foreach (var m in model.Classes)
            {
                var className           = m.Name + "CrudService";
                var crudServiceTemplate = new CrudServiceTemplate(name, className, appContext, m.Name);
                var crudServiceContent  = crudServiceTemplate.TransformText();
                var dest = Path.Combine(servicesFolder, className + ".cs");
                File.WriteAllText(dest, crudServiceContent);
                servicesToRegister.Add(className);
            }
            foreach (var reference in model.Classes.SelectMany(x => x.Fields).Where(x => x.IsReference).Select(x => x.References).Distinct())
            {
                var @class                = model.Classes.First(x => x.Name == reference);
                var className             = @class.Name + "LookupService";
                var lookupServiceTemplate = new LookupServiceTemplate(appContext, name, className, @class.Key.Name, @class);
                var lsContent             = lookupServiceTemplate.TransformText();
                var dest = Path.Combine(servicesFolder, className + ".cs");
                File.WriteAllText(dest, lsContent);
                servicesToRegister.Add(className);
            }

            // Service registration with DI container
            var regTemplate = new CrudServiceRegistrationTemplate(name, servicesToRegister);
            var regContent  = regTemplate.TransformText();
            var regCsPath   = Path.Combine(output, "CrudServiceRegistration.cs");

            File.WriteAllText(regCsPath, regContent);

            var navMenuTemplate = new NavMenuTemplate(navLinks);
            var navMenuPath     = Path.Combine(output, "Shared", "CrudNavMenu.razor");

            File.WriteAllText(navMenuPath, navMenuTemplate.TransformText());



            return(0);
        }
 public Pluralizer([NotNull] Inflector.Inflector inflector)
 {
     _inflector = inflector ?? throw new ArgumentNullException(nameof(inflector));
 }
Ejemplo n.º 22
0
        /// <summary>
        /// Razorに入力するModelを作成する
        /// </summary>
        /// <param name="excel">Excelデータ</param>
        /// <param name="outScript"></param>
        /// <returns></returns>
        public static dynamic CreateModel(Dictionary <string, List <List <string> > > excel, Dictionary <string, string> outScript = null)
        {
            try
            {
                var inf    = new Inflector.Inflector(new CultureInfo("en-US"));
                var errors = new List <string>();

                // データ作成順を決める
                var sequence = MakeSequence(excel, errors);

                // 親を持たない各シートのデータ:キーはシート名
                var topDataList = new Dictionary <string, dynamic>();

                // 外部スクリプトの生成結果を追加
                if (outScript != null)
                {
                    var outData = new Dictionary <string, object>();
                    foreach (var script in outScript)
                    {
                        outData.Add(script.Key, script.Value);
                    }
                    topDataList.Add(OutSheet, outData.ToDynamic());
                }

                // 子情報取得
                var childList = MakeChildData(excel, errors);

                // 子シートデータ
                var childDynamic = new Dictionary <string, Dictionary <string, Dictionary <string, dynamic> > >();

                // 子シートから順番にデータ作成
                var isRequiredSheetExists = false;
                var isRootListExists      = false;
                foreach (var sheetName in sequence)
                {
                    // 1つのシート
                    var sheet = excel[sheetName];


                    // 親シート名
                    var parentName = string.Empty;

                    // キー取得
                    var keyIndex = GetIndex(sheet, KeyCulumn);

                    if (sheetName.StartsWith(DocumentSheetPrefix))
                    {
                        // なにもなし
                        continue;
                    }
                    else if (sheetName.EndsWith(OutListSheetSuffix) || sheetName == OutSheet)
                    {
                        // OutList:外部入力リスト
                        // なにもなし
                        continue;
                    }
                    else if (sheetName.EndsWith(ListSheetSuffix))
                    {
                        // List:通常リスト
                        // 必須シート存在チェック
                        if (sheetName == RootListSheet)
                        {
                            isRootListExists = true;
                        }
                        parentName = MakeListModel(inf, errors, topDataList, childList, childDynamic, sheetName, sheet, parentName);
                    }
                    else
                    {
                        // 必須シート存在チェック
                        if (sheetName == SettingsSheet)
                        {
                            isRequiredSheetExists = true;
                        }

                        // 今回、通常シートは親子関係を持たない。持たせたい場合はListシートと同様に実装すればできるはず。
                        // …というか、リストの下位互換かも。通常シート不要説。
                        // 通常シート:1列目が名前、2列目が値
                        if (sheet.Count > 2)
                        {
                            var data = new Dictionary <string, object>();
                            // 2行目まで読まない
                            for (int row = 2; row < sheet.Count; row++)
                            {
                                var name = sheet[row][0];
                                // 必須項目チェック

                                var value = sheet[row][1];
                                if (name.StartsWith(BoolCulumnPrefix))
                                {
                                    // bool型判定
                                    var val = sheet[row][1];
                                    try
                                    {
                                        data.Add(name, ToBool(sheet[row][1]));
                                    }
                                    catch (Exception)
                                    {
                                        errors.Add($"{BoolCulumnPrefix}で始まってる項目なのにboolにできない。sheet:{sheetName} row:{row} value:{val}");
                                    }
                                }
                                else
                                {
                                    data.Add(name, value);
                                }
                            }
                            // 親がないのでトップデータリストに追加
                            topDataList.Add(sheetName, data.ToDynamic());
                        }
                    }
                }
                if (!isRootListExists)
                {
                    errors.Add($"{RootListSheet}という名前のシートがない。");
                }
                if (!isRequiredSheetExists)
                {
                    errors.Add($"{SettingsSheet}という名前のシートがない。");
                }
                if (errors.Count > 0)
                {
                    throw new Exception($"Excelの内容がおかしい:\n{string.Join(",\n", errors)}");
                }

                // 共通変数としてGeneral.Index=0を入れる
                var generalData = new Dictionary <string, object>
                {
                    { "Index", "0" }
                };
                topDataList.Add("General", generalData.ToDynamic());

                var result = topDataList.ToDynamic();

                return(result);
            }
            catch (Exception e)
            {
                throw e;
            }
        }