public void Pascalize()
 {
     foreach (var pair in TestData)
     {
         Assert.AreEqual(Inflector.Pascalize(pair.Key), pair.Value);
     }
 }
        public string GenerateSerializeCallFor(string namespacePostfix, string dtoNamespacePrefix, string httpVerb,
                                               bool prependSchemaNameIndicator, IEntityType entity)
        {
            StringBuilder sb = new StringBuilder();
            string        clientMethodCallPrefix = httpVerb.ToLowerInvariant() == "post" ? "Create" : "Update";
            string        serializeCallPostfix   = httpVerb.ToLowerInvariant() == "post" ? "Post" : "Put";
            string        entityName             = Inflector.Pascalize(entity.ClrType.Name);
            string        tablenamePlural        = Inflector.Pluralize(entity.ClrType.Name);
            string        keylist = "item." + string.Join("}/{item.", entity.GetKeys().Select(k => k.Properties[0].Name));

            sb.AppendLine($"\t\t\tpublic async Task<IHttpCallResultCGHT<{dtoNamespacePrefix}.{entityName}>> {clientMethodCallPrefix}{entityName}Async({dtoNamespacePrefix}.{entityName} item)");
            sb.AppendLine("\t\t\t{");
            sb.AppendLine($"\t\t\t\tvar retVal = await SerializationHelper.Instance.SerializeCallResults{serializeCallPostfix}<{dtoNamespacePrefix}.{entityName}>(");
            sb.AppendLine("\t\t\t\t\tLog, HttpClient,");
            sb.Append($"\t\t\t\t\t$\"{namespacePostfix}/{tablenamePlural}/");
            if (httpVerb.ToLowerInvariant() != "post")
            {
                sb.Append($"{{{keylist}}}");
            }
            sb.AppendLine($"\", item);");

            sb.AppendLine("\t\t\t\treturn retVal;");
            sb.AppendLine("\t\t\t}");
            sb.AppendLine(string.Empty);

            return(sb.ToString());
        }
        public string GenerateHeader(string baseNamespace, string namespacePostfix,
                                     string classNamespace,
                                     string modelsBackedByDtoInterfaceNamespace,
                                     string webApiDataServiceInterfaceNamespace,
                                     string webApiDataServiceInterfaceClassName,
                                     IEntityType entity)
        {
            string entityName = Inflector.Pascalize(entity.ClrType.Name);

            StringBuilder sb = new StringBuilder();

            sb.AppendLine($"using CodeGenHero.Logging;");
            sb.AppendLine($"using CodeGenHero.DataService;");
            sb.AppendLine($"using System;");
            sb.AppendLine($"using System.Collections.Generic;");
            sb.AppendLine($"using System.Linq;");
            sb.AppendLine($"using {webApiDataServiceInterfaceNamespace};");
            sb.AppendLine($"using {modelsBackedByDtoInterfaceNamespace};");
            sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"using xDTO = { baseNamespace }.DTO;" : $"using xDTO = {baseNamespace}.DTO.{namespacePostfix};");

            sb.AppendLine(string.Empty);
            sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {classNamespace}" : $"namespace {classNamespace}.{namespacePostfix}");
            sb.AppendLine($"{{");

            sb.AppendLine(string.Empty);
            sb.AppendLine(GenerateLoadRequestEventArgs(entity: entity));
            sb.AppendLine(string.Empty);
            sb.AppendLine($"\tpublic partial class {entityName} : BaseModel<{webApiDataServiceInterfaceClassName}>, I{entityName}");

            sb.AppendLine("\t{");

            return(sb.ToString());
        }
Пример #4
0
        public string GenerateConstructor(
            bool prependSchemaNameIndicator,
            bool dtoIncludeRelatedObjects,
            IEntityType entity,
            IList <IEntityNavigation> excludedNavigationProperties)
        {
            StringBuilder sb         = new StringBuilder();
            string        entityName = Inflector.Pascalize(entity.ClrType.Name);

            // Constructor .ctor code
            sb.AppendLine($"\t\tpublic {entityName}()");
            sb.AppendLine("\t\t{");

            if (dtoIncludeRelatedObjects)
            {
                #region Collection Initialization

                // Commenting out default initialization of collections to better align with being able to detect/lazy load data in the model classes.
                //foreach (var reverseFK in table.ReverseNavigations)
                //{
                //	string name = reverseFK.RefTableHumanCase;
                //	bool excludeCircularReferenceNavigationIndicator = reverseFK.ExcludeCircularReferenceNavigationIndicator(excludedNavigationProperties);

                //	sb.Append($"\t\t\t");
                //	if (excludeCircularReferenceNavigationIndicator)
                //	{   // Include the line, but comment it out.
                //		sb.Append($"// ");
                //	}

                //	if (!(reverseFK.Relationship == Library.Enums.Relationship.OneToOne))
                //	{
                //		sb.Append($"{name} = new System.Collections.Generic.List<{reverseFK.FullRefTableName}>();");
                //	}

                //	if (excludeCircularReferenceNavigationIndicator)
                //	{
                //		sb.AppendLine(EXCLUDEPERNAVIGATIONPROPERTYCONFIGURATION);
                //	}
                //	else
                //	{
                //		sb.AppendLine(string.Empty);
                //	}
                //}

                //if (table.ReverseNavigations.Count > 0)
                //{
                //	sb.AppendLine(string.Empty);
                //}

                #endregion Collection Initialization
            }

            sb.AppendLine("\t\t\tInitializePartial();");
            sb.AppendLine("\t\t}");

            return(sb.ToString());
        }
Пример #5
0
        internal string GenerateInterface(string baseNamespace, string namespacePostfix, string classNamespace,
                                          bool InludeRelatedObjects, bool prependSchemaNameIndicator, IList <IEntityNavigation> excludeCircularReferenceNavigationProperties,
                                          IEntityType entity)
        {
            var    sb         = new StringBuilder();
            string entityName = Inflector.Pascalize(Inflector.Humanize(entity.ClrType.Name));

            sb.AppendLine($"using System;");
            sb.AppendLine($"using System.Collections.Generic;");
            sb.AppendLine($"using System.Text;");
            sb.AppendLine($"using System.Threading.Tasks;");
            sb.AppendLine(string.Empty);
            sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.DataAccess" : $"namespace {baseNamespace}.DataAccess.{namespacePostfix}");
            sb.AppendLine($"{{");
            sb.AppendLine($"\tpublic partial interface I{entityName}Dal");
            sb.AppendLine($"\t{{");

            ////////////
            // DELETE
            ////////////
            sb.AppendLine($"\t bool Delete({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())});");
            sb.AppendLine(string.Empty);
            ////////////
            // EXISTS
            ////////////
            sb.AppendLine($"\t bool Exists({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())});");
            sb.AppendLine(string.Empty);
            ////////////
            // SINGLE GET
            ////////////
            sb.AppendLine($"\t {entityName}Entity Get({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())});");
            sb.AppendLine(string.Empty);
            ////////////
            // List GET
            ////////////
            sb.AppendLine($"\t List<{entityName}Entity> Get();");
            sb.AppendLine(string.Empty);
            ////////////
            // INSERT
            ////////////
            sb.AppendLine($"\t {entityName}Entity Insert({entityName}Entity {Inflector.ToLowerFirstCharacter(entityName)});");
            sb.AppendLine(string.Empty);
            ////////////
            // UPDATE
            ////////////

            sb.AppendLine($"\t {entityName}Entity Update({entityName}Entity {Inflector.ToLowerFirstCharacter(entityName)});");

            sb.AppendLine(string.Empty);

            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t}}");
            sb.AppendLine($"}}");

            return(sb.ToString());
        }
        private string GenerateModelMapperExtensionMethods(IList <IEntityType> entityTypes,
                                                           string methodName, string returnNamespacePrefix, string fromNamespacePrefix, bool prependSchemaNameIndicator)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var entity in entityTypes)
            {
                var    k                      = entity.FindPrimaryKey();
                string entityName             = Inflector.Pascalize(entity.ClrType.Name);
                var    entityProperties       = entity.GetProperties().OrderBy(n => n.Name).ToList();
                bool   hasMultiplePrimaryKeys = entity.FindPrimaryKey().Properties.Count > 1;
                string compositePKFieldName   = string.Empty;
                string compositePKFieldValue  = string.Empty;
                sb.AppendLine($"\t\tpublic static {returnNamespacePrefix}.{entityName} {methodName}(this {fromNamespacePrefix}.{entityName} source)");
                sb.AppendLine($"\t\t{{");
                sb.AppendLine($"\t\t\treturn new {returnNamespacePrefix}.{entityName}()");
                sb.AppendLine($"\t\t\t{{");
                var primaryKey = entity.FindPrimaryKey();
                for (int i = 0; i < entityProperties.Count(); i++)
                {
                    var    property     = entityProperties[i];
                    string propertyName = Inflector.Pascalize(property.Name);

                    string ctype      = GetCType(property);
                    var    simpleType = ConvertToSimpleType(ctype);

                    if (!IsUnknownType(property))
                    {
                        sb.AppendLine($"\t\t\t\t{propertyName} = source.{propertyName},");
                    }

                    if (primaryKey.Properties.Where(x => x.Name == propertyName).Any())
                    {
                        if (hasMultiplePrimaryKeys)
                        {
                            compositePKFieldName  += propertyName;
                            compositePKFieldValue += $"{{source.{propertyName}}}";
                        }
                    }
                }

                // Create an extra line to handle a limitation in SQLite when dealing with tables that use composite primary keys
                //   i.e. VehicleIdVehicleFeatureTypeId = $"{source.VehicleId}{source.VehicleFeatureTypeId}"
                if (hasMultiplePrimaryKeys && methodName.ToLowerInvariant() == "tomodeldata")
                {
                    sb.AppendLine($"{Environment.NewLine}\t\t\t\t// Create an extra line to handle a limitation in SQLite when dealing with tables that use composite primary keys");
                    sb.AppendLine($"\t\t\t\t{compositePKFieldName} = $\"{compositePKFieldValue}\"");
                }

                sb.AppendLine($"\t\t\t}};");
                sb.AppendLine($"\t\t}}");
                sb.AppendLine(string.Empty);
            }
            return(sb.ToString());
        }
