public GeneratorManagerParams(GenerateDTOsParams dtosParams, 
     GenerateAssemblersParams assemblersParams, bool generateAssemblers)
 {
     this.DTOsParams = dtosParams;
     this.AssemblersParams = assemblersParams;
     this.GenerateAssemblers = generateAssemblers;
 }
        /// <summary>
        /// Creates an instance of <see cref="EntityKeyProperty"/>.
        /// </summary>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        public EntityKeyProperty(XElement entityNode, XElement propertyRefNode, 
            IEnumerable<XElement> propertyNodeElements, GenerateDTOsParams genParams)
        {
            // Get the Entity name
            string entityName = entityNode.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

            // Set the DTO name
            this.DTOName = Utils.ConstructDTOName(entityName, genParams);

            // Set the Property name
            string propertyNameDesired = propertyRefNode.Attribute(EdmxNodeAttributes.PropertyRef_Name).Value;
            this.Name = PropertyHelper.GetPropertyName(propertyNameDesired, entityName);

            // Find the Property node
            XElement propertyNode = propertyNodeElements.FirstOrDefault(p =>
                p.Attribute(EdmxNodeAttributes.Property_Name).Value == propertyNameDesired);

            // Check Property node exists
            if (propertyNode == null)
            {
                throw new ApplicationException(string.Format(Resources.Error_PropertyKeyMissing,
                    entityName, propertyNameDesired));
            }

            this.Type = PropertyHelper.GetTypeFromEDMXProperty(propertyNode, entityName);
        }
Example #3
0
 public GeneratorManagerParams(GenerateDTOsParams dtosParams,
                               GenerateAssemblersParams assemblersParams, bool generateAssemblers)
 {
     this.DTOsParams         = dtosParams;
     this.AssemblersParams   = assemblersParams;
     this.GenerateAssemblers = generateAssemblers;
 }
Example #4
0
        /// <summary>
        /// Creates an instance of <see cref="DTOEntity"/>.
        /// </summary>
        /// <param name="typeNode">Type node.</param>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <param name="navigations">Entity navigations available.</param>
        public DTOEntity(XElement typeNode, GenerateDTOsParams genParams, List<EntityNavigation> navigations)
            : base(typeNode, genParams)
        {
            // Define Class Base Type (if exists)
            string entityBaseType = EdmxHelper.GetEntityBaseType(typeNode);
            if (string.IsNullOrWhiteSpace(entityBaseType) == false)
            {
                // Check if base type is going to be generated
                if (genParams.TypesToGenerateFilter.Contains(entityBaseType) == true)
                {
                    this.NameBaseDTO = Utils.ConstructDTOName(entityBaseType, genParams);
                }
            }

            #region Set IsAbstract

            if (typeNode.Attribute(EdmxNodeAttributes.EntityType_Abstract) != null)
            {
                string abstractValue = typeNode.Attribute(EdmxNodeAttributes.EntityType_Abstract).Value.ToLower();
                this.IsAbstract = (abstractValue == Resources.XmlBoolTrue);
            }

            #endregion Set IsAbstract

            #region Set Navigation Properties

            if (navigations != null)
            {
                IEnumerable<EntityNavigation> myNavigations = navigations.Where(a => a.DTOName == this.NameDTO);

                foreach (EntityNavigation entityNav in myNavigations)
                {
                    foreach (EntityNavigationProperty navProperty in entityNav.NavigationProperties)
                    {
                        // Add property only if target type is going to be generated
                        if (genParams.TypesToGenerateFilter.Contains(navProperty.EntityTargetName) == true)
                        {
                            if (genParams.AssociationType == AssociationType.KeyProperty
                                && this.Properties.Exists(p => p.PropertyName == navProperty.Name))
                            {
                                VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                                    string.Format(Resources.Warning_PropertyNameConflict, this.Name, navProperty.Name, navProperty.EntityTargetName),
                                    genParams.TargetProject, null, null, null);
                            }
                            else
                            {
                                this.Properties.Add(new DTOClassProperty(
                                    entityNav.NavigationPropertyNameEDMX, navProperty, genParams.DTOsServiceReady));
                            }
                        }
                    }
                }
            }

            #endregion Set Association Properties
        }
