Skip to content

Instantly share code, notes, and snippets.

@robertmclaws
Created August 20, 2017 16:50
Show Gist options
  • Save robertmclaws/04ffa1e3a1b79735f88f73df46e43b20 to your computer and use it in GitHub Desktop.
Save robertmclaws/04ffa1e3a1b79735f88f73df46e43b20 to your computer and use it in GitHub Desktop.
Sorts AssemblyBindingRedirects and Removes Duplicates
// ===========================================
// Fix AssemblyBindingRedirects
// Prototype by Robert McLaws (@robertmclaws)
// Last Updated 20 Aug 2017
// ===========================================
//RWM: Set these to your specific project.
var projectFolder = @"D:\GitHub\SomeSolution\src\SomeProject";
const string configFile = "app.config";
//RWM: Don't mess with these.
XNamespace defaultNs = "";
XNamespace assemblyBindingNs = "urn:schemas-microsoft-com:asm.v1";
var assemblyBindings = new XElement(assemblyBindingNs + "assemblyBinding");
var newBindings = new SortedDictionary<string, XElement>();
//RWM: Start by backing up the files.
File.Copy(Path.Combine(projectFolder, configFile), Path.Combine(projectFolder, configFile + ".bak"), true);
//RWM: Load the files.
var config = XDocument.Load(Path.Combine(projectFolder, configFile));
var oldBindingRoot = config.Root.Descendants().FirstOrDefault(c => c.Name.LocalName == "assemblyBinding");
foreach (var dependentAssembly in oldBindingRoot.Elements().ToList())
{
var assemblyIdentity = dependentAssembly.Element(assemblyBindingNs + "assemblyIdentity");
var bindingRedirect = dependentAssembly.Element(assemblyBindingNs + "bindingRedirect");
if (newBindings.ContainsKey(assemblyIdentity.Attribute("name").Value))
{
//RWM: We've seen this assembly before. Check to see if we can update the version.
var newBindingRedirect = newBindings[assemblyIdentity.Attribute("name").Value].Descendants(assemblyBindingNs + "bindingRedirect").First();
var oldVersion = Version.Parse(newBindingRedirect.Attribute("newVersion").Value);
var newVersion = Version.Parse(bindingRedirect.Attribute("newVersion").Value);
if (newVersion > oldVersion)
{
newBindingRedirect.ReplaceWith(bindingRedirect);
}
}
else
{
newBindings.Add(assemblyIdentity.Attribute("name").Value, dependentAssembly);
}
}
//RWM: Add the SortedDictionary items to our new assemblyBindingd element.
foreach (var binding in newBindings)
{
assemblyBindings.Add(binding.Value);
}
//RWM: Fix up the web.config by adding the new assemblyBindings and removing the old one.
oldBindingRoot.AddBeforeSelf(assemblyBindings);
oldBindingRoot.Remove();
//RWM: Save the condfig file.
config.Save(Path.Combine(projectFolder, configFile));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment