Create an extension for visual studio that dynamically adds classes

4

I'm creating an extension for visual studio that aims to create a project based on the options the programmer wants. In this case a wizard will be created where it will choose the entity (s) you want to create, and based on this selection will create the classes.

I have already created the template (in my case empty) and its wizard for the selection of entities. The feature selection wizard that is displayed when you create the project is in the image below. The purpose is that when doing OK a project is created with the classes that it chose, for example "ConsolidationSaldos" should give rise to a class inside an "Accounting" folder

Doubt is how to create classes dynamically based on selection.

namespacePrimavera.Extensibility.Wizard{publicclassWizardImplementation:IWizard{privateModulesfrm;privatestringcustomMessage;//Thismethodiscalledbeforeopeninganyitemthat//hastheOpenInEditorattribute.publicvoidBeforeOpeningFile(ProjectItemprojectItem){}publicvoidProjectFinishedGenerating(Projectproject){}//Thismethodisonlycalledforitemtemplates,//notforprojecttemplates.publicvoidProjectItemFinishedGenerating(ProjectItemprojectItem){}//Thismethodiscalledaftertheprojectiscreated.publicvoidRunFinished(){}publicvoidRunStarted(objectautomationObject,Dictionary<string,string>replacementsDictionary,WizardRunKindrunKind,object[]customParams){try{//Displayaformtotheuser.Theformcollectstheclassescheckedfrm=newModules();frm.ShowDialog();customMessage=Modules.CustomMessage;replacementsDictionary.Add("$custommessage$",
                    customMessage);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        // This method is only called for item templates,  
        // not for project templates.  
        public bool ShouldAddProjectItem(string filePath)
        {
            return true;
        }
    }
}
    
asked by anonymous 13.07.2018 / 16:59

1 answer

3

This is simple to do.

You have to create a template item with the class template that you want to add to your project, and then just cycle to iterate over the collection of objects you have.

EnvDTE80.Solution2 solution = project.DTE.Solution as EnvDTE80.Solution2;
string itemPath = solution.GetProjectItemTemplate("Class.zip", "CSharp");

string[] namespaceParts = type.Namespace.Split('.');
if (namespaceParts.Length == 4)
{
    string module = namespaceParts[2];
    string moduleType = namespaceParts[3];
    string className = type.Name;     

    ProjectItem rootFolder = project.ProjectItems.Cast<ProjectItem>().FirstOrDefault(i => i.Name == module) ?? project.ProjectItems.AddFolder(module);
    ProjectItem itemEditors = rootFolder.ProjectItems.AddFromTemplate(itemPath, className + ".cs");
}
    
05.09.2018 / 15:34