WiX project is never up-to-date - visual-studio

I have an installer (.msi) project that uses Wix Toolset v3.14. For some reason it is never up-to-date -- i.e. building it again always produces some activity (C:\Program Files (x86)\WiX Toolset v3.14\bin\Light.exe gets called, but not candle.exe). Is there any way to track down and fix the cause?
Here is what I observe when detailed output is ON:
Target "ReadPreviousBindInputsAndBuiltOutputs" in file "C:\Program Files (x86)\MSBuild\Microsoft\WiX\v3.x\wix.targets" from project "<my-project>" (target "Link" depends on it):
Task "ReadLinesFromFile"
Task Parameter:File=obj\x64\Debug\<my-project>.wixproj.BindContentsFileListen-us.txt
Output Item(s):
_BindInputs=
C:\Users\<me>\AppData\Local\Temp\a5uljxg1\MergeId.418703\api_ms_win_core_console_l1_1_0.dll.AF4EABEE_4589_3789_BA0A_C83A71662E1D
...
Done building target "ReadPreviousBindInputsAndBuiltOutputs" in project "<my-project>.wixproj".
Target "Link" in file "C:\Program Files (x86)\MSBuild\Microsoft\WiX\v3.x\wix.targets" from project "<my-project>.wixproj" (target "CompileAndLink" depends on it):
Building target "Link" completely.
Input file "C:\Users\<me>\AppData\Local\Temp\a5uljxg1\MergeId.418703\api_ms_win_core_console_l1_1_0.dll.AF4EABEE_4589_3789_BA0A_C83A71662E1D" does not exist.
...
<and here it executes Light.exe>
So, it looks like it reads BindContentsFileListen-us.txt and expects it to contain files that were inputs during last build run. But, unfortunately some of these files were generated in temporary folder and got wiped out (presumably during last build) and since they don't exist anymore -- Link step is re-executed. I observe this pattern every time I press F7, only number in MergeId.418703 gets changed every time (looks like process id to me).
UPDATE: this is a known (and pretty old) issue. As of now it is planned to be fixed in WiX v4.0.