Example #5
0
        /// <summary>
        /// Constructs a dto name using the entity name and configuration received.
        /// </summary>
        /// <param name="entityName">Entity name.</param>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        public static string ConstructDTOName(string entityName, GenerateDTOsParams genParams)
        {
            if (string.IsNullOrWhiteSpace(entityName) == true)
            {
                return null;
            }

            string dtoName = entityName;

            if (genParams.ClassIdentifierUse == ClassIdentifierUse.Prefix)
            {
                dtoName = (genParams.ClassIdentifierWord + dtoName);
            }
            else if (genParams.ClassIdentifierUse == ClassIdentifierUse.Suffix)
            {
                dtoName = (dtoName + genParams.ClassIdentifierWord);
            }

            return dtoName;
        }
        /// <summary>
        /// Creates an instance of <see cref="EntityAssociation"/>.
        /// </summary>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        public EntityAssociation(XElement associationNode, EntityAssociationEnd entityAssociationEndDesired, 
            GenerateDTOsParams genParams)
        {
            // Set Association Name
            this.AssociationName = associationNode.Attribute(EdmxNodeAttributes.Association_Name).Value;

            // Get End nodes
            XElement[] endNodes = associationNode.DescendantsCSDL(EdmxNodes.End).ToArray();

            // Get the position of the desired End node
            int endPosition = (entityAssociationEndDesired == EntityAssociationEnd.First ? 0 : 1);

            // Set DTO Name
            this.EntityName = endNodes[endPosition].Attribute(EdmxNodeAttributes.End_Type).Value;
            string[] entityNameSplitted = this.EntityName.Split(new string[] { Resources.Dot }, StringSplitOptions.RemoveEmptyEntries);
            this.EntityName = entityNameSplitted[(entityNameSplitted.Length - 1)];
            this.DTOName = Utils.ConstructDTOName(this.EntityName, genParams);

            // Set End Role Name
            this.EndRoleName = endNodes[endPosition].Attribute(EdmxNodeAttributes.End_Role).Value;

            // Set Multiplicity
            this.EndMultiplicity = EntityAssociationHelper.GetMultiplicity(endNodes[endPosition]);
        }
Example #7
0
 /// <summary>
 /// Creates an instance of <see cref="DTOComplex"/>.
 /// </summary>
 /// <param name="typeNode">Type node.</param>
 /// <param name="genParams">Parameters for the generation of DTOs.</param>
 public DTOComplex(XElement typeNode, GenerateDTOsParams genParams)
     : base(typeNode, genParams)
 {
 }
Example #8
0
        /// <summary>
        /// Gets the enum types available.
        /// </summary>
        /// <param name="parameters">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List<EnumType> GetEnumTypes(GenerateDTOsParams parameters)
        {
            var enums = new List<EnumType>();

            foreach (XElement xEnum in EdmxHelper.GetEnumTypeNodes(parameters.EDMXDocument))
            {
                var enumType = new EnumType();
                enumType.Name = xEnum.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

                XAttribute attrExternalType = xEnum.Attribute(EdmxNodeAttributes.EnumType_ExternalTypeName);
                if (attrExternalType != null)
                {
                    enumType.ExternalTypeName = attrExternalType.Value;

                    VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                        string.Format(Resources.Warning_ManuallyAddReferenceForEnum, enumType.ExternalTypeName),
                        parameters.TargetProject, null, null, null);
                }

                enums.Add(enumType);
            }

            return enums;
        }
Example #9
0
        /// <summary>
        /// Generates the DTOs of the EDMX Document provided using the parameters received.
        /// </summary>
        /// <param name="parameters">Parameters for the generation of DTOs.</param>
        /// <param name="worker">BackgroundWorker reference.</param>
        public static List<DTOEntity> GenerateDTOs(GenerateDTOsParams parameters, BackgroundWorker worker)
        {
            LogManager.LogMethodStart();

            if (parameters.DTOsServiceReady)
            {
                VisualStudioHelper.AddReferenceToProject(parameters.TargetProject,
                    Resources.AssemblySystemRuntimeSerialization, Resources.AssemblySystemRuntimeSerialization);
            }

            if (GeneratorManager.CheckCancellationPending()) return null;

            EditPoint objEditPoint; // EditPoint to reuse
            CodeParameter objCodeParameter; // CodeParameter to reuse
            CodeNamespace objNamespace = null; // Namespace item to add Classes
            ProjectItem sourceFileItem = null; // Source File Item to save
            int dtosGenerated = 0;

            List<EnumType> enums = DTOGenerator.GetEnumTypes(parameters);
            PropertyHelper.SetEnumTypes(enums);

            List<DTOEntity> entitiesDTOs = DTOGenerator.GetEntityDTOs(parameters);

            if (GeneratorManager.CheckCancellationPending()) return null;

            worker.ReportProgress(0, new GeneratorOnProgressEventArgs(0,
                string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count)));

            TemplateClass.CreateFile();

            // Imports to add to the Source File
            var importList = new List<SourceCodeImport>();

            // EnumTypes defined in the EDMX ?
            if (enums.Exists(e => e.IsExternal == false))
            {
                importList.Add(new SourceCodeImport(parameters.EntitiesNamespace));
                VisualStudioHelper.AddReferenceToProject(parameters.TargetProject, parameters.EDMXProject);
            }

            // Include imports of external enums.
            foreach (string externalEnumNamespace in enums.Where(e => e.IsExternal).Select(e => e.Namespace).Distinct())
            {
                importList.Add(new SourceCodeImport(externalEnumNamespace));
            }

            // Generate Source File if type is One Source File
            if (parameters.SourceFileGenerationType == SourceFileGenerationType.OneSourceFile)
            {
                sourceFileItem = null;

                // Generate Source and Get the Namespace item
                objNamespace = VisualStudioHelper.GenerateSourceAndGetNamespace(
                    parameters.TargetProject, parameters.TargetProjectFolder,
                    parameters.SourceFileName, parameters.SourceFileHeaderComment,
                    parameters.SourceNamespace, parameters.DTOsServiceReady, out sourceFileItem);

                // Add Imports to Source File
                VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList);
            }

            // Check Cancellation Pending
            if (GeneratorManager.CheckCancellationPending()) return null;

            // Loop through Entities DTOs
            foreach (DTOEntity entityDTO in entitiesDTOs)
            {
                // Generate Source File if type is Source File per Class
                if (parameters.SourceFileGenerationType == SourceFileGenerationType.SourceFilePerClass)
                {
                    sourceFileItem = null;

                    // Generate Source and Get the Namespace item
                    objNamespace = VisualStudioHelper.GenerateSourceAndGetNamespace(
                        parameters.TargetProject, parameters.TargetProjectFolder,
                        entityDTO.NameDTO, parameters.SourceFileHeaderComment,
                        parameters.SourceNamespace, parameters.DTOsServiceReady, out sourceFileItem);

                    // Add Imports to Source File
                    VisualStudioHelper.AddImportsToSourceCode(ref sourceFileItem, importList);
                }

                // Add Class
                CodeClass objCodeClass = objNamespace.AddClassWithPartialSupport(entityDTO.NameDTO, entityDTO.NameBaseDTO,
                    entityDTO.DTOClassAccess, entityDTO.DTOClassKind);

                // Set IsAbstract
                objCodeClass.IsAbstract = entityDTO.IsAbstract;

                // Set Class Attributes
                foreach (DTOAttribute classAttr in entityDTO.Attributes)
                {
                    objCodeClass.AddAttribute(classAttr.Name, classAttr.Parameters, AppConstants.PLACE_AT_THE_END);
                }

                // Set Class Properties
                foreach (DTOClassProperty entityProperty in entityDTO.Properties)
                {
                    // Add Property
                    CodeProperty objCodeProperty = objCodeClass.AddProperty(entityProperty.PropertyName,
                        entityProperty.PropertyName, entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END,
                        entityProperty.PropertyAccess, null);

                    // Get end of accessors auto-generated code
                    objEditPoint = objCodeProperty.Setter.EndPoint.CreateEditPoint();
                    objEditPoint.LineDown();
                    objEditPoint.EndOfLine();
                    var getSetEndPoint = objEditPoint.CreateEditPoint();

                    // Move to the start of accessors auto-generated code
                    objEditPoint = objCodeProperty.Getter.StartPoint.CreateEditPoint();
                    objEditPoint.LineUp();
                    objEditPoint.LineUp();
                    objEditPoint.EndOfLine();

                    // Replace accessors auto-generated code with a more cleaner one
                    objEditPoint.ReplaceText(getSetEndPoint, Resources.CSharpCodeGetSetWithBrackets,
                        Convert.ToInt32(vsEPReplaceTextOptions.vsEPReplaceTextAutoformat));

                    // Set Property Attributes
                    foreach (DTOAttribute propAttr in entityProperty.PropertyAttributes)
                    {
                        objCodeProperty.AddAttribute(propAttr.Name,
                            propAttr.Parameters, AppConstants.PLACE_AT_THE_END);
                    }

                    objEditPoint = objCodeProperty.StartPoint.CreateEditPoint();
                    objEditPoint.SmartFormat(objEditPoint);
                }

                if (parameters.GenerateDTOConstructors)
                {
                    // Add empty Constructor
                    CodeFunction emptyConstructor = objCodeClass.AddFunction(objCodeClass.Name,
                        vsCMFunction.vsCMFunctionConstructor, null, AppConstants.PLACE_AT_THE_END,
                        vsCMAccess.vsCMAccessPublic, null);

                    // Does this DTO have a Base Class ?
                    if (entityDTO.BaseDTO != null)
                    {
                        // Add call to empty Base Constructor
                        objEditPoint = emptyConstructor.StartPoint.CreateEditPoint();
                        objEditPoint.EndOfLine();
                        objEditPoint.Insert(Resources.Space + Resources.CSharpCodeBaseConstructor);
                    }

                    // Does this DTO have properties ?
                    if (entityDTO.Properties.Count > 0)
                    {
                        // Add Constructor with all properties as parameters
                        CodeFunction constructorWithParams = objCodeClass.AddFunction(objCodeClass.Name,
                            vsCMFunction.vsCMFunctionConstructor, null, AppConstants.PLACE_AT_THE_END,
                            vsCMAccess.vsCMAccessPublic, null);

                        foreach (DTOClassProperty entityProperty in entityDTO.Properties)
                        {
                            // Add Constructor parameter
                            objCodeParameter = constructorWithParams.AddParameter(
                                Utils.SetFirstLetterLowercase(entityProperty.PropertyName),
                                entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END);

                            // Add assignment
                            objEditPoint = constructorWithParams.EndPoint.CreateEditPoint();
                            objEditPoint.LineUp();
                            objEditPoint.EndOfLine();
                            objEditPoint.Insert(Environment.NewLine + AppConstants.TAB + AppConstants.TAB + AppConstants.TAB);
                            objEditPoint.Insert(string.Format(Resources.CSharpCodeAssignmentThis,
                                entityProperty.PropertyName, objCodeParameter.Name));
                        }

                        // Does this DTO have a Base Class ?
                        if (entityDTO.BaseDTO != null)
                        {
                            // Get the Base Class properties (includes the properties of the base recursively)
                            List<DTOClassProperty> baseProperties =
                                DTOGenerator.GetPropertiesForConstructor(entityDTO.BaseDTO);

                            // Base Constructor parameters
                            var sbBaseParameters = new StringBuilder();

                            foreach (DTOClassProperty entityProperty in baseProperties)
                            {
                                // Add Constructor parameter
                                objCodeParameter = constructorWithParams.AddParameter(
                                    Utils.SetFirstLetterLowercase(entityProperty.PropertyName),
                                    entityProperty.PropertyType, AppConstants.PLACE_AT_THE_END);

                                // Add parameter separation if other parameters exists
                                if (sbBaseParameters.Length > 0)
                                {
                                    sbBaseParameters.Append(Resources.CommaSpace);
                                }

                                // Add to Base Constructor parameters
                                sbBaseParameters.Append(objCodeParameter.Name);
                            }

                            // Add call to Base Constructor with parameters
                            objEditPoint = constructorWithParams.StartPoint.CreateEditPoint();
                            objEditPoint.EndOfLine();
                            objEditPoint.Insert(
                                Environment.NewLine + AppConstants.TAB + AppConstants.TAB + AppConstants.TAB);
                            objEditPoint.Insert(
                                string.Format(Resources.CSharpCodeBaseConstructorWithParams, sbBaseParameters.ToString()));

                        } // END if DTO has a Base Class

                    } // END if DTO has properties

                } // END if Generate DTO Constructor methods

                // Save changes to Source File Item
                sourceFileItem.Save();

                // Count DTO generated
                dtosGenerated++;

                // Report Progress
                int progress = ((dtosGenerated * 100) / entitiesDTOs.Count);
                if (progress < 100)
                {
                    worker.ReportProgress(progress, new GeneratorOnProgressEventArgs(progress,
                        string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count)));
                }

                // Check Cancellation Pending
                if (GeneratorManager.CheckCancellationPending()) return null;

            } // END Loop through Entities DTOs

            // Save Target Project
            parameters.TargetProject.Save();

            // Delete Template Class File
            TemplateClass.Delete();

            // Report Progress
            worker.ReportProgress(100, new GeneratorOnProgressEventArgs(100,
                string.Format(Resources.Text_DTOsGenerated, dtosGenerated, entitiesDTOs.Count)));

            LogManager.LogMethodEnd();

            // Return the DTOs generated
            return entitiesDTOs;
        }
Example #10
0
        /// <summary>
        /// Gets the Keys of an Entity.
        /// </summary>
        /// <param name="entityNodeKeysOwner">EntityType node to get the keys from.</param>
        /// <param name="entityNodeToSetKeys">EntityType node to set the keys.</param>
        /// <param name="entityNodeElements">EntityType nodes.</param>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List<EntityKeyProperty> GetEntityKeys(XElement entityNodeKeysOwner, XElement entityNodeToSetKeys,
            IEnumerable<XElement> entityNodeElements, GenerateDTOsParams genParams)
        {
            LogManager.LogMethodStart();

            var result = new List<EntityKeyProperty>();

            IEnumerable<XElement> propertyRefNodeElements = entityNodeKeysOwner.DescendantsCSDL(EdmxNodes.PropertyRef);

            IEnumerable<XElement> propertyNodeElements = entityNodeKeysOwner.DescendantsCSDL(EdmxNodes.Property);

            foreach (var propertyRefNode in propertyRefNodeElements)
            {
                result.Add(new EntityKeyProperty(entityNodeToSetKeys, propertyRefNode,
                    propertyNodeElements, genParams));
            }

            // Does this Entity have a Base Type ?
            string entityBaseType = EdmxHelper.GetEntityBaseType(entityNodeKeysOwner);
            if (entityBaseType != null)
            {
                // Find the Base Type node
                XElement entityBaseTypeNode = entityNodeElements.FirstOrDefault(
                    e => e.Attribute(EdmxNodeAttributes.EntityType_Name).Value == entityBaseType);

                if (entityBaseTypeNode == null)
                {
                    throw new ApplicationException(string.Format(Resources.Error_BaseTypeNotFound,
                        entityNodeKeysOwner.Attribute(EdmxNodeAttributes.EntityType_Name).Value, entityBaseType));
                }

                // Add the Entity Base Type keys to the resulting keys
                result.AddRange(DTOGenerator.GetEntityKeys(entityBaseTypeNode, entityNodeToSetKeys,
                    entityNodeElements, genParams));
            }

            LogManager.LogMethodEnd();

            return result;
        }
Example #11
0
        /// <summary>
        /// Gets the objects that represents the DTOs that needs to be generated from the received EDMX Document.
        /// </summary>
        /// <param name="parameters">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List<DTOEntity> GetEntityDTOs(GenerateDTOsParams parameters)
        {
            LogManager.LogMethodStart();

            // Variables
            string typeName = null;
            bool generateType = false;
            var complexTypeDTOs = new List<DTOEntity>();
            var entityTypeDTOs = new List<DTOEntity>();

            // Get the DTOs for the ComplexType nodes
            foreach (XElement complexType in EdmxHelper.GetComplexTypeNodes(parameters.EDMXDocument))
            {
                typeName = complexType.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

                generateType = parameters.TypesToGenerateFilter.Contains(typeName);

                if (generateType == true)
                {
                    List<EntityNavigation> entityNavigations = null;

                    complexTypeDTOs.Add(new DTOEntity(complexType, parameters, entityNavigations));
                }
            }

            // Set the Complex Types available
            PropertyHelper.SetComplexTypes(complexTypeDTOs);

            // Get Navigation Properties
            List<EntityNavigation> entitiesNavigations = DTOGenerator.GetEntitiesNavigations(parameters);

            // Get the DTOs for the EntityType nodes
            foreach (XElement entityTypeNode in EdmxHelper.GetEntityTypeNodes(parameters.EDMXDocument))
            {
                typeName = entityTypeNode.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

                generateType = parameters.TypesToGenerateFilter.Contains(typeName);

                if (generateType == true)
                {
                    entityTypeDTOs.Add(new DTOEntity(entityTypeNode, parameters, entitiesNavigations));
                }
            }

            foreach (DTOEntity dto in entityTypeDTOs)
            {
                // Set Know Types of DTO
                dto.SetKnownTypes(entityTypeDTOs, parameters.DTOsServiceReady);

                // Set DTOs childs of DTO
                dto.SetChilds(entityTypeDTOs);

                // Set reference to DTO Base Class
                dto.SetDTOBase(entityTypeDTOs);

                // Set Navigation Target DTO references
                foreach (DTOClassProperty dtoProperty in dto.Properties.Where(p => p.IsNavigation == true))
                {
                    DTOEntity dtoTarget = entityTypeDTOs.FirstOrDefault(e => e.NameDTO == dtoProperty.NavigatesToDTOName);

                    if (dtoTarget != null)
                    {
                        dtoProperty.SetNavigatesToDTOReference(dtoTarget);
                    }
                }
            }

            // Get the final result
            var result = new List<DTOEntity>();
            result.AddRange(complexTypeDTOs);
            result.AddRange(entityTypeDTOs);

            LogManager.LogMethodEnd();

            return result;
        }
Example #12
0
        /// <summary>
        /// Gets the Entity Navigations from the provided EDMX Document.
        /// </summary>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List<EntityNavigation> GetEntitiesNavigations(GenerateDTOsParams genParams)
        {
            LogManager.LogMethodStart();

            // Get Entity Associations
            List<EntityAssociation> entitiesAssociations = DTOGenerator.GetEntitiesAssociations(genParams);

            // Get Entity Key Properties
            List<EntityKeyProperty> entitiesKeys = DTOGenerator.GetEntitiesKeyProperties(genParams);

            // Get Entities NavigationProperty Nodes
            IEnumerable<XElement> navigationNodeElements = genParams.EDMXDocument.DescendantsCSDL(EdmxNodes.NavigationProperty);

            var result = new List<EntityNavigation>();

            foreach (XElement navigationNode in navigationNodeElements)
            {
                result.Add(new EntityNavigation(navigationNode,
                    entitiesAssociations, entitiesKeys, genParams));
            }

            LogManager.LogMethodEnd();

            return result;
        }
Example #13
0
        /// <summary>
        /// Gets the Entity Keys of the provided EDMX Document.
        /// </summary>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List<EntityKeyProperty> GetEntitiesKeyProperties(GenerateDTOsParams genParams)
        {
            LogManager.LogMethodStart();

            IEnumerable<XElement> entityNodeElements =
                genParams.EDMXDocument.DescendantsCSDL(EdmxNodes.EntityType);

            var result = new List<EntityKeyProperty>();

            foreach (XElement entityNode in entityNodeElements)
            {
                result.AddRange(DTOGenerator.GetEntityKeys(entityNode, entityNode,
                    entityNodeElements, genParams));
            }

            LogManager.LogMethodEnd();

            return result;
        }
