Create Visual Studio Solutions and Projects at Runtime

Recently, I have been toying with a crazy idea (I do that often, ask my kids), the idea is to create an engine which creates applications based on user input. Let's think of this for a moment....
You define your domain model and document it using something like a word document or UML diagrams, hand it to a business analyst and ask them to generate the code. The data analyst opens up this magic engine and start creating the model using drag and drop controls. Maybe something like this:

Easy enough eh?

So, what are the steps needed to achieve this?

  1. We need a way to create a visual studio solution
  2. Add a project to this solution
  3. Save user input on a medium (json, xml or even a database)
  4. Create a T4 template to generate our domain models from the user's input and add them to the project in a Models directory

Let's start with step 1:

Let's create a windows form project to start with, once you have the project created, add the following references:



Step 2:
Now we start writing some code to create the solution:

var solutionName = "MagicCodeGenerator";
var solutionPath = @"E:\temp";
Type typeDTE = Type.GetTypeFromProgID("VisualStudio.DTE.12.0");
var dte = (DTE)Activator.CreateInstance(typeDTE, true);
var sln = (Solution4)dte.Solution;
sln.Create(solutionPath, solutionName);
sln.SaveAs(solutionName + ".sln");

The solution will be created in E:\temp and will be named MagicCodeGenerator.sln

Step 3:
We will modify the code (I will comment the code to further explain it) to create a project (C# Asp.net MVC) and add it to the solution.

Here is our modified full code to create the solution and project:

var solutionName = "MagicCodeGenerator";
           var solutionPath = @"E:\temp";
           var projectName = "MagicWeb";
           var projectPath = solutionName + "\\" + projectName;
 
           Type typeDTE = Type.GetTypeFromProgID("VisualStudio.DTE.12.0");
           var dte = (DTE)Activator.CreateInstance(typeDTE, true);
           var sln = (Solution4)dte.Solution;
           //this line will locate the MVC project's vsTemplate
           var csProjectTemplatePath=sln.GetProjectTemplate(@"EmptyMvcWebApplicationProjectTemplate.12.cshtml.vstemplate", "CSharp");
           // This line will add the empty MVC project to the solution
           sln.AddFromTemplate(csProjectTemplatePath, projectPath, projectName, false);
           //finalize the solution creation
           sln.Create(solutionPath, solutionName);
           //save your work
           sln.SaveAs(solutionName + ".sln");

If you run your code, you will have a brand new solution with a single MVC project inside.

In the next part of the series we will store the user input then create the T4 template and convert the user input into C# classes.

Comments (2) -

Thank you, thank you, thank you
I spent 2 days on this and gave up before I saw this.

You are most welcome Michelle Smile

Add comment