Пример #7
0
        private static string NormalizeName(string name, string naming)
        {
            switch (naming)
            {
            case "Snake":
                return(Inflector.Underscore(name));

            case "UpperSnake":
                return(Inflector.Underscore(name, true));

            case "Camel":
                return(Inflector.Camelize(name));

            default:
                return(Inflector.Pascalize(name));
            }
        }
Пример #8
0
        public string GenerateConstructor(bool prependSchemaNameIndicator,
                                          IList <IEntityNavigation> excludedNavigationProperties,
                                          IEntityType entity)
        {
            StringBuilder           sb     = new StringBuilder();
            SortedSet <IForeignKey> fklist = entity.ForeignKeys;

            // Constructor .ctor code
            sb.AppendLine($"\t\tpublic {Inflector.Pascalize(entity.ClrType.Name)}()");
            sb.AppendLine("\t\t{");

            foreach (var navigation in entity.Navigations)
            {
                // Really, we only want to exclude these if the referenced Foreign Key table does not exist in our metadata (was excluded by regex).
                //bool excludeCircularReferenceNavigationIndicator = reverseFK.ExcludeCircularReferenceNavigationIndicator(excludedNavigationProperties);
                //if (excludeCircularReferenceNavigationIndicator)
                //{
                //	sb.AppendLine($"\t\t\t// Excluding '{name}' per configuration setting.");
                //	continue;
                //}

                if (navigation.ClrType.Name.Equals("ICollection`1"))
                {
                    //Collection
                }
                else if (navigation.ClrType.Name.Equals("List`1"))
                {
                    //List
                    string fkNamePl = Inflector.Pluralize(navigation.Name);
                    string fkName   = Inflector.Singularize(navigation.Name);

                    sb.AppendLine($"\t\t\t{fkNamePl} = new System.Collections.Generic.List<{fkName}>(); // Reverse Navigation");
                }
            }

            if (entity.Navigations.Count > 0)
            {
                sb.AppendLine(string.Empty);
            }

            sb.AppendLine("\t\t\tInitializePartial();");
            sb.AppendLine("\t\t}");

            return(sb.ToString());
        }
        private string GenerateLoadRequestEventArgs(IEntityType entity)
        {
            StringBuilder sb = new StringBuilder();

            //string tableName = table.GetNameHumanCaseSingular(false);
            string entityName = Inflector.Pascalize(entity.ClrType.Name); // GetNameHumanCaseSingular(prependSchemaNameIndicator);

            sb.AppendLine($"\tpublic class LoadRequest{entityName} : EventArgs");
            sb.AppendLine($"\t{{");
            sb.AppendLine($"\t\tpublic LoadRequest{entityName}(string propertyNameRequestingLoad)");
            sb.AppendLine($"\t\t{{");
            sb.AppendLine($"\t\t\tPropertyNameRequestingLoad = propertyNameRequestingLoad;");
            sb.AppendLine($"\t\t}}");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\tpublic string PropertyNameRequestingLoad {{ get; set; }}");
            sb.AppendLine($"\t}}");

            return(sb.ToString());
        }
Пример #10
0
        internal string GenerateEntity(string baseNamespace, string namespacePostfix, string classNamespace,
                                       IList <IEntityNavigation> excludeCircularReferenceNavigationProperties, IEntityType entity,
                                       bool InludeRelatedObjects, bool prependSchemaNameIndicator)
        {
            var    sb         = new StringBuilder();
            string entityName = Inflector.Humanize(entity.ClrType.Name);

            sb.AppendLine($"using System;");
            sb.AppendLine($"using System.Collections.Generic;");
            sb.AppendLine($"using System.Text;");

            sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.DataAccess" : $"namespace {baseNamespace}.DataAccess.{namespacePostfix}");
            sb.AppendLine($"{{");
            sb.AppendLine($"\tpublic partial class {entityName}Entity");
            sb.AppendLine($"\t{{");

            var primaryKeyList   = GetPrimaryKeys(entity);
            var entityProperties = entity.GetProperties();

            foreach (var property in entityProperties)
            {
                string ctype        = GetCType(property);
                string propertyName = property.Name;

                bool isPrimaryKey = primaryKeyList.Any(x => x.Equals(property.Name));

                sb.Append($"\t\tpublic {ctype} {Inflector.Pascalize(propertyName)} {{ get; set; }}");
                if (isPrimaryKey)
                {
                    sb.AppendLine($" // Primary key");
                }
                else
                {
                    sb.AppendLine(string.Empty);
                }
            }

            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t}}");
            sb.AppendLine($"}}");

            return(sb.ToString());
        }
        public string GenerateConstructor(bool prependSchemaNameIndicator,
                                          string webApiDataServiceInterfaceClassName, IEntityType entity)
        {
            StringBuilder sb = new StringBuilder();
            //List<ForeignKey> fklist = table.ForeignKeys;
            SortedSet <IForeignKey> fklist = entity.ForeignKeys;
            //CGHInflector myInflector = new CGHInflector();

            // First Constructor .ctor code

            string entityName = Inflector.Pascalize(entity.ClrType.Name);

            // Prepended the entity name with the schema, if required
            string dtoEntityName = entityName;

            //TODO: Currently we don't have the schema name in the entity, I believe. We need a metadatasource with schemanames to test it
            //if (prependSchemaNameIndicator && !string.IsNullOrEmpty(entity.SchemaName) && !entity.SchemaName.ToLower().Equals("dbo"))
            //{
            //	dtoEntityName = $"{entity.SchemaName}.{entityName}";
            //}

            sb.AppendLine($"\t\tpublic event EventHandler<LoadRequest{entityName}> OnLazyLoadRequest = delegate {{ }}; // Empty delegate. Thus we are sure that value is always != null because no one outside of the class can change it.");
            sb.AppendLine($"\t\tprivate xDTO.{dtoEntityName} _dto = null;");
            sb.AppendLine(string.Empty);

            string signature = $"ILoggingService log, IDataService<{webApiDataServiceInterfaceClassName}> dataService";

            sb.AppendLine($"\t\tpublic {entityName}({signature}) : base(log, dataService)");
            sb.AppendLine("\t\t{");
            sb.AppendLine($"\t\t\t_dto = new xDTO.{dtoEntityName}();");
            sb.AppendLine($"\t\t\tOnLazyLoadRequest += HandleLazyLoadRequest;");
            sb.AppendLine("\t\t}");
            sb.AppendLine(string.Empty);

            signature = $"ILoggingService log, IDataService<{webApiDataServiceInterfaceClassName}> dataService, xDTO.{dtoEntityName} dto";
            sb.AppendLine($"\t\tpublic {entityName}({signature}) : this(log, dataService)");
            sb.AppendLine("\t\t{");
            sb.AppendLine($"\t\t\t_dto = dto;");
            sb.AppendLine("\t\t}");
            sb.AppendLine(string.Empty);

            return(sb.ToString());
        }
Пример #12
0
        public override TemplateOutput Generate()
        {
            TemplateOutput retVal = new TemplateOutput();

            try
            {
                var entityTypes = ProcessModel.MetadataSourceModel.GetEntityTypesByRegEx(excludeRegExPattern: RegexExclude, includeRegExPattern: RegexInclude);

                foreach (var entity in entityTypes)
                {
                    string entityName = Inflector.Pascalize(entity.ClrType.Name);
                    string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity,
                                                                               fileName: Consts.OUT_sqliteModelData);
                    outputfile = outputfile.Replace("[tablename]", entityName).Replace("[tablepluralname]", Inflector.Pluralize(entityName));
                    string filepath = outputfile;

                    var    generator     = new SqliteModelDataGenerator(inflector: Inflector);
                    string generatedCode = generator.GenerateSqliteModelData(
                        classNamespace: SqliteModelDataNamespace,
                        baseAuditEditNamespace: SqliteModelDataBaseAuditEditNamespace,
                        prependSchemaNameIndicator: PrependSchemaNameIndicator,
                        entity: entity);

                    retVal.Files.Add(new OutputFile()
                    {
                        Content = generatedCode,
                        Name    = filepath
                    });
                }
            }
            catch (Exception ex)
            {
                base.AddError(ref retVal, ex, Enums.LogLevel.Error);
            }

            AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error);
            return(retVal);
        }
        public PropertyInfo SelectProperty(PropertyInfo[] properties, string name)
        {
            var pi = properties.FirstOrDefault(x => IsMatchName(x, name, false)) ??
                     properties.FirstOrDefault(x => IsMatchName(x, name, true));

            if (pi != null)
            {
                return(pi);
            }

            var pascalName = Inflector.Pascalize(name);

            if (pascalName != name)
            {
                pi = properties.FirstOrDefault(x => IsMatchName(x, pascalName, false)) ??
                     properties.FirstOrDefault(x => IsMatchName(x, pascalName, true));
                if (pi != null)
                {
                    return(pi);
                }
            }

            return(null);
        }
Пример #14
0
        public string GenerateDTO(
            IList <IEntityNavigation> excludedNavigationProperties,
            IEntityType entity, string namespacePostfix,
            string baseNamespace, bool dtoIncludeRelatedObjects, bool prependSchemaNameIndicator, string dtoNamespace
            )
        {
            var    sb         = new StringBuilder();
            string entityName = Inflector.Pascalize(entity.ClrType.Name);

            string useDTONamespace = dtoNamespace.Replace("baseNamespace", baseNamespace).Replace("namespacePostfix", namespacePostfix);

            sb.AppendLine($"using System;");
            sb.AppendLine($"namespace {useDTONamespace}");
            //sb.AppendLine(string.IsNullOrWhiteSpace(namespacePostfix) ? $"namespace {baseNamespace}.DTO" : $"namespace {baseNamespace}.DTO.{namespacePostfix}");
            sb.AppendLine($"{{");
            sb.AppendLine($"\tpublic partial class {entityName}");
            sb.AppendLine($"\t{{");
            sb.AppendLine(GenerateConstructor(
                              prependSchemaNameIndicator: prependSchemaNameIndicator,
                              dtoIncludeRelatedObjects: dtoIncludeRelatedObjects,
                              entity: entity,
                              excludedNavigationProperties: excludedNavigationProperties));

            //var keys = entity.Keys;
            var primaryKeyList = GetPrimaryKeys(entity);

            var entityProperties = entity.GetProperties();

            foreach (var property in entityProperties)
            {
                // string ctype = property.ClrType.Name;
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;
                //string ctype = property.Name; //.CType();
                // property.Key seems to be inaccessible.
                //bool isPrimaryKey = keys.Where(x => x.Key[0].Name.Equals(property.Key));
                bool isPrimaryKey = primaryKeyList.Any(x => x.Equals(property.Name));

                sb.Append($"\t\tpublic {simpleType} {Inflector.Pascalize(propertyName)} {{ get; set; }}"); // was NameCamelCase
                if (isPrimaryKey)
                {
                    sb.AppendLine($" // Primary key");
                }
                else
                {
                    sb.AppendLine(string.Empty);
                }
            }

            sb.Append(GenerateReverseNav(
                          prependSchemaNameIndicator: prependSchemaNameIndicator,
                          dtoIncludeRelatedObjects: dtoIncludeRelatedObjects,
                          entity: entity,
                          excludedNavigationProperties: excludedNavigationProperties));

            sb.AppendLine(string.Empty);
            sb.AppendLine("\t\tpartial void InitializePartial();");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t}}");
            sb.AppendLine($"}}");

            return(sb.ToString());
        }
Пример #15
0
        /*
         * public static BingoContent SampleBingoContent01
         * {
         *  get
         *  {
         *      return new BingoContent()
         *      {
         *          BingoContentId = SampleBingoContentId01,
         *          Content = "'Let's take this offline'",
         *          CreatedDate = DateTime.UtcNow,
         *          CreatedUserId = DemoUser.UserIdAlexander,
         *          FreeSquareIndicator = false,
         *          IsDeleted = false,
         *          NumberOfDownvotes = 0,
         *          NumberOfUpvotes = 0,
         *          UpdatedDate = DateTime.UtcNow,
         *          UpdatedUserId = DemoUser.UserIdAlexander
         *      };
         *  }
         * }
         */

        public string GenerateSampleData(
            IEntityType entity,
            string sqliteModelDataNamespace,
            bool prependSchemaNameIndicator,
            int sampleDataCount,
            int sampleDataDigits)
        {
            var    sb                     = new StringBuilder();
            var    k                      = entity.FindPrimaryKey();
            string entityName             = Inflector.Pascalize(entity.ClrType.Name);
            var    entityProperties       = entity.GetProperties();
            bool   hasMultiplePrimaryKeys = entity.FindPrimaryKey().Properties.Count > 1;
            string numberFormat           = new String('0', sampleDataDigits);
            Dictionary <string, string> uniquePKModuleLevelVariableNames = new Dictionary <string, string>();

            sb.AppendLine("using System;");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"namespace {sqliteModelDataNamespace}");
            sb.AppendLine($"{{");

            sb.AppendLine($"\tpublic static class Demo{entityName}");
            sb.AppendLine("\t{");
            //sb.AppendLine($"\t\t//number format is \"{numberFormat}\" and sampledigits is {SampleDataDigits}");
            for (int sampleNumber = 0; sampleNumber < sampleDataCount; sampleNumber++)
            {
                string uniquePKModuleLevelVariableName;
                // Generate unique keys for use in the sample objects
                for (int i = 0; i < entityProperties.Count(); i++)
                {
                    var    property     = entityProperties[i];
                    string propertyName = Inflector.Pascalize(property.Name);
                    string ctype        = GetCType(property);
                    var    simpleType   = ConvertToSimpleType(ctype);

                    if (property.Name == k.Properties[0].Name)
                    {
                        var sampleNumberFormatted = sampleNumber.ToString(numberFormat);

                        uniquePKModuleLevelVariableName = GetUniquePKModuleLevelVariableName(entityName: entityName, sampleNumber: sampleNumber, columnNumber: i, numberFormat: numberFormat);
                        uniquePKModuleLevelVariableNames[$"{propertyName}{sampleNumberFormatted}"] = uniquePKModuleLevelVariableName; // Gather up the unique PK variable names for use below.

                        if (hasMultiplePrimaryKeys)
                        {                                                                                                                                                                         // By and large, this really only happens with link/associative tables that are pointing at other tables.
                            //   So, here we are depending on values in another sample data class.
                            var nameOfOtherSampleDataClass = propertyName.Replace("Id", string.Empty);                                                                                            //.GetNameHumanCaseSingular(prependSchemaNameIndicator);
                            sb.AppendLine($"\t\tpublic static {simpleType} {uniquePKModuleLevelVariableName} = Demo{nameOfOtherSampleDataClass}.Sample{propertyName}{sampleNumberFormatted}00;"); // Note assumption with "00" in place of the column number there only being one PK in the associated table
                        }
                        else
                        {
                            sb.AppendLine($"\t\tpublic static {simpleType} {uniquePKModuleLevelVariableName} = {SampleValue(property)};");
                        }
                    }
                }
            }
            sb.AppendLine(string.Empty);

            // Constructor .ctor code

            for (int sampleNumber = 0; sampleNumber < sampleDataCount; sampleNumber++)
            {
                string sampleNumberFormatted = sampleNumber.ToString(numberFormat);
                sb.AppendLine($"\t\tpublic static {entityName} Sample{entityName}{sampleNumberFormatted}");
                sb.AppendLine("\t\t{");

                sb.AppendLine("\t\t\tget");
                sb.AppendLine("\t\t\t{");
                sb.AppendLine($"\t\t\t\treturn new {entityName}()");
                sb.AppendLine("\t\t\t\t{");

                for (int i = 0; i < entityProperties.Count(); i++)
                {
                    var    property     = entityProperties[i];
                    string propertyName = Inflector.Pascalize(property.Name);
                    string ctype        = GetCType(property);
                    var    simpleType   = ConvertToSimpleType(ctype);
                    // We need to pass the sampleNumber along in case this is a primary key column
                    var sampleType = GetSampleDataValueOrUniquePKModuleLevelVariableName(property: property, sampleNumber: sampleNumber,
                                                                                         columnNumber: i, numberFormat: numberFormat, uniquePKModuleLevelVariableNames: uniquePKModuleLevelVariableNames, entityName: entityName, k.Properties[0].Name);
                    sb.AppendLine($"\t\t\t\t\t{propertyName} = {sampleType},");
                }

                sb.AppendLine("\t\t\t\t};");

                sb.AppendLine("\t\t\t}");
                sb.AppendLine("\t\t}");
            }

            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t}}");
            sb.AppendLine($"}}");

            return(sb.ToString());
        }