Example #14
0
        /// <summary>
        /// Gets the Associations of the provided EDMX Document.
        /// </summary>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        /// <returns></returns>
        private static List<EntityAssociation> GetEntitiesAssociations(GenerateDTOsParams genParams)
        {
            LogManager.LogMethodStart();

            IEnumerable<XElement> associationNodeElements =
                EdmxHelper.GetAssociationNodes(genParams.EDMXDocument);

            var result = new List<EntityAssociation>();

            foreach (XElement associationNodeElement in associationNodeElements)
            {
                result.Add(new EntityAssociation(associationNodeElement,
                    EntityAssociationEnd.First, genParams));

                result.Add(new EntityAssociation(associationNodeElement,
                    EntityAssociationEnd.Second, genParams));
            }

            LogManager.LogMethodEnd();

            return result;
        }
 /// <summary>
 /// Gets target name of <see cref="GenerateDTOsParams"/>.
 /// </summary>
 /// <param name="dtosParams">DTO parameters from where to obtain the target name.</param>
 /// <returns></returns>
 private static string GetTargetName(GenerateDTOsParams dtosParams)
 {
     return ConfigurationHelper.GetTargetName(dtosParams.TargetType,
         dtosParams.TargetProject, dtosParams.TargetProjectFolder);
 }
Example #16
0
        /// <summary>
        /// Creates an instance of <see cref="EntityNavigation"/>.
        /// </summary>
        /// <param name="genParams">Parameters for the generation of DTOs.</param>
        public EntityNavigation(XElement navigationNode, List<EntityAssociation> entitiesAssociations,
            List<EntityKeyProperty> entitiesKeys, GenerateDTOsParams genParams)
        {
            // Set DTO Name
            string entityName = navigationNode.Parent.Attribute(EdmxNodeAttributes.EntityType_Name).Value;
            this.DTOName = Utils.ConstructDTOName(entityName, genParams);

            // Get the To Role End name
            string toRole = navigationNode.Attribute(EdmxNodeAttributes.NavigationProperty_ToRole).Value;

            // Get the Association Name
            string associationName = EdmxHelper.GetNavigationAssociationName(navigationNode);

            this.NavigationProperties = new List<EntityNavigationProperty>();

            // Find the Association
            EntityAssociation association = (
                from a in entitiesAssociations
                where (a.AssociationName == associationName) && (a.EndRoleName == toRole)
                select a
                ).FirstOrDefault();

            // Find the DTO associated keys
            IEnumerable<EntityKeyProperty> dtoToKeys = entitiesKeys.Where(k => k.DTOName == association.DTOName);

            // Get the base Property Name
            this.NavigationPropertyNameEDMX = navigationNode.Attribute(EdmxNodeAttributes.NavigationProperty_Name).Value;
            string propertyName = PropertyHelper.GetPropertyName(this.NavigationPropertyNameEDMX, entityName);

            // Set association type desired, can change if requirements are not met
            AssociationType associationTypeDesired = genParams.AssociationType;

            if (association.EndMultiplicity == EntityAssociationMultiplicity.Many)
            {
                if ((associationTypeDesired != AssociationType.ClassType)
                    && (dtoToKeys.Count() != 1))
                {
                    // TODO: ffernandez, indicate Project-ProjectItem-Line-Column
                    VisualStudioHelper.AddToErrorList(TaskErrorCategory.Warning,
                        string.Format(Resources.Warning_CannotCreateNavPropManyKeyProp, this.DTOName, association.DTOName),
                        null, null, null, null);

                    associationTypeDesired = AssociationType.ClassType;
                }

                bool isList = true;

                if (associationTypeDesired == AssociationType.ClassType)
                {
                    // List<T> Type
                    string type = string.Format(Resources.CSharpTypeListT, association.DTOName);

                    this.NavigationProperties.Add(new EntityNavigationProperty(type, propertyName, isList,
                        association.DTOName, association.EntityName, association.DTOName));
                }
                else
                {
                    // AssociationTypeEnum.KeyProperty
                    EntityKeyProperty dtoToKey = dtoToKeys.First();

                    // List<T> Type
                    string type = string.Format(Resources.CSharpTypeListT, dtoToKey.Type);

                    propertyName += (Resources.NameSeparator + dtoToKey.Name);

                    this.NavigationProperties.Add(new EntityNavigationProperty(type, propertyName, isList,
                        dtoToKey.Type, association.EntityName, association.DTOName));
                }
            }
            else
            {
                // EntityAssociationMultiplicityEnum.One
                // EntityAssociationMultiplicityEnum.ZeroOrOne
                bool isList = false;
                string listOf = null;

                if (associationTypeDesired == AssociationType.ClassType)
                {
                    this.NavigationProperties.Add(new EntityNavigationProperty(association.DTOName, propertyName, isList,
                        listOf, association.EntityName, association.DTOName));
                }
                else
                {
                    // AssociationTypeEnum.KeyProperty

                    foreach (EntityKeyProperty dtoToKey in dtoToKeys)
                    {
                        string propName = (propertyName + Resources.NameSeparator + dtoToKey.Name);

                        this.NavigationProperties.Add(new EntityNavigationProperty(dtoToKey.Type, propName, isList,
                            listOf, association.EntityName, association.DTOName));
                    }
                }
            }
        }
Example #17
0
        /// <summary>
        /// Gets the parameters for GeneratorManager.
        /// </summary>
        /// <returns></returns>
        private GeneratorManagerParams GetGeneratorManagerParams()
        {
            #region Entity source

            dynamic entitySource = null;
            if (this.rbSourceEdmx.Checked == true)
            {
                // Get entity source as ProjectItem (it is an EDMX Document)
                entitySource = (this.lstEntitySources.SelectedItem as ProjectItem);
            }
            else
            {
                // Get entity source as Project
                entitySource = this.CurrentSourceProject;
            }

            #endregion Entity source

            #region General

            // Source File Header Comment
            string sourceFileHeaderComment = null;
            if (this.cbCustomHeaderComment.Checked)
            {
                sourceFileHeaderComment = this.txtCustomHeaderComment.Text;
            }

            #endregion General

            #region DTOs
            // Get the types to generate filter
            List<string> typesToGenerateFilter = this.GetTypesToGenerateFilter(onlyFilteredTypes: true);

            // Target
            Project targetProjectDTOs = null;
            ProjectItem targetProjectFolderDTOs = null;
            object nodeValueDTOs = (this.treeTargetDTOs.SelectedNode as TreeNodeExtended).Value;
            if (nodeValueDTOs is Project)
            {
                targetProjectDTOs = (nodeValueDTOs as Project);
            }
            else
            {
                targetProjectDTOs = (nodeValueDTOs as ProjectItem).ContainingProject;
                targetProjectFolderDTOs = (nodeValueDTOs as ProjectItem);
            }

            string sourceNamespaceDTOs = this.GetSourceFileNamespaceForDTOs();

            string sourceFileNameDTOs = this.txtSourceFileNameDTOs.Text.Trim();

            // Get source file generation type for DTOs
            SourceFileGenerationType sourceFileGenerationTypeDTOs = SourceFileGenerationType.SourceFilePerClass;
            if (this.rbOneSourceFileDTOs.Checked)
            {
                sourceFileGenerationTypeDTOs = SourceFileGenerationType.OneSourceFile;
            }

            AssociationType associationType = AssociationType.KeyProperty;
            if (this.rbAssociationConfigUseClassTypes.Checked)
            {
                associationType = AssociationType.ClassType;
            }

            // Set generate types flags
            bool generateAllTypes = (this.chbGenerateAllTypes.CheckState == CheckState.Checked);
            bool generateAllComplexTypes = (this.chbGenerateComplexTypes.CheckState == CheckState.Checked);
            bool generateAllEntityTypes = (this.chbGenerateEntityTypes.CheckState == CheckState.Checked);

            // Set Identifier
            ClassIdentifierUse dtosClassIdentifierUse = ClassIdentifierUse.None;
            string dtosClassIdentifierWord = string.Empty;
            if (this.rbDTOIdentifierPrefix.Checked == true)
            {
                dtosClassIdentifierUse = ClassIdentifierUse.Prefix;
                dtosClassIdentifierWord = this.txtDTOIdentifierWord.Text.Trim();
            }
            else if (this.rbDTOIdentifierSuffix.Checked == true)
            {
                dtosClassIdentifierUse = ClassIdentifierUse.Suffix;
                dtosClassIdentifierWord = this.txtDTOIdentifierWord.Text.Trim();
            }

            // Set DTOs parameters
            var dtosParams = new GenerateDTOsParams(targetProjectDTOs, targetProjectFolderDTOs, entitySource,
                typesToGenerateFilter, generateAllTypes, generateAllComplexTypes, generateAllEntityTypes,
                sourceFileHeaderComment, this.cbUseDefaultNamespaceDTOs.Checked, sourceNamespaceDTOs,
                this.cbServiceReadyDTOs.Checked, dtosClassIdentifierUse, dtosClassIdentifierWord,
                sourceFileGenerationTypeDTOs, sourceFileNameDTOs, associationType,
                this.cbGenerateDTOConstructors.Checked);
            #endregion DTOs

            #region Assemblers
            GenerateAssemblersParams assemblersParams = null;

            if (this.cbGenerateAssemblers.Checked)
            {
                // Target
                Project targetProjectAssemblers = null;
                ProjectItem targetProjectFolderAssemblers = null;
                object nodeValueAssemblers = (this.treeTargetAssemblers.SelectedNode as TreeNodeExtended).Value;
                if (nodeValueAssemblers is Project)
                {
                    targetProjectAssemblers = (nodeValueAssemblers as Project);
                }
                else
                {
                    targetProjectAssemblers = (nodeValueAssemblers as ProjectItem).ContainingProject;
                    targetProjectFolderAssemblers = (nodeValueAssemblers as ProjectItem);
                }

                string sourceNamespaceAssemblers = this.GetSourceFileNamespaceForAssemblers();

                string sourceFileNameAssemblers = this.txtSourceFileNameAssemblers.Text.Trim();

                // Get the source file generation type for Assemblers
                SourceFileGenerationType sourceFileGenerationTypeAssemblers = SourceFileGenerationType.SourceFilePerClass;
                if (this.rbOneSourceFileAssemblers.Checked)
                {
                    sourceFileGenerationTypeAssemblers = SourceFileGenerationType.OneSourceFile;
                }

                // Set Identifier
                ClassIdentifierUse assemblersClassIdentifierUse = ClassIdentifierUse.None;
                string assemblersClassIdentifierWord = string.Empty;
                if (this.rbAssemblerIdentifierPrefix.Checked == true)
                {
                    assemblersClassIdentifierUse = ClassIdentifierUse.Prefix;
                    assemblersClassIdentifierWord = this.txtAssemblerIdentifierWord.Text.Trim();
                }
                else if (this.rbAssemblerIdentifierSuffix.Checked == true)
                {
                    assemblersClassIdentifierUse = ClassIdentifierUse.Suffix;
                    assemblersClassIdentifierWord = this.txtAssemblerIdentifierWord.Text.Trim();
                }

                // Set Assemblers parameters
                assemblersParams = new GenerateAssemblersParams(targetProjectAssemblers, targetProjectFolderAssemblers,
                    sourceFileHeaderComment, this.cbUseDefaultNamespaceAssemblers.Checked,
                    sourceNamespaceAssemblers, assemblersClassIdentifierUse, assemblersClassIdentifierWord,
                    sourceFileGenerationTypeAssemblers, sourceFileNameAssemblers, this.cbServiceReadyDTOs.Checked,
                    sourceNamespaceDTOs, targetProjectDTOs, entitySource);
            }
            #endregion Assemblers

            // Return the result generator parameters
            return new GeneratorManagerParams(dtosParams, assemblersParams, this.cbGenerateAssemblers.Checked);
        }
Example #18
0
        public DTOClass(XElement typeNode, GenerateDTOsParams genParams)
        {
            // Set source type name
            this.Name = typeNode.Attribute(EdmxNodeAttributes.EntityType_Name).Value;

            // Set DTO name
            this.NameDTO = Utils.ConstructDTOName(this.Name, genParams);

            #region Set Class Attributes

            this.Attributes = new List<DTOAttribute>();

            if (genParams.DTOsServiceReady)
            {
                const string parameters = null;
                this.Attributes.Add(new DTOAttribute(Resources.AttributeDataContract, parameters));
            }

            #endregion Set Class Attributes

            // Set Assembler (it does not have one by default)
            this.Assembler = null;

            // Set Class Access
            this.DTOClassAccess = vsCMAccess.vsCMAccessPublic;

            // Set the Class Kind to partial so the final user can extend it
            this.DTOClassKind = vsCMClassKind.vsCMClassKindPartialClass;

            #region Set Properties

            this.Properties = new List<DTOClassProperty>();

            // Get Key Node
            XElement keyNode = typeNode.DescendantsCSDL(EdmxNodes.Key).FirstOrDefault();

            // Get source keys
            var sourceKeys = new List<string>();
            if (keyNode != null)
            {
                sourceKeys = keyNode.DescendantsCSDL(EdmxNodes.PropertyRef)
                    .Select(n => n.Attribute(EdmxNodeAttributes.PropertyRef_Name).Value).ToList();
            }

            // Get Property nodes
            IEnumerable<XElement> entityPropertiesNodes = typeNode.DescendantsCSDL(EdmxNodes.Property);

            // Variables
            string edmxTypeValue;
            string[] edmxTypeValueSplitted;
            string edmxTypeName;
            bool addProperty;
            bool isEnum;

            foreach (XElement propertyNode in entityPropertiesNodes)
            {
                addProperty = true;
                isEnum = false;

                // Get the Type value
                edmxTypeValue = propertyNode.Attribute(EdmxNodeAttributes.Property_Type).Value;

                // Split typeValue to check if it is a Complex Type
                edmxTypeValueSplitted = edmxTypeValue.Split(new string[] { Resources.Dot }, StringSplitOptions.RemoveEmptyEntries);

                // Get EDMX type name (split to ensure that if it is from the same model we only get the name)
                edmxTypeName = edmxTypeValueSplitted[(edmxTypeValueSplitted.Length - 1)];

                // Check if property type is complex or entity type
                if (genParams.AllComplexTypesNames.Contains(edmxTypeName) == true
                    || genParams.AllEntityTypesNames.Contains(edmxTypeName) == true)
                {
                    // Check if the type is going to be generated
                    addProperty = genParams.TypesToGenerateFilter.Contains(edmxTypeName);
                }
                else if(genParams.AllEnumTypesNames.Contains(edmxTypeName) == true)
                {
                    isEnum = true;
                }

                if (addProperty == true)
                {
                    // Check if it is a complex type property
                    bool isComplex = (genParams.AllComplexTypesNames.Contains(edmxTypeName) == true);

                    this.Properties.Add(new DTOClassProperty(propertyNode, sourceKeys,
                        this.Name, genParams.DTOsServiceReady, isComplex, isEnum));
                }
            }

            #endregion Set Properties
        }