Instantly share code, notes, and snippets.

Embed
What would you like to do?
CSX Script to update projects to the new format
using System;
using System.IO;
using System.Xml;
const string classLibraryTemplate =
@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
</PropertyGroup>
<ItemGroup>
##Packages
</ItemGroup>
</Project>
";
const string exeTemplate = @"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net461</TargetFramework>
</PropertyGroup>
<ItemGroup>
##Packages
</ItemGroup>
</Project>
";
const string testTemplate =
@"
<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>net46</TargetFramework>
</PropertyGroup>
<ItemGroup>##Packages</ItemGroup>
<ItemGroup>
<PackageReference Include=""Microsoft.NET.Test.Sdk"" Version=""15.0.0"" />
<PackageReference Include=""xunit"" Version=""2.2.0"" />
<PackageReference Include=""xunit.runner.visualstudio"" Version=""2.2.0"" />
</ItemGroup>
<ItemGroup>
##Packages
</ItemGroup>
</Project>
";
string ConvertPackages(string fullPathToProject)
{
var packagesStr = new System.Text.StringBuilder();
var projectDir = Path.GetDirectoryName(fullPathToProject);
var packagesFile = Path.Combine(projectDir, "packages.config");
if (File.Exists(packagesFile))
{
var doc = new XmlDocument();
doc.Load(packagesFile);
var packages = doc.SelectNodes("//package");
foreach (System.Xml.XmlElement p in packages)
{
packagesStr.AppendLine($"<PackageReference Include=\"{p.Attributes["id"].Value}\" Version=\"{p.Attributes["version"]}\" />");
}
}
return packagesStr.ToString();
}
void ConvertLibrary(string fullPathToProject) {
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fullPathToProject);
var newProjectFile = Path.Combine(fileNameWithoutExt, ".New.csproj");
var packages = ConvertPackages(fullPathToProject);
File.WriteAllText(newProjectFile, classLibraryTemplate.Replace("##Packages", packages));
}
void ConvertExe(string fullPathToProject) {
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fullPathToProject);
var newProjectFile = Path.Combine(fileNameWithoutExt, ".New.csproj");
var packages = ConvertPackages(fullPathToProject);
File.WriteAllText(newProjectFile, exeTemplate.Replace("##Packages", packages));
}
void ConvertTest(string fullPathToProject) {
var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fullPathToProject);
var newProjectFile = Path.Combine(fileNameWithoutExt, ".New.csproj");
var packages = ConvertPackages(fullPathToProject);
File.WriteAllText(newProjectFile, testTemplate.Replace("##Packages", packages));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment