public void createFormDSExtension(IFormDataSource formDataSource)
        {
            // Find current model
            var modelSaveInfo    = Common.CommonUtil.GetCurrentModelSaveInfo();
            var metaModelService = Common.CommonUtil.GetModelSaveService();

            string className    = Common.CommonUtil.GetNextClassExtensionName(formDataSource.Name);
            string intrinsicStr = "formdatasourcestr";

            string extensionOfStr = $"ExtensionOf({intrinsicStr}({formDataSource.RootElement.Name},{formDataSource.Name}))";

            Microsoft.Dynamics.AX.Metadata.MetaModel.AxClass extensionClass = ClassHelper.GetExistingExtensionClass(formDataSource.Name, extensionOfStr);
            if (extensionClass == null)
            {
                extensionClass = new AxClass()
                {
                    Name = className
                };

                extensionClass.SourceCode.Declaration = $"[{extensionOfStr}]\npublic final class {className}\n{{\n\n}}";
            }

            metaModelService.CreateClass(extensionClass, modelSaveInfo);
            Common.CommonUtil.AddElementToProject(extensionClass);
        }
Beispiel #2
0
        protected void AddClassMethodCode(AxClass newAxClass)
        {
            if (String.IsNullOrEmpty(CodeGenerate.GetResult()))
            {
                return;
            }
            if (IsPreviewMode)
            {
                CodeGenerate.AppendLine("");
            }
            else
            {
                if (CodeGenerate.MethodType == ClassMethodType.ClassDeclaration)
                {
                    newAxClass.SourceCode.Declaration = CodeGenerate.GetResult();
                }
                else
                {
                    AxMethod axMethod = new AxMethod();
                    axMethod.Name     = CodeGenerate.MethodName;
                    axMethod.IsStatic = (CodeGenerate.MethodType == ClassMethodType.Static);
                    axMethod.Source   = CodeGenerate.GetResult();

                    newAxClass.AddMethod(axMethod);
                }
                CodeGenerate.ClearResult();
            }
        }
        public void applyValidateMethod(AxClass selectedClass, AxClass contractClass)
        {
            var      validateMethod   = selectedClass.Methods.Where(m => m.Name.Equals("Validate", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            AxMethod axValidateMethod = new AxMethod()
            {
                Name = "validate", ReturnType = new AxMethodReturnType()
                {
                    Type = Microsoft.Dynamics.AX.Metadata.Core.MetaModel.CompilerBaseType.AnyType, TypeName = "boolean"
                }
            };

            if (validateMethod != null)
            {
                axValidateMethod.Source = validateMethod.Source.Replace("Object calledFrom = null", "");
            }
            else
            {
                // we need to put a dummy method here
                axValidateMethod.Source = @"    public boolean validate(Object calledFrom = null)
    {
        boolean ret;

        ret = super(calledFrom);

        return ret;
    }" + Environment.NewLine;
            }

            contractClass.AddMethod(axValidateMethod);
        }
Beispiel #4
0
        public void run()
        {
            AxClass axClass = MetadataProvider.Classes.Read(classItem.Name);

            bool allMethodsDocumented = true; // Please do not disappoint me! :)

            foreach (AxMethod method in axClass.Methods)
            {
                IContent tagContent = null;
                string   devDoc     = string.Empty;

                if (!method.Source.Contains("<summary>"))
                {
                    tagContent = new SummaryTag(method);
                    tagContent = new ParamTag(tagContent, method);
                    tagContent = new ExceptionTag(tagContent, method);
                    tagContent = new ReturnsTag(tagContent, method);
                    tagContent = new RemarksTag(tagContent, method);

                    method.Source = method.Source.Insert(0, $"{tagContent.getContent()}\n");

                    allMethodsDocumented = false; // Shame on you! :(
                }
            }

            if (allMethodsDocumented)
            {
                CoreUtility.DisplayInfo("All your methods are documented already! I've transfered $500,00 to your bank account as reward!");
            }
            else
            {
                this.MetaModelService.UpdateClass(axClass, this.ModelSaveInfo);
            }
        }
        public static AxClass GetExistingExtensionClass(string className, string extensionOfStr)
        {
            AxClass axClass = null;

            var metaModelService = Common.CommonUtil.GetModelSaveService();
            //This searches across all models
            var classNameExts = metaModelService.GetClassNames().ToList()
                                .Where(searchClass => searchClass.ToLowerInvariant().Contains(className.ToLowerInvariant()) &&
                                       metaModelService.GetClass(searchClass).Declaration.ToLowerInvariant().Contains(extensionOfStr.ToLowerInvariant())
                                       )
                                .ToList();

            string classNameExt = String.Empty;
            var    currentModel = Common.CommonUtil.GetCurrentModel();

            foreach (var classNameE in classNameExts)
            {
                // Determine if the model this class belongs to is a part of the current project model
                var modelInfo = metaModelService.GetClassModelInfo(classNameE).ToList()
                                .Where(modelInfoCur => modelInfoCur.Module.Equals(currentModel.Module, StringComparison.InvariantCultureIgnoreCase))
                                .FirstOrDefault();
                if (modelInfo != null)
                {
                    classNameExt = classNameE;
                    break;
                }
            }

            if (String.IsNullOrEmpty(classNameExt) == false)
            {
                axClass = metaModelService.GetClass(classNameExt);
            }

            return(axClass);
        }
        /// <summary>
        /// Called when user clicks on the add-in menu
        /// </summary>
        /// <param name="e">The context of the VS tools and metadata</param>
        public override void OnClick(AddinDesignerEventArgs e)
        {
            try
            {
                // we will create Extension class here
                var selectedElement = e.SelectedElement as Microsoft.Dynamics.Framework.Tools.MetaModel.Automation.IRootElement;
                if (selectedElement != null)
                {
                    // Find current model
                    var modelSaveInfo    = Common.CommonUtil.GetCurrentModelSaveInfo();
                    var metaModelService = Common.CommonUtil.GetModelSaveService();

                    // Create a class with the same name + _Extension and add it to the project
                    string className = Common.CommonUtil.GetNextClassExtensionName(selectedElement.Name);


                    string intrinsicStr = String.Empty;
                    if (selectedElement is ITable ||
                        selectedElement is IDataEntityView)
                    {
                        intrinsicStr = "tableStr";
                    }
                    else if (selectedElement is IClassItem)
                    {
                        intrinsicStr = "classStr";
                    }
                    else if (selectedElement is IForm)
                    {
                        intrinsicStr = "formStr";
                    }

                    Microsoft.Dynamics.AX.Metadata.MetaModel.AxClass extensionClass;

                    string extensionOfStr = $"ExtensionOf({intrinsicStr}({selectedElement.Name}))";
                    // Find an existing class where the extension is already used
                    extensionClass = ClassHelper.GetExistingExtensionClass(selectedElement.Name, extensionOfStr);
                    if (extensionClass == null)
                    {
                        extensionClass = new AxClass()
                        {
                            Name = className
                        };

                        extensionClass.SourceCode.Declaration = $"[{extensionOfStr}]\npublic final class {className}\n{{\n\n}}";
                    }

                    metaModelService.CreateClass(extensionClass, modelSaveInfo);
                    Common.CommonUtil.AddElementToProject(extensionClass);
                }
                else if (e.SelectedElement is IFormDataSource)
                {
                    this.createFormDSExtension(e.SelectedElement as IFormDataSource);
                }
            }
            catch (Exception ex)
            {
                CoreUtility.HandleExceptionWithErrorMessage(ex);
            }
        }
Beispiel #7
0
        protected override void Create()
        {
            var element = new AxClass {
                Name = ElementName
            };

            MetaService.CreateClass(element, Model);
        }
Beispiel #8
0
        /// <summary>
        /// Called when user clicks on the add-in menu
        /// </summary>
        /// <param name="e">The context of the VS tools and metadata</param>
        public override void OnClick(AddinDesignerEventArgs e)
        {
            try
            {
                // we will create Extension class here
                var selectedElement = e.SelectedElement as Microsoft.Dynamics.Framework.Tools.MetaModel.Automation.IRootElement;
                if (selectedElement != null)
                {
                    // Find current model
                    var modelSaveInfo    = Common.CommonUtil.GetCurrentModelSaveInfo();
                    var metaModelService = Common.CommonUtil.GetModelSaveService();

                    var metadataType = selectedElement.GetMetadataType();

                    // Create a class with the same name + _Extension and add it to the project
                    // ClassName
                    string baseClassName   = selectedElement.Name + "_Extension";
                    string className       = baseClassName;
                    int    numClassesFound = 0;
                    while (metaModelService.GetClass(className) != null)
                    {
                        numClassesFound++;
                        className = baseClassName + numClassesFound.ToString();
                    }

                    string intrinsicStr = String.Empty;
                    if (selectedElement is ITable ||
                        selectedElement is IDataEntityView)
                    {
                        intrinsicStr = "tableStr";
                    }
                    else if (selectedElement is IClassItem)
                    {
                        intrinsicStr = "classStr";
                    }
                    else if (selectedElement is IForm)
                    {
                        intrinsicStr = "formStr";
                    }

                    Microsoft.Dynamics.AX.Metadata.MetaModel.AxClass extensionClass = new AxClass()
                    {
                        Name = className
                    };

                    extensionClass.SourceCode.Declaration = $"[ExtensionOf({intrinsicStr}({selectedElement.Name}))]\npublic final class {className}\n{{\n\n}}";


                    metaModelService.CreateClass(extensionClass, modelSaveInfo);
                    Common.CommonUtil.AddElementToProject(extensionClass);
                }
            }
            catch (Exception ex)
            {
                CoreUtility.HandleExceptionWithErrorMessage(ex);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Called when user clicks on the add-in menu
        /// </summary>
        /// <param name="e">The context of the VS tools and metadata</param>
        public override void OnClick(AddinEventArgs e)
        {
            try
            {
                // Find project to work with
                VSProjectNode project = LocalUtils.GetActiveProject();
                // An alternative way is calling ProjectHelper.GetProjectDetails(), but it's not consistent
                // with how projectService.AddElementToActiveProject() determines the active project.
                // ProjectHelper return the startup project, which doens't have to be the active project.

                if (project == null)
                {
                    throw new InvalidOperationException("No project selected.");
                }

                // Create a new class
                AxClass axClass = new AxClass()
                {
                    Name       = "MyNewClass",
                    IsAbstract = true // Set a property for demonstration
                };

                // Find metamodel service needed below


                // Find current model
                //ModelInfo model = metaModelService.GetModel(ProjectHelper.GetProjectDetails().Model);
                ModelInfo model = project.GetProjectsModelInfo();

                // Prepare information needed for saving
                ModelSaveInfo saveInfo = new ModelSaveInfo
                {
                    Id    = model.Id,
                    Layer = model.Layer
                };

                // Create class in the right model
                var metaModelProviders = ServiceLocator.GetService(typeof(IMetaModelProviders)) as IMetaModelProviders;
                var metaModelService   = metaModelProviders.CurrentMetaModelService;
                metaModelService.CreateClass(axClass, saveInfo);

                // Add the class to the active project
                var projectService = ServiceLocator.GetService(typeof(IDynamicsProjectService)) as IDynamicsProjectService;
                projectService.AddElementToActiveProject(axClass);
            }
            catch (Exception ex)
            {
                CoreUtility.HandleExceptionWithErrorMessage(ex);
            }
        }
Beispiel #10
0
        /// <summary>
        /// Called when user clicks on the add-in menu
        /// </summary>
        /// <param name="e">The context of the VS tools and metadata</param>
        public override void OnClick(AddinEventArgs e)
        {
            try
            {
                // Find project to work with
                VSProjectNode project = LocalUtils.GetActiveProject();
                // An alternative way is calling ProjectHelper.GetProjectDetails(), but it's not consistent
                // with how projectService.AddElementToActiveProject() determines the active project.
                // ProjectHelper return the startup project, which doens't have to be the active project.

                if (project == null)
                {
                    throw new InvalidOperationException("No project selected.");
                }

                // Create a new class
                AxClass axClass = new AxClass()
                {
                    Name = "MyNewClass",
                    IsAbstract = true // Set a property for demonstration
                };

                // Find metamodel service needed below

                // Find current model
                //ModelInfo model = metaModelService.GetModel(ProjectHelper.GetProjectDetails().Model);
                ModelInfo model = project.GetProjectsModelInfo();

                // Prepare information needed for saving
                ModelSaveInfo saveInfo = new ModelSaveInfo
                {
                    Id = model.Id,
                    Layer = model.Layer
                };

                // Create class in the right model
                var metaModelProviders = ServiceLocator.GetService(typeof(IMetaModelProviders)) as IMetaModelProviders;
                var metaModelService = metaModelProviders.CurrentMetaModelService;
                metaModelService.CreateClass(axClass, saveInfo);

                // Add the class to the active project
                var projectService = ServiceLocator.GetService(typeof(IDynamicsProjectService)) as IDynamicsProjectService;
                projectService.AddElementToActiveProject(axClass);

            }
            catch (Exception ex)
            {
                CoreUtility.HandleExceptionWithErrorMessage(ex);
            }
        }
Beispiel #11
0
        public static AxClass Construct(string name, dynamic baseElement = null)
        {
            AxClass myClass = new AxClass {
                Name = name
            };

            if (baseElement != null)
            {
                string  baseClassInterfaceName = baseElement.Caption;
                AxClass myBaseClassInterface   = LocalUtils.MetaService.GetClass(baseClassInterfaceName);

                if (myBaseClassInterface.IsInterface)
                {
                    myClass.Implements = new System.Collections.Generic.List <string> {
                        baseClassInterfaceName
                    };

                    foreach (var axMethod in myBaseClassInterface.Methods)
                    {
                        myClass.Methods.Add(axMethod);
                    }
                }
                else
                {
                    myClass.Extends = baseClassInterfaceName;

                    if (myBaseClassInterface.IsFinal)
                    {
                        throw new Exception("Selected class is set as final, it cannot be extended");
                    }

                    if (myBaseClassInterface.IsAbstract)
                    {
                        foreach (var axAbstractMethod in myBaseClassInterface.Methods.Where(m => m.IsAbstract))
                        {
                            axAbstractMethod.IsAbstract = false;
                            axAbstractMethod.Source     = axAbstractMethod.Source.Replace("abstract ", "");
                            myClass.Methods.Add(axAbstractMethod);
                        }
                    }
                }
            }

            return(myClass);
        }
        /// <summary>
        /// Adds a new method (with a hard-coded name and empty body) to the selected class.
        /// </summary>
        /// <param name="c">The class to which the method will be added.</param>
        /// <remarks>
        /// The method is added to the underlying file, but not to the designer.
        /// Visual Studio will detect the change and asks the user if the file should be reloaded.
        /// Another approach is needed to update the designer directly.
        /// </remarks>
        void AddMethodToFile(ClassItem c)
        {
            AxClass axClass = (AxClass)c.GetMetadataType();

            // Add the method to the class
            axClass.AddMethod(BuildMethod());

            // Prepare objects needed for saving
            var metaModelProviders = ServiceLocator.GetService(typeof(IMetaModelProviders)) as IMetaModelProviders;
            var metaModelService   = metaModelProviders.CurrentMetaModelService;
            // Getting the model will likely have to be more sophisticated, such as getting the model of the project and checking
            // if the object has the same model.
            // But this shold do for demonstration.
            ModelInfo model = DesignMetaModelService.Instance.CurrentMetadataProvider.Classes.GetModelInfo(axClass.Name).FirstOrDefault <ModelInfo>();

            // Update the file
            metaModelService.UpdateClass(axClass, new ModelSaveInfo(model));
        }
Beispiel #13
0
        void CreateClass()
        {
            AxHelper axHelper = new AxHelper();

            NewAxClass = axHelper.MetadataProvider.Classes.Read(ClassName);
            //newAxClass = axHelper.MetadataProvider.Classes.Read("Tutorial_RunbaseBatch");
            if (NewAxClass != null)
            {
                throw new Exception($"Class {ClassName} already exists");
            }

            if (IsCreateMenuItem)
            {
                if (axHelper.MetadataProvider.MenuItemActions.Read(ClassName) != null)
                {
                    throw new Exception($"Menu item action {ClassName} already exists");
                }
            }

            NewAxClass = new AxClass {
                Name = ClassName
            };
            CreateClassMethods();

            axHelper.MetaModelService.CreateClass(NewAxClass, axHelper.ModelSaveInfo);
            axHelper.AppendToActiveProject(NewAxClass);

            AddLog($"Class: {NewAxClass.Name}; ");

            if (IsCreateMenuItem)
            {
                AxMenuItemAction axMenuItem = new AxMenuItemAction
                {
                    Name = ClassName, Object = ClassName, ObjectType = MenuItemObjectType.Class
                };
                axMenuItem.Label    = ClassDescription;
                axMenuItem.HelpText = $"{axMenuItem.Label} operation";
                axHelper.MetaModelService.CreateMenuItemAction(axMenuItem, axHelper.ModelSaveInfo);
                axHelper.AppendToActiveProject(axMenuItem);

                AddLog($"MenuItem: {axMenuItem.Name}; ");
            }
        }
        void CreateClass()
        {
            AxHelper axHelper = new AxHelper();

            NewAxClass = axHelper.MetadataProvider.Classes.Read(ClassName);

            if (NewAxClass != null)
            {
                throw new Exception($"Class {ClassName} already exists");
            }

            NewAxClass = new AxClass {
                Name = ClassName
            };
            CreateClassMethodsContract();

            axHelper.MetaModelService.CreateClass(NewAxClass, axHelper.ModelSaveInfo);
            axHelper.AppendToActiveProject(NewAxClass);

            AddLog($"Class: {NewAxClass.Name}; ");
        }
Beispiel #15
0
        public static AxClass GetExistingExtensionClass(string className, string extensionOfStr)
        {
            AxClass axClass = null;

            var metaModelService = Common.CommonUtil.GetModelSaveService();

            var classNameExt = metaModelService.GetClassNames().ToList()
                               .Where(searchClass =>
                                      searchClass.ToLowerInvariant().Contains(className.ToLowerInvariant())
                                      &&
                                      metaModelService.GetClass(searchClass)
                                      .Declaration.ToLowerInvariant()
                                      .Contains(extensionOfStr.ToLowerInvariant())
                                      )
                               .FirstOrDefault();

            if (String.IsNullOrEmpty(classNameExt) == false)
            {
                axClass = metaModelService.GetClass(classNameExt);
            }

            return(axClass);
        }
        void CreateControllerClass()
        {
            AxHelper axHelper = new AxHelper();

            NewAxClass = axHelper.MetadataProvider.Classes.Read(ClassNameController);

            if (NewAxClass != null)
            {
                CoreUtility.DisplayInfo($"Class {NewAxClass.Name} already exists");
                axHelper.AppendToActiveProject(NewAxClass);
            }
            else
            {
                NewAxClass = new AxClass {
                    Name = ClassNameController
                };
                CreateControllerMethods();

                axHelper.MetaModelService.CreateClass(NewAxClass, axHelper.ModelSaveInfo);
                axHelper.AppendToActiveProject(NewAxClass);

                AddLog($"Class: {NewAxClass.Name}; ");
            }
        }
Beispiel #17
0
        public static void Create(UtilElementType type, string name)
        {
            if (Project == null)
            {
                throw new InvalidOperationException("No project selected.");
            }

            _name = name;
            switch (type)
            {
            case UtilElementType.DisplayTool:
                var existsDisplayTool = LocalUtils.MetaService.GetMenuItemDisplayNames().Contains(name);

                if (!existsDisplayTool)
                {
                    var displayMenu = new AxMenuItemDisplay {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateMenuItemDisplay(displayMenu, Model);
                    AddAotElement <AxMenuItemDisplay>();
                }

                break;

            case UtilElementType.OutputTool:
                var existsOutputTool = LocalUtils.MetaService.GetMenuItemDisplayNames().Contains(name);

                if (!existsOutputTool)
                {
                    var outputMenu = new AxMenuItemOutput {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateMenuItemOutput(outputMenu, Model);
                    AddAotElement <AxMenuItemOutput>();
                }

                break;

            case UtilElementType.ActionTool:
                var existsActionTool = LocalUtils.MetaService.GetMenuItemDisplayNames().Contains(name);

                if (!existsActionTool)
                {
                    var actionMenu = new AxMenuItemAction {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateMenuItemAction(actionMenu, Model);
                    AddAotElement <AxMenuItemAction>();
                }
                break;

            case UtilElementType.Query:
                var existsQuery = LocalUtils.MetaService.GetQueryNames().Contains(name);

                if (!existsQuery)
                {
                    var query = new AxQuerySimple {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateQuery(query, Model);
                    AddAotElement <AxQuerySimple>();
                }
                break;

            case UtilElementType.Enum:
                var Enum = LocalUtils.MetaService.GetEnumNames().Contains(name);

                if (!Enum)
                {
                    var edtEnum = new AxEnum {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateEnum(edtEnum, Model);
                    AddAotElement <AxEnum>();
                }
                break;

            case UtilElementType.ExtendedType:



                break;

            case UtilElementType.Table:
                var existsTable = LocalUtils.MetaService.GetTableNames().Contains(name);

                if (!existsTable)
                {
                    var table = new AxTable {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateTable(table, Model);
                    AddAotElement <AxTable>();
                }
                break;

            case UtilElementType.Class:
                var existsClass = LocalUtils.MetaService.GetClassNames().Contains(name);

                if (!existsClass)
                {
                    var axClass = new AxClass {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateClass(axClass, Model);
                    AddAotElement <AxClass>();
                }
                break;

            case UtilElementType.SSRSReport:
                var existsSsrsReport = LocalUtils.MetaService.GetReportNames().Contains(name);

                if (!existsSsrsReport)
                {
                    var srsReport = new AxReport {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateReport(srsReport, Model);
                    AddAotElement <AxReport>();
                }
                break;

            case UtilElementType.Form:
                var existsForm = LocalUtils.MetaService.GetFormNames().Contains(name);

                if (!existsForm)
                {
                    var axForm = new AxForm {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateForm(axForm, Model);
                    AddAotElement <AxForm>();
                }
                break;

            case UtilElementType.Menu:
                var existsMenu = LocalUtils.MetaService.GetMenuNames().Contains(name);

                if (!existsMenu)
                {
                    var axMenu = new AxMenu {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateMenu(axMenu, Model);
                    AddAotElement <AxMenu>();
                }
                break;

            case UtilElementType.SecDuty:
                var existsSecDuty = LocalUtils.MetaService.GetSecurityDutyNames().Contains(name);

                if (!existsSecDuty)
                {
                    var axDuty = new AxSecurityDuty {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateSecurityDuty(axDuty, Model);
                    AddAotElement <AxSecurityDuty>();
                }
                break;

            case UtilElementType.SecPolicy:
                var existsSecPolicy = LocalUtils.MetaService.GetSecurityPolicyNames().Contains(name);

                if (!existsSecPolicy)
                {
                    var axPolicy = new AxSecurityPolicy {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateSecurityPolicy(axPolicy, Model);
                    AddAotElement <AxSecurityPolicy>();
                }
                break;

            case UtilElementType.SecPrivilege:
                var existsSecPrivilege = LocalUtils.MetaService.GetSecurityPrivilegeNames().Contains(name);

                if (!existsSecPrivilege)
                {
                    var privilege = new AxSecurityPrivilege {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateSecurityPrivilege(privilege, Model);
                    AddAotElement <AxSecurityPrivilege>();
                }
                break;

            case UtilElementType.SecRole:
                var existsSecRole = LocalUtils.MetaService.GetSecurityRoleNames().Contains(name);

                if (!existsSecRole)
                {
                    var role = new AxSecurityRole {
                        Name = name
                    };
                    LocalUtils.MetaService.CreateSecurityRole(role, Model);
                    AddAotElement <AxSecurityRole>();
                }
                break;

            default:
                throw new Exception("Element not supported");
            }
        }
        public bool Run()
        {
            if (ResultClassName.Length > 80)
            {
                throw new Exception($"Class name can't be more than 80 symbols({ResultClassName.Length})");
            }

            AxHelper axHelper = new AxHelper();

            AxClass newClass = axHelper.MetadataProvider.Classes.Read(ResultClassName);
            bool    res      = false;

            if (newClass == null)
            {
                res = true;
                //throw new Exception($"Class {ResultClassName} already exists");

                newClass = new AxClass {
                    IsFinal = true, Name = ResultClassName
                };

                if (ClassModeType == ExtensionClassModeType.EventHandler)
                {
                    newClass.IsStatic = true;
                }

                string typeStr = "";
                switch (ElementType)
                {
                case Kernel.ExtensionClassType.Form:
                    typeStr = "formstr";
                    break;

                case Kernel.ExtensionClassType.Class:
                    typeStr = "classstr";
                    break;

                case Kernel.ExtensionClassType.Table:
                    typeStr = "tablestr";
                    break;

                case Kernel.ExtensionClassType.FormDataField:
                    typeStr = "formdatafieldstr";
                    break;

                case Kernel.ExtensionClassType.FormDataSource:
                    typeStr = "formdatasourcestr";
                    break;

                case Kernel.ExtensionClassType.FormControl:
                    typeStr = "formcontrolstr";
                    break;

                case Kernel.ExtensionClassType.DataEntityView:
                    typeStr = "dataentityviewstr";
                    break;

                case Kernel.ExtensionClassType.View:
                    typeStr = "viewstr";
                    break;

                case Kernel.ExtensionClassType.Map:
                    typeStr = "mapstr";
                    break;
                }

                StringBuilder declarationText = new StringBuilder();
                if (ClassModeType == ExtensionClassModeType.Extension)
                {
                    if (string.IsNullOrWhiteSpace(SubElementName))
                    {
                        declarationText.AppendLine($"[ExtensionOf({typeStr}({ElementName}))]");
                    }
                    else
                    {
                        declarationText.AppendLine($"[ExtensionOf({typeStr}({ElementName}, {SubElementName}))]");
                    }
                }

                declarationText.AppendLine($"final{(newClass.IsStatic ? " static " : " ")}class {newClass.Name}");
                declarationText.AppendLine("{");
                declarationText.AppendLine("}");

                newClass.SourceCode.Declaration = declarationText.ToString();
                axHelper.MetaModelService.CreateClass(newClass, axHelper.ModelSaveInfo);

                axHelper.AppendToActiveProject(newClass);
                AddLog($"Class: {newClass.Name}; ");
            }
            else
            {
                CoreUtility.DisplayInfo($"Class {newClass.Name} already exists");
                axHelper.AppendToActiveProject(newClass);
            }

            return(res);
        }
Beispiel #19
0
        public void Run()
        {
            AxHelper axHelper = new AxHelper();

            AxClass newClass = axHelper.MetadataProvider.Classes.Read(ResultClassName);

            if (newClass != null)
            {
                throw new Exception($"Class {ResultClassName} already exists");
            }

            newClass = new AxClass {
                IsFinal = true, Name = ResultClassName
            };

            if (ClassType == ExtensionClassType.EventHandler)
            {
                newClass.IsStatic = true;
            }

            string typeStr = "";

            switch (ElementType)
            {
            case ExtensionClassObject.Form:
                typeStr = "formstr";
                break;

            case ExtensionClassObject.Class:
                typeStr = "classstr";
                break;

            case ExtensionClassObject.Table:
                typeStr = "tablestr";
                break;

            case ExtensionClassObject.FormDataField:
                typeStr = "formdatafieldstr";
                break;

            case ExtensionClassObject.FormDataSource:
                typeStr = "formdatasourcestr";
                break;

            case ExtensionClassObject.FormControl:
                typeStr = "formcontrolstr";
                break;

            case ExtensionClassObject.DataEntityView:
                typeStr = "dataentityviewstr";
                break;
            }

            StringBuilder declarationText = new StringBuilder();

            if (ClassType == ExtensionClassType.Extension)
            {
                if (string.IsNullOrWhiteSpace(SubElementName))
                {
                    declarationText.AppendLine($"[ExtensionOf({typeStr}({ElementName}))]");
                }
                else
                {
                    declarationText.AppendLine($"[ExtensionOf({typeStr}({ElementName}, {SubElementName}))]");
                }
            }

            declarationText.AppendLine($"final{(newClass.IsStatic ? " static " : " ")}class {newClass.Name}");
            declarationText.AppendLine("{");
            declarationText.AppendLine("}");

            newClass.SourceCode.Declaration = declarationText.ToString();
            axHelper.MetaModelService.CreateClass(newClass, axHelper.ModelSaveInfo);
            axHelper.AppendToActiveProject(newClass);

            AddLog($"Class: {newClass.Name}; ");
        }
        /// <summary>
        /// Called when user clicks on the add-in menu
        /// </summary>
        /// <param name="e">The context of the VS tools and metadata</param>
        public override void OnClick(AddinDesignerEventArgs e)
        {
            try
            {
                int displayOrder = 0;
                // we will create Extension class here
                var selectedElement = e.SelectedElement as Microsoft.Dynamics.Framework.Tools.MetaModel.Automation.IRootElement;
                if (selectedElement != null)
                {
                    // Find current model

                    var modelSaveInfo    = Common.CommonUtil.GetCurrentModelSaveInfo();
                    var metaModelService = Common.CommonUtil.GetModelSaveService();

                    IClassItem classItem = selectedElement as IClassItem;
                    // Get the selected class AxClass object
                    AxClass selectedClass = Common.CommonUtil.GetModelSaveService().GetClass(classItem.Name);

                    // TODO: check that the class is a RunBaseBatch class. Otherwise send message that this is not required.


                    // Create Contract class
                    Microsoft.Dynamics.AX.Metadata.MetaModel.AxClass contractClass = new AxClass()
                    {
                        Name = classItem.Name + "Contract",
                    };
                    contractClass.Implements.Add("SysOperationValidatable");
                    contractClass.AddAttribute(new AxAttribute()
                    {
                        Name = "DataContract"
                    });
                    contractClass.SourceCode.Declaration = $"[DataContract]\npublic final class {contractClass.Name} implements SysOperationValidatable\n{{\n\n}}"; // this is replaced again later with the variables


                    List <string>   contractParms        = new List <string>(); // store the variables here
                    List <string>   contractParmMethods  = new List <string>(); // store the parm methods here
                    List <string>   axParmVariables      = new List <string>();
                    List <AxMethod> axMethods            = new List <AxMethod>();
                    string          currentGroup         = string.Empty;
                    string          headerAttributes     = "DataContract";
                    int             headerAttributeOrder = 0;

                    var dialogMethod = selectedClass.Methods.Where(m => m.Name.Equals("dialog", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                    if (dialogMethod != null)
                    {
                        // from the dialog method we would know what the code fields should be
                        var dialogSource = dialogMethod.Source;

                        //
                        var dialogLines = dialogSource.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
                        foreach (var dialogLine in dialogLines)
                        {
                            if (dialogLine.Trim().StartsWith("public"))
                            {
                                continue;
                            }
                            else if (dialogLine.Contains(".addGroup("))
                            {
                                // set the group name here
                                string dialogSourceLine = dialogLine.Substring(dialogLine.IndexOf("(") + 1);
                                dialogSourceLine = dialogSourceLine.Replace(");", "").Replace("\"", "").Trim();
                                string currentGrouplabel = dialogSourceLine;
                                currentGroup = dialogSourceLine;
                                if (currentGroup.StartsWith("@"))
                                {
                                    // we need to get a name for this group
                                    var label = Labels.LabelHelper.FindLabelGlobally(currentGrouplabel);
                                    if (label != null)
                                    {
                                        currentGroup = label.LabelText;
                                    }
                                }
                                currentGroup = currentGroup.Replace(" ", "").Trim();

                                headerAttributes += $", SysOperationGroupAttribute('{currentGroup}', \"{currentGrouplabel}\", '{headerAttributeOrder}')";

                                headerAttributeOrder++;
                            }
                            else if (dialogLine.Contains(".addField"))
                            {
                                string addFieldLine = dialogLine.Trim();
                                // so over here we will get the field to add as a member & parm method
                                addFieldLine = addFieldLine.Substring(addFieldLine.IndexOf(".addField"));
                                addFieldLine = addFieldLine.Substring(addFieldLine.IndexOf("(") + 1);

                                addFieldLine = addFieldLine.Replace(");", "").Trim();
                                var parameters = addFieldLine.Split(new string[] { "," }, StringSplitOptions.None).ToList();
                                parameters.ForEach(p => p.Trim());
                                string fieldType  = String.Empty;
                                string fieldLabel = String.Empty;
                                string fieldHelp  = String.Empty;
                                string fieldName  = String.Empty;

                                string attributes = String.Empty;
                                attributes = $"[DataMember, SysOperationDisplayOrder('{displayOrder}')";
                                // we will always have a fieldType (or atleast we should)
                                fieldType = parameters[0].Substring(parameters[0].IndexOf("(") + 1)
                                            .Replace("(", "").Replace(")", "").Trim();
                                if (parameters.Count >= 2)
                                {
                                    fieldName = parameters[1].Replace("\"", "").Trim();
                                    //if (String.IsNullOrEmpty(fieldLabel) == false)
                                    //{
                                    //    attributes += $", SysOperationLabel('{fieldName}')";
                                    //}
                                }

                                if (parameters.Count >= 3)
                                {
                                    fieldLabel = parameters[2].Replace("\"", "").Trim();
                                    if (String.IsNullOrEmpty(fieldLabel) == false)
                                    {
                                        attributes += $", SysOperationLabel(\"{fieldLabel}\")";
                                    }
                                }
                                if (parameters.Count >= 4)
                                {
                                    fieldHelp = parameters[3].Replace("\"", "").Trim();
                                    if (String.IsNullOrEmpty(fieldHelp) == false)
                                    {
                                        attributes += $", SysOperationHelpText(\"{fieldHelp}\")";
                                    }
                                }
                                // add the group here
                                if (!String.IsNullOrEmpty(currentGroup))
                                {
                                    attributes += $", SysOperationGroupMemberAttribute(\"{currentGroup}\")";
                                }
                                attributes += "]";



                                /* Crude method
                                 * string fieldType = addFieldLine.Substring(0, addFieldLine.IndexOf(","));
                                 * fieldType = fieldType.Substring(fieldType.IndexOf("(") + 1)
                                 *                      .Replace("(", "").Replace(")", "").Trim();
                                 *
                                 * string fieldLabel = String.Empty;
                                 * string fieldHelp = String.Empty;
                                 * string fieldName = addFieldLine.Substring(addFieldLine.IndexOf(",") + 1)
                                 *                      .Replace(")", "").Replace(";", "").Trim();
                                 * if (fieldName.Count(c => c == ',') > 0)
                                 * {
                                 *  // that means there is a label / help label in here as well
                                 *  // Break the fieldname further
                                 *  // find the label here
                                 *  string fieldNameLabel = fieldName;
                                 *  fieldName = fieldNameLabel.Substring(0, fieldNameLabel.IndexOf(",")).Trim();
                                 *
                                 *  // find the help label here
                                 * }
                                 */

                                AxClassMemberVariable axVar = new AxClassMemberVariable {
                                    TypeName = fieldType, Name = fieldName
                                };
                                axVar.Type = Microsoft.Dynamics.AX.Metadata.Core.MetaModel.CompilerBaseType.AnyType;
                                axParmVariables.Add($"\t{fieldType} {fieldName};");
                                contractClass.AddMember(axVar);



                                // need to add Attributes here
                                // add parameters to the method
                                //fieldName = System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fieldName);
                                AxMethod method = new AxMethod
                                {
                                    Name       = "parm" + System.Globalization.CultureInfo.CurrentCulture.TextInfo.ToTitleCase(fieldName),
                                    ReturnType = new AxMethodReturnType()
                                    {
                                        TypeName = fieldType
                                    }
                                };
                                //,{SysOperationLabelAttribute(""{}"")} // add the group & label & help attribute
                                method.Source =
                                    //$@"    [DataMember,SysOperationDisplayOrder('{displayOrder}')]
                                    $@"    {attributes}    
    public {fieldType} {method.Name} ({fieldType} _{fieldName} = {fieldName})
    {{
        {fieldName} = _{fieldName};
        return {fieldName};
    }}" + Environment.NewLine;
                                //contractClass.AddMethod(method);
                                axMethods.Add(method);

                                displayOrder++;
                            }
                        }
                    }

                    // Add all the axmethods here
                    string parmVarSource = string.Empty;
                    axParmVariables.ForEach(s => parmVarSource = parmVarSource + "\n" + s);
                    //contractClass.SourceCode.Declaration = $"[DataContract]\npublic final class {contractClass.Name}\n{{\n{parmVarSource}\n\n}}";
                    contractClass.SourceCode.Declaration = $"[{headerAttributes}]\npublic final class {contractClass.Name} implements SysOperationValidatable\n{{\n{parmVarSource}\n\n}}";
                    axMethods.ForEach(method => contractClass.AddMethod(method));

                    // Create validate method
                    this.applyValidateMethod(selectedClass, contractClass);


                    metaModelService.CreateClass(contractClass, modelSaveInfo);
                    Common.CommonUtil.AddElementToProject(contractClass);


                    //extensionClass.SourceCode.Declaration = $"[ExtensionOf({intrinsicStr}({selectedElement.Name}))]\npublic final class {className}\n{{\n\n}}";

                    /*
                     *
                     * metaModelService.CreateClass(extensionClass, modelSaveInfo);
                     * Common.CommonUtil.AddElementToProject(extensionClass);
                     */
                }
            }
            catch (Exception ex)
            {
                CoreUtility.HandleExceptionWithErrorMessage(ex);
            }
        }