Пример #16
0
        public string GenerateReverseNav(bool prependSchemaNameIndicator,
                                         bool dtoIncludeRelatedObjects,
                                         IEntityType entity,
                                         IList <IEntityNavigation> excludedNavigationProperties)
        {
            StringBuilder           sb     = new StringBuilder();
            SortedSet <IForeignKey> fklist = entity.ForeignKeys;

            // CGHInflector myInflector = new CGHInflector();

            if (dtoIncludeRelatedObjects)
            {
                foreach (var reverseFK in entity.Navigations)
                {
                    string name      = reverseFK.DeclaringType.ClrType.Name;
                    string humanCase = Inflector.Humanize(name);

                    sb.Append("\t\t");
                    //bool excludeCircularReferenceNavigationIndicator = reverseFK.ExcludeCircularReferenceNavigationIndicator(excludedNavigationProperties);
                    bool excludeCircularReferenceNavigationIndicator = IsEntityInExcludedReferenceNavigionationProperties(excludedNavigationProperties, name);
                    if (excludeCircularReferenceNavigationIndicator)
                    {   // Include the line, but comment it out.
                        sb.Append("// ");
                    }

                    string reverseFKName = reverseFK.ForeignKey.PrincipalEntityType.ClrType.Name;

                    // We don't have the same Relationship.OneToOne status as from the reverse poco type.  EntityFramework just gives us the type of ICollection'1 or the field name
                    //if (reverseFK.ClrType == Library.Enums.Relationship.OneToOne)
                    if (!reverseFK.ClrType.Name.Equals("ICollection`1"))
                    {
                        sb.Append($"public virtual {reverseFKName} {Inflector.Pascalize(reverseFKName)} {{ get; set; }} // One to One mapping"); // Foreign Key
                    }
                    else
                    {
                        sb.Append($"public virtual System.Collections.Generic.ICollection<{reverseFK.ForeignKey.DeclaringEntityType.ClrType.Name}> {reverseFK.Name} {{ get; set; }} // Many to many mapping"); // Foreign Key
                    }

                    if (excludeCircularReferenceNavigationIndicator)
                    {
                        sb.AppendLine(EXCLUDEPERNAVIGATIONPROPERTYCONFIGURATION);
                    }
                    else
                    {
                        sb.AppendLine(string.Empty);
                    }
                }

                // With Reverse POCO, we had to go forward and backward.  However, by using entity.Navigations, the following seems duplicative.
                //var orderedFKs = entity.ForeignKeys.OrderBy(x => x.DependentToPrincipal.Name).ToList();
                //foreach (var fk in orderedFKs)
                //{
                //    string principalEntityTypeName = fk.PrincipalEntityType.ClrType.Name;
                //    string propertyName = "";
                //    if (string.IsNullOrEmpty(principalEntityTypeName))
                //    {
                //        sb.AppendLine($"// ERROR: {entity.Name} foreign key for {fk.PrincipalEntityType.Name}: A PrincipalEntityType.Name is null");
                //    }
                //    else
                //    {
                //        propertyName = principalEntityTypeName.Humanize(); // Humanize the name
                //    }
                //    sb.Append("\t\t");

                //    // TODO: Not sure if this is correct.  Does the excludedNavigationProperties exclude by table/ref or just by table? Or just by column?
                //    //bool excludeCircularReferenceNavigationIndicator = fk.ExcludeCircularReferenceNavigationIndicator(excludedNavigationProperties);
                //    bool excludeCircularReferenceNavigationIndicator = IsEntityInExcludedReferenceNavigionationProperties(excludedNavigationProperties, propertyName);

                //    if (excludeCircularReferenceNavigationIndicator)
                //    {   // Include the line, but comment it out.
                //        sb.Append("// ");
                //    }

                //    sb.Append($"public virtual {principalEntityTypeName} {propertyName} {{ get; set; }} "); // Foreign Key

                //    if (excludeCircularReferenceNavigationIndicator)
                //    {
                //        sb.AppendLine(EXCLUDEPERNAVIGATIONPROPERTYCONFIGURATION);
                //    }
                //    else
                //    {
                //        sb.AppendLine(string.Empty);
                //    }
                //}
            }

            return(sb.ToString());
        }
Пример #17
0
        public string GenerateSqliteModelData(
            string classNamespace,
            string baseAuditEditNamespace,
            bool prependSchemaNameIndicator,
            IEntityType entity)
        {
            string        tableName               = Inflector.Pascalize(entity.ClrType.Name);
            StringBuilder sb                      = new StringBuilder();
            var           entityProperties        = entity.GetProperties().OrderBy(n => n.Name).ToList();
            bool          containsAuditEditFields = ContainsAuditEditFields(entityProperties);

            sb.Append(GenerateHeader(classNamespace, baseAuditEditNamespace, containsAuditEditFields));

            sb.AppendLine($"\t[Table(\"{entity.ClrType.Name}\")]");
            if (containsAuditEditFields)
            {
                sb.AppendLine($"\tpublic partial class {tableName} : BaseAuditEdit");
            }
            else
            {
                sb.AppendLine($"\tpublic partial class {tableName}");
            }

            sb.AppendLine("\t{");
            int    pknum                  = 1;
            string pkstring               = string.Empty;
            string compositePKFieldName   = string.Empty;
            bool   hasMultiplePrimaryKeys = entity.FindPrimaryKey().Properties.Count > 1;
            var    primaryKey             = entity.FindPrimaryKey();

            for (int i = 0; i < entityProperties.Count; i++)
            {
                var    property     = entityProperties[i];
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;

                if ((!containsAuditEditFields || !IsColumnAnAuditEditField(property)) &&
                    !IsUnknownType(property))
                {
                    if (primaryKey.Properties.Where(x => x.Name == propertyName).Any())
                    {
                        sb.AppendLine(string.Empty);
                        if (hasMultiplePrimaryKeys)
                        {
                            //pkstring = $"\t\t// Mutiple primary keys - composite PK used instead [Indexed(Name = \"{tableName}\", Order = {pknum++}, Unique = true)]";
                            pkstring              = $"\t\t// Mutiple primary keys - composite PK used instead ";
                            compositePKFieldName += propertyName;
                        }
                        else
                        {
                            pkstring = "\t\t[PrimaryKey]";
                        }

                        sb.AppendLine(pkstring);
                    }
                    sb.AppendLine($"\t\tpublic {simpleType} {propertyName} {{ get; set; }}");

                    if (propertyName == primaryKey.Properties[0].Name)
                    {
                        sb.AppendLine(string.Empty);  // Blank line after the primary key(s) for visual effect only.
                    }
                }
            }

            if (hasMultiplePrimaryKeys)
            {
                sb.AppendLine($"\t\t[PrimaryKey]\n\t\tpublic string {compositePKFieldName} {{ get; set; }}");
            }

            sb.Append(GenerateFooter());

            return(sb.ToString());
        }
        public string GenerateWebApiDataService(
            string iLoggingServiceNamespace,
            string serializationHelperNamespace,
            string webApiDataServiceInterfaceNamespace,
            string webApiDataServiceNamespace,
            string dtoNamespacePrefix,
            string dtoNamespace,
            string classNamespace,
            string namespacePostfix,
            string defaultCriteria,
            bool prependSchemaNameIndicator,
            IList <IEntityType> entityTypes,
            string baseNamespace)
        {
            var entitiesSortedByName = entityTypes.OrderBy(f => f.ClrType.Name);

            var sb            = new StringBuilder();
            var sbGetAllPages = new StringBuilder();
            var sbGetOnePage  = new StringBuilder();
            var sbGetByPK     = new StringBuilder();
            var sbCreate      = new StringBuilder();
            var sbUpdate      = new StringBuilder();
            var sbDelete      = new StringBuilder();

            sb.Append(GenerateHeader(
                          iLoggingServiceNamespace: iLoggingServiceNamespace,
                          serializationHelperNamespace: serializationHelperNamespace,
                          webApiDataServiceInterfaceNamespace: webApiDataServiceInterfaceNamespace,
                          webApiDataServiceNamespace: webApiDataServiceNamespace,
                          dtoNamespacePrefix: dtoNamespacePrefix,
                          dtoNamespace: dtoNamespace,
                          namespacePostfix: namespacePostfix, baseNamespace: baseNamespace));

            sbGetAllPages.AppendLine($"{Environment.NewLine}\t\t#region GetAllPages{Environment.NewLine}");
            sbGetOnePage.AppendLine($"{Environment.NewLine}\t\t#region GetOnePage{Environment.NewLine}");
            sbGetByPK.AppendLine($"{Environment.NewLine}\t\t#region Get By PK{Environment.NewLine}");
            sbCreate.AppendLine($"{Environment.NewLine}\t\t#region Create{Environment.NewLine}");
            sbUpdate.AppendLine($"{Environment.NewLine}\t\t#region Update{Environment.NewLine}");
            sbDelete.AppendLine($"{Environment.NewLine}\t\t#region Delete{Environment.NewLine}");

            foreach (var entity in entitiesSortedByName)
            {
                string defaultCriteriaTableNameSubstituted   = defaultCriteria?.Replace("[tablename]", Inflector.Humanize(entity.ClrType.Name));
                var    defaultCriteriaAsTypeAndFieldNameList = GetDefaultCriteriaListForWebApi(defaultCriteriaTableNameSubstituted);
                string entityName = Inflector.Pascalize(entity.ClrType.Name);
                var    criteriaFieldsThatExistInTable        = FilterFieldTypeAndNamesByExistingColumns(entity, defaultCriteriaAsTypeAndFieldNameList);
                var    criteriaTypeAndFieldNamesConcatenated = GetFieldTypeAndNamesConcatenated(criteriaFieldsThatExistInTable);
                var    criteriaFieldNamesConcatenated        = GetFieldNamesConcatenated(criteriaFieldsThatExistInTable);
                string keylist = string.Join("}/{", entity.GetKeys().Select(n => Inflector.ToLowerFirstCharacter(n.Properties[0].Name)));

                // Get All Pages
                // Begin method signature
                sbGetAllPages.AppendLine($"\t\tpublic async Task<IList<{dtoNamespacePrefix}.{entityName}>> GetAllPages{Inflector.Pluralize(entityName)}Async(");
                sbGetAllPages.Append($"\t\t\t");
                if (!string.IsNullOrEmpty(criteriaTypeAndFieldNamesConcatenated))
                {
                    sbGetAllPages.Append($"{criteriaTypeAndFieldNamesConcatenated}, ");
                }
                sbGetAllPages.AppendLine($"string sort = null)");
                // End method signature

                sbGetAllPages.AppendLine($"\t\t{{");
                BuildFilterCriteria(ref sbGetAllPages, criteriaFieldsThatExistInTable);

                sbGetAllPages.AppendLine($"\t\t\tIPageDataRequest pageDataRequest = new PageDataRequest(filterCriteria: filterCriteria, sort: sort, page: 1, pageSize: 100);");
                //sbGetAllPages.AppendLine($"\t\t\treturn await GetAllPageDataResultsAsync<{dtoNamespacePrefix}.{tableName}>(pageDataRequest, Get{table.NamePlural}Async);");
                sbGetAllPages.AppendLine($"\t\t\treturn await GetAllPageDataResultsAsync(pageDataRequest, Get{Inflector.Pluralize(entityName)}Async);");
                sbGetAllPages.AppendLine($"\t\t}}");
                sbGetAllPages.AppendLine(string.Empty);

                // Get One Page - Part 1
                sbGetOnePage.AppendLine($"\t\tpublic async Task<IHttpCallResultCGHT<IPageDataT<IList<{dtoNamespacePrefix}.{entityName}>>>> Get{Inflector.Pluralize(entityName)}Async(IPageDataRequest pageDataRequest)");
                sbGetOnePage.AppendLine($"\t\t{{");
                sbGetOnePage.AppendLine($"\t\t\tList<string> filter = BuildFilter(pageDataRequest.FilterCriteria);");
                sbGetOnePage.AppendLine($"\t\t\treturn await SerializationHelper.Instance.SerializeCallResultsGet<IList<{dtoNamespacePrefix}.{entityName}>>(Log, HttpClient, ");
                sbGetOnePage.AppendLine($"\t\t\t\t$\"{namespacePostfix}/{Inflector.Pluralize(entityName)}\", filter, page: pageDataRequest.Page, pageSize: pageDataRequest.PageSize);");
                sbGetOnePage.AppendLine($"\t\t}}");
                sbGetOnePage.AppendLine(string.Empty);

                // Get One Page - Part 2
                sbGetOnePage.AppendLine($"\t\tpublic async Task<IHttpCallResultCGHT<IPageDataT<IList<{dtoNamespacePrefix}.{entityName}>>>> Get{Inflector.Pluralize(entityName)}Async(");
                sbGetOnePage.Append($"\t\t\t");
                if (!string.IsNullOrEmpty(criteriaTypeAndFieldNamesConcatenated))
                {
                    sbGetOnePage.Append($"{criteriaTypeAndFieldNamesConcatenated}, ");
                }

                sbGetOnePage.AppendLine($"string sort = null, int page = 1, int pageSize = 100)");
                sbGetOnePage.AppendLine($"\t\t{{");
                BuildFilterCriteria(ref sbGetOnePage, criteriaFieldsThatExistInTable);

                sbGetOnePage.AppendLine(string.Empty);
                sbGetOnePage.AppendLine($"\t\t\tIPageDataRequest pageDataRequest = new PageDataRequest(filterCriteria: filterCriteria, sort: sort, page: page, pageSize: pageSize);");
                sbGetOnePage.AppendLine($"\t\t\treturn await Get{Inflector.Pluralize(entityName)}Async(pageDataRequest);");
                sbGetOnePage.AppendLine($"\t\t}}");
                sbGetOnePage.AppendLine(string.Empty);

                // Get By PK
                sbGetByPK.AppendLine($"\t\tpublic async Task<IHttpCallResultCGHT<{dtoNamespacePrefix}.{entityName}>> Get{entityName}Async({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())}, int numChildLevels)");
                sbGetByPK.AppendLine($"\t\t{{");

                sbGetByPK.AppendLine($"\t\t\tvar retVal = await SerializationHelper.Instance.SerializeCallResultsGet<{dtoNamespacePrefix}.{entityName}>(Log, HttpClient, $\"{namespacePostfix}/{Inflector.Pluralize(entityName)}/{{{keylist}}}?numChildLevels={{numChildLevels}}\");");
                sbGetByPK.AppendLine($"\t\t\treturn retVal;");
                sbGetByPK.AppendLine($"\t\t}}");
                sbGetByPK.AppendLine(string.Empty);

                // Create
                sbCreate.Append(GenerateSerializeCallFor(namespacePostfix: namespacePostfix, dtoNamespacePrefix: dtoNamespacePrefix,
                                                         httpVerb: "Post", prependSchemaNameIndicator: prependSchemaNameIndicator, entity: entity));

                // Update
                sbUpdate.Append(GenerateSerializeCallFor(namespacePostfix: namespacePostfix, dtoNamespacePrefix: dtoNamespacePrefix,
                                                         httpVerb: "Put", prependSchemaNameIndicator: prependSchemaNameIndicator, entity: entity));

                // Delete
                sbDelete.AppendLine($"\t\tpublic async Task<IHttpCallResultCGHT<{dtoNamespacePrefix}.{entityName}>> Delete{Inflector.Humanize(entity.ClrType.Name)}Async({GetSignatureWithFieldTypes(string.Empty, entity.FindPrimaryKey())})");
                sbDelete.AppendLine($"\t\t{{");

                sbDelete.AppendLine($"\t\t\tvar retVal = await SerializationHelper.Instance.SerializeCallResultsDelete<{dtoNamespacePrefix}.{entityName}>(Log, HttpClient, $\"{namespacePostfix}/{Inflector.Pluralize(entityName)}/{{{keylist}}}\");");
                sbDelete.AppendLine($"\t\t\treturn retVal;");
                sbDelete.AppendLine($"\t\t}}");
                sbDelete.AppendLine(string.Empty);
            }

            sbGetAllPages.AppendLine($"\t\t#endregion GetAllPages{Environment.NewLine}");
            sb.AppendLine(sbGetAllPages.ToString());

            sbGetOnePage.AppendLine($"\t\t#endregion GetOnePage{Environment.NewLine}");
            sb.AppendLine(sbGetOnePage.ToString());

            sbGetByPK.AppendLine($"\t\t#endregion Get By PK{Environment.NewLine}");
            sb.AppendLine(sbGetByPK.ToString());

            sbCreate.AppendLine($"\t\t#endregion Create{Environment.NewLine}");
            sb.AppendLine(sbCreate.ToString());

            sbUpdate.AppendLine($"\t\t#endregion Update{Environment.NewLine}");
            sb.AppendLine(sbUpdate.ToString());

            sbDelete.AppendLine($"\t\t#endregion Delete{Environment.NewLine}");
            sb.AppendLine(sbDelete.ToString());

            sb.Append(GenerateFooter());

            return(sb.ToString());
        }
Пример #19
0
 public string Pascalize() => Inflector.Pascalize("aaa_bbb_ccc_ddd");
Пример #20
0
        public string GenerateMapperSqliteModelDataToMvvmLightModelObject(
            string classNamespace,
            string className,
            string modelObjNamespacePrefix,
            string modelObjNamespace,
            string modelDataNamespacePrefix,
            string modelDataNamespace,
            bool prependSchemaNameIndicator,
            IList <IEntityType> entityTypes)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(GenerateHeader(classNamespace, className,
                                     modelObjNamespacePrefix, modelObjNamespace,
                                     modelDataNamespacePrefix, modelDataNamespace));

            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\t#region ModelObj to ModelData");
            sb.AppendLine(string.Empty);

            foreach (var entity in entityTypes)
            {
                string entityName = Inflector.Pascalize(entity.ClrType.Name);
                sb.AppendLine($"\t\tpublic static {modelDataNamespacePrefix}.{entityName} ToModelData(this {modelObjNamespacePrefix}.{entityName} source)");
                sb.AppendLine($"\t\t{{");
                sb.AppendLine($"\t\t\treturn new {modelDataNamespacePrefix}.{entityName}()");
                sb.AppendLine($"\t\t\t{{");

                var entityProperties = entity.GetProperties().OrderBy(n => n.Name);

                foreach (var property in entityProperties)
                {
                    string propertyName = Inflector.Pascalize(property.Name);
                    if (!IsUnknownType(property))
                    {
                        sb.AppendLine($"\t\t\t\t{propertyName} = source.{propertyName},");
                    }
                }

                sb.AppendLine($"\t\t\t}};");
                sb.AppendLine($"\t\t}}");
                sb.AppendLine(string.Empty);
            }

            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\t#endregion ModelObj to ModelData");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\t#region ModelData to ModelObj");
            sb.AppendLine(string.Empty);

            foreach (var entity in entityTypes)
            {
                string entityName       = Inflector.Pascalize(entity.ClrType.Name);
                var    entityProperties = entity.GetProperties().OrderBy(n => n.Name);
                sb.AppendLine($"\t\tpublic static {modelObjNamespacePrefix}.{entityName} ToModelObj(this {modelDataNamespacePrefix}.{entityName} source)");
                sb.AppendLine($"\t\t{{");
                sb.AppendLine($"\t\t\treturn new {modelObjNamespacePrefix}.{entityName}()");
                sb.AppendLine($"\t\t\t{{");

                foreach (var property in entityProperties)
                {
                    string propertyName = Inflector.Pascalize(property.Name);
                    if (!IsUnknownType(property))
                    {
                        sb.AppendLine($"\t\t\t\t{propertyName} = source.{propertyName},");
                    }
                }

                sb.AppendLine($"\t\t\t}};");
                sb.AppendLine($"\t\t}}");
                sb.AppendLine(string.Empty);
            }

            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\t#endregion ModelData to ModelObj");
            sb.AppendLine(string.Empty);

            sb.Append(GenerateFooter());

            return(sb.ToString());
        }
 public virtual string GetEntityNameFromTableName(string tableName)
 {
     return(Inflector.Pascalize(
                Inflector.Singularize(tableName.Trim('_'))
                ));
 }
Пример #22
0
        public string Generate(
            List <string> usings,
            string classNamespace,
            bool prependSchemaNameIndicator,
            IList <IEntityType> entityTypes)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(GenerateUsings(usings));

            sb.AppendLine(string.Empty);
            sb.AppendLine($"namespace {classNamespace}");
            sb.AppendLine($"{{");
            sb.AppendLine($"\tpublic static class ToDataMappers");
            sb.AppendLine($"\t{{");

            foreach (var entity in entityTypes)
            {
                var    k                      = entity.FindPrimaryKey();
                string entityName             = Inflector.Pascalize(entity.ClrType.Name);
                var    entityProperties       = entity.GetProperties().OrderBy(n => n.Name).ToList();
                bool   hasMultiplePrimaryKeys = entity.FindPrimaryKey().Properties.Count > 1;
                string compositePKFieldName   = string.Empty;
                string compositePKFieldValue  = string.Empty;

                sb.AppendLine($"\t\tpublic static xData.{entityName} ToData(this xModel.{entityName} obj)");
                sb.AppendLine($"\t\t{{"); //Beginning of main method bracket

                //Null Check
                sb.AppendLine($"\t\t\tif (obj == null)");
                sb.AppendLine("\t\t\treturn null;");

                //Declaration of return mapped value
                sb.AppendLine($"\t\t\tvar retVal = new xData.{entityName}()");
                sb.AppendLine($"\t\t\t{{");

                //Loop through properties
                for (int i = 0; i < entityProperties.Count(); i++)
                {
                    var    property     = entityProperties[i];
                    string propertyName = Inflector.Pascalize(property.Name);

                    string ctype      = GetCType(property);
                    var    simpleType = ConvertToSimpleType(ctype);

                    if (simpleType == "DateTime")
                    {
                        sb.AppendLine($"\t\t\t\t{propertyName} = DateTime.SpecifyKind(obj.{propertyName}, DateTimeKind.Utc),");
                    }
                    else
                    {
                        sb.AppendLine($"\t\t\t\t{propertyName} = obj.{propertyName},");
                    }
                }

                //Loop through navigations
                foreach (var reverseFK in entity.Navigations)
                {
                    string name          = reverseFK.DeclaringType.ClrType.Name;
                    string humanCase     = Inflector.Humanize(name);
                    string reverseFKName = reverseFK.ForeignKey.PrincipalEntityType.Name;
                    if (!reverseFK.ClrType.Name.Equals("ICollection`1"))
                    {
                        sb.AppendLine($"\t\t\t\t{reverseFK.ClrType.Name} = obj.{reverseFK.ClrType.Name}.ToData(),");
                    }
                    else
                    {
                        sb.AppendLine($"\t\t\t\t{Inflector.Pluralize(humanCase)} = obj.{Inflector.Pluralize(humanCase)}.ToData<xData.{humanCase}, xModel.{humanCase}>(),");
                    }
                }

                sb.AppendLine($"\t\t}};");
                sb.AppendLine("\t\treturn retVal;");
                sb.AppendLine($"}}");

                sb.AppendLine(string.Empty);
            }
            GenerateFooter(sb);
            return(sb.ToString());
        }
Пример #23
0
        public string Generate(
            List <string> usings,
            string classNamespace,
            bool prependSchemaNameIndicator,
            IList <IEntityType> entityTypes)
        {
            StringBuilder sb = new StringBuilder();

            sb.Append(GenerateUsings(usings));

            sb.AppendLine(string.Empty);
            sb.AppendLine($"namespace {classNamespace}");
            sb.AppendLine($"{{");
            sb.AppendLine($"\tpublic static class ToModelMappers");
            sb.AppendLine($"\t{{");

            foreach (var entity in entityTypes)
            {
                var    k                      = entity.FindPrimaryKey();
                string entityName             = Inflector.Pascalize(entity.ClrType.Name);
                var    entityProperties       = entity.GetProperties().OrderBy(n => n.Name).ToList();
                bool   hasMultiplePrimaryKeys = entity.FindPrimaryKey().Properties.Count > 1;
                string compositePKFieldName   = string.Empty;
                string compositePKFieldValue  = string.Empty;

                sb.AppendLine($"\t\tpublic static xModel.{entityName} ToModel(this xData.{entityName} obj, cEnums.RecordStatus recordStatus, bool removeSelfReferencingChildEntities = true)");
                sb.AppendLine($"\t\t{{"); //Beginning of main method bracket

                //Null Check
                sb.AppendLine($"\t\t\tif (obj == null || (obj.StatusTypeId & (int)recordStatus) != obj.StatusTypeId)");
                sb.AppendLine("\t\t\treturn null;");

                //Remove self referencing child entities
                sb.AppendLine($"\t\t\tif(removeSelfReferencingChildEntities)");
                sb.AppendLine($"\t\t\t{{  // Avoid circular references from causing infinite loops during serialization.");
                sb.AppendLine($"\t\t\t\t\tvar crr = new Service.CircularReferenceRemover<xData.{entityName}>();");
                sb.AppendLine($"\t\t\t\t\tcrr.RemoveSelfReferencingChildEntities(obj);");
                sb.AppendLine($"\t\t\t}}");

                //Declaration of return mapped value
                sb.AppendLine($"\t\t\tvar retVal = new xModel.{entityName}()");
                sb.AppendLine($"\t\t\t{{");

                //Loop through properties
                for (int i = 0; i < entityProperties.Count(); i++)
                {
                    var    property     = entityProperties[i];
                    string propertyName = Inflector.Pascalize(property.Name);

                    string ctype      = GetCType(property);
                    var    simpleType = ConvertToSimpleType(ctype);

                    if (simpleType == "DateTime")
                    {
                        sb.AppendLine($"\t\t\t\t{propertyName} = DateTime.SpecifyKind(obj.{propertyName}, DateTimeKind.Utc),");
                    }
                    else
                    {
                        sb.AppendLine($"\t\t\t\t{propertyName} = obj.{propertyName},");
                    }
                }

                //Loop through navigations
                foreach (var reverseFK in entity.Navigations)
                {
                    string name          = reverseFK.DeclaringType.ClrType.Name;
                    string humanCase     = Inflector.Humanize(name);
                    string reverseFKName = reverseFK.ForeignKey.PrincipalEntityType.Name;
                    if (!reverseFK.ClrType.Name.Equals("ICollection`1"))
                    {
                        sb.AppendLine($"\t\t\t\t{reverseFK.ClrType.Name} = obj.{reverseFK.ClrType.Name}.ToModel(recordStatus),");
                    }
                    else
                    {
                        sb.AppendLine($"\t\t\t\t{Inflector.Pluralize(humanCase)} = obj.{Inflector.Pluralize(humanCase)}.ToModel<xData.{humanCase}, xModel.{humanCase}>(recordStatus),");
                    }
                }

                sb.AppendLine($"\t\t}};");
                sb.AppendLine("\t\treturn retVal;");
                sb.AppendLine($"}}");

                sb.AppendLine(string.Empty);
            }
            GenerateFooter(sb);
            return(sb.ToString());
        }
 public virtual string GetIdPropertyNameFromColumnName(string columnName)
 {
     return(Inflector.Pascalize(columnName.Trim('_')));
 }
