Tuesday, May 3, 2011

[Revit API] How to allow add-ins to be loaded off a network drive, in code

I previously posted about how in Revit 2012, you can no longer store your add-ins on a network drive, unless you edit the revit.exe.config. This is a bit of a pain if you have to go to each users machine and edit this file individually, especially given that if you make a typo, your Revit won’t open.

Here’s how to do this edit in C# code, so if you make an installation utility to run on your users computers, you can add this bit of code in to do the changes for you.

Configuration revitExeConfig = ConfigurationManager.OpenExeConfiguration(
      @"C:\Program Files\Autodesk\Revit Structure 2012\Program\Revit.exe");
ConfigurationSection section = revitExeConfig.GetSection("runtime");
string xml = section.SectionInformation.GetRawXml();
if (!xml.Contains("<loadFromRemoteSources enabled=\"true\" />"))
{
    xml = xml.Replace("<runtime>", "<runtime> \r\n <loadFromRemoteSources enabled=\"true\" />");
    section.SectionInformation.SetRawXml(xml);
    revitExeConfig.Save();
}

 

Of course, I’ve hard coded in Revit Structure 2012 here as Revit installation to edit. You could change this to the installation that suits yours, or alternatively you could use the RevitAddinUtility.dll that ships with Revit. If you add a reference to that to your project you can then get the install location of all Revit products using:

foreach (RevitProduct product in RevitProductUtility.GetAllInstalledRevitProducts())
{
    //no point editing the Revit 2011 exe config files
    if (product.Version == RevitVersion.Revit2012)
    {
        string productLocation = product.InstallLocation + "program\\revit.exe";
    }
}

 

If you put that all together with the above code you can do something like:

public void EditExeConfigs()
{
    foreach (RevitProduct product in RevitProductUtility.GetAllInstalledRevitProducts())
    {
        //no point editing the Revit 2011 exe config files
        if (product.Version == RevitVersion.Revit2012)
        {
            string productLocation = product.InstallLocation + "program\\revit.exe";
            Configuration revitExeConfig = ConfigurationManager.OpenExeConfiguration(productLocation);
            ConfigurationSection section = revitExeConfig.GetSection("runtime");
            string xml = section.SectionInformation.GetRawXml();
            if (!xml.Contains("<loadFromRemoteSources enabled=\"true\" />"))
            {
                xml = xml.Replace("<runtime>", "<runtime> \r\n <loadFromRemoteSources enabled=\"true\" />");
                section.SectionInformation.SetRawXml(xml);
                revitExeConfig.Save();
            }
        }
    }
}

Which will edit the exe.config file for all 3 Revit products if they are installed, or do nothing if they aren’t.

No comments: