Update assembly configuration file on the fly (from code)

The following code could be used to update the DLL configuration file from the code. It could be useful for example when User changes some parameter in Dynamics AX and .NET assemble should use other instance of external application.

//_webReferenceName - the name of webReference (AOT\References)
//_endPoint - the new address
server static void updateAppConfig(str _webReferenceName, str _endPoint)
{
#define.Ax32Serv('Ax32Serv.config')
#define.endPointTag('endpoint')
#define.addressAttribute('address')

SysReference sysReference;
FilePath serverConfigFile;
Microsoft.Dynamics.IntegrationFramework.WebService.AppDomainCache appDomainCache;
XMLDocument xmlDocument;
XMLNodeList xmlNodeList;
XmlElement xmlElement;
;

//Create SysReference object
new InteropPermission(InteropKind::ClrInterop).assert();
sysReference = SysReference::newFromReferenceName(_webReferenceName);
if (sysReference == null)
{
throw error(strfmt("Referenct '%1' was not found", _webReferenceName));
}
CodeAccessPermission::revertAssert();

//Configure
serverConfigFile = xinfo::directory(DirectoryType::Bin) + #Ax32Serv;

new FileIOPermission(serverConfigFile, SysDataExpImp::readWrite2Mode(ReadWrite::read)).assert();
xmlDocument = new XMLDocument();
xmlDocument.load(serverConfigFile);
xmlNodeList = xmlDocument.getElementsByTagName(#endPointTag);
xmlElement = xmlNodeList.nextNode();
while (xmlElement)
{
xmlElement.setAttribute(#addressAttribute, _endPoint);
xmlElement = xmlNodeList.nextNode();
}
CodeAccessPermission::revertAssert();

//BP Deviation documented
new FileIOPermission(serverConfigFile, SysDataExpImp::readWrite2Mode(ReadWrite::Write)).assert();
xmlDocument.save(serverConfigFile);
CodeAccessPermission::revertAssert();

//Reset application cashe - update end point adress
new InteropPermission(InteropKind::ClrInterop).assert();
appDomainCache = Microsoft.Dynamics.IntegrationFramework.WebService.AppDomainCache::get_Instance();
if (appDomainCache)
{
appDomainCache.Remove('LaserNet');
}
CodeAccessPermission::revertAssert();
}