I have hit the same issue, and the only information I found apart from this question was a pretty unhelpful mail thread from 2013 (1, 2) and an issue from the same era.
Troubleshooting
Reading through the logs and Wix's source code shows that the bugs occurs as follows:
light.exe, the linker, receives all of the object (.wixobj) files it should combine, some of them referencing the .msm merge module's file path.
light.exe uses a combination of mergemod.dll's IMsmMerge::ExtractCAB and cabinet.dll's ::FDICopy (through their own winterop.dll) to extract the contents of the merge module to a temporary path:
// Binder.cs:5612, ProcessMergeModules
// extract the module cabinet, then explode all of the files to a temp directory
string moduleCabPath = String.Concat(this.TempFilesLocation, Path.DirectorySeparatorChar, safeMergeId, ".module.cab");
merge.ExtractCAB(moduleCabPath);
string mergeIdPath = String.Concat(this.TempFilesLocation, Path.DirectorySeparatorChar, "MergeId.", safeMergeId);
Directory.CreateDirectory(mergeIdPath);
using (WixExtractCab extractCab = new WixExtractCab())
{
try
{
extractCab.Extract(moduleCabPath, mergeIdPath);
}
// [...]
}
At the same time, the contents of the merge module are inserted among the other input files in the fileRows collection:
// Binder.cs:5517, ProcessMergeModules
// NOTE: this is very tricky - the merge module file rows are not added to the
// file table because they should not be created via idt import. Instead, these
// rows are created by merging in the actual modules
FileRow fileRow = new FileRow(null, this.core.TableDefinitions["File"]);
// [...]
fileRow.Source = String.Concat(this.TempFilesLocation, Path.DirectorySeparatorChar, "MergeId.", wixMergeRow.Number.ToString(CultureInfo.InvariantCulture.NumberFormat), Path.DirectorySeparatorChar, record[1]);
FileRow collidingFileRow = fileRows[fileRow.File];
FileRow collidingModuleFileRow = (FileRow)uniqueModuleFileIdentifiers[fileRow.File];
if (null == collidingFileRow && null == collidingModuleFileRow)
{
fileRows.Add(fileRow);
// keep track of file identifiers in this merge module
uniqueModuleFileIdentifiers.Add(fileRow.File, fileRow);
}
// [...]
fileRows ends up being written to the <project_name>BindContentsFileList<culture>.txt file inside the intermediate directory, including the temporary (and randomly named) files extracted from the merge module:
// Binder.cs:7346
private void CreateContentsFile(string path, FileRowCollection fileRows)
{
string directory = Path.GetDirectoryName(path);
if (!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
using (StreamWriter contents = new StreamWriter(path, false))
{
foreach (FileRow fileRow in fileRows)
{
contents.WriteLine(fileRow.Source);
}
}
}
During the next build, the ReadPreviousBindInputsAndBuiltOutputs target from wix2010.targets reads the file into the #(_BindInputs) item group. This item group is then listed as input to the Link target. Since the temporary files have since disappeared, the target is always considered out-of-date and re-run, generating an new set of temporary files that get listed in BindContentsFileList, and so on.
Workaround
An actual fix would be to patch Wix so that merge modules discoverd in .wixobj files are listed in BindContentsFileList, and files extracted from them during linking aren't. Unfortunately I wasn't able to make Wix's source code compile, and can't be bothered to go through its distribution process. Hence, here is the workaround I have implemented.
Removing temporary files from the input list
This is done using a custom target which slots in-between ReadPreviousBindInputsAndBuiltOutputs and Link and filters #(_BindInputs) to remove whatever is under %temp%.
<Target
Name="RemoveTempFilesFromBindInputs"
DependsOnTargets="ReadPreviousBindInputsAndBuiltOutputs"
BeforeTargets="Link"
>
<PropertyGroup>
<!-- This includes a final backslash, so we can use StartsWith. -->
<TemporaryDirectory>$([System.IO.Path]::GetTempPath())</TemporaryDirectory>
</PropertyGroup>
<ItemGroup>
<_BindInputs
Remove="#(_BindInputs)"
Condition="$([System.String]::new('%(FullPath)').StartsWith('$(TemporaryDirectory)'))"
/>
</ItemGroup>
</Target>
At that point, Link triggers only when actual input files change. Success! However, changes to the .msm files are not detected. This might be good enough a solution anyway, since merge modules are generally static. Otherwise...
Detecting changes to merge modules
The main hurdle is that the only reference to the .msm file is within a .wxs source file, so we need to bridge the gap between that and MSBuild. There are a couple ways that can be used, such as parsing the .wixobj to fish out the WixMerge tables. However, I already had code in place to generate Wix code, so I went that way, lifting the merge modules into an MSBuild item group and using a custom task to generate a .wxs file referencing them in a feature. Full code below:
<Target
Name="GenerateMsmFragment"
BeforeTargets="GenerateCompileWithObjectPath"
Inputs="#(MsmFiles)"
Outputs="$(IntermediateOutputPath)MsmFiles.wxs"
>
<GenerateMsmFragment
MsmFiles="#(MsmFiles)"
FeatureName="MsmFiles"
MediaId="2"
OutputFile="$(IntermediateOutputPath)MsmFiles.wxs"
>
<Output TaskParameter="OutputFile" ItemName="Compile" />
</GenerateMsmFragment>
</Target>
// GenerateMsmFragment.cs
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;
namespace tasks
{
[ComVisible(false)]
public class GenerateMsmFragment : Task
{
[Required]
public ITaskItem[] MsmFiles { get; set; }
[Required]
public string FeatureName { get; set; }
[Required]
public string MediaId { get; set; }
[Output]
public ITaskItem OutputFile { get; set; }
public override bool Execute()
{
var xmlns = "http://schemas.microsoft.com/wix/2006/wi";
var outputXml = new XmlDocument();
outputXml.AppendChild(outputXml.CreateXmlDeclaration("1.0", "utf-8", null));
var fragmentElem = outputXml
.AppendElement("Wix", xmlns)
.AppendElement("Fragment", xmlns);
{
var mediaElem = fragmentElem.AppendElement("Media", xmlns);
mediaElem.SetAttribute("Id", MediaId);
mediaElem.SetAttribute("Cabinet", "MsmFiles.cab");
mediaElem.SetAttribute("EmbedCab", "yes");
}
{
var directoryRefElem = fragmentElem.AppendElement("DirectoryRef", xmlns);
directoryRefElem.SetAttribute("Id", "TARGETDIR");
var featureElem = fragmentElem.AppendElement("Feature", xmlns);
featureElem.SetAttribute("Id", FeatureName);
featureElem.SetAttribute("Title", "Imported MSM files");
featureElem.SetAttribute("AllowAdvertise", "no");
featureElem.SetAttribute("Display", "hidden");
featureElem.SetAttribute("Level", "1");
foreach (var msmFilePath in MsmFiles.Select(i => i.ItemSpec)) {
var mergeElem = directoryRefElem.AppendElement("Merge", xmlns);
mergeElem.SetAttribute("Id", msmFilePath);
mergeElem.SetAttribute("SourceFile", msmFilePath);
mergeElem.SetAttribute("DiskId", MediaId);
mergeElem.SetAttribute("Language", "0");
featureElem
.AppendElement("MergeRef", xmlns)
.SetAttribute("Id", msmFilePath);
}
}
Directory.CreateDirectory(Path.GetDirectoryName(OutputFile.GetMetadata("FullPath")));
outputXml.Save(OutputFile.GetMetadata("FullPath"));
return true;
}
}
}
// XmlExt.cs
using System.Xml;
namespace nrm
{
public static class XmlExt
{
public static XmlElement AppendElement(this XmlDocument element, string qualifiedName, string namespaceURI)
{
var newElement = element.CreateElement(qualifiedName, namespaceURI);
element.AppendChild(newElement);
return newElement;
}
public static XmlElement AppendElement(this XmlNode element, string qualifiedName, string namespaceURI)
{
var newElement = element.OwnerDocument.CreateElement(qualifiedName, namespaceURI);
element.AppendChild(newElement);
return newElement;
}
}
}
And voilĂ , working up-to-date detection for merge modules.

Related

Get a Xamarin assembly build date on iOS, Android and OS X

In my code I need a Xamarin assembly build date. On Windows I can use linker time stamp. However on iOS this does not work. I guess it would not work on OS X too as Portable Executable header is specific to Windows.
There is also an option to embed a resource with a date, however I would like to avoid using resources in this particular project.
Are there any way to find a Xamarin assembly build date that works on iOS, Android and OS X?
One approach would be to use an MSBuild task to substitute the build time into a string that is returned by a property on the app. We are using this approach successfully in an app that has Xamarin.Forms, Xamarin.Android, and Xamarin.iOS projects.
If using msbuild, this can be an MSBuild inline task, while on Mac using xbuild, it will need to be an MSBuild custom task compiled for Mono.
EDIT:
Simplified by moving all of the logic into the build task, and using Regex instead of simple string replace so that the file can be modified by each build without a "reset".
The MSBuild inline task definition (saved in a SetBuildDate.targets file local to the Xamarin.Forms project for this example):
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003' ToolsVersion="12.0">
<UsingTask TaskName="SetBuildDate" TaskFactory="CodeTaskFactory"
AssemblyFile="$(MSBuildToolsPath)\Microsoft.Build.Tasks.v12.0.dll">
<ParameterGroup>
<FilePath ParameterType="System.String" Required="true" />
</ParameterGroup>
<Task>
<Code Type="Fragment" Language="cs"><![CDATA[
DateTime now = DateTime.UtcNow;
string buildDate = now.ToString("F");
string replacement = string.Format("BuildDate => \"{0}\"", buildDate);
string pattern = #"BuildDate => ""([^""]*)""";
string content = File.ReadAllText(FilePath);
System.Text.RegularExpressions.Regex rgx = new System.Text.RegularExpressions.Regex(pattern);
content = rgx.Replace(content, replacement);
File.WriteAllText(FilePath, content);
File.SetLastWriteTimeUtc(FilePath, now);
]]></Code>
</Task>
</UsingTask>
</Project>
EDIT:
Added an MSBuild Exec step to remove readonly attribute. Gotta love TFS.
Invoking the MSBuild task (inline or compiled, inline approach is commented for xbuild) in the Xamarin.Forms csproj file in target BeforeBuild:
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets. -->
<!--<Import Project="SetBuildDate.targets" />-->
<UsingTask AssemblyFile="$(MSBuildProjectDirectory)\BI.Framework.BuildExtensions.dll" TaskName="Some.Framework.BuildExtensions.BuildDateTask" />
<Target Name="BeforeBuild">
<Exec Command="attrib $(MSBuildProjectDirectory)\BuildMetadata.cs -r" />
<!--<SetBuildDate FilePath="$(MSBuildProjectDirectory)\BuildMetadata.cs" />-->
<BuildDateTask FilePath="$(MSBuildProjectDirectory)\BuildMetadata.cs" />
</Target>
The FilePath property is set to a BuildMetadata.cs file in the Xamarin.Forms project that contains a simple class with a string property BuildDate, into which the build time will be substituted:
public class BuildMetadata
{
public static string BuildDate => "This can be any arbitrary string";
}
Add this file BuildMetadata.cs to project. It will be modified by every build, but in a manner that allows repeated builds (repeated replacements), so you may include or omit it in source control as desired.
ADDED:
Here is a custom MSBuild task to replace the MSBuild inline task for when building with xbuild on Mac:
using System;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
namespace Some.Framework.BuildExtensions
{
public class BuildDateTask : Task
{
#region Methods
/// <summary>
/// Called automatically when the task is run.
/// </summary>
/// <returns><c>true</c>for task success, <c>false</c> otherwise.</returns>
public override bool Execute()
{
const string pattern = #"BuildDate => ""([^""]*)""";
var now = DateTime.UtcNow;
var buildDate = now.ToString("F");
var replacement = $"BuildDate => \"{buildDate}\"";
var content = File.ReadAllText(FilePath);
var rgx = new Regex(pattern);
content = rgx.Replace(content, replacement);
File.WriteAllText(FilePath, content);
File.SetLastWriteTimeUtc(FilePath, now);
return true;
}
#endregion Methods
#region Properties
[Required]
public string FilePath { get; set; }
#endregion Properties
}
}
Build this custom task for Release via xbuild, then copy the output custom task dll to the project directory of the project for which you want to set the build date.

Resolve actual Reference path using Microsoft.Build.Evaluation

I'm doing some introspection and analysis of csproj files using the Microsoft.Build.Evaluation tools in a small C# console app. I want to locate the actual location of Reference items, using the same heuristics as MSBuild itself ie the locations described here. I'm heading towards auto conversion of build artifacts into packages, similar to what's outlined on the JetBrains blog here
The only examples I can find expect the HintPath to be correct, for example this project, and I know there are some HintPaths that are not currently correct, I don't want to trust them. This project very close what I'm trying to do, with the added complication that I want to use real resolution behaviour to find dependencies.
I have an instance of a Microsoft.Build.Evaluation.Project object for my csproj, and I can't see any methods available on it that could exersize the resolution for me. I think what I'm hoping for is a magic Resolve() method for a Reference or a ProjectItem, a bit like this method.
I can probably find an alternative by constraining my own search to a set of limited output paths used by this build system, but I'd like to hook into MSBuild if I can.
The reference resolution is one of the trickiest parts of MSBuild. The logic of how assemblies are located is implemented inside the a standard set of tasks:
ResolveAssemblyReference, ResolveNativeReference, etc. The logic is how this works is very complicated, you can see that just by looking at number of possible parameters to those tasks.
However you don't need to know the exact logic to find the location of referenced files. There are standard targets called "ResolveAssemblyReferences", "ResolveProjectReferences" and some others more specialized for native references, COM references. Those targets are executed as part of the normal build. If you just execute those targets separately, you can find out the return values, which is exactly what you need. The same mechanism is used by IDE to get location of refereces, for Intellisense, introspection, etc.
Here is how you can do it in code:
using Microsoft.Build.BuildEngine;
using Microsoft.Build.Execution;
using Microsoft.Build.Framework;
using System;
using System.Collections.Generic;
class Program
{
static int Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage: GetReferences.exe <projectFileName>");
return -1;
}
string projectFileName = args[0];
ConsoleLogger logger = new ConsoleLogger(LoggerVerbosity.Normal);
BuildManager manager = BuildManager.DefaultBuildManager;
ProjectInstance projectInstance = new ProjectInstance(projectFileName);
var result = manager.Build(
new BuildParameters()
{
DetailedSummary = true,
Loggers = new List<ILogger>() { logger }
},
new BuildRequestData(projectInstance, new string[]
{
"ResolveProjectReferences",
"ResolveAssemblyReferences"
}));
PrintResultItems(result, "ResolveProjectReferences");
PrintResultItems(result, "ResolveAssemblyReferences");
return 0;
}
private static void PrintResultItems(BuildResult result, string targetName)
{
var buildResult = result.ResultsByTarget[targetName];
var buildResultItems = buildResult.Items;
if (buildResultItems.Length == 0)
{
Console.WriteLine("No refereces detected in target {0}.", targetName);
return;
}
foreach (var item in buildResultItems)
{
Console.WriteLine("{0} reference: {1}", targetName, item.ItemSpec);
}
}
}
Notice, the engine is called to invoke specific targets in the project. Your project usually does not build, but some targets might be invoked by pre-requisite targets.
Just compile it and will print a sub-set of all dependencies. There might be more dependencies if you use COM references or native dependencies for your project. It should be easy to modify the sample to get those as well.

