Beispiel #1
0
        private TextWriter AppendSettingCompositePk(TextWriter output, EntityContractDeclarationModel entityContractDeclaration, string entityParamName, string pkParamName)
        {
            bool appendSeparator = false;

            foreach (var pkProp in entityContractDeclaration.PkProperties)
            {
                if (appendSeparator)
                {
                    output.Write($@"
                && ");
                }

                output.Write($"{entityParamName}.{pkProp.Name} = {pkParamName}.{pkProp.Name}");
                appendSeparator = true;
            }

            foreach (var pkProp in entityContractDeclaration.PkEntityReferences)
            {
                if (appendSeparator)
                {
                    output.Write($@"
                && ");
                }

                output.Write($"{entityParamName}.{pkProp.Name}Id = {pkParamName}.{pkProp.Name}Id");
                appendSeparator = true;
            }

            return(output);
        }
Beispiel #2
0
        private static string GetPrimaryKeyTypeName(EntityContractDeclarationModel entityContractDeclaration)
        {
            if (entityContractDeclaration == null)
            {
                throw new ArgumentNullException(nameof(entityContractDeclaration));
            }
            if (!entityContractDeclaration.HasPk)
            {
                throw new ArgumentException("Entity does not have a primary key.", nameof(entityContractDeclaration));
            }

            if (entityContractDeclaration.HasCompositePk)
            {
                return(entityContractDeclaration.FriendlyName + "Pk");
            }
            else if (entityContractDeclaration.PkProperties.Length == 1)
            {
                return(entityContractDeclaration.PkProperties[0].TypeFriendlyName);
            }
            else if (entityContractDeclaration.PkEntityReferences.Length == 1)
            {
                throw new NotSupportedException("Primary key entity references are not supported!");
            }
            else
            {
                throw new NotSupportedException();
            }
        }
Beispiel #3
0
        private TextWriter WriteStaticRegion(TextWriter output, EntityContractDeclarationModel entityContractDeclaration)
        {
            if (entityContractDeclaration.HasPk)
            {
                output.Write(
                    $@"
        #region STATIC");

                WritePublicStaticPkComparerFields(output, entityContractDeclaration);
                output.Write(
                    @"
        ");

                WritePublicStaticGetPkMethod(output, entityContractDeclaration);
                output.Write(
                    @"
        ");

                WritePublicStaticSetPkMethod(output, entityContractDeclaration);

                output.Write(
                    $@"
        #endregion STATIC
        ");
            }
            return(output);
        }
Beispiel #4
0
        private static string GetBaseClassAndImplementedInterfaceListString(EntityContractDeclarationModel entityContractDeclaration)
        {
            var sb = new StringBuilder();

            sb.Append(" : I").Append(entityContractDeclaration.FriendlyName);
            if (entityContractDeclaration.HasPk)
            {
                sb.Append(", IHasPk<").Append(GetPrimaryKeyTypeName(entityContractDeclaration)).Append(">");
            }

            var interfaces = entityContractDeclaration.DeclaringInterfaceType.GetInterfaces();

            if ((interfaces != null) && (interfaces.Length > 0))
            {
                //    sb.Append(@"
                //");

                foreach (var intrfce in entityContractDeclaration.DeclaringInterfaceType.GetInterfaces())
                {
                    sb.Append(", ").AppendFriendlyTypeName(intrfce);
                }
            }

            return(sb.ToString());
        }
        public void UnitTest_SerializeEntityContractDeclarationModel()
        {
            var auditableEntityType    = typeof(IGetListItemsRequestV01);
            var entityDeclarationTypes = auditableEntityType.Assembly.DefinedTypes.Where(type => Attribute.IsDefined(type, typeof(EntityContractDeclarationAttribute))).ToArray();

            var jsonSerializerSettings = new JsonSerializerSettings()
            {
                NullValueHandling     = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
                DefaultValueHandling  = DefaultValueHandling.IgnoreAndPopulate,
            };

            foreach (var typeDeclaringEntityContract in entityDeclarationTypes)
            {
                var entityCodeGenModel = new EntityContractDeclarationModel(typeDeclaringEntityContract);

                string filePath = Path.Combine(Environment.CurrentDirectory, $"{entityCodeGenModel.DeclaringInterfaceType.Namespace.Replace(auditableEntityType.Namespace, "").TrimStart('.')}.{entityCodeGenModel.FriendlyName}.codeGenModel.json");
                using (System.IO.FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (var writer = new System.IO.StreamWriter(fs, Encoding.UTF8, 4096))
                    {
                        var jsonString = JsonConvert.SerializeObject(entityCodeGenModel, Formatting.Indented, jsonSerializerSettings);
                        writer.Write(jsonString);
                    }
                }
            }
        }
        public void UnitTest_EntityClassGenerator()
        {
            var auditableEntityType    = typeof(IGetListItemsRequestV01);
            var entityDeclarationTypes = auditableEntityType.Assembly.DefinedTypes.Where(type => Attribute.IsDefined(type, typeof(EntityContractDeclarationAttribute))).ToArray();
            var targetBaseFolderPath   = Path.GetFullPath(@"../../../../Product.Generated/");
            var targetBaseFolder       = new DirectoryInfo(targetBaseFolderPath);

            if (!targetBaseFolder.Exists)
            {
                targetBaseFolder.Create();
            }

            foreach (var typeDeclaringEntityContract in entityDeclarationTypes)
            {
                var entityCodeGenModel = new EntityContractDeclarationModel(typeDeclaringEntityContract);

                var subDirPath      = entityCodeGenModel.DeclaringInterfaceType.Namespace.Replace(auditableEntityType.Namespace, "").TrimStart('.').Replace(".", @"/");
                var targetDirectory = string.IsNullOrWhiteSpace(subDirPath)
                    ? targetBaseFolder
                    : targetBaseFolder.CreateSubdirectory(subDirPath);

                //string filePath = Path.Combine(targetDirectory.FullName, $"{entityCodeGenModel.DeclaringInterfaceType.Namespace.Replace(auditableEntityType.Namespace, "").TrimStart('.')}.{entityCodeGenModel.FriendlyName}.cs");
                string filePath = Path.Combine(targetDirectory.FullName, $"{entityCodeGenModel.FriendlyName}.cs");
                using (System.IO.FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite))
                {
                    using (var writer = new System.IO.StreamWriter(fs, Encoding.UTF8, 4096))
                    {
                        var entityClassGenerator = new EntityClassGenerator();
                        entityClassGenerator.Generate(writer, entityCodeGenModel, entityCodeGenModel.EntityContractDeclarationAttribute.Namespace ?? "ProductName.Data.Model");
                    }
                }
            }
        }
        public TextWriter Generate(TextWriter output, EntityContractDeclarationModel entityContractDeclaration, string targetNamespace)
        {
            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }
            if (entityContractDeclaration == null)
            {
                throw new ArgumentNullException(nameof(entityContractDeclaration));
            }
            if (!entityContractDeclaration.DeclaringInterfaceType.IsInterface)
            {
                throw new ArgumentException("The provided entity contract declaration is not an interface!", nameof(entityContractDeclaration));
            }

            output.Write(
                $@"{GetAdditionalNamespaceUsings(entityContractDeclaration, targetNamespace)}

namespace {targetNamespace}
{{
    public interface I{entityContractDeclaration.FriendlyName}{GetBaseClassAndImplementedInterfaceListString(entityContractDeclaration)}
    {{");

            WritePropertyDeclarations(output, entityContractDeclaration);

            output.Write(
                $@"
    }}
}}");
            return(output);
        }
Beispiel #8
0
        private TextWriter AppendGettingCompositePk(TextWriter output, EntityContractDeclarationModel entityContractDeclaration, string paramName)
        {
            bool appendSeparator = false;

            output.Write($"new {entityContractDeclaration.FriendlyName}Pk(");

            foreach (var pkProp in entityContractDeclaration.PkProperties)
            {
                if (appendSeparator)
                {
                    output.Write($", ");
                }

                output.Write($"{paramName}.{pkProp.Name}");
                appendSeparator = true;
            }

            foreach (var pkEntityRefProp in entityContractDeclaration.PkEntityReferences)
            {
                if (appendSeparator)
                {
                    output.Write($", ");
                }

                output.Write($"{paramName}.{pkEntityRefProp.Name}Id");
                appendSeparator = true;
            }

            output.Write($");");

            return(output);
        }
 public void Test_EntityContractDeclarationModel_constructor()
 {
     foreach (var typeDeclaringEntityContract in typeof(IGetListItemsRequestV01).Assembly.GetExportedTypes().Where(type => Attribute.IsDefined(type, typeof(EntityContractDeclarationAttribute))))
     {
         var entityCodeGenModel = new EntityContractDeclarationModel(typeDeclaringEntityContract);
         System.Diagnostics.Debug.WriteLine(entityCodeGenModel);
     }
 }
Beispiel #10
0
 private TextWriter AppendSettingPrimaryKey(TextWriter output, EntityContractDeclarationModel entityContractDeclaration, string entityParamName, string pkParamName)
 {
     if (entityContractDeclaration.HasCompositePk)
     {
         return(AppendSettingCompositePk(output, entityContractDeclaration, entityParamName, pkParamName));
     }
     else
     {
         return(AppendSettingSimplePk(output, entityContractDeclaration, entityParamName, pkParamName));
     }
 }
Beispiel #11
0
        private static string GetAdditionalNamespaceUsings(EntityContractDeclarationModel entityContractDeclaration, string targetNamespace)
        {
            var namespaceUsings = new HashSet <string>(defaultNamespacesUsed, StringComparer.InvariantCulture);

            foreach (var i in entityContractDeclaration.DeclaringInterfaceType.GetInterfaces())
            {
                if (!namespaceUsings.Contains(i.Namespace))
                {
                    namespaceUsings.Add(i.Namespace);
                }
            }

            foreach (var prop in entityContractDeclaration.GetProperties())
            {
                var entityNamespace = entityContractDeclaration.EntityContractDeclarationAttribute?.Namespace ?? prop.DeclaringProperty.PropertyType.Namespace;
                if ((entityNamespace != targetNamespace) && !namespaceUsings.Contains(entityNamespace))
                {
                    namespaceUsings.Add(entityNamespace);
                }
            }

            foreach (var a in entityContractDeclaration.GetCustomAttributes())
            {
                if (!namespaceUsings.Contains(a.AttributeType.Namespace))
                {
                    namespaceUsings.Add(a.AttributeType.Namespace);
                }

                if ((a.ConstructorArguments != null) && (a.ConstructorArguments.Count > 0))
                {
                    foreach (var ca in a.ConstructorArguments)
                    {
                        if (!namespaceUsings.Contains(ca.ArgumentType.Namespace))
                        {
                            namespaceUsings.Add(ca.ArgumentType.Namespace);
                        }
                    }
                }
            }

            StringBuilder sb = new StringBuilder();

            foreach (var ns in namespaceUsings.OrderBy(s => s, StringComparer.InvariantCulture))
            {
                sb.Append(@"
using ").Append(ns).Append(";");
            }

            return(sb.ToString());
        }
Beispiel #12
0
        private TextWriter WritePropertyDeclarations(TextWriter output, EntityContractDeclarationModel entityContractDeclaration)
        {
            foreach (var prop in entityContractDeclaration.PkProperties)
            {
                output.WriteLine(
                    $@"
        /// <summary>
        /// {GetPropertyGetSetXmlCommentPrefix(prop)} the '{prop.Name}' primary key property value.
        /// </summary>
        [Key]{GetAttributeDeclarations(prop)}
        public {prop.TypeFriendlyName} {prop.Name} {{ {GetPropertyGetSetDeclaration(prop)} }}");
            }

            foreach (var prop in entityContractDeclaration.PkEntityReferences
                     .Where(pker => pker.EntityRefAttribute.Multiplicity != EntityReferenceMultiplicityEnum.Many))
            {
                //prop.EntityRefAttribute.Multiplicity // TODO handle multiplicity
                output.WriteLine(
                    $@"
        /// <summary>
        /// {GetPropertyGetSetXmlCommentPrefix(prop)} the foreign key of the '{prop.Name}' entity reference that is part of the primary key.
        /// </summary>{GetAttributeDeclarations(prop)}
        public virtual {prop.TypeFriendlyName} {prop.Name} {{ {GetPropertyGetSetDeclaration(prop)} }}");
            }

            foreach (var prop in entityContractDeclaration.NonPkProperties)
            {
                output.WriteLine(
                    $@"
        /// <summary>
        /// {GetPropertyGetSetXmlCommentPrefix(prop)} the '{prop.Name}' simple property value.
        /// </summary>{GetAttributeDeclarations(prop)}
        public {prop.TypeFriendlyName} {prop.Name} {{ {GetPropertyGetSetDeclaration(prop)} }}");
            }

            foreach (var prop in entityContractDeclaration.EntityReferences
                     .Where(pker => pker.EntityRefAttribute.Multiplicity != EntityReferenceMultiplicityEnum.Many))
            {
                //prop.EntityRefAttribute.Multiplicity // TODO handle multiplicity
                output.WriteLine(
                    $@"
        /// <summary>
        /// {GetPropertyGetSetXmlCommentPrefix(prop)} the '{prop.Name}' navigation property value.
        /// </summary>{GetAttributeDeclarations(prop)}
        public virtual {prop.TypeFriendlyName} {prop.Name} {{ {GetPropertyGetSetDeclaration(prop)} }}");
            }

            return(output);
        }
Beispiel #13
0
        private TextWriter WritePublicStaticPkComparerFields(TextWriter output, EntityContractDeclarationModel entityContractDeclaration)
        {
            output.Write(
                $@"
        /// <summary>
        /// Read-only field for the primary key equality comparer of the '{entityContractDeclaration.FriendlyName}' entity.
        /// </summary>
        public static readonly IEqualityComparer<{entityContractDeclaration.FriendlyName}> PkEqualityComparer = new EqualityComparer<{entityContractDeclaration.FriendlyName}>(GetPk, EqualityComparer<{GetPrimaryKeyTypeName(entityContractDeclaration)}>.Default);
        
        /// <summary>
        /// Read-only field for the primary key comparer of the '{entityContractDeclaration.FriendlyName}' entity.
        /// </summary>
        public static readonly IComparer<{entityContractDeclaration.FriendlyName}> PkComparer = new Comparer<{entityContractDeclaration.FriendlyName}>(GetPk, Comparer<{GetPrimaryKeyTypeName(entityContractDeclaration)}>.Default);");

            return(output);
        }
Beispiel #14
0
        private TextWriter WritePublicInstanceSetPkMethod(TextWriter output, EntityContractDeclarationModel entityContractDeclaration)
        {
            output.Write(
                $@"
        /// <summary>
        /// Sets the primary key of this '{entityContractDeclaration.FriendlyName}' instance to the given value.
        /// </summary>
        /// <param name=""pk"">The primary key to set.</param>
        public void SetPk({GetPrimaryKeyTypeName(entityContractDeclaration)} pk)
        {{
            ");
            AppendSettingPrimaryKey(output, entityContractDeclaration, "this", "pk");
            output.Write(
                @";
        }");

            return(output);
        }
Beispiel #15
0
        private TextWriter WritePublicInstanceGetPkMethod(TextWriter output, EntityContractDeclarationModel entityContractDeclaration)
        {
            output.Write(
                $@"
        /// <summary>
        /// Gets the primary key of this '{entityContractDeclaration.FriendlyName}' instance.
        /// </summary>
        /// <returns>The primary key value of this '{entityContractDeclaration.FriendlyName}' instance.</returns>
        public {GetPrimaryKeyTypeName(entityContractDeclaration)} GetPk()
        {{
            return ");
            AppendGettingPrimaryKey(output, entityContractDeclaration, "this");
            output.Write(
                @";
        }");

            return(output);
        }
Beispiel #16
0
        private TextWriter WriteIHasPkInterfaceImplementation(TextWriter output, EntityContractDeclarationModel entityContractDeclaration)
        {
            output.Write(
                $@"
        #region IHasPk<{GetPrimaryKeyTypeName(entityContractDeclaration)}> implementation");

            WritePublicInstanceGetPkMethod(output, entityContractDeclaration);

            output.Write(
                @"
        ");
            WritePublicInstanceSetPkMethod(output, entityContractDeclaration);

            output.Write(
                $@"
        #endregion IHasPk<{GetPrimaryKeyTypeName(entityContractDeclaration)}> implementation");

            return(output);
        }
Beispiel #17
0
        private TextWriter WriteInterfaceImplementation(TextWriter output, EntityContractDeclarationModel entityContractDeclaration, Type intrfceType)
        {
            var intrfaceFriendlyTypeName = intrfceType.GetFriendlyTypeName();

            output.Write(
                $@"
        #region {intrfaceFriendlyTypeName} implementation");

            output = WriteImplicitImplementationForInterfaceProperties(output, entityContractDeclaration, intrfceType);

//            output.Write(
//@"
//        ");
            output = WriteImplicitImplementationForInterfaceMethods(output, entityContractDeclaration, intrfceType);

            output.Write(
                $@"
        #endregion {intrfaceFriendlyTypeName} implementation");

            return(output);
        }
        private static string GetBaseClassAndImplementedInterfaceListString(EntityContractDeclarationModel entityContractDeclaration)
        {
            var interfaces = entityContractDeclaration.DeclaringInterfaceType.GetInterfaces();

            bool          appendSeparator = false;
            StringBuilder sb = new StringBuilder();

            if (entityContractDeclaration.HasPk)
            {
                sb.Append(" : IHasPk<").Append(GetPrimaryKeyTypeName(entityContractDeclaration)).Append(">");
                appendSeparator = true;
            }

            if ((interfaces != null) && (interfaces.Length > 0))
            {
                if (!appendSeparator)
                {
                    sb.Append(" : ");
                }

                foreach (var i in interfaces)
                {
                    if (appendSeparator)
                    {
                        sb.Append(", ");
                    }
                    else
                    {
                        appendSeparator = true;
                    }

                    sb.AppendFriendlyTypeName(i);
                }
            }
            return(sb.ToString());
        }
Beispiel #19
0
        private TextWriter WritePublicStaticSetPkMethod(TextWriter output, EntityContractDeclarationModel entityContractDeclaration)
        {
            output.Write(
                $@"
        /// <summary>
        /// Sets the primary key of the given '{entityContractDeclaration.FriendlyName}' instance to the given value.
        /// </summary>
        /// <param name=""entity"">The '{entityContractDeclaration.FriendlyName}' instance to set primary key of.</param>
        /// <param name=""pk"">The primary key to set.</param>
        /// <exception cref=""ArgumentNullException"">Thrown if <paramref name=""entity""/> is null.</exception>
        public static void SetPk<TEntity>(TEntity entity, {GetPrimaryKeyTypeName(entityContractDeclaration)} pk)
            where TEntity : I{entityContractDeclaration.FriendlyName}
        {{
            if (entity == null)
                throw new ArgumentNullException(nameof(entity));

            ");
            AppendSettingPrimaryKey(output, entityContractDeclaration, "entity", "pk");
            output.Write(
                @";
        }");

            return(output);
        }
Beispiel #20
0
        private TextWriter WriteImplicitImplementationForInterfaceMethods(TextWriter output, EntityContractDeclarationModel entityContractDeclaration, Type intrfceType)
        {
            foreach (var mi in intrfceType.GetMethods())
            {
                if (mi.IsStatic || !mi.IsPublic || mi.IsSpecialName)
                {
                    continue;
                }

                var methodParams = mi.GetParameters() ?? Array.Empty <ParameterInfo>();

                output.WriteLine(
                    $@"
        /// <summary>
        /// 
        /// </summary>
        public {mi.ReturnType.GetFriendlyTypeName()} {mi.Name}({GetMethodParameterDeclaration(mi)})
        {{
            // TODO Implement method
        }}");
            }

            return(output);
        }
Beispiel #21
0
        private TextWriter WriteImplicitImplementationForInterfaceProperties(TextWriter output, EntityContractDeclarationModel entityContractDeclaration, Type intrfceType)
        {
            foreach (var pi in intrfceType.GetProperties())
            {
                var prop = new PropertyDeclarationModel(pi);

                output.WriteLine(
                    $@"
        /// <summary>
        /// {GetPropertyGetSetXmlCommentPrefix(prop)} the '{prop.Name}' property value.
        /// </summary>{GetAttributeDeclarations(prop)}
        public {prop.TypeFriendlyName} {prop.Name} {{ {GetPropertyGetSetDeclaration(prop)} }}");
            }

            return(output);
        }
Beispiel #22
0
        private TextWriter AppendSettingSimplePk(TextWriter output, EntityContractDeclarationModel entityContractDeclaration, string entityParamName, string pkParamName)
        {
            output.Write($"{entityParamName}.{entityContractDeclaration.PkProperties[0].Name} = {pkParamName}");

            return(output);
        }