public Load ( AssemblyName assemblyRef ) : Assembly | ||
assemblyRef | AssemblyName | |
return | Assembly |
static void Main() { //включаем визуальные стили для прилжения, поскольку оно является оконным Application.EnableVisualStyles(); /*создаём необходимые домены приложений с дружественными именами и * сохраняем ссылки на них в соответствующие переменные*/ Drawer = AppDomain.CreateDomain("Drawer"); TextWindow = AppDomain.CreateDomain("TextWindow"); /*загружаем сборки с оконными приложениями в соответствующие домены приложений*/ DrawerAsm = Drawer.Load(AssemblyName.GetAssemblyName("TextDrawer.exe")); TextWindowAsm = Drawer.Load(AssemblyName.GetAssemblyName("TextWindow.exe")); /*создаём объекты окон на сонове оконных типов данных из загруженных сборок*/ DrawerWindow = Activator.CreateInstance(DrawerAsm.GetType("TextDrawer.Form1")) as Form; TextWindowWnd = Activator.CreateInstance( TextWindowAsm.GetType("TextWindow.Form1"), new object[] { DrawerAsm.GetModule("TextDrawer.exe"), DrawerWindow }) as Form; /*запускаем потоки*/ (new Thread(new ThreadStart(RunVisualizer))).Start(); (new Thread(new ThreadStart(RunDrawer))).Start(); /*добавляем обработчик события DomainUnload*/ Drawer.DomainUnload += new EventHandler(Drawer_DomainUnload); }
public DynamicAssemblyProxy(string luceneIndexFolder) { _currentDomain = AppDomain.CurrentDomain; const string asemblyName = "dynamicProcessLib"; const string systemAsemblyName = "dynamicProcessLibSys"; //const string asemblyName = "dynamicProcessLib, Version=1.1.166.5, Culture=neutral, PublicKeyToken=null"; //const string systemAsemblyName = "dynamicProcessLibSys, Version=1.1.166.5, Culture=neutral, PublicKeyToken=null"; try { systemAssembly = _currentDomain.Load(systemAsemblyName); userAssembly = _currentDomain.Load(asemblyName); } catch (Exception ex) { throw new ApplicationException( string.Format(CultureInfo.InvariantCulture, "Global Search Exception : AppDomain/ problem on loading (AssemblyName : {1}) /{0}/", luceneIndexFolder, asemblyName), ex); } _luceneIndexFolder = luceneIndexFolder; InitializeService(); }
/// <summary> /// Initializes a new instance of the NamespaceDeclaration class. /// </summary> /// <param name="nsdecl">The namespace being compiled.</param> public DomTester(NamespaceDeclaration nsdecl) { _nsdecl = nsdecl; _appDomain = AppDomain.CreateDomain("testdomain"); this.Compile(); _appDomain.Load("System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"); _appDomain.Load(_compiled.GetName()); }
/// <summary> /// Starts this instance. /// </summary> /// <exception cref="System.InvalidOperationException">Job already started.</exception> public static void Start() { if (_job != null) throw new InvalidOperationException("Job already started."); var evidence = new Evidence(AppDomain.CurrentDomain.Evidence); var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase, ShadowCopyFiles = "false" }; _appDomain = AppDomain.CreateDomain("eSync-" + Guid.NewGuid(), evidence, setup); try { var assembly = _appDomain.Load(typeof(SyncServiceJob).Assembly.GetName()); var jobTypeName = typeof(SyncServiceJob).FullName; _job = (IJob)_appDomain.CreateInstanceAndUnwrap(assembly.FullName, jobTypeName); _job.Start(); } catch { _job = null; AppDomain.Unload(_appDomain); _appDomain = null; throw; } }
public static void RegisterWithBuilderFromPath(ContainerBuilder builder, AppDomain currentDomain, EnumRegistrationType enumRegistrationType) { List<Assembly> vuelingAssembliesList = new List<Assembly>(); Assembly[] vuelingAssembliesArray; customRegistration(builder); List<Assembly> assemblies = currentDomain.GetAssemblies().ToList<Assembly>(); var loadedAssemblies = currentDomain.GetAssemblies().ToList(); var loadedPaths = loadedAssemblies.Select(a => a.Location).ToArray(); var referencedPaths = Directory.GetFiles(currentDomain.BaseDirectory, "*.dll"); var toLoad = referencedPaths.Where(r => !loadedPaths.Contains(r, StringComparer.InvariantCultureIgnoreCase)).ToList(); toLoad.ForEach(path => loadedAssemblies.Add(currentDomain.Load(AssemblyName.GetAssemblyName(path)))); foreach (var referencedAssembly in toLoad) { assemblies.Add(Assembly.LoadFrom(referencedAssembly)); } foreach (var assembly in assemblies.Distinct()) { if (assembly.GetName().Name.ToLower().Contains("vueling")) vuelingAssembliesList.Add(Assembly.Load(assembly.GetName().Name)); } vuelingAssembliesArray = vuelingAssembliesList.ToArray<Assembly>(); if (enumRegistrationType == EnumRegistrationType.justWithDecoratedClasses) RegisterAssemblyTypesWithDecoratedClasses(builder, vuelingAssembliesArray); else RegisterAssemblyTypes(builder, vuelingAssembliesArray); }
public void SetUp() { string path = new Uri(Assembly.GetExecutingAssembly().EscapedCodeBase).LocalPath; _localDomain = AppDomain.CreateDomain("NewDomain"); _localDomain.Load(typeof(DataAccessor).Assembly.GetName()); _localTest = (DataAccessorBuilderTest)_localDomain.CreateInstanceFromAndUnwrap(path, GetType().FullName); }
private static void LoadAssembly(AppDomain newAppDomain, string assemblyName) { try { newAppDomain.Load(assemblyName); } catch (FileNotFoundException ex) { Console.WriteLine(ex.Message); } }
public void Init() { AppDomainSetup testDomainSetup = new AppDomainSetup() { ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase }; _TestDomain = AppDomain.CreateDomain("SampleServiceDomain", null, testDomainSetup); _TestDomain.Load("SampleService"); }
public void Init() { _EmptyDomain = AppDomain.CreateDomain("EmptyDomain"); //_EmptyDomain = AppDomain.CurrentDomain; //this doesn't seem to work as expected - if this is run concurrently with the EmptyResourceList test using CurrentDomain, things break AppDomainSetup testDomainSetup = new AppDomainSetup(); testDomainSetup.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; _TestDomain = AppDomain.CreateDomain("SampleServiceDomain", null, testDomainSetup); _TestDomain.Load("SampleService"); }
public void CreateAppdomain() { var appdomainSetup = new AppDomainSetup(); //string appBase = Environment.CurrentDirectory; //string appBase = HttpContext.Current.Request.ApplicationPath; appdomainSetup.ApplicationBase = CodeTemplateProjectInfo.BLASSEMBLYLOCATIONPATHONLY; //System.Diagnostics.Debug.WriteLine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase); appdomainSetup.DisallowBindingRedirects = false; appdomainSetup.DisallowCodeDownload = true; appdomainSetup.ConfigurationFile = AppDomain.CurrentDomain.SetupInformation.ConfigurationFile; appDomain = AppDomain.CreateDomain("compilerAppdomain", null, appdomainSetup); appDomain.Load(AssemblyName.GetAssemblyName(CodeTemplateProjectInfo.BLASSEMBLYLOCATION)); }
private void LoadAssembliesForVersion() { _appDomain = AppDomain.CreateDomain("NHibernateContext"); var nhibernatePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, string.Format(@"DataContext\{0}", _version)); var assembliesToLoad = Directory.GetFiles(nhibernatePath, "*.dll"); foreach (var assemblyFile in assembliesToLoad) { var assemblyFileName = new FileInfo(assemblyFile).Name; var assemblyFileToCreate = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, assemblyFileName); File.Copy(assemblyFile, assemblyFileToCreate, true); _appDomain.Load(AssemblyName.GetAssemblyName(assemblyFileToCreate)); } }
public void Launch(string pluginPath, AppDomain appDomain, Uri pluginApiUri, int clientPort, string tokenValue) { var token = Token.With(tokenValue); var assembly = appDomain.Load(AssemblyName.GetAssemblyName(pluginPath)); var pluginDirectory = Path.GetDirectoryName(pluginPath); appDomain.AssemblyResolve += (sender, args) => { var ad = sender as AppDomain; var path = Path.Combine(pluginDirectory, args.Name.Split(',')[0] + ".dll"); return ad.Load(path); }; var pluginBootstrapperType = assembly.GetTypes().Single(t => typeof (IPluginBootstrapper).IsAssignableFrom(t)); var pluginBootstrapper = (IPluginBootstrapper) Activator.CreateInstance(pluginBootstrapperType); var uri = new Uri($"http://127.0.0.1:{clientPort}"); var pluginRegistration = new PluginRegistration( uri, token, new CommandApi(pluginApiUri, token), new MessageApi(pluginApiUri, token), new HttpApi(), new Apis.PluginApi(pluginApiUri, token), new ConfigApi(pluginApiUri, token), new SettingApi(pluginApiUri, token)); pluginBootstrapper.Start(r => { r(pluginRegistration); if (pluginRegistration.PluginInformation == null) { throw new InvalidOperationException("You must call SetPluginInformation(...)"); } using (var a = AsyncHelper.Wait) { a.Run(pluginRegistration.CommandApi.RegisterAsync( pluginRegistration.CommandDescriptions, CancellationToken.None)); } }); _apiHost = new ApiHost(); _apiHost.Start(uri, pluginRegistration); }
public static void StartServers(TestContext ctx) { #region TCP Duplex // Setup TCP Duplex Server AppDomain AppDomainSetup tcpDuplexAppDomainSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) }; _tcpDuplexServerAppDomain = AppDomain.CreateDomain("RecreateClientConnectionTests_Server", null, tcpDuplexAppDomainSetup); _tcpDuplexServerAppDomain.Load(typeof(ZyanConnection).Assembly.GetName()); // Start Zyan host inside the TCP Duplex Server AppDomain var tcpDuplexServerWork = new CrossAppDomainDelegate(() => { var server = TcpDuplexServerHostEnvironment.Instance; if (server != null) { Console.WriteLine("TCP Duplex Server running."); } }); _tcpDuplexServerAppDomain.DoCallBack(tcpDuplexServerWork); #endregion #region TCP Simplex // Setup TCP Simplex Server AppDomain AppDomainSetup tcpSimplexAppDomainSetup = new AppDomainSetup() { ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) }; _tcpSimplexServerAppDomain = AppDomain.CreateDomain("RecreateClientConnectionTests_Server", null, tcpSimplexAppDomainSetup); _tcpSimplexServerAppDomain.Load(typeof(ZyanConnection).Assembly.GetName()); // Start Zyan host inside the TCP Simplex Server AppDomain var tcpSimplexServerWork = new CrossAppDomainDelegate(() => { var server = TcpSimplexServerHostEnvironment.Instance; if (server != null) { Console.WriteLine("TCP Simplex Server running."); } }); _tcpSimplexServerAppDomain.DoCallBack(tcpSimplexServerWork); #endregion }
public Assembly Inject(Guid checksum, object arg, Stream rawStream = null) { Contract.Requires(checksum != Guid.Empty); if (rawStream != null) { var raw = new MemoryStream(); rawStream.FixedCopyTo(raw); raw.Position = 0L; Guid checksumNew = CryptoManaged.MD5Hash(raw); if (checksum != checksumNew) { throw new InvalidOperationException("checksum"); } return(this.Mapper.GetOrAdd(checksum, k => _Domain.Load(raw.ToArray()))); } Assembly assembly; if (!this.Mapper.TryGetValue(checksum, out assembly)) { throw new InvalidOperationException("checksum"); } var eType = typeof(IAppEntry); var q = from t in assembly.GetTypes() where t.IsSubclassOf(eType) select t; var entryType = q.FirstOrDefault(); if (entryType != null) { var creator = entryType.GetConstructor(Type.EmptyTypes); if (creator != null) { var entry = (IAppEntry)creator.Invoke(null); entry.DoEntry(arg); } } return(assembly); }
public static SR.Assembly CreateReflectionAssembly (AssemblyDefinition asm, AppDomain domain) { using (MemoryBinaryWriter writer = new MemoryBinaryWriter ()) { WriteAssembly (asm, writer); return domain.Load (writer.ToArray ()); } }
private void Initialize() { string szAssm = typeof( AppDomainTest ).Assembly.FullName; m_appDomain = AppDomain.CreateDomain( this.GetType().FullName ); m_appDomain.Load( szAssm ); m_mbroProxy = (MyMarshalByRefObject)m_appDomain.CreateInstanceAndUnwrap( szAssm, typeof( MyMarshalByRefObject ).FullName ); m_mbro = new MyMarshalByRefObject(); }
public static int Main(string[] args) { AppDomainSetup setup = new AppDomainSetup(); setup.ApplicationBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); _serverAppDomain = AppDomain.CreateDomain("Server", null, setup); _serverAppDomain.Load(typeof(ZyanConnection).Assembly.GetName()); CrossAppDomainDelegate serverWork = new CrossAppDomainDelegate(() => { var server = EventServer.Instance; if (server != null) { Console.WriteLine("Event server started."); } }); _serverAppDomain.DoCallBack(serverWork); // Test IPC Binary int ipcBinaryTestResult = IpcBinaryTest.RunTest(); Console.WriteLine("Passed: {0}", ipcBinaryTestResult == 0); // Test TCP Binary int tcpBinaryTestResult = TcpBinaryTest.RunTest(); Console.WriteLine("Passed: {0}", tcpBinaryTestResult == 0); // Test TCP Custom int tcpCustomTestResult = TcpCustomTest.RunTest(); Console.WriteLine("Passed: {0}", tcpCustomTestResult == 0); // Test TCP Duplex int tcpDuplexTestResult = TcpDuplexTest.RunTest(); Console.WriteLine("Passed: {0}", tcpDuplexTestResult == 0); // Test HTTP Custom int httpCustomTestResult = HttpCustomTest.RunTest(); Console.WriteLine("Passed: {0}", httpCustomTestResult == 0); // Test NULL Channel const string nullChannelResultSlot = "NullChannelResult"; _serverAppDomain.DoCallBack(new CrossAppDomainDelegate(() => { int result = NullChannelTest.RunTest(); AppDomain.CurrentDomain.SetData(nullChannelResultSlot, result); })); var nullChannelTestResult = Convert.ToInt32(_serverAppDomain.GetData(nullChannelResultSlot)); Console.WriteLine("Passed: {0}", nullChannelTestResult == 0); // Stop the event server EventServerLocator locator = _serverAppDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, "IntegrationTest_DistributedEvents.EventServerLocator") as EventServerLocator; locator.GetEventServer().Dispose(); Console.WriteLine("Event server stopped."); if (!MonoCheck.IsRunningOnMono || MonoCheck.IsUnixOS) { // Mono/Windows bug: // AppDomain.Unload freezes in Mono under Windows if tests for // System.Runtime.Remoting.Channels.Tcp.TcpChannel were executed. AppDomain.Unload(_serverAppDomain); Console.WriteLine("Server AppDomain unloaded."); } if (ipcBinaryTestResult + tcpBinaryTestResult + tcpCustomTestResult + tcpDuplexTestResult + httpCustomTestResult + nullChannelTestResult == 0) { Console.WriteLine("All tests passed."); return 0; } return 1; }
public void OnServiceStart(string[] args) { banManagers = new Dictionary<string, FWBanTimeManager>(); instances = new Dictionary<string, object[]>(); moduleDomain = AppDomain.CreateDomain("Modules"); // Read Modules string ModulePath = System.IO.Path.Combine(DataPath, "modules.json"); if (System.IO.File.Exists(ModulePath)) { Newtonsoft.Json.Linq.JArray modules = (Newtonsoft.Json.Linq.JArray)JsonConvert.DeserializeObject(System.IO.File.ReadAllText(ModulePath)); foreach (var item in modules) { string assemblyName = ((string)item).ToLower(); string assemblyPath = System.IO.Path.Combine(DataPath, assemblyName, assemblyName + ".dll"); if (System.IO.File.Exists(assemblyPath)) { banManagers.Add(assemblyName, new FWBanTimeManager("WinBan." + assemblyName)); LoadBanList(assemblyName); System.Reflection.AssemblyName assemblyName2 = new System.Reflection.AssemblyName(); assemblyName2.CodeBase = assemblyPath; System.Reflection.Assembly assembly = moduleDomain.Load(assemblyName2); Type t = assembly.GetType("WinBanModule." + assemblyName); System.Reflection.MethodInfo mod_OnStart = t.GetMethod("OnStart"); System.Reflection.MethodInfo mod_OnStop = t.GetMethod("OnStop"); object instance = assembly.CreateInstance("WinBanModule." + assemblyName); instances.Add(assemblyName, new object[] { instance, mod_OnStart, mod_OnStop }); mod_OnStart.Invoke(instance, new object[] { this, typeof(WinBanService) }); } } } }
/// <summary> /// Creates a test worker in another domain /// </summary> /// <param name="domain"> /// The domain. /// </param> /// <returns> /// A StaticXamlTestWorker /// </returns> private static StaticXamlTestWorker CreateTestWorker(AppDomain domain) { domain.Load(Assembly.GetExecutingAssembly().GetName().FullName); var worker = (StaticXamlTestWorker) domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().GetName().FullName, "Microsoft.Activities.Extensions.Tests.StaticXamlTestWorker"); return worker; }
public PluginResponse LoadAssembly(AppDomain domain, FileInfo resolvePlugin) { var asmBin = File.ReadAllBytes(resolvePlugin.FullName); assembly = domain.Load(asmBin); return LoadAssembly(domain, assembly); }
private void CheckNamespace(AppDomain appDomain, string ns) { foreach (var assembly in assemblies) foreach (var type in appDomain.Load(assembly).GetTypes()) if (type.Namespace == ns) return; // todo: error message throw new EdgeAnalyzerException(); }
/// <summary> /// Creates an ITask instance and returns it. /// </summary> internal static ITask CreateTask(LoadedType loadedType, string taskName, string taskLocation, int taskLine, int taskColumn, LogError logError, AppDomainSetup appDomainSetup, bool isOutOfProc, out AppDomain taskAppDomain) { bool separateAppDomain = loadedType.HasLoadInSeparateAppDomainAttribute(); s_resolverLoadedType = null; taskAppDomain = null; ITask taskInstanceInOtherAppDomain = null; try { if (separateAppDomain) { if (!loadedType.Type.IsMarshalByRef) { logError ( taskLocation, taskLine, taskColumn, "TaskNotMarshalByRef", taskName ); return null; } else { // Our task depend on this name to be precisely that, so if you change it make sure // you also change the checks in the tasks run in separate AppDomains. Better yet, just don't change it. // Make sure we copy the appdomain configuration and send it to the appdomain we create so that if the creator of the current appdomain // has done the binding redirection in code, that we will get those settings as well. AppDomainSetup appDomainInfo = new AppDomainSetup(); // Get the current app domain setup settings byte[] currentAppdomainBytes = appDomainSetup.GetConfigurationBytes(); // Apply the appdomain settings to the new appdomain before creating it appDomainInfo.SetConfigurationBytes(currentAppdomainBytes); AppDomain.CurrentDomain.AssemblyResolve += AssemblyResolver; s_resolverLoadedType = loadedType; taskAppDomain = AppDomain.CreateDomain(isOutOfProc ? "taskAppDomain (out-of-proc)" : "taskAppDomain (in-proc)", null, appDomainInfo); if (loadedType.LoadedAssembly != null) { taskAppDomain.Load(loadedType.LoadedAssembly.GetName()); } // Hook up last minute dumping of any exceptions taskAppDomain.UnhandledException += new UnhandledExceptionEventHandler(ExceptionHandling.UnhandledExceptionHandler); } } else { // perf improvement for the same appdomain case - we already have the type object // and don't want to go through reflection to recreate it from the name. return (ITask)Activator.CreateInstance(loadedType.Type); } if (loadedType.Assembly.AssemblyFile != null) { taskInstanceInOtherAppDomain = (ITask)taskAppDomain.CreateInstanceFromAndUnwrap(loadedType.Assembly.AssemblyFile, loadedType.Type.FullName); // this will force evaluation of the task class type and try to load the task assembly Type taskType = taskInstanceInOtherAppDomain.GetType(); // If the types don't match, we have a problem. It means that our AppDomain was able to load // a task assembly using Load, and loaded a different one. I don't see any other choice than // to fail here. if (taskType != loadedType.Type) { logError ( taskLocation, taskLine, taskColumn, "ConflictingTaskAssembly", loadedType.Assembly.AssemblyFile, loadedType.Type.Assembly.Location ); taskInstanceInOtherAppDomain = null; } } else { taskInstanceInOtherAppDomain = (ITask)taskAppDomain.CreateInstanceAndUnwrap(loadedType.Type.Assembly.FullName, loadedType.Type.FullName); } return taskInstanceInOtherAppDomain; } finally { // Don't leave appdomains open if (taskAppDomain != null && taskInstanceInOtherAppDomain == null) { AppDomain.Unload(taskAppDomain); RemoveAssemblyResolver(); } } }
private static Assembly LoadAssambly(AppDomain domain, string assambly) { Assembly assemble; try { if (Logger.IsTraceEnabled && Log.IsDebugEnabled) { Log.DebugFormat("loadAssambly('{0}') called...", assambly); } string assambly1 = assambly; if(assambly1.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || assambly1.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) { assambly1 = assambly1.Substring(0, assambly1.Length - 4); } var assembles = domain.GetAssemblies(); foreach (var assembleLoaded in assembles) { var an = assembleLoaded.GetName(); if (String.Compare(an.Name, assambly1, StringComparison.OrdinalIgnoreCase) == 0) { return assembleLoaded; } } // Load the requested assembly from file if (string.IsNullOrEmpty(domain.SetupInformation.CachePath)) { /*if (logger.IsDebugEnabled) { logger.DebugFormat(@"App ApplicationBase '{0}', CachePath is {1}, PrivateBinPath is {2} ShadowCopyDirectories: {3} ", domain.SetupInformation.ApplicationBase, domain.SetupInformation.CachePath, domain.SetupInformation.PrivateBinPath, domain.SetupInformation.ShadowCopyDirectories); }*/ } if(File.Exists(assambly)) { //assambly = IOUtil.GetFullPath(assambly); //assemble = Assembly.LoadFile(assambly); assemble = Assembly.LoadFrom(assambly); //byte[] buf = IOUtil.binReadFile(assambly); //assemble = domain.Load(buf); } else { if (!Path.IsPathRooted(assambly)) { if (AssemblyPathes.Select(t => t + Path.DirectorySeparatorChar + assambly).Any(File.Exists)) { var buf = IOUtil.BinReadFile(assambly); assemble = domain.Load(buf); return assemble; } } assemble = domain.Load(assambly); } } catch (FileNotFoundException e) { if (Logger.IsTraceEnabled) Log.ErrorFormat("Could not load Assembly '{0}', error: {1}", assambly, e.Message); throw; } return assemble; }
public AppInvokeEntryPointResult FindForm(AppDomain ad, string assemblyFile, string configFile) { //IAppInvokeEntryPoint result = null; AppInvokeEntryPointResult result = new AppInvokeEntryPointResult(); try { // Load the primary assembly here Assembly asmEntryPoint = Assembly.LoadFrom(assemblyFile); // other assemblies Assembly[] asms = AppDomain.CurrentDomain.GetAssemblies(); // entry point if (asmEntryPoint.EntryPoint == null) { // find the entry point assembly foreach (Assembly asm in asms) { if (asm.EntryPoint != null) { asmEntryPoint = asm; break; } } } // Load all the assemblies IDictionary<string, string> loadedAssemblies = result.LoadedAssemblies; foreach (Assembly asm in asms) { string fullName = asm.FullName; if (!loadedAssemblies.ContainsKey(fullName)) { loadedAssemblies.Add(fullName, asm.Location); } foreach (var asmRef in asm.GetReferencedAssemblies()) { fullName = asmRef.FullName; if (!loadedAssemblies.ContainsKey(fullName)) { Assembly asm2 = ad.Load(asmRef); loadedAssemblies.Add(fullName, asm2.Location); } } } // find the entry point class implements our interface Type typeEntryPoint = asmEntryPoint.EntryPoint.DeclaringType; if (typeof(IAppInvokeEntryPoint).IsAssignableFrom(typeEntryPoint)) { AssemblyName asm = AssemblyName.GetAssemblyName(assemblyFile); //result = ad.CreateInstanceAndUnwrap(asm.FullName, typeEntryPoint.FullName) as IAppInvokeEntryPoint; result.AssemblyName = asm.FullName; result.TypeName = typeEntryPoint.FullName; result.Instance = ad.CreateInstance(asm.FullName, typeEntryPoint.FullName); } } catch (Exception ex) { ExceptionManagement.ExceptionManager.Publish(ex); } return result; }
public void LoadDllViaNewAppDomain() { AppDomainSetup domainInfo = new AppDomainSetup(); domainInfo.ApplicationBase = @"file:///c:/Projects/oa-public/src/OrbisAccess.PublicSite.Specs/bin"; domainInfo.PrivateBinPath = "c:/Projects/oa-public/src/OrbisAccess.PublicSite.Specs/bin"; domainInfo.ShadowCopyFiles = true.ToString(); domainInfo.ShadowCopyDirectories = "Debug"; domainInfo.PrivateBinPathProbe = "c:/Projects/oa-public/src/OrbisAccess.PublicSite.Specs/bin/Debug"; // domainInfo.ApplicationBase = @"file:///" + System.Environment.SystemDirectory; Evidence evidence = AppDomain.CurrentDomain.Evidence; domain = AppDomain.CreateDomain("GetRefs", evidence, domainInfo); domain.AssemblyResolve +=new ResolveEventHandler(domain_AssemblyResolve); Console.WriteLine(domainInfo.ApplicationBase); var bytes = File.ReadAllBytes(@"C:\\Projects\\oa-public\src\\OrbisAccess.PublicSite.Specs\\bin\\debug\\OrbisAccess.PublicSite.Specs.dll"); var assembly = domain.Load("OrbisAccess.PublicSite.Specs"); Assert.IsNotNull(assembly); }
public PluginResponse LoadAssembly(AppDomain domain, AssemblyName resolveName) { assembly = domain.Load(resolveName); return LoadAssembly(domain, assembly); }
/// <summary> /// Load the script from an assembly into an AppDomain. /// </summary> /// <param name='dom'></param> /// <param name='assembly'></param> /// <param name='stateSource'></param> /// <returns>false if load failed, true if suceeded</returns> public bool Load(AppDomain dom, string assembly, StateSource stateSource) { m_Assembly = assembly; m_stateSource = stateSource; ApiManager am = new ApiManager(); foreach (string api in am.GetApis()) { m_Apis[api] = am.CreateApi(api); m_Apis[api].Initialize(Engine, Part, ScriptTask, m_coopSleepHandle); } try { object[] constructorParams; Assembly scriptAssembly = dom.Load(Path.GetFileNameWithoutExtension(assembly)); Type scriptType = scriptAssembly.GetType("SecondLife.XEngineScript"); if (scriptType != null) { constructorParams = new object[] { m_coopSleepHandle }; } else if (!m_coopTermination) { scriptType = scriptAssembly.GetType("SecondLife.Script"); constructorParams = null; } else { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. You must remove all existing {6}* script DLL files before using enabling co-op termination" + ", either by setting DeleteScriptsOnStartup = true in [XEngine] for one run" + " or by deleting these files manually.", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly); return false; } // m_log.DebugFormat( // "[SCRIPT INSTANCE]: Looking to load {0} from assembly {1} in {2}", // scriptType.FullName, Path.GetFileNameWithoutExtension(assembly), Engine.World.Name); if (dom != System.AppDomain.CurrentDomain) m_Script = (IScript)dom.CreateInstanceAndUnwrap( Path.GetFileNameWithoutExtension(assembly), scriptType.FullName, false, BindingFlags.Default, null, constructorParams, null, null, null); else m_Script = (IScript)scriptAssembly.CreateInstance( scriptType.FullName, false, BindingFlags.Default, null, constructorParams, null, null); //ILease lease = (ILease)RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); //RemotingServices.GetLifetimeService(m_Script as ScriptBaseClass); // lease.Register(this); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error loading assembly {6}. Exception {7}{8}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, assembly, e.Message, e.StackTrace); return false; } try { foreach (KeyValuePair<string,IScriptApi> kv in m_Apis) { m_Script.InitApi(kv.Key, kv.Value); } // // m_log.Debug("[Script] Script instance created"); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Error initializing script instance. Exception {6}{7}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, e.Message, e.StackTrace); return false; } m_SaveState = true; string savedState = Path.Combine(Path.GetDirectoryName(assembly), ItemID.ToString() + ".state"); if (File.Exists(savedState)) { string xml = String.Empty; try { FileInfo fi = new FileInfo(savedState); int size = (int)fi.Length; if (size < 512000) { using (FileStream fs = File.Open(savedState, FileMode.Open, FileAccess.Read, FileShare.None)) { Byte[] data = new Byte[size]; fs.Read(data, 0, size); xml = Encoding.UTF8.GetString(data); ScriptSerializer.Deserialize(xml, this); AsyncCommandManager.CreateFromData(Engine, LocalID, ItemID, ObjectID, PluginData); // m_log.DebugFormat("[Script] Successfully retrieved state for script {0}.{1}", PrimName, m_ScriptName); Part.SetScriptEvents(ItemID, (int)m_Script.GetStateEventFlags(State)); if (!Running) m_startOnInit = false; Running = false; // we get new rez events on sim restart, too // but if there is state, then we fire the change // event // We loaded state, don't force a re-save m_SaveState = false; m_startedFromSavedState = true; } } else { m_log.WarnFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. Memory limit exceeded.", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState); } } catch (Exception e) { m_log.ErrorFormat( "[SCRIPT INSTANCE]: Not starting script {0} (id {1}) in part {2} (id {3}) in object {4} in {5}. Unable to load script state file {6}. XML is {7}. Exception {8}{9}", ScriptTask.Name, ScriptTask.ItemID, Part.Name, Part.UUID, Part.ParentGroup.Name, Engine.World.Name, savedState, xml, e.Message, e.StackTrace); } } // else // { // ScenePresence presence = Engine.World.GetScenePresence(part.OwnerID); // if (presence != null && (!postOnRez)) // presence.ControllingClient.SendAgentAlertMessage("Compile successful", false); // } return true; }
private void CreateSandbox() { Contract.Requires(engineType != null); using (Perfomance.Trace("SandboxEngine::CreateSandbox()").BindToConsole()) { sandboxDomain = AppDomain.CreateDomain(SandboxDomainName); //sandboxDomain.AssemblyLoad += (_, e) => //{ // Debug.Print("SANDBOX: Loaded rawAssembly {0}", e.LoadedAssembly.FullName); //}; //sandboxDomain.AssemblyResolve += (_, e) => //{ // Debug.Print("SANDBOX: Resolving rawAssembly {0}", e.Name); //}; foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies()) { sandboxDomain.Load(assembly.GetName()); } var sandBoxAssembly = sandboxDomain.Load(engineType.Assembly.FullName); sandbox = sandboxDomain.CreateInstanceAndUnwrap(sandBoxAssembly.FullName, engineType.FullName) as IExecutionEngine; sandbox.Repository = Repository; sandbox.SystemResources = SystemResources; } }
private dynamic CreateAppDomainExecutor(AppDomain VSRunnerDomain) { // until the vsrunner is included with mspec we will need to ship it with the adapter and copy it into the target mspec directory // get the location of the adpter so we know where to copy the vsrunner from Assembly mspecVsTestAdapterAssembly = AppDomain.CurrentDomain.GetAssemblies().Where(x => x.FullName.StartsWith(adapterName)).SingleOrDefault(); if (mspecVsTestAdapterAssembly == null) { throw new Exception(); } // we will copy it to the vsrunner app domains base directory string vsRunnerDestinationFileName = Path.Combine(VSRunnerDomain.BaseDirectory, runnerDllName); // from the current mstestadapter domain location string vsRunnerSourceFileName = Path.Combine(Path.GetDirectoryName(mspecVsTestAdapterAssembly.Location), runnerDllName); if (File.Exists(vsRunnerDestinationFileName)) { File.Delete(vsRunnerDestinationFileName); } File.Copy(vsRunnerSourceFileName, vsRunnerDestinationFileName); // load the vs runner assembly into the appdomain VSRunnerDomain.Load(runnerName); return VSRunnerDomain.CreateInstanceAndUnwrap(runnerName, runnerClassName, false, BindingFlags.Default, (Binder)null, new object[0], (CultureInfo)null, (object[])null); }
void DetectResharperLoading(AppDomain vsAppDomain) { while (_retries <= MAX_RETRIES) { Assembly resharperAssembly; try { resharperAssembly = vsAppDomain.Load("JetBrains.Platform.ReSharper.Shell"); } catch { resharperAssembly = null; } if (resharperAssembly == null && _retries++ <= MAX_RETRIES) { _output.Write("ReSharper not found, try {0}/{1}, sleeping for 2 seconds.", _retries, MAX_RETRIES); Thread.Sleep(TimeSpan.FromSeconds(2)); continue; } var resharperVersion = resharperAssembly.GetName().Version; var pluginManagerType = LoadTypeFromVersion(resharperVersion); if (pluginManagerType == null) return; var assemblyLocation = pluginManagerType.Assembly.Location; var destinationAssemblyFile = CopyAndSign(assemblyLocation); _pluginManager = vsAppDomain.CreateInstanceFromAndUnwrap(destinationAssemblyFile.Path, pluginManagerType.FullName); return; } }
/// <summary> /// Gets the documentation domain. /// </summary> /// <returns></returns> private AppDomain GetDocumentationDomain() { if(DocumentationDomain == null) { // create a new app domain for processing. DocumentationDomain = AppDomain.CreateDomain("Documentation"); var dir = new DirectoryInfo(HostingEnvironment.MapPath("~/app_data/")); dir.GetFiles("*.dll").ForEach(a => { DocumentationDomain.Load(AssemblyName.GetAssemblyName(a.FullName)); }); } return DocumentationDomain; }