how to disable T4 template auto-run in visual studio (2012)?

I have some T4 templates in my project. Whenever I make changes and save the tt file, it auto update the generated files. This is a template that loops all tables in a database and generates about 100+ files. So visual studio hangs for a few seconds every time I save my template and this is annoying. Is there a way to disable to "auto-refresh" function and I can manually run the template through the context menu.
Thanks!
You could delete TextTemplatingFileGenerator under "Custom Tool" in the file's Properties while you are editing it, and then put it back when you are finished.
I had a similiar issue. I found a quick work around by creating a ttinclude file (actually this was already a standard include file containing utility functions for my templates) and including it in all of my T4 templates. Then I simply created a compiler error in the include file. Thus when the generator attempted to run it would simply fail on the compile. Then when I'm ready to actually generate, I get rid of the offending code and then generate.
e.g. To cause a failure:
<#+
#
#>
To disable the failure:
<#+
//#
#>
You can also use this trick in the T4 template itself if you just want to disable the one you're working on.
Hopefully future VS versions will allow you to simply disable the auto-transform.
Since the TT is always executed (still), I found a different way to control the output when the TT is executed.
/********SET THIS TO REGENERATE THE FILE (OR NOT) ********/
var _RegenerateFile = true;
/********COS VS ALWAYS REGENERATES ON SAVE ***************/
// Also, T4VSHostProcess.exe may lock files.
// Kill it from task manager if you get "cannot copy file in use by another process"
var _CurrentFolder = new FileInfo(Host.ResolvePath(Host.TemplateFile)).DirectoryName;
var _AssemblyLoadFolder = Path.Combine(_CurrentFolder, "bin\\Debug");
Directory.SetCurrentDirectory(_CurrentFolder);
Debug.WriteLine($"Using working folder {_CurrentFolder}");
if (_RegenerateFile == false)
{
Debug.WriteLine($"Not Regenerating File");
var existingFileName = Path.ChangeExtension(Host.TemplateFile, "cs");
var fileContent = File.ReadAllText(existingFileName);
return fileContent;
}
Debug.WriteLine($"Regenerating File"); //put the rest of your usual template
Another way (what I eventually settled on) is based on reading a conditional compilation symbol that sets a property on one of the the classes that is providing the data for the T4. This gives the benefit of skipping all that preparation (and IDE lag) unless you add the REGEN_CODE_FILES conditional compilation symbol. (I guess this could also be made into a new solution configuration too. yes, this does work and removes the need for the class change below)
An example of the class i am calling in the same assembly..
public class MetadataProvider
{
public bool RegenCodeFile { get; set; }
public MetadataProvider()
{
#if REGEN_CODE_FILES
RegenCodeFile = true; //try to get this to set the property
#endif
if (RegenCodeFile == false)
{
return;
}
//code that does some degree of preparation and c...
}
}
In the TT file...
var _MetaProvider = new MetadataProvider();
var _RegenerateFile = _MetaProvider.RegenCodeFile;
// T4VSHostProcess.exe may lock files.
// Kill it from task manager if you get "cannot copy file in use by another process"
var _CurrentFolder = new FileInfo(Host.ResolvePath(Host.TemplateFile)).DirectoryName;
var _AssemblyLoadFolder = Path.Combine(_CurrentFolder, "bin\\Debug");
Directory.SetCurrentDirectory(_CurrentFolder);
Debug.WriteLine($"Using working folder {_CurrentFolder}");
if (_RegenerateFile == false)
{
Debug.WriteLine($"Not Regenerating File");
var existingFileName = Path.ChangeExtension(Host.TemplateFile, "cs");
var fileContent = File.ReadAllText(existingFileName);
return fileContent;
}
Debug.WriteLine($"Regenerating File");

Entity Framework Designer Extension Not loading

I created a small extension for the EF designer that adds a new property to the property window. I did this using a vsix project (new project -> c# -> extensibility -> vsix project). When I hit F5 the experimental VS instance starts up. I create a new project, add an entity data model and add an entity. However, my break points never get hit and I don't see the property. Any ideas as to what I might be doing wrong?
public class AggregateRootValue
{
internal static XName AggregateRootElementName = XName.Get("AggregateRoot", "http://efex");
private readonly XElement _property;
private readonly PropertyExtensionContext _context;
public AggregateRootValue(XElement parent, PropertyExtensionContext context)
{
_property = parent;
_context = context;
}
[DisplayName("Aggregate Root")]
[Description("Determines if an entity is an Aggregate Root")]
[Category("Extensions")]
[DefaultValue(true)]
public string AggregateRoot
{
get
{
XElement child = _property.Element(AggregateRootElementName);
return (child == null) ? bool.TrueString : child.Value;
}
set
{
using (EntityDesignerChangeScope scope = _context.CreateChangeScope("Set AggregateRoot"))
{
var element = _property.Element(AggregateRootElementName);
if (element == null)
_property.Add(new XElement(AggregateRootElementName, value));
else
element.SetValue(value);
scope.Complete();
}
}
}
}
[Export(typeof(IEntityDesignerExtendedProperty))]
[EntityDesignerExtendedProperty(EntityDesignerSelection.ConceptualModelEntityType)]
public class AggregateRootFactory : IEntityDesignerExtendedProperty
{
public object CreateProperty(XElement element, PropertyExtensionContext context)
{
var edmXName = XName.Get("Key", "http://schemas.microsoft.com/ado/2008/09/edm");
var keys = element.Parent.Element(edmXName).Elements().Select(e => e.Attribute("Name").Value);
if (keys.Contains(element.Attribute("Name").Value))
return new AggregateRootValue(element, context);
return null;
}
}
EDIT: I put the code on Github: https://github.com/devlife/Sandbox
EDIT: After Adding the MEF component to the manifest as suggested, the extension still never loads. Here is a picture of the manifest:
So the answer, as it turns out, is in how I setup my project. I put both classes inside the project which produces the VSIX file. By simply moving those classes into another project and setting that project as the MEF Component in the manifest (and thus copying the assembly) it worked like a charm!
For VS2012, it is only needed to add Solution as MEF component also. Just add whole solution as MEF component also.
Then it works surprisingly fine.
It seems the dll built by your project isn't automatically included in the generated VSIX package, and VS2013 doesn't give you options through the IDE to change this (that I can work out, anyway).
You have to manually open the project file and alter the XML. The property to change is IncludeAssemblyInVSIXContainer.
Seen here: How to include VSIX output in it's package?

Issue with visual studio template & directory creation

I'm trying to make a Visual Studio (2010) template (multi-project). Everything seems good, except that the projects are being created in a sub-directory of the solution. This is not the behavior I'm looking for.
The zip file contains:
Folder1
+-- Project1
+-- Project1.vstemplate
+-- Project2
+-- Project2.vstemplate
myapplication.vstemplate
Here's my root template:
<VSTemplate Version="3.0.0" Type="ProjectGroup" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005">
<TemplateData>
<Name>My application</Name>
<Description></Description>
<Icon>Icon.ico</Icon>
<ProjectType>CSharp</ProjectType>
<RequiredFrameworkVersion>4.0</RequiredFrameworkVersion>
<DefaultName>MyApplication</DefaultName>
<CreateNewFolder>false</CreateNewFolder>
</TemplateData>
<TemplateContent>
<ProjectCollection>
<SolutionFolder Name="Folder1">
<ProjectTemplateLink ProjectName="$safeprojectname$.Project1">Folder1\Project1\Project1.vstemplate</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="$safeprojectname$.Project2">Folder2\Project2\Project2.vstemplate</ProjectTemplateLink>
</SolutionFolder>
</ProjectCollection>
</TemplateContent>
</VSTemplate>
And, when creating the solution using this template, I end up with directories like this:
Projects
+-- MyApplication1
+-- MyApplication1 // I'd like to have NOT this directory
+-- Folder1
+-- Project1
+-- Project2
solution file
Any help?
EDIT:
It seems that modifying <CreateNewFolder>false</CreateNewFolder>, either to true or false, doesn't change anything.
To create solution at root level (not nest them in subfolder) you must create two templates:
1) ProjectGroup stub template with your wizard inside that will create new project at the end from your
2) Project template
use the following approach for that
1. Add template something like this
<VSTemplate Version="2.0.0" xmlns="http://schemas.microsoft.com/developer/vstemplate/2005" Type="ProjectGroup">
<TemplateData>
<Name>X Application</Name>
<Description>X Shell.</Description>
<ProjectType>CSharp</ProjectType>
<Icon>__TemplateIcon.ico</Icon>
</TemplateData>
<TemplateContent>
</TemplateContent>
<WizardExtension>
<Assembly>XWizard, Version=1.0.0.0, Culture=neutral</Assembly>
<FullClassName>XWizard.FixRootFolderWizard</FullClassName>
</WizardExtension>
</VSTemplate>
2. Add code to wizard
// creates new project at root level instead of subfolder.
public class FixRootFolderWizard : IWizard
{
#region Fields
private string defaultDestinationFolder_;
private string templatePath_;
private string desiredNamespace_;
#endregion
#region Public Methods
...
public void RunFinished()
{
AddXProject(
defaultDestinationFolder_,
templatePath_,
desiredNamespace_);
}
public void RunStarted(object automationObject,
Dictionary<string, string> replacementsDictionary,
WizardRunKind runKind, object[] customParams)
{
defaultDestinationFolder_ = replacementsDictionary["$destinationdirectory$"];
templatePath_ =
Path.Combine(
Path.GetDirectoryName((string)customParams[0]),
#"Template\XSubProjectTemplateWizard.vstemplate");
desiredNamespace_ = replacementsDictionary["$safeprojectname$"];
string error;
if (!ValidateNamespace(desiredNamespace_, out error))
{
controller_.ShowError("Entered namespace is invalid: {0}", error);
controller_.CancelWizard();
}
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
#endregion
}
public void AddXProject(
string defaultDestinationFolder,
string templatePath,
string desiredNamespace)
{
var dte2 = (DTE) System.Runtime.InteropServices.Marshal.GetActiveObject("VisualStudio.DTE.10.0");
var solution = (EnvDTE100.Solution4) dte2.Solution;
string destinationPath =
Path.Combine(
Path.GetDirectoryName(defaultDestinationFolder),
"X");
solution.AddFromTemplate(
templatePath,
destinationPath,
desiredNamespace,
false);
Directory.Delete(defaultDestinationFolder);
}
This is based on #drweb86 answer with some improvments and explanations.
Please notice few things:
The real template with projects links is under some dummy folder since you can't have more than one root vstemplate. (Visual studio will not display your template at all at such condition).
All the sub projects\templates have to be located under the real template file folder.
Zip template internal structure example:
RootTemplateFix.vstemplate
-> Template Folder
YourMultiTemplate.vstemplate
-->Sub Project Folder 1
SubProjectTemplate1.vstemplate
-->Sub Project Folder 2
SubProjectTemplate2.vstemplate
...
On the root template wizard you can run your user selection form and add them into a static variable. Sub wizards can copy these Global Parameters into their private dictionary.
Example:
public class WebAppRootWizard : IWizard
{
private EnvDTE._DTE _dte;
private string _originalDestinationFolder;
private string _solutionFolder;
private string _realTemplatePath;
private string _desiredNamespace;
internal readonly static Dictionary<string, string> GlobalParameters = new Dictionary<string, string>();
public void BeforeOpeningFile(ProjectItem projectItem)
{
}
public void ProjectFinishedGenerating(Project project)
{
}
public void ProjectItemFinishedGenerating(ProjectItem
projectItem)
{
}
public void RunFinished()
{
//Run the real template
_dte.Solution.AddFromTemplate(
_realTemplatePath,
_solutionFolder,
_desiredNamespace,
false);
//This is the old undesired folder
ThreadPool.QueueUserWorkItem(new System.Threading.WaitCallback(DeleteDummyDir), _originalDestinationFolder);
}
private void DeleteDummyDir(object oDir)
{
//Let the solution and dummy generated and exit...
System.Threading.Thread.Sleep(2000);
//Delete the original destination folder
string dir = (string)oDir;
if (!string.IsNullOrWhiteSpace(dir) && Directory.Exists(dir))
{
Directory.Delete(dir);
}
}
public void RunStarted(object automationObject,
Dictionary<string, string> replacementsDictionary,
WizardRunKind runKind, object[] customParams)
{
try
{
this._dte = automationObject as EnvDTE._DTE;
//Create the desired path and namespace to generate the project at
string temlateFilePath = (string)customParams[0];
string vsixFilePath = Path.GetDirectoryName(temlateFilePath);
_originalDestinationFolder = replacementsDictionary["$destinationdirectory$"];
_solutionFolder = replacementsDictionary["$solutiondirectory$"];
_realTemplatePath = Path.Combine(
vsixFilePath,
#"Template\BNHPWebApplication.vstemplate");
_desiredNamespace = replacementsDictionary["$safeprojectname$"];
//Set Organization
GlobalParameters.Add("$registeredorganization$", "My Organization");
//User selections interface
WebAppInstallationWizard inputForm = new WebAppInstallationWizard();
if (inputForm.ShowDialog() == DialogResult.Cancel)
{
throw new WizardCancelledException("The user cancelled the template creation");
}
// Add user selection parameters.
GlobalParameters.Add("$my_user_selection$",
inputForm.Param1Value);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
public bool ShouldAddProjectItem(string filePath)
{
return true;
}
}
Notice that the original destination folder deletion is done via a different thread.
The reason is that the solution is generated after your wizard ends and this destination folder will get recreated.
By using ohter thread we assume that the solution and final destination folder will get created and only then we can safely delete this folder.
Another solution with using a Wizard alone:
public void RunStarted(object automationObject, Dictionary<string, string> replacementsDictionary, WizardRunKind runKind, object[] customParams)
{
try
{
_dte = automationObject as DTE2;
_destinationDirectory = replacementsDictionary["$destinationdirectory$"];
_safeProjectName = replacementsDictionary["$safeprojectname$"];
//Add custom parameters
}
catch (WizardCancelledException)
{
throw;
}
catch (Exception ex)
{
MessageBox.Show(ex + Environment.NewLine + ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
throw new WizardCancelledException("Wizard Exception", ex);
}
}
public void RunFinished()
{
if (!_destinationDirectory.EndsWith(_safeProjectName + Path.DirectorySeparatorChar + _safeProjectName))
return;
//The projects were created under a seperate 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;
var projectGoodPath = projectBadPath.Replace(
_safeProjectName + Path.DirectorySeparatorChar + _safeProjectName + Path.DirectorySeparatorChar,
_safeProjectName + Path.DirectorySeparatorChar);
_dte.Solution.Remove(projectObject.Item2);
Directory.Move(Path.GetDirectoryName(projectBadPath), Path.GetDirectoryName(projectGoodPath));
if (projectObject.Item1 != null) //Solution Folder
{
var solutionFolder = (SolutionFolder)projectObject.Item1.Object;
solutionFolder.AddFromFile(projectGoodPath);
}
else
{
_dte.Solution.AddFromFile(projectGoodPath);
}
}
ThreadPool.QueueUserWorkItem(dir =>
{
System.Threading.Thread.Sleep(2000);
Directory.Delete(_destinationDirectory, true);
}, _destinationDirectory);
}
This supports one level of solution folder (if you want you can make my solution recursive to support every levels)
Make Sure to put the projects in the <ProjectCollection> tag in order of most referenced to least referenced. because of the removal and adding of projects.
Multi-project templates are very tricky. I've found that the handling of $safeprojectname$ makes it almost impossible to create a multi-project template and have the namespace values replaced correctly. I've had to create a custom wizard which light up a new variable $saferootprojectname$ which is always the value that the user enters into the name for the new project.
In SideWaffle (which is a template pack with many templates) we have a couple multi-project templates. SideWaffle uses the TemplateBuilder NuGet package. TemplateBuilder has the wizards that you'll need for your multi-project template.
I have a 6 minute video on creating project templates with TemplateBuilder. For multi-project templates the process is a bit more cumbersome (but still much better than w/o TemplateBuilder. I have a sample multi-project template in the SideWaffle sources at https://github.com/ligershark/side-waffle/tree/master/TemplatePack/ProjectTemplates/Web/_Sample%20Multi%20Project.
Actually there is a workaround, it is ugly, but after diggin' the web I couldnt invent anything better. So, when creating a new instance of multiproject solution, you have to uncheck the 'create new folder' checkbox in the dialog. And before you start the directory structure should be like
Projects
{no dedicated folder yet}
After you create a solution a structure would be the following:
Projects
+--MyApplication1
+-- Project1
+-- Project2
solution file
So the only minor difference from the desired structure is the place of the solution file. So the first thing you should do after the new solution is generated and shown - select the solution and select "Save as" in menu, then move the file into the MyApplication1 folder. Then delete the previous solution file and here you are, the file structure is like this:
Projects
+--MyApplication1
+-- Project1
+-- Project2
solution file
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 Projects, is basically copied straight from EliSherer. We sort out which Projects 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.

Resources