protected override HostedService CreateRemoteHost(AppDomain appDomain) { appDomain.SetData("ConnectionString",_connectionString); appDomain.DoCallBack(SetConnectionStringInAppDomain); var service = base.CreateRemoteHost(appDomain); return service; }
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> /// Creates a new AppDomain based on the parent AppDomains /// Evidence and AppDomainSetup /// </summary> /// <param name="parentDomain">The parent AppDomain</param> /// <returns>A newly created AppDomain</returns> private AppDomain BuildChildDomain(AppDomain parentDomain) { Evidence evidence = new Evidence(parentDomain.Evidence); AppDomainSetup setup = parentDomain.SetupInformation; return AppDomain.CreateDomain("DiscoveryRegion", evidence, setup); }
protected AppDomainTypeResolver(AppDomain domain, string baseDir) { _domain = domain; this.baseDir = baseDir; domain.AssemblyResolve += new ResolveEventHandler(domain_AssemblyResolve); }
public void Dispose() { _extActivator.Dispose(); _extActivator = null; AppDomain.Unload(_appdomain); _appdomain = null; }
public static void RegisterAppDomainUnhandledExceptionHandler(this ExceptionlessClient client, AppDomain appDomain = null) { if (appDomain == null) appDomain = AppDomain.CurrentDomain; if (_onAppDomainUnhandledException == null) _onAppDomainUnhandledException = (sender, args) => { var exception = args.ExceptionObject as Exception; if (exception == null) return; var contextData = new ContextData(); contextData.MarkAsUnhandledError(); contextData.SetSubmissionMethod("AppDomainUnhandledException"); exception.ToExceptionless(contextData, client).Submit(); // process queue immediately since the app is about to exit. client.ProcessQueue(); }; try { appDomain.UnhandledException -= _onAppDomainUnhandledException; appDomain.UnhandledException += _onAppDomainUnhandledException; } catch (Exception ex) { client.Configuration.Resolver.GetLog().Error(typeof(ExceptionlessClientExtensions), ex, "An error occurred while wiring up to the unhandled exception event. This will happen when you are not running under full trust."); } }
public void LoadFrom(string path) { if (_domain != null) { _scanner.Teardown(); AppDomain.Unload(_domain); } var name = Path.GetFileNameWithoutExtension(path); var dirPath = Path.GetFullPath(Path.GetDirectoryName(path)); var setup = new AppDomainSetup { ApplicationBase = AppDomain.CurrentDomain.BaseDirectory, PrivateBinPath = dirPath, ShadowCopyFiles = "true", ShadowCopyDirectories = dirPath, }; _domain = AppDomain.CreateDomain(name + "Domain", AppDomain.CurrentDomain.Evidence, setup); var scannerType = typeof(Scanner); _scanner = (Scanner)_domain.CreateInstanceAndUnwrap(scannerType.Assembly.FullName, scannerType.FullName); _scanner.Load(name); _scanner.Setup(); }
public ApplicationDomains() { InitializeComponent(); //Create an application domain upon opening the form domain = AppDomain.CreateDomain("FormsDomain"); }
static void Load() { if (AppDomain.CurrentDomain.FriendlyName != "OnlineVideosSiteUtilDlls") { if (useSeperateDomain) { domain = AppDomain.CreateDomain("OnlineVideosSiteUtilDlls", null, null, null, true); pluginLoader = (PluginLoader)domain.CreateInstanceAndUnwrap( typeof(PluginLoader).Assembly.FullName, typeof(PluginLoader).FullName); domain.SetData(typeof(PluginLoader).FullName, pluginLoader); } else { domain = AppDomain.CurrentDomain; pluginLoader = new PluginLoader(); } } else { domain = AppDomain.CurrentDomain; pluginLoader = (PluginLoader)AppDomain.CurrentDomain.GetData(typeof(PluginLoader).FullName); } }
private void StartInternal() { ConfigurationManipulation.RemoveAzureTraceListenerFromConfiguration(_configurationFilePath); CopyStubAssemblyToRoleDirectory(_appDomainSetup.ApplicationBase, _role); _appDomain = AppDomain.CreateDomain("LightBlue", null, _appDomainSetup); _hostStub = (HostStub)_appDomain.CreateInstanceAndUnwrap(typeof(HostStub).Assembly.FullName, typeof(HostStub).FullName); var shipper = new EventTraceShipper(); Action<string> twh = m => _role.TraceWrite(Identifier, m); Action<string> twlh = m => _role.TraceWriteLine(Identifier, m); shipper.TraceWrite += twh; shipper.TraceWriteLine += twlh; _hostStub.ConfigureTracing(shipper); // TODO: decide how this is going to work. _appDomain.UnhandledException += StubExceptionHandler.Handler; try { _started.SetResult(new object()); _role.TraceWriteLine(Identifier, "Role started in app domain: " + _appDomain.Id + " by " + Thread.CurrentThread.Name); _hostStub.Run(_assemblyFilePath, _configurationFilePath, _serviceDefinitionFilePath, _roleName, false); } catch (Exception ex) { _role.TraceWriteLine(Identifier, ex.ToString()); } finally { shipper.TraceWrite -= twh; shipper.TraceWriteLine -= twlh; _completed.SetResult(new object()); } }
// Private Methods private static void Print(AppDomain defaultAppDomain) { Assembly[] loadedAssemblies = defaultAppDomain.GetAssemblies(); Console.WriteLine("Here are the assemblies loaded in {0}\n", defaultAppDomain.FriendlyName); foreach (Assembly a in loadedAssemblies) PrintAssemblyName(a.GetName()); }
public void Dispose() { var dir = Domain.BaseDirectory; AppDomain.Unload(Domain); Directory.Delete(dir, true); Domain = null; }
public override bool Load( TestPackage package ) { Unload(); try { if ( domain == null ) { domain = DomainManager.CreateDomain( package ); } if ( agent == null ) { agent = DomainAgent.CreateInstance( domain ); agent.Start(); } if ( TestRunner == null ) { TestRunner = agent.CreateRunner( ID ); } return TestRunner.Load( package ); } catch { Unload(); throw; } }
/// <summary> /// Creates a new child domain and copies the evidence from a parent domain. /// </summary> /// <param name="parentDomain">The parent domain.</param> /// <returns>The new child domain.</returns> /// <remarks> /// Grabs the <paramref name="parentDomain"/> evidence and uses it to construct the new /// <see cref="AppDomain"/> because in a ClickOnce execution environment, creating an /// <see cref="AppDomain"/> will by default pick up the partial trust environment of /// the AppLaunch.exe, which was the root executable. The AppLaunch.exe does a /// create domain and applies the evidence from the ClickOnce manifests to /// create the domain that the application is actually executing in. This will /// need to be Full Trust for Composite Application Library applications. /// </remarks> public static AppDomain BuildChildDomain(AppDomain parentDomain) { if (parentDomain == null) throw new ArgumentNullException("parentDomain"); var evidence = new Evidence(parentDomain.Evidence); AppDomainSetup setup = parentDomain.SetupInformation; return AppDomain.CreateDomain("DiscoveryRegion", evidence, setup); }
public static void RegisterAllAssemblies(IExecutionContext context, AppDomain domain) { foreach(Assembly assembly in domain.GetAssemblies()) { context.RegisterAssembly(assembly); } }
/// <summary> /// Loads the decision module based on the decision metadata /// </summary> /// <param name="decisionMetadata">The decision metadata.</param> /// <param name="workspaceWrapper">The workspace wrapper.</param> /// <param name="componentsAppDomain">The components app domain is the app domain which decision assembly is going to be loaded into.</param> /// <returns>Loaded decision</returns> internal static ILoopDecisionModule LoadDecisionModule(LoopScopeMetadata loopMetadata, IWorkspaceInternal workspaceWrapper, AppDomain componentsAppDomain) { DecisionLoader loader = ConstructDecisionModuleInComponentsAppDomain(loopMetadata, workspaceWrapper, componentsAppDomain); return (ILoopDecisionModule)loader.LoadedDecisionModule; }
/// <summary> /// Gets a driver for a given test assembly and a framework /// which the assembly is already known to reference. /// </summary> /// <param name="domain">The domain in which the assembly will be loaded</param> /// <param name="assemblyName">The name of the test framework reference</param> /// <param name="version">The version of the test framework reference</param> /// <returns></returns> public IFrameworkDriver GetDriver(AppDomain domain, string assemblyName, Version version) { if (!IsSupportedTestFramework(assemblyName, version)) throw new ArgumentException("Invalid framework name", "frameworkAssemblyName"); return _driverNode.CreateExtensionObject(domain) as IFrameworkDriver; }
static void Main() { try { Trace.CurrentTrace.SetLogFile(__logFile, LogOptions.None); //Trace.WriteLine("runsource_launch.Program.Main()"); object runSourceRestartParameters = null; while (true) { UpdateRunSourceFiles(); Run(runSourceRestartParameters); // attention récupérer RunSourceRestartParameters avant UpdateRunSourceFiles(), UpdateRunSourceFiles() fait AppDomain.Unload() runSourceRestartParameters = __domain.GetData(__domainRestartParametersName); //UpdateRunSourceFiles(); if (runSourceRestartParameters == null) break; //__domain.DomainUnload += domain_DomainUnload; //Trace.WriteLine("__domain.IsFinalizingForUnload() : {0}", __domain.IsFinalizingForUnload()); //Trace.WriteLine("AppDomain.Unload(__domain)"); AppDomain.Unload(__domain); __domain = null; //Trace.WriteLine("__domain.IsFinalizingForUnload() : {0}", __domain.IsFinalizingForUnload()); } } catch (Exception ex) { zerrf.ErrorMessageBox(ex); } }
/// <summary> /// Construct a FrameworkDriver for a particular assembly in a domain, /// and associate some settings with it. The assembly must reference /// the NUnit framework so that we can remotely create the FrameworkController. /// </summary> /// <param name="assemblyPath">The path to the test assembly</param> /// <param name="testDomain">The domain in which the assembly will be loaded</param> /// <param name="settings">A dictionary of load and run settings</param> public FrameworkDriver(string assemblyPath, AppDomain testDomain, IDictionary<string, object> settings) { this.testDomain = testDomain; this.assemblyPath = assemblyPath; this.settings = settings; this.testController = CreateObject(CONTROLLER_TYPE, assemblyPath, settings); }
public ScriptContainer(AppDomain domain, string name) { _name = name; _appDomain = domain; _appDomain.Execute<string>(Initialize, name); }
internal AppDomainEvidenceFactory(AppDomain target) { Contract.Assert(target != null); Contract.Assert(target == AppDomain.CurrentDomain, "AppDomainEvidenceFactory should not be used across domains."); m_targetDomain = target; }
public RemoteDebugger() { // Create a new debugger session mSessionId = Guid.NewGuid().ToString(); Evidence evidence = new Evidence(AppDomain.CurrentDomain.Evidence); AppDomainSetup appDomainSetup = AppDomain.CurrentDomain.SetupInformation; mAppDomain = AppDomain.CreateDomain(String.Format("Debugger-{0}", mSessionId), evidence, appDomainSetup); /* Type assemblyLoaderType = typeof(AssemblyLoader); AssemblyLoader loader = mAppDomain.CreateInstanceAndUnwrap(assemblyLoaderType.Assembly.GetName().Name, assemblyLoaderType.FullName) as AssemblyLoader; foreach (String assemblyPath in Directory.GetFiles(DebuggerConfig.ApplicationPath, "Tridion*.dll")) { loader.LoadAssembly(assemblyPath); } */ Type debuggerHostType = typeof(DebugEngineServer); mDebuggerHost = mAppDomain.CreateInstanceAndUnwrap( debuggerHostType.Assembly.GetName().Name, debuggerHostType.FullName, true, BindingFlags.Default, null, new Object[] { mSessionId }, null, null) as DebugEngineServer; }
public AssemblyEmitter( string assemblyName, bool canSave ) { m_AssemblyName = assemblyName; m_AppDomain = AppDomain.CurrentDomain; m_AssemblyBuilder = m_AppDomain.DefineDynamicAssembly( new AssemblyName( assemblyName ), canSave ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.Run ); if ( canSave ) { m_ModuleBuilder = m_AssemblyBuilder.DefineDynamicModule( assemblyName, String.Format( "{0}.dll", assemblyName.ToLower() ), false ); } else { m_ModuleBuilder = m_AssemblyBuilder.DefineDynamicModule( assemblyName, false ); } }
public OSAEUserControl(string assemblyName, string assemblyType, AppDomain domain, string location) { PluginDescription desc = new PluginDescription(); List<string> osaudFiles = new List<string>(); string[] pluginFile = Directory.GetFiles(location, "*.osaud", SearchOption.AllDirectories); osaudFiles.AddRange(pluginFile); foreach (string path in osaudFiles) { if (!string.IsNullOrEmpty(path)) { desc = new PluginDescription(); desc.Deserialize(path); _userControlVersion = desc.Version; } } _userControlType = desc.Type; _userControlName = PluginManager.GetPluginName(_userControlType, Common.ComputerName); _assemblyType = assemblyType; _assemblyName = assemblyName; _domain = domain; _latestAvailableVersion = string.Empty; }
public void Add(AppDomain appDomain) { foreach (Assembly assembly in appDomain.GetAssemblies()) { Add(assembly); } }
/// <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 virtual void Init() { serverDomain = AppDomainFactory.Create("server"); clientDomain = AppDomainFactory.Create("client"); serverContainer = CreateRemoteContainer(serverDomain, GetServerConfigFile()); }
public static void SetShadowPathForNativeDll(AppDomain appDomain, string dllFileName, string dllPath) { if (dllFileName == null) throw new ArgumentNullException("dllFileName"); if (dllPath == null) throw new ArgumentNullException("dllPath"); var key = AppDomainCustomDllPathKey + dllFileName.ToLowerInvariant(); appDomain.SetData(key, dllPath); }
public override bool Load( TestPackage package ) { Unload(); log.Info("Loading " + package.Name); try { if ( this.domain == null ) this.domain = Services.DomainManager.CreateDomain( package ); if (this.agent == null) { this.agent = DomainAgent.CreateInstance(domain); this.agent.Start(); } if ( this.TestRunner == null ) this.TestRunner = this.agent.CreateRunner( this.ID ); log.Info( "Loading tests in AppDomain, see {0}_{1}.log", domain.FriendlyName, Process.GetCurrentProcess().Id); return TestRunner.Load( package ); } catch { log.Error("Load failure"); Unload(); throw; } }
/// <summary> /// Creates a new child domain and copies the evidence from a parent domain. /// </summary> /// <param name="parentDomain">The parent domain.</param> /// <returns>The new child domain.</returns> /// <remarks> /// Grabs the <paramref name="parentDomain"/> evidence and uses it to construct the new /// <see cref="AppDomain"/> because in a ClickOnce execution environment, creating an /// <see cref="AppDomain"/> will by default pick up the partial trust environment of /// the AppLaunch.exe, which was the root executable. The AppLaunch.exe does a /// create domain and applies the evidence from the ClickOnce manifests to /// create the domain that the application is actually executing in. This will /// need to be Full Trust for Composite Application Library applications. /// </remarks> protected virtual AppDomain BuildChildDomain(AppDomain parentDomain) { Evidence evidence = new Evidence(parentDomain.Evidence); AppDomainSetup setup = parentDomain.SetupInformation; var domain = AppDomain.CreateDomain("DiscoveryRegion", evidence, setup); return domain; }
public static System.Type[] GetAllDerivedTypes(this System.AppDomain aAppDomain, System.Type aType) { var result = new List <System.Type>(); var assemblies = aAppDomain.GetAssemblies(); foreach (var assembly in assemblies) { var types = assembly.GetTypes(); foreach (var type in types) { if (type.IsSubclassOf(aType)) { result.Add(type); } } } return(result.ToArray()); }
public static System.Type[] GetTypesWithInterface(this System.AppDomain aAppDomain, System.Type aInterfaceType) { List <System.Type> result = new List <System.Type>(); System.Reflection.Assembly[] assemblies = aAppDomain.GetAssemblies(); foreach (var assembly in assemblies) { var types = assembly.GetTypes(); foreach (var type in types) { if (aInterfaceType.IsAssignableFrom(type)) { result.Add(type); } } } return(result.ToArray()); }
//可以使用工具类 public static T[] GetAllImplementTypes <T> (System.AppDomain aAppDomain) where T : class { var result = new List <T>(); var assemblies = aAppDomain.GetAssemblies(); foreach (var assembly in assemblies) { var types = assembly.GetTypes(); foreach (var type in types) { if (typeof(T).IsAssignableFrom(type)) { if (!type.IsAbstract) { var tar = assembly.CreateInstance(type.FullName) as T; result.Add(tar); } } } } return(result.ToArray()); }
//Create new enum from arrays public static System.Enum CreateEnum(List <string> list) { System.AppDomain currentDomain = System.AppDomain.CurrentDomain; AssemblyName aName = new AssemblyName("Enum"); AssemblyBuilder ab = currentDomain.DefineDynamicAssembly(aName, AssemblyBuilderAccess.Run); ModuleBuilder mb = ab.DefineDynamicModule(aName.Name); EnumBuilder enumerator = mb.DefineEnum("Enum", TypeAttributes.Public, typeof(int)); int i = 0; enumerator.DefineLiteral("None", i); //Here = enum{ None } foreach (string names in list) { i++; enumerator.DefineLiteral(names, i); } //Here = enum { None, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday } System.Type finished = enumerator.CreateType(); return((System.Enum)System.Enum.ToObject(finished, 0)); }
/// <summary> /// Initializes the static fields of the <see cref = "CDimensions"/> class /// </summary> /// <remarks>Loads units and unit category data from XML files.</remarks> static CDimensions() { units = new System.Collections.ArrayList(); unitCategories = new System.Collections.ArrayList(); System.AppDomain domain = System.AppDomain.CurrentDomain; //System.Reflection.Assembly myAssembly = System.Reflection.Assembly.GetExecutingAssembly(); //System.IO.Stream resStream = myAssembly.GetManifestResourceStream("CapeOpen.Resources.units.xml.resources"); //System.Resources.ResourceReader resReader = new System.Resources.ResourceReader(resStream); //System.Collections.IDictionaryEnumerator en = resReader.GetEnumerator(); //String temp = String.Empty; //while (en.MoveNext()) //{ // if (en.Key.ToString() == "units") temp = en.Value.ToString(); //} System.Xml.XmlDocument reader = new System.Xml.XmlDocument(); reader.LoadXml(Properties.Resources.units); System.Xml.XmlNodeList list = reader.SelectNodes("Units/Unit_Specs"); System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(0x0409, false); for (int i = 0; i < list.Count; i++) { unit newUnit; String UnitName = list[i].SelectSingleNode("Unit").InnerText; newUnit.Name = UnitName.Trim(); newUnit.Description = ""; newUnit.Category = list[i].SelectSingleNode("Category").InnerText; newUnit.ConversionTimes = Convert.ToDouble(list[i].SelectSingleNode("ConversionTimes").InnerText, ci.NumberFormat); newUnit.ConversionPlus = Convert.ToDouble(list[i].SelectSingleNode("ConversionPlus").InnerText, ci.NumberFormat); units.Add(newUnit); } String userUnitPath = String.Concat(domain.BaseDirectory, "//data//user_defined_UnitsResult.XML"); if (System.IO.File.Exists(userUnitPath)) { reader.Load(userUnitPath); list = reader.SelectNodes("Units/Unit_Specs"); for (int i = 0; i < list.Count; i++) { unit newUnit = new unit(); String UnitName = list[i].SelectSingleNode("Unit").InnerText; newUnit.Name = UnitName.Trim(); newUnit.Category = list[i].SelectSingleNode("Category").InnerText; newUnit.ConversionTimes = Convert.ToDouble(list[i].SelectSingleNode("ConversionTimes").InnerText, ci.NumberFormat); newUnit.ConversionPlus = Convert.ToDouble(list[i].SelectSingleNode("ConversionPlus").InnerText, ci.NumberFormat); units.Add(newUnit); } } //resStream = myAssembly.GetManifestResourceStream("CapeOpen.Resources.unitCategories.xml.resources"); //resReader = new System.Resources.ResourceReader(resStream); //en = resReader.GetEnumerator(); //while (en.MoveNext()) //{ // if (en.Key.ToString() == "unitCategories") temp = en.Value.ToString(); //} reader.LoadXml(Properties.Resources.unitCategories); list = reader.SelectNodes("CategorySpecifications/Category_Spec"); for (int i = 0; i < list.Count; i++) { String UnitName = list[i].SelectSingleNode("Category").InnerText; unitCategory category; category.Name = UnitName; category.AspenUnit = list[i].SelectSingleNode("Aspen").InnerText; category.SI_Unit = list[i].SelectSingleNode("SI_Unit").InnerText; category.Mass = Convert.ToDouble(list[i].SelectSingleNode("Mass").InnerText); category.Time = Convert.ToDouble(list[i].SelectSingleNode("Time").InnerText); category.Length = Convert.ToDouble(list[i].SelectSingleNode("Length").InnerText); category.ElectricalCurrent = Convert.ToDouble(list[i].SelectSingleNode("ElectricalCurrent").InnerText); category.Temperature = Convert.ToDouble(list[i].SelectSingleNode("Temperature").InnerText); category.AmountOfSubstance = Convert.ToDouble(list[i].SelectSingleNode("AmountOfSubstance").InnerText); category.Luminous = Convert.ToDouble(list[i].SelectSingleNode("Luminous").InnerText, ci.NumberFormat); category.Currency = Convert.ToDouble(list[i].SelectSingleNode("Currency").InnerText, ci.NumberFormat); unitCategories.Add(category); } String userUnitCategoryPath = String.Concat(domain.BaseDirectory, "data//user_defined_units.XML"); if (System.IO.File.Exists(userUnitCategoryPath)) { reader.Load(userUnitCategoryPath); list = reader.SelectNodes("CategorySpecifications/Category_Spec"); for (int i = 0; i < list.Count; i++) { String UnitName = list[i].SelectSingleNode("Category").InnerText; unitCategory category; category.Name = UnitName; category.AspenUnit = list[i].SelectSingleNode("Aspen").InnerText; category.SI_Unit = list[i].SelectSingleNode("SI_Unit").InnerText; category.Mass = Convert.ToDouble(list[i].SelectSingleNode("Mass").InnerText, ci.NumberFormat); category.Time = Convert.ToDouble(list[i].SelectSingleNode("Time").InnerText, ci.NumberFormat); category.Length = Convert.ToDouble(list[i].SelectSingleNode("Length").InnerText, ci.NumberFormat); category.ElectricalCurrent = Convert.ToDouble(list[i].SelectSingleNode("ElectricalCurrent").InnerText, ci.NumberFormat); category.Temperature = Convert.ToDouble(list[i].SelectSingleNode("Temperature").InnerText, ci.NumberFormat); category.AmountOfSubstance = Convert.ToDouble(list[i].SelectSingleNode("AmountOfSubstance").InnerText, ci.NumberFormat); category.Luminous = Convert.ToDouble(list[i].SelectSingleNode("Luminous").InnerText, ci.NumberFormat); category.Currency = Convert.ToDouble(list[i].SelectSingleNode("Currency").InnerText, ci.NumberFormat); unitCategories.Add(category); } } }
public ContinuousDatabaseAppDomainProxy() { _domain = System.AppDomain.CreateDomain("ContinuousDatabaseActivity"); _remoteClass = _domain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(ContinuousDatabaseAppDomain).FullName) as ContinuousDatabaseAppDomain; }
public static void Main() { System.AppDomain a = null; a?.AssemblyLoad += (sender, args) => Console.Write(args); }
public static System.Type[] GetTypesWithInterface <T>(this System.AppDomain aAppDomain) { return(GetTypesWithInterface(aAppDomain, typeof(T))); }
public void RegsiterTypesInDomain(System.AppDomain domain = null) { systems.RegsiterTypesInDomain(domain); }
private static void SetEnvironmentVariableCore(string variable, string value, EnvironmentVariableTarget target) { if (target == EnvironmentVariableTarget.Process) { SetEnvironmentVariableCore(variable, value); return; } #if FEATURE_WIN32_REGISTRY if (AppDomain.IsAppXModel()) #endif { // other targets ignored return; } #if FEATURE_WIN32_REGISTRY // explicitly null out value if is the empty string. if (string.IsNullOrEmpty(value) || value[0] == '\0') { value = null; } RegistryKey baseKey; string keyName; if (target == EnvironmentVariableTarget.Machine) { baseKey = Registry.LocalMachine; keyName = @"System\CurrentControlSet\Control\Session Manager\Environment"; } else if (target == EnvironmentVariableTarget.User) { // User-wide environment variables stored in the registry are limited to 255 chars for the environment variable name. const int MaxUserEnvVariableLength = 255; if (variable.Length >= MaxUserEnvVariableLength) { throw new ArgumentException(SR.Argument_LongEnvVarValue, nameof(variable)); } baseKey = Registry.CurrentUser; keyName = "Environment"; } else { throw new ArgumentException(SR.Format(SR.Arg_EnumIllegalVal, (int)target)); } using (RegistryKey environmentKey = baseKey.OpenSubKey(keyName, writable: true)) { if (environmentKey != null) { if (value == null) { environmentKey.DeleteValue(variable, throwOnMissingValue: false); } else { environmentKey.SetValue(variable, value); } } } // send a WM_SETTINGCHANGE message to all windows IntPtr r = Interop.User32.SendMessageTimeout(new IntPtr(Interop.User32.HWND_BROADCAST), Interop.User32.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", 0, 1000, IntPtr.Zero); Debug.Assert(r != IntPtr.Zero, "SetEnvironmentVariable failed: " + Marshal.GetLastWin32Error()); #endif // FEATURE_WIN32_REGISTRY }
public static Assembly[] GetAppAssemblies(this AppDomain @this) { return(@this.GetAssemblies() .Where(x => x.FullName.StartsWith(AssemblieName)) .ToArray()); }
public static IEnumerable <Type> GetAppTypes(this AppDomain @this) { return(@this.GetAssemblies() .Where(x => x.FullName.StartsWith(AssemblieName)) .SelectMany(x => x.GetTypes())); }
public virtual void Run() { this.TryObtainLock(); try { this.Preconditions(Pre.SiteSet | Pre.RootNamespaceSet | Pre.RootMonikerSet | Pre.EngineNotRunning | Pre.EngineNotClosed); System.AppDomain currentDomain = System.AppDomain.CurrentDomain; if (this.haveCompiledState) { if (this.rootNamespace != this.compiledRootNamespace) { throw new JSVsaException(JSVsaError.RootNamespaceInvalid); } this.loadedAssembly = this.LoadCompiledState(); currentDomain.SetData(this.engineMoniker, this.loadedAssembly); } else { if (this.failedCompilation) { throw new JSVsaException(JSVsaError.EngineNotCompiled); } this.startupClass = null; this.loadedAssembly = currentDomain.GetData(this.engineMoniker) as System.Reflection.Assembly; if (this.loadedAssembly == null) { string name = this.engineMoniker + "/" + currentDomain.GetHashCode().ToString(CultureInfo.InvariantCulture); Mutex mutex = new Mutex(false, name); if (mutex.WaitOne()) { try { this.loadedAssembly = currentDomain.GetData(this.engineMoniker) as System.Reflection.Assembly; if (this.loadedAssembly == null) { byte[] buffer; byte[] buffer2; this.engineSite.GetCompiledState(out buffer, out buffer2); if (buffer == null) { throw new JSVsaException(JSVsaError.GetCompiledStateFailed); } this.loadedAssembly = System.Reflection.Assembly.Load(buffer, buffer2, this.executionEvidence); currentDomain.SetData(this.engineMoniker, this.loadedAssembly); } } finally { mutex.ReleaseMutex(); mutex.Close(); } } } } try { if (this.startupClass == null) { this.startupClass = this.loadedAssembly.GetType(this.rootNamespace + "._Startup", true); } } catch (Exception exception) { throw new JSVsaException(JSVsaError.BadAssembly, exception.ToString(), exception); } try { this.startupInstance = (BaseVsaStartup)Activator.CreateInstance(this.startupClass); this.isEngineRunning = true; this.startupInstance.SetSite(this.engineSite); this.startupInstance.Startup(); } catch (Exception exception2) { throw new JSVsaException(JSVsaError.UnknownError, exception2.ToString(), exception2); } } finally { this.ReleaseLock(); } }
public static System.Type[] GetAllDerivedTypes <T>(this System.AppDomain aAppDomain) { return(GetAllDerivedTypes(aAppDomain, typeof(T))); }
/// <summary> /// Starts a runner instance /// </summary> /// <returns>The awaitable task.</returns> /// <param name="domain">The AppDomain to use.</param> /// <param name="config">The server configuration.</param> /// <param name="usessl">If set to <c>true</c> use ssl.</param> /// <param name="port">The port to listen on.</param> private async Task StartRunnerAsync(System.AppDomain domain, ServerConfig config, bool usessl, string address, int port) { var enabled = !string.IsNullOrWhiteSpace(address); // Ensure it parses ConfigParser.ParseIPAddress(address); var prev = m_handlers.Where(x => x.UseSSL == usessl).FirstOrDefault(); if (enabled) { var addcrashhandler = true; var wrapper = new AppDomainWrapper(domain); wrapper.SetupFromFile(usessl, m_path, config.Storage); if (prev == null) { prev = new RunnerInstance(wrapper, address, port, usessl, config); m_handlers.Add(prev); } else { if (prev.RunnerTask.IsFaulted || prev.RunnerTask.IsCanceled || prev.RunnerTask.IsCompleted) { var cur = new RunnerInstance(wrapper, address, port, usessl, config); m_handlers.Remove(prev); m_handlers.Add(cur); prev = cur; } else if (prev.Port != port || !string.Equals(prev.Address, address, StringComparison.Ordinal)) { // Address or port change, start new listener first var cur = new RunnerInstance(wrapper, address, port, usessl, config); if (!prev.RunnerTask.IsFaulted) { await prev.StopAsync(); } m_handlers.Remove(prev); m_handlers.Add(cur); prev = cur; } else if (prev.Config.SocketBacklog != config.SocketBacklog) { await prev.RestartAsync(wrapper, address, port, usessl, config); } else { addcrashhandler = false; // We already have it prev.Wrapper = wrapper; // Assign the new wrapper } } if (addcrashhandler) { var dummy = prev.RunnerTask.ContinueWith(x => { if (!prev.ShouldStop && InstanceCrashed != null) { InstanceCrashed(address, usessl, x.IsFaulted ? x.Exception : new Exception("Unexpected stop")); } }); } } else if (prev != null) { await prev.StopAsync(); m_handlers.Remove(prev); } }
public Result OnStartup(UIControlledApplication application) { System.AppDomain currentDomain = System.AppDomain.CurrentDomain; currentDomain.AssemblyResolve += new ResolveEventHandler(currentDomain_AssemblyResolve); try { application.ControlledApplication.DocumentChanged += new EventHandler <Autodesk.Revit.DB.Events.DocumentChangedEventArgs>(documentChangedEventFillingListOfElements); } catch (Exception) { return(Result.Failed); } // Get the absolut path of this assembly string ExecutingAssemblyPath = System.Reflection.Assembly.GetExecutingAssembly( ).Location; // Create a ribbon panel RibbonPanel m_projectPanel = application.CreateRibbonPanel( NameSpaceNm); //Execute File location string fileLctn = NameSpaceNm + ".MainCommand"; //Button PushButton pushButton = m_projectPanel.AddItem(new PushButtonData( NameSpaceNm, NameSpaceNm, ExecutingAssemblyPath, fileLctn)) as PushButton; //Add Help ToolTip pushButton.ToolTip = NameSpaceNm; //Add long description pushButton.LongDescription = "This addin helps you to ..."; //Icon file location string iconFlLctn = NameSpaceNm + ".Resources.RevitLogo.png"; // Set the large image shown on button. pushButton.LargeImage = PngImageSource( iconFlLctn); // Get the location of the solution DLL string path = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location); // Combine path with \ string newpath = Path.GetFullPath(Path.Combine(path, @"..\")); ContextualHelp contextHelp = new ContextualHelp( ContextualHelpType.Url, "https://google.com"); // Assign contextual help to pushbutton pushButton.SetContextualHelp(contextHelp); //Execute File location string fileLctnExport = NameSpaceNm + ".ExportCommand"; //Button Export Model PushButton pushButtonExport = m_projectPanel.AddItem(new PushButtonData( "Export model", "Export model", ExecutingAssemblyPath, fileLctnExport)) as PushButton; //Add Help ToolTip pushButtonExport.ToolTip = "Export model"; //Add long description pushButtonExport.LongDescription = "This addin helps you to ..."; //Icon file location string iconFlLctnExport = NameSpaceNm + ".Resources.ExportLogo.png"; // Set the large image shown on button. pushButtonExport.LargeImage = PngImageSource( iconFlLctnExport); // Get the location of the solution DLL string pathExport = System.IO.Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location); // Combine path with \ string newpathExport = Path.GetFullPath(Path.Combine(path, @"..\")); ContextualHelp contextHelpExport = new ContextualHelp( ContextualHelpType.Url, "https://google.com"); // Assign contextual help to pushbutton pushButtonExport.SetContextualHelp(contextHelp); // A new handler to handle request posting by the dialog ExportEvent handler = new ExportEvent(); // External Event for the dialog to use (to post requests) ExportChangesExternalEvent = ExternalEvent.Create(handler); // A new handler to handle request posting by the dialog ExportModelEvent handlerB = new ExportModelEvent(); // External Event for the dialog to use (to post requests) ExportModelExternalEvent = ExternalEvent.Create(handlerB); // A new handler to handle request posting by the dialog ReceiveChangesEvent handlerC = new ReceiveChangesEvent(); // External Event for the dialog to use (to post requests) ReceiveChangesExternalEvent = ExternalEvent.Create(handlerC); return(Result.Succeeded); }
/// <summary> /// Reload this instance. /// </summary> public async Task ReloadAsync(bool http, bool https) { var cfg = ConfigParser.ParseTextFile(m_path); var config = ConfigParser.CreateServerConfig(cfg); config.Storage = m_storage; ((MemoryStorageCreator)m_storage).ExpireCheckInterval = cfg.StorageExpirationCheckIntervalSeconds; // Not a part of .Net Standard or .Net core, but we can call it if we run .Net Framework var createMethod = typeof(System.AppDomain) .GetMethods(BindingFlags.Public | BindingFlags.Static) .Where(x => x.Name == nameof(System.AppDomain.CreateDomain)) .Where(x => x.GetParameters().Length == 5) .Where(x => x.GetParameters().Last().ParameterType == typeof(bool)) .FirstOrDefault(); var domain = (System.AppDomain)createMethod.Invoke(null, new object[] { "CeenRunner-" + Guid.NewGuid().ToString(), null, cfg.Basepath, cfg.Assemblypath, true }); //var domain = System.AppDomain.CreateDomain( // "CeenRunner-" + Guid.NewGuid().ToString(), // null, // cfg.Basepath, // cfg.Assemblypath, // true //); // For debugging, use the same domain //domain = AppDomain.CurrentDomain; var prevdomains = m_handlers.Select(x => x.Wrapper).ToList(); try { await Task.WhenAll(new[] { http?StartRunnerAsync(domain, config, false, cfg.HttpAddress, cfg.HttpPort) : null, https ? StartRunnerAsync(domain, config, true, cfg.HttpsAddress, cfg.HttpsPort) : null }.Where(x => x != null)); } catch { try { System.AppDomain.Unload(domain); } catch { } throw; } var prevdomain = m_appDomain; m_appDomain = domain; await Task.Run(async() => { // Give old domain time to terminate var maxtries = cfg.MaxUnloadWaitSeconds; while (maxtries-- > 0) { if (prevdomains.Select(x => x.ActiveClients).Sum() == 0) { break; } await Task.Delay(1000); } if (prevdomain != null && prevdomain != System.AppDomain.CurrentDomain) { try { System.AppDomain.Unload(prevdomain); } catch { } } }); }
static AppDomain() { CurrentDomain = new AppDomain(); }
static public void Main(string[] args) { if (args.Length < 10 || args.Length > 11) { show_usage(Process.GetCurrentProcess().ProcessName); return; } string url = args[0]; int broker_id; try { broker_id = Int32.Parse(args[1]); } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } string symbol = args[2]; char side; switch (args[3].ToUpper()) { case "BUY": side = OrderSide.BUY; break; case "SELL": side = OrderSide.SELL; break; case "BOTH": side = default(char); break; default: show_usage(Process.GetCurrentProcess().ProcessName); return; } // ** temporary workaround to support market pegged sell order strategy without plugins ** TradingStrategy.PriceType priceType; switch (args[4].ToUpper()) { case "DEFAULT": case "FIXED": priceType = TradingStrategy.PriceType.FIXED; break; case "PEGGED": case "FLOAT": if (side == OrderSide.SELL) { priceType = TradingStrategy.PriceType.PEGGED; } else { throw new ArgumentException("PEGGED is currently supported only for SELL"); } break; default: show_usage(Process.GetCurrentProcess().ProcessName); return; } ulong maxTradeSize; try { maxTradeSize = (ulong)(Double.Parse(args[5]) * 1e8); if (maxTradeSize < 10000) { throw new ArgumentException("Invalid Trade Size, must be at least 10,000 satoshis"); } } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } // *** ulong buyTargetPrice; try { buyTargetPrice = (ulong)(Double.Parse(args[6]) * 1e8); if (buyTargetPrice < 0) { throw new ArgumentException("Invalid Buy Target Price"); } } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } ulong sellTargetPrice; try { sellTargetPrice = (ulong)(Double.Parse(args[7]) * 1e8); } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } try { if ((side == OrderSide.BUY || side == default(char)) && buyTargetPrice == 0) { throw new ArgumentException("Invalid BUY Target Price"); } if ((side == OrderSide.SELL || side == default(char)) && sellTargetPrice == 0) { throw new ArgumentException("Invalid SELL Target Price"); } if (side == default(char) && buyTargetPrice >= sellTargetPrice) { throw new ArgumentException("Invalid SELL and BUY Price RANGE"); } } catch (Exception e) { Console.WriteLine(e.Message); show_usage(Process.GetCurrentProcess().ProcessName); return; } string user = args[8]; string password = args[9]; string second_factor = args.Length == 11 ? args[10] : null; try { // instantiate the tradeclient object to handle the trading stuff TradingStrategy strategy = new TradingStrategy(maxTradeSize, buyTargetPrice, sellTargetPrice, side, priceType); // instantiate the protocol engine object to handle the blinktrade messaging stuff WebSocketClientProtocolEngine protocolEngine = new WebSocketClientProtocolEngine(); SimpleTradeClient tradeclient = new SimpleTradeClient(broker_id, symbol, strategy, protocolEngine); // tradeclient must subscribe to receive the callback events from the protocol engine protocolEngine.SystemEvent += tradeclient.OnBrokerNotification; protocolEngine.LogStatusEvent += LogStatus; strategy.LogStatusEvent += LogStatus; // workaround (on windows working only in DEBUG) to trap the console application exit // and dump the last state of the Market Data Order Book(s), MiniOMS and Security Status #if (__MonoCS__ || DEBUG) System.AppDomain appDom = System.AppDomain.CurrentDomain; appDom.ProcessExit += new EventHandler(tradeclient.OnApplicationExit); #if __MonoCS__ Thread signal_thread = new Thread(UnixSignalTrap); signal_thread.Start(); #else var consoleHandler = new HandlerRoutine(OnConsoleCtrlCheck); // hold handler to not get GC'd SetConsoleCtrlHandler(consoleHandler, true); #endif #endif // objects to encapsulate and provide user account credentials UserAccountCredentials userAccount = new UserAccountCredentials(broker_id, user, password, second_factor); while (!_userRequestExit) { try { LogStatus(LogStatusType.WARN, "Please Wait..."); // gather and provide the user device data (local ip, external ip etc) UserDevice userDevice = new UserDevice(); // start the connection task to handle the Websocket connectivity and initiate the whole process #if __MonoCS__ Task /*<int>*/ task = WebSocketSharpClientConnection.Start(url, userAccount, userDevice, protocolEngine); #else Task task = WebSocketClientConnection.Start(url, userAccount, userDevice, protocolEngine); #endif /* * Task<int>[] tasks = new Task<int>[2]; * tasks[0] = WebSocketSharpClientConnection.Start (url, userAccount, userDevice, protocolEngine); * //tasks[1] = ... * int index = Task.WaitAny(tasks); * tasks[index].Result; */ task.Wait(); // aguardar até a Task finalizar if (!_userRequestExit) { tradeclient.ResetData(); // must reset tradeclient to refresh whole data after new connection LogStatus(LogStatusType.WARN, "Trying to reconnect in 5 seconds..."); Task.Delay(TimeSpan.FromSeconds(5)).Wait(); } } catch (System.Net.WebException ex) { LogStatus(LogStatusType.ERROR, ex.Message + '\n' + ex.StackTrace); Task.Delay(TimeSpan.FromSeconds(5)).Wait(); continue; } } } catch (Exception ex) { LogStatus(LogStatusType.ERROR, ex.Message + '\n' + ex.StackTrace); return; } /* #if DEBUG * Console.WriteLine("Press any key to exit..."); * Console.ReadKey(); #endif */ }
public static void Unload(AppDomain domain) { Contract.Requires(domain != null); }
public AssemblyGen(Universe universe, string assemblyName, CompilerOptions options, ITypeMapper typeMapper = null) { Initialize(universe, assemblyName, AssemblyBuilderAccess.Save, options, typeMapper); }
/// <summary> /// Unloads the test runner app domain. /// </summary> /// <param name="domain">The domain to unload.</param> public static void UnloadDomain(System.AppDomain domain) { System.AppDomain.Unload(domain); }
} // PrepareDataForSetup private static Object Setup(Object arg) { Object[] args = (Object[])arg; String friendlyName = (String)args[0]; AppDomainSetup setup = (AppDomainSetup)args[1]; string[] propertyNames = (string[])args[2]; // can contain null elements string[] propertyValues = (string[])args[3]; // can contain null elements AppDomain ad = AppDomain.CurrentDomain; AppDomainSetup newSetup = new AppDomainSetup(setup, false); if (propertyNames != null && propertyValues != null) { for (int i = 0; i < propertyNames.Length; i++) { // We want to set native dll probing directories before any P/Invokes have a // chance to fire. The Path class, for one, has P/Invokes. if (propertyNames[i] == "NATIVE_DLL_SEARCH_DIRECTORIES") { if (propertyValues[i] == null) { throw new ArgumentNullException("NATIVE_DLL_SEARCH_DIRECTORIES"); } string paths = propertyValues[i]; if (paths.Length == 0) { break; } nSetNativeDllSearchDirectories(paths); } } for (int i = 0; i < propertyNames.Length; i++) { if (propertyNames[i] == "APPBASE") // make sure in sync with Fusion { if (propertyValues[i] == null) { throw new ArgumentNullException("APPBASE"); } if (PathInternal.IsPartiallyQualified(propertyValues[i])) { throw new ArgumentException(SR.Argument_AbsolutePathRequired); } newSetup.ApplicationBase = NormalizePath(propertyValues[i], fullCheck: true); } else if (propertyNames[i] == "TRUSTED_PLATFORM_ASSEMBLIES" || propertyNames[i] == "PLATFORM_RESOURCE_ROOTS" || propertyNames[i] == "APP_PATHS" || propertyNames[i] == "APP_NI_PATHS") { string values = propertyValues[i]; if (values == null) { throw new ArgumentNullException(propertyNames[i]); } ad.SetData(propertyNames[i], NormalizeAppPaths(values)); } else if (propertyNames[i] != null) { ad.SetData(propertyNames[i], propertyValues[i]); // just propagate } } } ad.SetupFusionStore(newSetup, null); // makes FusionStore a ref to newSetup // technically, we don't need this, newSetup refers to the same object as FusionStore // but it's confusing since it isn't immediately obvious whether we have a ref or a copy AppDomainSetup adSetup = ad.FusionStore; // set up the friendly name ad.nSetupFriendlyName(friendlyName); ad.CreateAppDomainManager(); // could modify FusionStore's object return(null); }
void Initialize(Universe universe, string assemblyName, AssemblyBuilderAccess access, CompilerOptions options, ITypeMapper typeMapper = null) { if (universe == null) { throw new ArgumentNullException(nameof(universe)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } _compilerOptions = options; if (typeMapper == null) #if FEAT_IKVM { typeMapper = new TypeMapper(universe); } #else { typeMapper = new TypeMapper(); } #endif ExpressionFactory = new ExpressionFactory(typeMapper); StaticFactory = new StaticFactory(typeMapper); #if SILVERLIGHT bool save = false; #elif NET5_0 || NETSTANDARD bool save = options.OutputPath != null; #else bool save = (access & AssemblyBuilderAccess.Save) != 0; #endif string path = options.OutputPath; if (path == null && save) { throw new ArgumentNullException("options.OutputPath"); } Universe = universe; TypeMapper = typeMapper; _access = access; if (Helpers.IsNullOrEmpty(assemblyName)) { if (save) { throw new ArgumentNullException(nameof(assemblyName)); } assemblyName = Guid.NewGuid().ToString(); } string moduleName = path == null ? assemblyName : assemblyName + Path.GetExtension(path); _fileName = path; AssemblyName an = new AssemblyName(); an.Name = assemblyName; AssemblyBuilder = #if NET5_0 || NETSTANDARD System.Reflection.Emit.AssemblyBuilder.DefineDynamicAssembly(an, access); #else #if !SILVERLIGHT path != null?Universe.DefineDynamicAssembly(an, access, Path.GetDirectoryName(path)) : #endif Universe.DefineDynamicAssembly(an, access); #endif #if FEAT_IKVM if (!Helpers.IsNullOrEmpty(options.KeyFile)) { AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(File.OpenRead(options.KeyFile))); } else if (!Helpers.IsNullOrEmpty(options.KeyContainer)) { AssemblyBuilder.__SetAssemblyKeyPair(new StrongNameKeyPair(options.KeyContainer)); } else if (!Helpers.IsNullOrEmpty(options.PublicKey)) { AssemblyBuilder.__SetAssemblyPublicKey(FromHex(options.PublicKey)); } if (!Helpers.IsNullOrEmpty(options.ImageRuntimeVersion) && options.MetaDataVersion != 0) { AssemblyBuilder.__SetImageRuntimeVersion(options.ImageRuntimeVersion, options.MetaDataVersion); } ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, path, options.SymbolInfo); #else #if !NET5_0 && !SILVERLIGHT && !NETSTANDARD if (save) { ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName, Path.GetFileName(path)); } else #endif ModuleBuilder = AssemblyBuilder.DefineDynamicModule(moduleName); #endif }
public AppDomain(System.AppDomain appDomain, bool unloadOnDispose = true) { _appDomain = appDomain; _unloadOnDispose = unloadOnDispose; }
/// <summary> /// Add new device profile. /// </summary> /// <param name="request"></param> /// <returns></returns> public GXDeviceProfilesUpdateResponse Post(GXDeviceProfilesUpdateRequest request) { List <GXEventsItem> events = new List <GXEventsItem>(); GXAmiDeviceProfile DeviceProfiles = null; lock (Db) { using (var trans = Db.OpenTransaction(IsolationLevel.ReadCommitted)) { string filename = Path.GetTempFileName(); using (FileStream stream = new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.None)) { BinaryWriter w = new BinaryWriter(stream); w.Write(request.Data); } string pathToDll = this.GetType().Assembly.CodeBase; // Create an Application Domain: AppDomainSetup domainSetup = new AppDomainSetup { PrivateBinPath = pathToDll }; System.AppDomain td = null; string dir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + Path.DirectorySeparatorChar); //Try to load device template and unload assmbly. try { td = AppDomain.CreateDomain("TestDomain", null, domainSetup); GXProxyClass pc = (GXProxyClass)(td.CreateInstanceFromAndUnwrap(pathToDll, typeof(GXProxyClass).FullName)); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } byte[] data; string addInType, assemblyName; List <object[]> items = pc.Import(filename, dir, out data, out assemblyName, out addInType); ulong DeviceProfileID = 0; ulong categoryTemplateID = 0; ulong propertyTemplateID = 0; ulong tableTemplateID = 0; int version = 0; foreach (object[] it in items) { if (it[1] is GXAmiDeviceProfile) { DeviceProfiles = it[1] as GXAmiDeviceProfile; events.Add(new GXEventsItem(ActionTargets.DeviceProfile, Actions.Add, DeviceProfiles)); //Find new version number for the template. foreach (GXAmiDeviceProfile dt in Db.Select <GXAmiDeviceProfile>(q => q.Guid == DeviceProfiles.Guid)) { if (dt.ProfileVersion > version) { version = dt.ProfileVersion; } } ++version; DeviceProfiles.ProtocolAddInType = addInType; DeviceProfiles.ProtocolAssembly = assemblyName; DeviceProfiles.ProfileVersion = version; } else if (it[1] is GXAmiCategoryTemplate) { tableTemplateID = 0; (it[1] as GXAmiCategoryTemplate).DeviceID = DeviceProfileID; (it[1] as GXAmiCategoryTemplate).Id += DeviceProfileID << 16; (it[1] as GXAmiCategoryTemplate).TemplateVersion = version; } else if (it[1] is GXAmiDataTableTemplate) { categoryTemplateID = 0; (it[1] as GXAmiDataTableTemplate).DeviceID = DeviceProfileID; (it[1] as GXAmiDataTableTemplate).Id += DeviceProfileID << 16; (it[1] as GXAmiDataTableTemplate).TemplateVersion = version; } else if (it[1] is GXAmiPropertyTemplate) { (it[1] as GXAmiPropertyTemplate).DeviceID = DeviceProfileID; (it[1] as GXAmiPropertyTemplate).TemplateVersion = version; if (categoryTemplateID != 0) { (it[1] as GXAmiPropertyTemplate).ParentID = categoryTemplateID; } else if (tableTemplateID != 0) { (it[1] as GXAmiPropertyTemplate).ParentID = tableTemplateID; } else { throw new ArgumentOutOfRangeException("Parent ID."); } (it[1] as GXAmiPropertyTemplate).Id += DeviceProfileID << 16; } else if (it[1] is GXAmiParameterTemplate) { (it[1] as GXAmiParameterTemplate).DeviceID = DeviceProfileID; (it[1] as GXAmiParameterTemplate).TemplateVersion = version; if (it[0] is GXAmiDeviceProfile) { (it[1] as GXAmiParameterTemplate).ParentID = DeviceProfileID << 16; } else if (it[0] is GXAmiCategoryTemplate) { (it[1] as GXAmiParameterTemplate).ParentID = categoryTemplateID; } else if (it[0] is GXAmiDataTableTemplate) { (it[1] as GXAmiParameterTemplate).ParentID = tableTemplateID; } else if (it[0] is GXAmiPropertyTemplate) { (it[1] as GXAmiParameterTemplate).ParentID = propertyTemplateID; } } Db.Insert(it[1]); if (it[1] is GXAmiDeviceProfile) { #if !SS4 ulong value = (ulong)Db.GetLastInsertId(); #else ulong value = (ulong)Db.LastInsertId(); #endif (it[1] as GXAmiDeviceProfile).Id = value; DeviceProfileID = value; //Update allowed media types. foreach (GXAmiMediaType mt in (it[1] as GXAmiDeviceProfile).AllowedMediaTypes) { mt.DeviceProfileId = DeviceProfileID; Db.Insert(mt); } } else if (it[1] is GXAmiCategoryTemplate) { categoryTemplateID = (it[1] as GXAmiCategoryTemplate).Id; } else if (it[1] is GXAmiDataTableTemplate) { tableTemplateID = (it[1] as GXAmiDataTableTemplate).Id; } else if (it[1] is GXAmiPropertyTemplate) { propertyTemplateID = (it[1] as GXAmiPropertyTemplate).Id; if ((it[1] as GXAmiPropertyTemplate).Values != null && (it[1] as GXAmiPropertyTemplate).Values.Length != 0) { #if !SS4 ulong value = (ulong)Db.GetLastInsertId(); #else ulong value = (ulong)Db.LastInsertId(); #endif foreach (GXAmiValueItem vi in (it[1] as GXAmiPropertyTemplate).Values) { vi.ProfileId = DeviceProfileID; vi.PropertyId = value; Db.Insert(vi); } } } else if (it[1] is GXAmiParameterTemplate) { if ((it[1] as GXAmiParameterTemplate).Values != null && (it[1] as GXAmiParameterTemplate).Values.Length != 0) { #if !SS4 ulong value = (ulong)Db.GetLastInsertId(); #else ulong value = (ulong)Db.LastInsertId(); #endif foreach (GXAmiValueItem vi in (it[1] as GXAmiParameterTemplate).Values) { vi.ProfileId = DeviceProfileID; vi.ParameterId = value; Db.Insert(vi); } } } } //Save device template to data blocks. foreach (GXAmiDeviceProfilesDataBlock it in SplitDataToPackets(DeviceProfileID, filename)) { Db.Insert(it); } foreach (GXAmiDeviceProfilesDataBlock it in SplitDataToPackets(DeviceProfileID, filename)) { Db.Insert(it); } if (request.UserGroups != null) { foreach (long ugId in request.UserGroups) { GXAmiUserGroupDeviceProfile it = new GXAmiUserGroupDeviceProfile(); it.DeviceProfileID = DeviceProfileID; it.UserGroupID = ugId; Db.Insert(it); } } } finally { // Unload the application domain: if (td != null) { System.AppDomain.Unload(td); } if (dir != null) { try { Directory.Delete(dir, true); } catch { //It's OK if this fails. } } } trans.Commit(); } } AppHost host = this.ResolveService <AppHost>(); host.SetEvents(Db, this.Request, 0, events); return(new GXDeviceProfilesUpdateResponse(request.UserGroups, DeviceProfiles)); }