Пример #25
0
        public string GenerateAutomapperProfile(string baseNamespace,
                                                string namespacePostfix,
                                                string dtoNamespace,
                                                string repositoryEntitiesNamespace,
                                                IList <IEntityType> entityTypes,
                                                IList <IEntityNavigation> excludedNavigationProperties
                                                )
        {
            var sb = new StringBuilder();

            sb.AppendLine($"using AutoMapper;");
            sb.AppendLine($"using xDTO = {dtoNamespace};");
            sb.AppendLine($"using xENT = {repositoryEntitiesNamespace};");

            sb.AppendLine(string.Empty);
            sb.AppendLine($"namespace {baseNamespace}.Repository.Infrastructure");
            sb.AppendLine($"{{");

            sb.AppendLine($"\tpublic partial class {namespacePostfix}AutoMapperProfile : Profile");
            sb.AppendLine($"\t{{");

            sb.AppendLine($"\t\tpublic {namespacePostfix}AutoMapperProfile()");
            sb.AppendLine($"\t\t{{");
            sb.AppendLine($"\t\t\tInitializeProfile();");
            sb.AppendLine($"\t\t\tInitializePartial();");
            sb.AppendLine($"\t\t}}");

            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\tpartial void InitializePartial();");

            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\tprivate void InitializeProfile()");
            sb.AppendLine($"\t\t{{");

            foreach (var entity in entityTypes)
            {
                string tableName = Inflector.Pascalize(entity.ClrType.Name); // entity.GetNameHumanCaseSingular(prependSchemaNameIndicator);
                sb.AppendLine($"\t\t\tCreateMap<xDTO.{tableName}, xENT.{tableName}>()");

                //bool addtable = table.FKs.Count + table.

                if (entity.ForeignKeys.Any() || entity.Navigations.Any())
                {
                    List <string> listed = new List <string>(); //keep a list of these so we don't duplicate because the user table, for example, is referenced twice by many tables.

                    foreach (var navigation in entity.Navigations)
                    {
                        sb.Append($"\t\t\t\t");

                        string name = navigation.Name;
                        bool   excludeCircularReferenceNavigationIndicator = IsEntityInExcludedReferenceNavigionationProperties(excludedNavigationProperties, name);
                        if (excludeCircularReferenceNavigationIndicator) // We want to negate the value check because we are saying AutoMapper should ignore the property below.
                        {                                                // Include the line, but comment it out.
                            sb.Append("// ");
                        }

                        sb.Append($".ForMember(d => d.{name}, opt => opt.Ignore()) // Reverse nav");

                        if (excludeCircularReferenceNavigationIndicator)
                        {
                            sb.Append(EXCLUDEPERNAVIGATIONPROPERTYCONFIGURATION);
                        }

                        sb.AppendLine(string.Empty);
                    }

                    foreach (var foreignKey in entity.ForeignKeys)
                    {
                        sb.Append($"\t\t\t\t");

                        string name = Inflector.Pascalize(foreignKey.DependentToPrincipal.ClrType.Name); //foreignKey.RefTableHumanCase;
                        bool   excludeCircularReferenceNavigationIndicator = IsEntityInExcludedReferenceNavigionationProperties(excludedNavigationProperties, name);
                        if (excludeCircularReferenceNavigationIndicator)                                 // We want to negate the value check because we are saying AutoMapper should ignore the property below.
                        {                                                                                // Include the line, but comment it out.
                            sb.Append("// ");
                        }

                        if (!string.IsNullOrEmpty(name))
                        {
                            sb.Append($".ForMember(d => d.{name}, opt => opt.Ignore())");
                        }

                        if (excludeCircularReferenceNavigationIndicator)
                        {
                            sb.Append($" // {EXCLUDEPERNAVIGATIONPROPERTYCONFIGURATION}");
                        }

                        sb.AppendLine(string.Empty);
                    }
                }

                sb.AppendLine($"\t\t\t.ReverseMap();");
                sb.AppendLine(string.Empty);
            }

            sb.AppendLine($"\t\t}}");
            sb.AppendLine($"\t}}");
            sb.AppendLine($"}}");

            return(sb.ToString());
        }
Пример #26
0
        private string SampleValue(IProperty property)
        {
            string retVal = string.Empty;

            string   propertyName = Inflector.Pascalize(property.Name);
            string   ctype        = GetCType(property);
            DateTime dateRandom   = RandomDate();
            var      simpleType   = ConvertToSimpleType(ctype);

            // return appropriate data for the given column type.
            switch (simpleType.ToLower())
            {
            case "guid":
            case "guid?":
            case "system.guid":
            case "system.guid?":
                retVal = $"Guid.Parse(\"{Guid.NewGuid().ToString()}\")";
                break;

            case "datetime":
            case "datetime?":
            case "datetimeoffset":
            case "system.datetime":
            case "system.datetime?":
                // While I can't imagine a datetime field as a primary key, it could happen
                retVal = $"DateTime({dateRandom.Year},{dateRandom.Month},{dateRandom.Day},{dateRandom.Hour},{dateRandom.Minute},{dateRandom.Second})";
                break;

            case "short":
            case "short?":
            case "int":
            case "int?":
            case "system.int32":
            case "system.int32?":
            case "system.int64":
            case "system.int64?":
            case "double":
            case "double?":
            case "long":
            case "long?":
            case "decimal":
            case "decimal?":
            case "float":
            case "float?":
                // Quite possibly an int would be used as a primary key but we definitely want a non-zero
                retVal = $"{RandomInt()}";
                break;

            case "bool":
            case "bool?":
                // As a primary key, highly unlikely
                retVal = "false";
                break;

            case "byte[]":
            case "byte[]?":
                // As a primary key, highly unlikely
                retVal = "new byte[0]";
                break;

            case "string":
                // I've seen people using strings as primary keys.  seriously.
                retVal = $"Sample{property.Name}{RandomInt()}";
                break;

            case "system.data.entity.spatial.dbgeometry":
                retVal = "geometry";
                break;

            default:
                retVal = "Unknown";
                break;
            }

            return(retVal);
        }
Пример #27
0
        public override TemplateOutput Generate()
        {
            TemplateOutput retVal = new TemplateOutput();

            try
            {
                var entityTypes = ProcessModel.MetadataSourceModel.GetEntityTypesByRegEx(excludeRegExPattern: RegexExclude, includeRegExPattern: RegexInclude);

                foreach (var entity in entityTypes)
                {
                    string entityName = Inflector.Pascalize(entity.ClrType.Name);

                    string outputfile = TemplateVariablesManager.GetOutputFile(templateIdentity: ProcessModel.TemplateIdentity,
                                                                               fileName: Consts.OUT_sampleData);
                    outputfile = outputfile.Replace("[tablename]", entityName).Replace("[tablepluralname]", Inflector.Pluralize(entityName));
                    string filepath = outputfile;

                    var generator = new SampleDataGenerator(inflector: Inflector);

                    int sampleDataCount = 0;
                    if (int.TryParse(SampleDataCount, out int sampleCount))
                    {
                        sampleDataCount = sampleCount;
                    }
                    else
                    {
                        ProcessModel.Errors.Add("Unable to parse the SampleDataCount from the blueprint");
                        sampleCount = 3; // Use 3 if we can parse the value
                    }

                    int sampleDataDigits = 2;
                    if (int.TryParse(SampleDataDigits, out int sampleDigits))
                    {
                        Debug.WriteLine($"Successfully parsed \"{SampleDataDigits}\" to {sampleDigits}");
                        sampleDataCount = sampleDigits;
                    }
                    else
                    {
                        Debug.WriteLine($"Failed trying to parse \"{SampleDataDigits}\" to a number");
                        ProcessModel.Errors.Add("Unable to parse the SampleDataDigits from the blueprint");
                        sampleCount = 2; // Use 2 if we can't parse the value
                    }

                    string generatedCode = generator.GenerateSampleData(
                        entity: entity,
                        sqliteModelDataNamespace: SqliteModelDataNamespace,
                        prependSchemaNameIndicator: PrependSchemaNameIndicator,
                        sampleDataCount: sampleDataCount,
                        sampleDataDigits: sampleDataDigits
                        );

                    retVal.Files.Add(new OutputFile()
                    {
                        Content = generatedCode,
                        Name    = filepath
                    });
                }
            }
            catch (Exception ex)
            {
                base.AddError(ref retVal, ex, Enums.LogLevel.Error);
            }

            AddTemplateVariablesManagerErrorsToRetVal(ref retVal, Enums.LogLevel.Error);
            return(retVal);
        }
        public string GenerateModelsBackedByDto(
            string baseNamespace,
            string namespacePostfix,
            string classNamespace,
            bool prependSchemaNameIndicator,
            string modelsBackedByDtoInterfaceNamespace,
            string webApiDataServiceInterfaceNamespace,
            string webApiDataServiceInterfaceClassName,
            IList <IEntityNavigation> excludedNavigationProperties,
            IEntityType entity)
        {
            string entityName   = Inflector.Pascalize(entity.ClrType.Name);
            string dtoTableName = entityName;
            //if (prependSchemaNameIndicator && !string.IsNullOrEmpty(entity.SchemaName) && !entity.SchemaName.ToLower().Equals("dbo"))
            //{
            //	dtoEntityName = $"{entity.SchemaName}.{entityName}";
            //}

            StringBuilder sb = new StringBuilder();
            var           entityProperties = entity.GetProperties();

            //var tabcols = table.Columns.OrderBy(x => x.Name).ToList();

            sb.Append(GenerateHeader(baseNamespace: baseNamespace, namespacePostfix: namespacePostfix,
                                     classNamespace: classNamespace, modelsBackedByDtoInterfaceNamespace: modelsBackedByDtoInterfaceNamespace,
                                     webApiDataServiceInterfaceNamespace: webApiDataServiceInterfaceNamespace,
                                     webApiDataServiceInterfaceClassName: webApiDataServiceInterfaceClassName, entity: entity));

            sb.AppendLine(GenerateConstructor(prependSchemaNameIndicator: prependSchemaNameIndicator,
                                              webApiDataServiceInterfaceClassName: webApiDataServiceInterfaceClassName, entity: entity));

            // Add the columns.  These only have a get on _dto.name
            foreach (var property in entityProperties)
            {
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;

                //string columnName = col.GetNameModuleLevelVariable();
                //string columnName = property.Name;
                sb.AppendLine($"\t\tpublic virtual {simpleType} {propertyName} {{ get {{ return _dto.{propertyName}; }} }}");
            }

            sb.AppendLine(string.Empty);

            //StringBuilder sbPropertyGets = new StringBuilder();
            StringBuilder sbPublicProperties  = new StringBuilder();
            StringBuilder sbPrivateProperties = new StringBuilder();
            // Add the ForeignKeys
            //foreach (var foreignKey in table.ForeignKeys)
            var orderedFKs = entity.ForeignKeys.OrderBy(x => x.DependentToPrincipal.Name).ToList();

            foreach (var fk in orderedFKs)
            {
                BuildForwardNavigation(
                    excludedNavigationProperties: excludedNavigationProperties,
                    entity: entity,
                    foreignKey: fk,
                    sbPrivateProperties: ref sbPrivateProperties,
                    sbPublicProperties: ref sbPublicProperties);
            }

            // Add the Reverse Navigation keys
            //foreach (var reverseNavigation in table.ReverseNavigations)
            foreach (var reverseFK in entity.Navigations)
            {
                BuildReverseNavigation(
                    excludedNavigationProperties: excludedNavigationProperties,
                    entity: entity,
                    foreignKey: reverseFK,
                    sbPrivateProperties: ref sbPrivateProperties,
                    sbPublicProperties: ref sbPublicProperties);
            }

            //Append private properties built in BuildForwardNavigation and BuildReverseNavigation methods
            sb.AppendLine(sbPrivateProperties.ToString());
            sb.AppendLine(string.Empty);
            //Append public properties built in BuildForwardNavigation and BuildReverseNavigation methods
            sb.AppendLine(sbPublicProperties.ToString());

            sb.Append(GenerateFooter());

            return(sb.ToString());

            // Add the foreign key data for the private get and as the public get
            // Only used by this method
        }
Пример #29
0
        public string GenerateMvvmLightModelObject(
            string classNamespace,
            string baseAuditEditNamespace,
            bool prependSchemaNameIndicator,
            IList <IEntityNavigation> excludedNavigationProperties,
            IEntityType entity)
        {
            string        entityName              = Inflector.Pascalize(entity.ClrType.Name);
            StringBuilder sb                      = new StringBuilder();
            var           entityProperties        = entity.GetProperties();
            bool          containsAuditEditFields = ContainsAuditEditFields(entityProperties);

            sb.Append(GenerateHeader(classNamespace, baseAuditEditNamespace, containsAuditEditFields));

            if (containsAuditEditFields)
            {
                sb.AppendLine($"\tpublic partial class {entityName} : BaseAuditEdit");
            }
            else
            {
                sb.AppendLine($"\tpublic partial class {entityName} : ObservableObject");
            }
            sb.AppendLine("\t{");
            sb.AppendLine(GenerateConstructor(prependSchemaNameIndicator: prependSchemaNameIndicator,
                                              excludedNavigationProperties: excludedNavigationProperties, entity: entity));

            // Add the properties
            foreach (var property in entityProperties)
            {
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;
                if ((!containsAuditEditFields || !IsColumnAnAuditEditField(property)) &&
                    !IsUnknownType(property))
                {
                    sb.AppendLine($"\t\tprivate {simpleType} {GetNameModuleLevelVariable(propertyName)};");
                }
            }

            sb.AppendLine(string.Empty);

            // For each field in properties, add a public method
            foreach (var property in entityProperties.OrderBy(x => x.Name).ToList())
            {
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;
                if ((!containsAuditEditFields || !IsColumnAnAuditEditField(property)) &&
                    !IsUnknownType(property))
                {
                    sb.AppendLine(string.Empty);
                    sb.AppendLine($"\t\tpublic {simpleType} {propertyName}");
                    sb.AppendLine("\t\t{");
                    sb.AppendLine("\t\t\tget { return " + GetNameModuleLevelVariable(propertyName) + "; }");
                    sb.AppendLine("\t\t\tset");
                    sb.AppendLine("\t\t\t{");
                    sb.AppendLine("\t\t\t\tSet<" + simpleType + ">(() => " + propertyName + ", ref " + GetNameModuleLevelVariable(propertyName) + ", value);");
                    sb.AppendLine($"\t\t\t\tRunCustomLogicSet{propertyName}(value);");
                    sb.AppendLine("\t\t\t}");
                    sb.AppendLine("\t\t}");
                }
            }

            sb.AppendLine(string.Empty);
            sb.AppendLine(GenerateNavigationProperties(prependSchemaNameIndicator: prependSchemaNameIndicator,
                                                       excludedNavigationProperties: excludedNavigationProperties, entity: entity));
            sb.AppendLine(string.Empty);
            sb.AppendLine("\t\tpartial void InitializePartial();");
            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\t#region RunCustomLogicSet"); // For each field in columns, add a partial method to run custom logic in each property settter.
            sb.AppendLine(string.Empty);
            foreach (var property in entityProperties.OrderBy(x => x.Name).ToList())
            {
                string ctype        = GetCType(property);
                var    simpleType   = ConvertToSimpleType(ctype);
                string propertyName = property.Name;
                if ((!containsAuditEditFields || !IsColumnAnAuditEditField(property)) &&
                    !IsUnknownType(property))
                {
                    sb.AppendLine($"\t\tpartial void RunCustomLogicSet{propertyName}({simpleType} value);");
                }
            }
            sb.AppendLine(string.Empty);
            sb.AppendLine($"\t\t#endregion RunCustomLogicSet"); // For each field in columns, add a partial method to run custom logic in each property settter.

            sb.Append(GenerateFooter());

            return(sb.ToString());
        }
Пример #30
0
        //TODO: Make an enum with the system types instead
        private string GetSampleDataValueOrUniquePKModuleLevelVariableName(IProperty property, int sampleNumber, int columnNumber, string numberFormat,
                                                                           Dictionary <string, string> uniquePKModuleLevelVariableNames, string entityName, string primaryKeyname)
        {
            string retVal       = string.Empty;
            string propertyName = Inflector.Pascalize(property.Name);
            string ctype        = GetCType(property);
            var    simpleType   = ConvertToSimpleType(ctype);

            // We need to use one of the existing premade identity keys if it's a PK
            // for now assume there are no 2 part keys
            if (property.Name == primaryKeyname)
            {
                string uniquePKModuleLevelVariableName    = GetUniquePKModuleLevelVariableName(entityName: entityName, sampleNumber: sampleNumber, columnNumber: columnNumber, numberFormat: numberFormat);
                string uniquePKModuleLevelVariableNameKey = $"{property.Name}{sampleNumber.ToString(numberFormat)}";

                if (!uniquePKModuleLevelVariableNames.ContainsKey(uniquePKModuleLevelVariableNameKey))
                {
                    throw new ApplicationException($"Error in GenerateSampleData.{nameof(GetSampleDataValueOrUniquePKModuleLevelVariableName)} - matching column name {propertyName} was not found in uniquePKModuleLevelVariableNames.");
                }

                retVal = uniquePKModuleLevelVariableNames[uniquePKModuleLevelVariableNameKey];
            }
            else
            {
                // These columns are not primary keys.
                switch (simpleType.ToLower())
                {
                case "guid":
                case "guid?":
                case "system.guid":
                case "system.guid?":
                    retVal = $"Guid.Parse(\"{Guid.NewGuid().ToString()}\")";
                    break;

                case "datetime":
                case "datetime?":
                case "datetimeoffset":
                case "system.datetime":
                case "system.datetime?":
                    retVal = "DateTime.Now";
                    break;

                case "short":
                case "short?":
                case "int":
                case "int?":
                case "system.int32":
                case "system.int32?":
                case "system.int64":
                case "system.int64?":
                case "double":
                case "double?":
                case "long":
                case "long?":
                case "decimal":
                case "decimal?":
                case "float":
                case "float?":
                    retVal = "0";
                    break;

                case "bool":
                case "bool?":
                    retVal = "false";
                    break;

                case "byte[]":
                case "byte[]?":
                    retVal = "new byte[0]";
                    break;

                case "string":
                    retVal = $"\"Sample{propertyName}\"";
                    break;

                case "system.data.entity.spatial.dbgeometry":
                    retVal = "\"geometry\"";
                    break;

                default:
                    retVal = "Unknown";
                    break;
                }
            }
            return(retVal);
        }