コード例 #1
0
 /// <summary>
 /// Adds the attribute.
 /// </summary>
 /// <param name="element">The element.</param>
 /// <param name="attributeName">Name of the attribute.</param>
 /// <param name="attributeValue">The attribute value.</param>
 public static void AddAttribute(CodeClass element, string attributeName, string attributeValue)
 {
     if(!HasAttribute(element, attributeName))
     {
         element.AddAttribute(attributeName, attributeValue, 0);
     }
 }
コード例 #2
0
 /// <summary>
 /// Adds the attribute.
 /// </summary>
 /// <param name="element">The element.</param>
 /// <param name="attributeName">Name of the attribute.</param>
 /// <param name="attributeValue">The attribute value.</param>
 public static void AddAttribute(CodeClass element, string attributeName, string attributeValue)
 {
     if (!HasAttribute(element, attributeName))
     {
         element.AddAttribute(attributeName, attributeValue, 0);
     }
 }
コード例 #3
0
 /// <summary>
 /// Finds the or create custom attribute element.
 /// </summary>
 /// <param name="clazz">The clazz.</param>
 /// <param name="name">The name.</param>
 /// <param name="value">The value.</param>
 /// <returns></returns>
 public static CodeAttribute2 FindOrCreateCustomAttributeElement(CodeClass clazz, string name, string value)
 {
     foreach (CodeElement ce in clazz.Attributes)
     {
         CodeAttribute2 attr = ce as CodeAttribute2;
         if (attr != null && attr.Name == name)
         {
             return(attr);
         }
     }
     return((CodeAttribute2)clazz.AddAttribute(name, value, -1));
 }
コード例 #4
0
        private void AddConfigurationElementTypeAttribute(CodeClass codeClass, ProjectItem customProvider)
        {
            CodeAttribute codeAttribute  = GetConfigurationElementTypeAttirbute(codeClass);
            string        attributeValue = null;

            if (!string.IsNullOrEmpty(Namespace))
            {
                attributeValue = string.Format(GetTypeOfDependingOnProjectTypeCSharpOrVisualBasic(), Namespace + NamespaceHelper.NamespaceSeparator + ConfigurationNamespacePart + NamespaceHelper.NamespaceSeparator + ConfigurationClassname);
            }
            else
            {
                attributeValue = string.Format(GetTypeOfDependingOnProjectTypeCSharpOrVisualBasic(), string.Concat(ConfigurationNamespacePart, NamespaceHelper.NamespaceSeparator, ConfigurationClassname));
            }

            if (codeAttribute != null)
            {
                RuntimeConfigurationBaseType = GetTypeFrom(codeAttribute);
                codeAttribute.Value          = attributeValue;
            }
            else
            {
                codeClass.AddAttribute(ConfigurationElementTypeAttributeName, attributeValue, 0);
            }
        }
コード例 #5
0
ファイル: CandleCodeClass.cs プロジェクト: malain/candle
 /// <summary>
 /// Adds the attribute internal.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <returns></returns>
 protected override CodeAttribute2 AddAttributeInternal(string name)
 {
     return(_codeElement.AddAttribute(name, String.Empty, null) as CodeAttribute2);
 }
コード例 #6
0
ファイル: DTOGenerator.cs プロジェクト: kzfabi/EntitiesToDTOs
        /// <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);
        }
コード例 #7
0
        private void DoClassGeneration(object state)
        {
            List <DBObjectWithType> objs = null;

            this.InvokeOnMe(() =>
            {
                this.IsEnabled = false;
                objs           = Tables.SelectedItems.Cast <DBObjectWithType>().ToList();
                SauceClassGenerationPackage.OutputWindow.Activate();
            });

            ProjectItem folder = GetFolder();

            if (folder != null)
            {
                try
                {
                    foreach (DBObjectWithType obj in objs)
                    {
                        SauceClassGenerationPackage.OutputWindow.OutputStringThreadSafe(string.Format("Working on Object: {0}{1}", obj.Object.Name, Environment.NewLine));
                        CodeClass newClass = GetCodeClass(obj.Object, folder);

                        if (obj.Type == ObjectType.Table)
                        {
                            newClass.AddAttribute("DataAccess.Core.Attributes.TableName", GetTableNameAttribute(obj.Object));
                        }
                        else if (obj.Type == ObjectType.View)
                        {
                            newClass.AddAttribute("DataAccess.Core.Attributes.ViewAttribute", GetTableNameAttribute(obj.Object));
                        }

                        bool          failure = false;
                        List <Column> columns = obj.Object.Columns;
                        columns.Reverse();

                        foreach (Column v in columns)
                        {
                            if (!AddPropertyToClass(obj, newClass, v))
                            {
                                failure = false;
                            }
                        }

                        if (failure)
                        {
                            MessageBox.Show("Unable to translate one or more columns to an appropriate CLR type, see output window for more details", "Error Fetching Objects", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                        newClass.ProjectItem.Save();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Error during class generation!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }

            this.InvokeOnMe(() =>
            {
                this.IsEnabled = true;
            });
        }