I made a project that keys off the YouTube tutorial of Joche Ojeda and the answer by EliSherer
above that addresses the question at the top of this article, and also allows us to create a dialog box that shows check boxes to toggle which sub-projects get generated.
Please click here for my GitHub repo that does the dialog box and tries to fix the folder issue in this question.
The README.md
at the Repository root goes into excruciating depth as to the solution.
EDIT 1: Relevant Code
I want to add to this post the relevant code that addresses the OP's question.
First, we have to deal with folder naming conventions for solutions. Note, that my code is only designed to deal with the case where we are NOT putting the .csproj
and .sln
in the same folder; i.e., the following checkbox should be left blank:
Leaving the Place Solution and Project in the Same Directory check box blank
NOTE: The construct /* ... */
is used to signify other code that is not relevant to this answer. Also, the try/catch
block structure I utilize is pretty much identical to that of EliSherer
, so I won't reproduce that here, either.
We need to put the following fields in the beginning of the WizardImpl
class in the MyProjectWizard
DLL (this is the Root
DLL that is called during the generation of the Solution). Please note that all code snippets are taken from my GitHub Repo I am linking to, and I am only going to show the pieces that have to deal with answering the OP's question. I will, however, echo all using
's where relevant:
using Core.Config;
using Core.Files;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace MyProjectWizard
{
/// <summary>
/// Implements a new project wizard in Visual Studio.
/// </summary>
public class WizardImpl : IWizard
{
/// <summary>
/// String containing the fully-qualified pathname
/// of the erroneously-generated sub-folder of the
/// Solution that is going to contain the individual
/// projects' folders.
/// </summary>
private string _erroneouslyCreatedProjectContainerFolder;
/// <summary>
/// String containing the name of the folder that
/// contains the generated <c>.sln</c> file.
/// </summary>
private string _solutionFileContainerFolderName;
/* ... */
}
}
Here's how we initialize these fields (in the RunStarted
method of the same class):
using Core.Config;
using Core.Files;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace MyProjectWizard
{
/// <summary>
/// Implements a new project wizard in Visual Studio.
/// </summary>
public class WizardImpl : IWizard
{
/* ... */
public void RunStarted(object automationObject,
Dictionary<string, string> replacementsDictionary,
WizardRunKind runKind, object[] customParams)
{
/* ... */
// Grab the path to the folder that
// is erroneously created to contain the sub-projects.
_erroneouslyCreatedProjectContainerFolder =
replacementsDictionary["$destinationdirectory$"];
// Here, in the 'root' wizard, the $safeprojectname$ variable
// contains the name of the containing folder of the .sln file
// generated by the process.
_solutionFileContainerFolderName =
replacementsDictionary["$safeprojectname$"];
/* ... */
}
}
}
To be fair, I don't think that the value in the _solutionFileContainerFolderName
field is ever used, but I wanted to put it there so you can see what value $safeprojectname$
takes on in the Root
Wizard.
In the screen shots in this article and in the GitHub, I call the example dummy project BrianApplication1
and the solution is named the same. In this example, then, the _solutionFileContainerFolderName
field will have the value of BrianApplication1
.
If I tell Visual Studio I want to create the solution and project (really, the multi-project template) in the C:\temp
folder, then $destinationdirectory$
gets filled with C:\temp\BrianApplication1\BrianApplication1
.
The projects in the multi-project template all get initially generated underneath the C:\temp\BrianApplication1\BrianApplication1
folder, like so:
C:\
|
--- temp
|
--- BrianApplication1
|
--- BrianApplication1.sln
|
--- BrianApplication1 <-- extra folder that needs to go away
|
--- BrianApplication1.DAL
| |
| --- BrianApplication1.DAL.csproj
| |
| --- <other project files and folders>
--- BrianApplication1.WindowsApp
| |
| --- BrianApplication1.WindowsApp.csproj
| |
| --- <other project files and folders>
The whole point of the OP's post, and my solution, is to create a folder structure that hews to convention; i.e.:
C:\
|
--- temp
|
--- BrianApplication1
|
--- BrianApplication1.sln
|
--- BrianApplication1.DAL
| |
| --- BrianApplication1.DAL.csproj
| |
| --- <other project files and folders>
--- BrianApplication1.WindowsApp
| |
| --- BrianApplication1.WindowsApp.csproj
| |
| --- <other project files and folders>
We are almost done with the Root
implementation of IWizard
's job. We still need to implement the RunFinished
method (btw, the other IWizard
methods are irrelevant to this solution).
The job of the RunFinished
method is to simply remove the erroneously-created container folder for the sub-projects, now that they've all been moved up one level in the file system:
using Core.Config;
using Core.Files;
using EnvDTE;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace MyProjectWizard
{
/// <summary>
/// Implements a new project wizard in Visual Studio.
/// </summary>
public class WizardImpl : IWizard
{
/* ... */
/// <summary>Runs custom wizard logic when the wizard
/// has completed all tasks.</summary>
public void RunFinished()
{
// Here, _erroneouslyCreatedProjectContainerFolder holds the path to the
// erroneously-created container folder for the
// sub projects. When we get here, this folder should be
// empty by now, so just remove it.
if (!Directory.Exists(_erroneouslyCreatedProjectContainerFolder) ||
!IsDirectoryEmpty(_erroneouslyCreatedProjectContainerFolder))
return; // If the folder does not exist or is not empty, then do nothing
if (Directory.Exists(_erroneouslyCreatedProjectContainerFolder))
Directory.Delete(
_erroneouslyCreatedProjectContainerFolder, true
);
}
/* ... */
/// <summary>
/// Checks whether the folder having the specified <paramref name="path" /> is
/// empty.
/// </summary>
/// <param name="path">
/// (Required.) String containing the fully-qualified pathname of the folder to be
/// checked.
/// </param>
/// <returns>
/// <see langword="true" /> if the folder contains no files nor
/// subfolders; <see langword="false" /> otherwise.
/// </returns>
/// <exception cref="T:System.ArgumentException">
/// Thrown if the required parameter,
/// <paramref name="path" />, is passed a blank or <see langword="null" /> string
/// for a value.
/// </exception>
/// <exception cref="T:System.IO.DirectoryNotFoundException">
/// Thrown if the folder whose path is specified by the <paramref name="path" />
/// parameter cannot be located.
/// </exception>
private static bool IsDirectoryEmpty(string path)
{
if (string.IsNullOrWhiteSpace(path))
throw new ArgumentException(
"Value cannot be null or whitespace.", nameof(path)
);
if (!Directory.Exists(path))
throw new DirectoryNotFoundException(
$"The folder having path '{path}' could not be located."
);
return !Directory.EnumerateFileSystemEntries(path)
.Any();
}
/* ... */
}
}
}
The implementation for the IsDirectoryEmpty
method was inspired by a Stack Overflow answer and validated by my own knowledge; unfortunately, I lost the link to the appropriate article; if I can find it, I'll make an update.
OKAY, so now we've handled the job of the Root
Wizard. Next is the Child
Wizard. This where we add (a slight variation of) EliSherer
's answer.
First, the fields we need to declare are:
using Core.Common;
using Core.Config;
using Core.Files;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Thread = System.Threading.Thread;
namespace ChildWizard
{
/// <summary>
/// Implements a wizard for the generation of an individual project in the
/// solution.
/// </summary>
public class WizardImpl : IWizard
{
/* ... */
/// <summary>
/// Contains the name of the folder that was erroneously
/// generated in order to contain the generated sub-projects,
/// which we assume has the same name as the solution (without
/// the <c>.sln</c> file extension, so we are giving it a
/// descriptive name as such.
/// </summary>
private string _containingSolutionName;
/// <summary>
/// Reference to an instance of an object that implements the
/// <see cref="T:EnvDTE.DTE" /> interface.
/// </summary>
private DTE _dte;
/// <summary>
/// String containing the fully-qualified pathname of the
/// sub-folder in which this particular project (this Wizard
/// is called once for each sub-project in a multi-project
/// template) is going to live in.
/// </summary>
private string _generatedSubProjectFolder;
/// <summary>
/// String containing the name of the project that is safe to use.
/// </summary>
private string _subProjectName;
/* ... */
}
}
We initialize these fields in the RunStarted
method thusly:
using Core.Common;
using Core.Config;
using Core.Files;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Thread = System.Threading.Thread;
namespace ChildWizard
{
/// <summary>
/// Implements a wizard for the generation of an individual project in the
/// solution.
/// </summary>
public class WizardImpl : IWizard
{
/* ... */
/// <summary>Runs custom wizard logic at the beginning of a template wizard run.</summary>
/// <param name="automationObject">
/// The automation object being used by the template
/// wizard.
/// </param>
/// <param name="replacementsDictionary">
/// The list of standard parameters to be
/// replaced.
/// </param>
/// <param name="runKind">
/// A
/// <see cref="T:Microsoft.VisualStudio.TemplateWizard.WizardRunKind" /> indicating
/// the type of wizard run.
/// </param>
/// <param name="customParams">
/// The custom parameters with which to perform
/// parameter replacement in the project.
/// </param>
public void RunStarted(object automationObject,
Dictionary<string, string> replacementsDictionary,
WizardRunKind runKind, object[] customParams)
{
/* ... */
_dte = automationObject as DTE;
_generatedSubProjectFolder =
replacementsDictionary["$destinationdirectory$"];
_subProjectName = replacementsDictionary["$safeprojectname$"];
// Assume that the name of the solution is the same as that of the folder
// one folder level up from this particular sub-project.
_containingSolutionName = Path.GetFileName(
Path.GetDirectoryName(_generatedSubProjectFolder)
);
/* ... */
}
/* ... */
}
}
When this Child
Wizard is called, e.g., to generate the BrianApplication1.DAL
project, the fields get the following values:
_dte
= Reference to the automation object exposed by the EnvDTE.DTE
interface
_generatedSubProjectFolder
= C:\temp\BrianApplication1\BrianApplication1\BrianApplication1.DAL
_subProjectName
= BrianApplication1.DAL
_containingSolutionName
= BrianApplcation1
Relevant to the OP's answer, initializing these fields is all the work that RunStarted
needs to do. Now, let's see how I needed to adapt EliSherer
's answer in the RunFinished
method of the Child
Wizard's code:
using Core.Common;
using Core.Config;
using Core.Files;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.TemplateWizard;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using Thread = System.Threading.Thread;
namespace ChildWizard
{
/// <summary>
/// Implements a wizard for the generation of an individual project in the
/// solution.
/// </summary>
public class WizardImpl : IWizard
{
/* ... */
/// <summary>Runs custom wizard logic when the
/// wizard has completed all tasks.</summary>
public void RunFinished()
{
try
{
if (!_generatedSubProjectFolder.Contains(
_containingSolutionName + Path.DirectorySeparatorChar +
_containingSolutionName
))
return;
//The projects were created under a separate folder -- lets fix
//it
var projectsObjects = new List<Tuple<Project, Project>>();
foreach (Project childProject in _dte.Solution.Projects)
if (string.IsNullOrEmpty(
childProject.FileName
)) //Solution Folder
projectsObjects.AddRange(
from dynamic projectItem in
childProject.ProjectItems
select new Tuple<Project, Project>(
childProject, projectItem.Object as Project
)
);
else
projectsObjects.Add(
new Tuple<Project, Project>(null, childProject)
);
foreach (var projectObject in projectsObjects)
{
var projectBadPath = projectObject.Item2.FileName;
if (!projectBadPath.Contains(_subProjectName))
continue; // wrong project
var projectGoodPath = projectBadPath.Replace(
_containingSolutionName + Path.DirectorySeparatorChar +
_containingSolutionName + Path.DirectorySeparatorChar,
_containingSolutionName + Path.DirectorySeparatorChar
);
_dte.Solution.Remove(projectObject.Item2);
var projectBadPathDirectory =
Path.GetDirectoryName(projectBadPath);
var projectGoodPathDirectory =
Path.GetDirectoryName(projectGoodPath);
if (Directory.Exists(projectBadPathDirectory) &&
!string.IsNullOrWhiteSpace(projectGoodPathDirectory))
Directory.Move(
projectBadPathDirectory, projectGoodPathDirectory
);
if (projectObject.Item1 != null) //Solution Folder
{
var solutionFolder =
(SolutionFolder)projectObject.Item1.Object;
solutionFolder.AddFromFile(projectGoodPath);
}
else
{
// TO BE COMPLETELY ROBUST, we should do
// File.Exists() on the projectGoodPath; since
// we are in a try/catch and Directory.Move would
// have otherwise thrown an exception if the
// folder move operation failed, it can be safely
// assumed here that projectGoodPath refers to a
// file that actually exists on the disk.
_dte.Solution.AddFromFile(projectGoodPath);
}
}
ThreadPool.QueueUserWorkItem(
dir =>
{
Thread.Sleep(2000);
if (Directory.Exists(_generatedSubProjectFolder))
Directory.Delete(_generatedSubProjectFolder, true);
}, _generatedSubProjectFolder
);
}
catch (Exception ex)
{
DumpToLog(ex);
}
}
/* ... */
}
}
More or less, this is the same answer as EliSherer
, except, where he uses the expression _safeProjectName + Path.DirectorySeparatorChar + _safeProjectName
, I substitute _safeProjectName
with _containingSolutionName
, which, if you look above the listing to the fields and their descriptive comments and example values, makes more sense in this context.
NOTE: I thought about explaining the RunFinished
code in the Child
Wizard line-by-line but I think I will leave that to the reader to figure out. Let me do some broad-brush:
- We check whether the path of the generated sub-project folder contains
<solution-name>\<solution-name>
such as is shown in the example value of the _generatedSubProjectFolder
field and the OP's issue. If not, then stop as there is nothing to do.
NOTE: I use a Contains
search and not an EndsWith
as in EliSherer
's original answer, due to the example value being what it is (and what I actually encountered during the crafting of this project).
The next loop, through the solution's Project
s, is basically copied straight from EliSherer
. We sort out which Project
s are merely Solution Folders and which are actual, well, bona-fide .csproj
-based project entries. Like EliSherer
, we just go one level down in Solution Folders. Recursion is left as an exercise for the reader.
The loop that follows, which is over the List<Tuple<Project, Project>>
that is built up in #2, is again, almost identical to EliSherer
's answer, but with two important modifications:
- We check the
projectBadPath
whether it contains the _subProjectName
; if not, then we actually are iterating over one of the OTHER projects in the solution BESIDES the one that this particular call to the Child
Wizard is dealing with; if so, we use a continue
statement to skip it.
- In the
EliSherer
answer, everywhere he used the contents of $safeprojectname$
in his pathname parsing expressions, I am using the "solution name" I derived from parsing the folder path in RunStarted
, via the _containingSolutionName
field.
Then DTE
is used to remove the project from the Solution being generated, temporarily. We then move the project's folder up on level in the file system. For robustness' sake, I test whether the projectBadPathDirectory
(the "source" folder for the Directory.Move
call) exists (pretty reasonable) and I also use string.IsNullOrWhiteSpace
on the projectGoodPathDirectory
just in case Path.GetDirectoryName
does not return a valid value when called on the projectGoodPath
for some reason.
I then again, adapted the EliSherer
code for dealing with a SolutionFolder
or a project with a .csproj
pathname to have DTE
add the project BACK to the Solution being generated, this time, from the correct file system path.
I am fairly certain this code works because I did LOTS of logging (which then got removed, otherwise it would be like trying to see the trees through the forest). The logging infrastructure functions are still there in the body of the WizardImpl
classes in both MyProjectWizard
and ChildWizard
, if you care to use them again.
As always, I make no promises regarding edge cases... =)
I tried many iterations of the EliSherer
code before I could get all the test cases to work. By the way, which reminds me:
Test Cases
In each case, the desired outcome is the same: the folder structure of the generated .sln
and .csproj
should match convention, i.e., in the second folder-structure fence diagram above.
Each case simply says which project(s) to toggle on and off in the Wizard as shown in the GitHub repo.
- Generate DAL:
True
, Generate UI Layer: True
- Generate DAL:
False
, Generate UI Layer: True
- Generate DAL:
True
, Generate UI Layer: False
Since it's pointless to even run the generation process if both are set to False
, then we simply do not include that as a fourth test case.
With the code I supply both above and in the repo linked, all test cases pass. With "passing" meaning, Visual Studio Solutions are generated with only the sub-project(s) selected, and the folder structure matches the conventional folder layout that solves the OP's original issue.