public object CreateInstanceFromAndUnwrap(string assemblyFile, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder binder, object[] args, System.Globalization.CultureInfo culture, object[] activationAttributes) { ObjectHandle oh = CreateInstanceFrom(assemblyFile, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes); return(oh?.Unwrap()); }
public object?CreateInstanceAndUnwrap(string assemblyName, string typeName, bool ignoreCase, BindingFlags bindingAttr, Binder?binder, object?[]?args, System.Globalization.CultureInfo?culture, object?[]?activationAttributes) { ObjectHandle?oh = CreateInstance(assemblyName, typeName, ignoreCase, bindingAttr, binder, args, culture, activationAttributes); return(oh?.Unwrap()); }
public void IsolatedRazorEngineService_CleanUpWorks() { var current = AppDomain.CurrentDomain; var appDomain = AppDomain.CreateDomain("TestDomain.IsolatedRazorEngineService_CleanUpWorks", current.Evidence, current.SetupInformation); ObjectHandle handle = Activator.CreateInstanceFrom( appDomain, typeof(AssemblyChecker).Assembly.ManifestModule.FullyQualifiedName, typeof(AssemblyChecker).FullName ); using (var remoteHelper = (AssemblyChecker)handle.Unwrap()) { remoteHelper.IsolatedRazorEngineService_CleanUpWorks(); } }
public void GetVariableAsHandle_RemoteEngineRemoteValue() { ScriptRuntime env = ScriptRuntimeTest.CreateRuntime(TestHelpers.CreateAppDomain("new domain")); ScriptEngine engine = env.GetEngine("py"); ScriptScope scope = engine.CreateScope(); ScriptSource code = engine.CreateScriptSourceFromString("two=1+1", SourceCodeKind.Statements); code.Execute(scope); ObjectHandle obj = scope.GetVariableHandle("two"); int two = (int)obj.Unwrap(); Assert.AreEqual(two, 2); }
protected virtual object CreateObject(SerializableData serializableData) { Type type = base.GetType(serializableData); if (type != null) { object obj = Activator.CreateInstance(type, null); ObjectHandle objectHandle = obj as ObjectHandle; if (objectHandle != null) { obj = objectHandle.Unwrap(); } return(obj); } throw new XmlSerializationException(null, serializableData); }
internal IsolatedRazorEngineService(IConfigCreator configCreator, IAppDomainFactory appDomainFactory) { _appDomain = CreateAppDomain(appDomainFactory ?? new DefaultAppDomainFactory()); var config = configCreator ?? new DefaultConfigCreator(); ObjectHandle handle = Activator.CreateInstanceFrom( _appDomain, typeof(SanboxHelper).Assembly.ManifestModule.FullyQualifiedName, typeof(SanboxHelper).FullName ); using (var helper = (SanboxHelper)handle.Unwrap()) { _proxy = helper.CreateEngine(config); } }
public IStorageProvider CreateInstance() { Assembly providerAssembly = System.Reflection.Assembly.Load(this.Assembly); ObjectHandle providerObjHandle = Activator.CreateInstance(this.Assembly, this.Class); if (providerObjHandle != null) { IStorageProvider provider = (IStorageProvider)providerObjHandle.Unwrap(); if (provider != null) { return(provider); } } throw new ArgumentException("Impossible to create the instance. Check the provider definition."); }
static void Main() { // Setting the AppDomainSetup. It is very important to set the // ApplicationBase to a folder other than the one in which // the sandboxer resides. AppDomainSetup adSetup = new AppDomainSetup(); adSetup.ApplicationBase = Path.GetFullPath(pathToUntrusted); // Setting the permissions for the AppDomain. We give the permission // to execute and to read/discover the location where the untrusted // code is loaded. PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission( new SecurityPermission(SecurityPermissionFlag.Execution)); // We want the sandboxer assembly's strong name, so that we can add // it to the full trust list. StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence <StrongName>(); // Now we have everything we need to create the AppDomain so, // let's create it. AppDomain newDomain = AppDomain.CreateDomain( "Sandbox", null, adSetup, permSet, fullTrustAssembly); // Use CreateInstanceFrom to load an instance of the Sandboxer class // into the new AppDomain. ObjectHandle handle = Activator.CreateInstanceFrom( newDomain, typeof(Sandboxer).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandboxer).FullName); // Unwrap the new domain instance into a reference in this domain and // use it to execute the untrusted code. Sandboxer newDomainInstance = (Sandboxer)handle.Unwrap(); newDomainInstance.ExecuteUntrustedCode( untrustedAssembly, untrustedClass, entryPoint, parameters); }
public void InvokeMethod() { //validate directory string paht = GetValidatePath(); AppDomain secondDomain = AppDomain.CreateDomain("Second domain"); Type LadaSedanType = Type.GetType("CarPro.LadaSedan, Cars"); ObjectHandle userHandle = secondDomain.CreateInstance("Cars", LadaSedanType.Name); dynamic userProxy = userHandle.Unwrap(); if (RemotingServices.IsTransparentProxy(userProxy)) { } }
public static void LoadAddins(List <Addin> addins, IAddinHost host) { // create instance of each addin foreach (Addin addin in addins) { // create instance ObjectHandle handle = Activator.CreateComInstanceFrom(addin.File, addin.Path); Addin instance = (Addin)handle.Unwrap(); addin.Instance = instance; // add the addin to the global collection Addins.Add(addin); // call the register method on the addin instance.Register(host); } }
/// <summary> /// Loads the specified assembly, instantiates the specified class and calls the ExecuteAsync method /// with the specified parameters. /// </summary> public async Task <string> ExecuteTaskAsync(string taskAssemblyPath, string taskClassName, string taskParameters) { // Sample code: no real error checking! try { ObjectHandle taskObjectHandle = Activator.CreateInstanceFrom(taskAssemblyPath, taskClassName); object taskInstance = taskObjectHandle.Unwrap(); MethodInfo executeMethod = taskInstance.GetType().GetMethod("ExecuteAsync"); Task <string> executeTask = (Task <string>)executeMethod.Invoke(taskInstance, new object[] { taskParameters }); await executeTask; return(executeTask.Result); } catch (Exception ex) { return(ex.ToString()); } }
public static object LoadClass(string className, params object[] args) { int namespaceSeperatorPos = className.IndexOf('.'); if (namespaceSeperatorPos == -1) { throw new Exception("Root class namespace must be the name of the containing assembly. Provided name: " + className); } string assemblyFile = className.Substring(0, namespaceSeperatorPos) + ".dll"; assemblyFile = Path.Combine(IOUtil.GetModuleDirectory("Shared.dll"), assemblyFile); ObjectHandle handle = Activator.CreateInstanceFrom(assemblyFile, className, true, 0, null, args, null, null); return(handle.Unwrap()); }
public static void initPanel(Panel panelContent) { Control _newControl; String _controlName = "MvrpLite.adminFuc.panelRealData"; //初始化面板 _newControl = panelContent.Controls[_controlName]; if (_newControl == null) { //面板没找到 则生成之. ObjectHandle _oh = AppDomain.CurrentDomain.CreateInstance(Assembly.GetExecutingAssembly().FullName, _controlName); _newControl = (Control)_oh.Unwrap(); _newControl.Name = _controlName; _newControl.Dock = DockStyle.Fill; panelContent.Controls.Add(_newControl); } }
public static void Stop() { if (ServiceStackAppDomain == null) { return; } // Notify ServiceStack that the AppDomain is going to be unloaded var host = (ServiceStackConsoleHost)Handle.Unwrap(); host.Shutdown(); // Shutdown the ServiceStack application AppDomain.Unload(ServiceStackAppDomain); ServiceStackAppDomain = null; }
static void Main() { PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); // permSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, "c:/temp")); AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation; AppDomain newDomain = AppDomain.CreateDomain( "Sandboxed domain", AppDomain.CurrentDomain.Evidence, setup, permSet); ObjectHandle oh = newDomain.CreateInstance("RequireFileIOPermissionsDemo", "Wrox.ProCSharp.Security.RequirePermissionsDemo"); object o = oh.Unwrap(); var io = o as RequirePermissionsDemo; string path = @"c:\temp\file.txt"; Console.WriteLine("has {0}permissions to write to {1}", io.RequireFilePermissions(path) ? null : "no ", path); }
public void Run() { //Setting the AppDomainSetup. It is very important to set the ApplicationBase to a folder //other than the one in which the sandboxer resides. AppDomainSetup adSetup = new AppDomainSetup(); adSetup.ApplicationBase = Path.GetFullPath(_sandboxingFolder); //Setting the permissions for the AppDomain. We give the permission to execute and to //read/discover the location where the untrusted code is loaded. PermissionSet permSet = new PermissionSet(PermissionState.None); permSet.AddPermission(new SecurityPermission(SecurityPermissionFlag.Execution)); //Now we have everything we need to create the AppDomain, so let's create it. AppDomain sandboxingDomain = AppDomain.CreateDomain("Sandbox", null, adSetup, permSet); //We want the sandboxer assembly's strong name, so that we can add it to the full trust list. //StrongName fullTrustAssembly = typeof(Sandboxer).Assembly.Evidence.GetHostEvidence<StrongName>(); Assembly loadedPluginAssembly = Assembly.LoadFrom(_originalPluginPath); Type fileSystemStoragePluginType = null; fileSystemStoragePluginType = loadedPluginAssembly.GetTypes().FirstOrDefault(t => t.GetInterfaces().Any(i => i.Equals(typeof(IFileSystemStorage)))); if (fileSystemStoragePluginType == null) { throw new ApplicationException("No implemntation of IFileSystemStorage type found in assembly: " + _sandboxingFolder); } //Use CreateInstanceFrom to load an instance of the Sandboxer class into the //new AppDomain. ObjectHandle fileSystemStorageHandle = Activator.CreateInstanceFrom( sandboxingDomain, loadedPluginAssembly.ManifestModule.FullyQualifiedName, fileSystemStoragePluginType.FullName ); //Unwrap the new domain instance into a reference in this domain and use it to execute the //untrusted code. IFileSystemStorage fileSystemStorageSandboxed = (IFileSystemStorage)fileSystemStorageHandle.Unwrap(); AccountData ad = fileSystemStorageSandboxed.LoadAccountData(); Console.WriteLine(ad); fileSystemStorageSandboxed.SaveAccountData(null); }
private Array StringToArray(string str, Array defValue) { if (str.Length == 0) { return(defValue); } string[] tmp = str.Split(';'); // check data (minimaly must be two items) if (tmp.Length < 2) { return(defValue); } object[] output = new object[tmp.Length - 1]; string[] types = tmp[0].Split(':'); // check format of saved data if (types.Length != 2) { return(defValue); } ObjectHandle typeHandle = Activator.CreateInstance(types[0], types[1]); Type type = typeHandle.Unwrap().GetType(); Type[] methTypes = new Type[] { typeof(string) }; bool bIsEnum = type.IsEnum; MethodInfo method = type.GetMethod("Parse", methTypes); // if we does not found Parse method then return default value if (method == null && bIsEnum == false) { return(defValue); } for (int i = 1; i < tmp.Length; i++) { output[i - 1] = (bIsEnum) ? Enum.Parse(type, tmp[i], true) : method.Invoke(null, new object[] { tmp[i] }); } return(output); }
public ABizLogic GetBiz(CMain initializedMain, System.Windows.Forms.Control control) { string assemblyFile = "YANGSYS.Biz.WHTM.DLL"; string typeName = "YANGSYS.Biz.CBiz"; ObjectHandle handle = Activator.CreateInstanceFrom(assemblyFile, typeName); if (handle == null) { _form = new SOFD.Gui.Window.frmSimpleMain(); } ABizLogic biz = handle.Unwrap() as ABizLogic; biz.Init(initializedMain, control); return(biz); }
private static void CreateClassInNewDomain() { Program.GetDomainInfo(AppDomain.CurrentDomain); try { AppDomain newDomain = AppDomain.CreateDomain("NewDomain"); ObjectHandle obj = newDomain.CreateInstance(Assembly.GetExecutingAssembly().FullName, typeof(MarshalByRef).FullName); MarshalByRef cl = (MarshalByRef)obj.Unwrap(); Console.WriteLine("Is Proxy - {0}", RemotingServices.IsTransparentProxy(cl)); //cl.GetDomainInfo(); } catch (Exception e) { Console.WriteLine("Exception - " + e.Message); } }
public async void Execute() { await Task.Yield(); try { CreateAppDomainAndPopulate(); ObjectHandle handle = Activator.CreateInstanceFrom( SandboxDomain, typeof(Sandbox).Assembly.ManifestModule.FullyQualifiedName, typeof(Sandbox).FullName); Sandbox instance = (Sandbox)handle.Unwrap(); if (options.Verbose) { Console.WriteLine("> Execution of sandboxed program started"); } // start execution with measuring time SandboxStartTime.Start(); waitForExecutionEvent.Set(); instance.Execute(Path.Combine(options.WorkingDirectory, options.ProgramName), options.ProgramArguments.ToArray(), newIn, newOut, newError); // update metadata after successful execution metadata.Update(SandboxStartTime.Elapsed.TotalSeconds, SandboxDomain.MonitoringTotalProcessorTime.TotalSeconds, SandboxDomain.MonitoringSurvivedMemorySize); if (options.Verbose) { Console.WriteLine("> Sandboxed program successfully ended"); } } catch (AppDomainUnloadedException) { // nothing to do here, watcher unloaded AppDomain } catch (Exception e) { Console.WriteLine(e.Message); metadata.Status = StatusCode.XX; metadata.ExceptionType = e.GetType().Name; metadata.Message = e.Message; } finally { // do not remember to set running state of sandboxer to false IsRunning = false; } }
public ActionInfo[] Reflector() { if (_assemblies == null || _assemblies.Count == 0) { return(null); } List <ActionInfo> actionNames = new List <ActionInfo>(); foreach (Assembly ass in _assemblies) { Type[] types = ass.GetTypes(); if (types == null || types.Length == 0) { continue; } foreach (Type t in types) { if (!t.IsClass || t.IsAbstract) { continue; } if (t.GetInterface("CodeCell.Bricks.ModelFabric.IAction") == null) { continue; } ActionAttribute name = null; object[] atts = t.GetCustomAttributes(typeof(ActionAttribute), true); if (atts == null || atts.Length == 0) { ObjectHandle actObj = Activator.CreateInstance(ass.FullName, t.FullName); object nameobj = actObj.Unwrap().GetType().InvokeMember("Name", BindingFlags.GetProperty, null, actObj.Unwrap(), null); if (nameobj != null) { name = new ActionAttribute(nameobj.ToString(), string.Empty); } } else { name = atts[0] as ActionAttribute; } actionNames.Add(new ActionInfo(ass.Location, t.FullName, name)); } } return(actionNames.Count > 0 ? actionNames.ToArray() : null); }
ILoadAndTest installLoader(AppDomain ad, string tempDir) { ad.Load("Loader"); //showAssemblies(ad); //Console.WriteLine(); // create proxy for LoadAndTest object in child AppDomain ObjectHandle oh = ad.CreateInstance("Loader", "LoaderTH.Loader"); object ob = oh.Unwrap(); // unwrap creates proxy to ChildDomain // Console.Write("\n {0}", ob); // set reference to LoadAndTest object in child ILoadAndTest landt = (ILoadAndTest)ob; // create Callback object in parent domain and pass reference // to LoadAndTest object in child landt.setCallback(cb_); landt.loadPath(tempDir); // send file path to LoadAndTest return landt; }
/// <summary> /// Gets a view for a given DataStoreItemViewmodel /// </summary> /// <param name="viewModel">The DataStoreItemViewModel that will be tied to the view</param> /// <returns>If there DataStoreItemViewModel has a preferred view attribute it will instantiate and /// return that. If not the method will try to instantiate and return a view based on the /// underlying DataStoreItem</returns> private static UserControl GetView(DataStoreItemViewModel viewModel) { System.Attribute[] attrs = System.Attribute.GetCustomAttributes(viewModel.GetType()); foreach (System.Attribute attr in attrs) { if (attr is PreferredViewAttribute) { PreferredViewAttribute a = (PreferredViewAttribute)attr; ObjectHandle handle = Activator.CreateInstance(a.AssemblyName, a.ViewName); object p = handle.Unwrap(); return((UserControl)p); } } ObjectHandle handler = Activator.CreateInstance("iRadiate.Desktop.Common", "iRadiate.Desktop.Common.View." + viewModel.Item.ConcreteType.Name + "View"); object pr = handler.Unwrap(); return((UserControl)pr); }
static void Main() { AppDomain domain = AppDomain.CreateDomain("Second Domain"); ObjectHandle handle = domain.CreateInstance("Domains", "Domains.MyClass"); // Создание прозрачного прокси-переходника для взаимодействия с объектом из другого домена. MyClass instance = handle.Unwrap() as MyClass; Console.WriteLine("Main DomainId : {0}", AppDomain.CurrentDomain.Id); Console.WriteLine("Main ThreadId : {0}", Thread.CurrentThread.ManagedThreadId); // Вызов метода объекта, находящегося во втором домене. instance.Operation(); // Delay Console.ReadKey(); }
/// <summary>Recycles the application domain by killing the current one and creating a new one.</summary> private void RecycleAppDomain() { if (appDomain != null) { var oldDomain = appDomain; try { Task.Run(() => AppDomain.Unload(oldDomain)); } catch { } } appDomain = AppDomain.CreateDomain("razorDomain", null, adSetup, permissionSet); ObjectHandle handle = Activator.CreateInstanceFrom(appDomain, typeof(RazorTemplater).Assembly.ManifestModule.FullyQualifiedName, typeof(RazorTemplater).FullName, false, BindingFlags.CreateInstance, null, new object[] { templateNamespace, SAFE_GUARD }, null, null); templater = (RazorTemplater)handle.Unwrap(); clientSponsor.Register(templater); }
/// <summary> /// Create an instance of the type. /// </summary> /// <param name="fullyQualifiedName">The string representing the fully qualified name and path to this module.</param> /// <param name="fullName">The fully qualified name of the System.Type, including the namespace of the System.Type but not the assembly.</param> /// <returns>The instantiated type.</returns> public static object CreateInstanceFrom(string fullyQualifiedName, string fullName) { // Make sure the page reference exists. if (fullyQualifiedName == null) { throw new ArgumentNullException("fullyQualifiedName"); } if (fullName == null) { throw new ArgumentNullException("fullName"); } ObjectHandle handle = Activator.CreateInstanceFrom(fullyQualifiedName, fullName); // Unwrap the new domain instance into a reference in // this domain and use it to execute the untrusted code. return(handle.Unwrap()); }
/// <summary> /// Create an instance of the type. /// </summary> /// <param name="assemblyName">The assembly given the long form of its name.</param> /// <param name="typeName">The namespace and type.</param> /// <returns>The instantiated type.</returns> public static object CreateInstance(string assemblyName, string typeName) { // Make sure the page reference exists. if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } if (typeName == null) { throw new ArgumentNullException("typeName"); } ObjectHandle handle = Activator.CreateInstance(assemblyName, typeName); // Unwrap the new domain instance into a reference in // this domain and use it to execute the untrusted code. return(handle.Unwrap()); }
static void Main() { // Hook up the event handler Thread.GetDomain().AssemblyResolve += new ResolveEventHandler(App.TypeResolveHandler); // Find a type that should be in our assembly but isn't ObjectHandle oh = Activator.CreateInstance("DynamicAssem", "ANonExistentType"); Type mt = oh.Unwrap().GetType(); // Construct an instance of a type Object objInstance = Activator.CreateInstance(mt); // Find a method in this type and call it on this object MethodInfo mi = mt.GetMethod("SimpleMethod"); mi.Invoke(objInstance, null); }
/// <summary> /// Creates an instance of the type whose name is specified, using the named /// assembly and the constructor that best matches the specified parameters. /// </summary> /// <param name="assembly">The name of the assembly where the type named typeName /// is sought. If assemblyName is a null reference, /// the executing assembly is searched. </param> /// <param name="classname">The name of the preferred type. </param> /// <param name="args">An array of arguments that match in number, order, and /// type the parameters of the constructor to invoke.</param> /// <returns>A reference to the newly created instance.</returns> public static object CreateObject(string assembly, string classname, object[] args) { try { #if !NETCORE ObjectHandle objHandle = null; objHandle = Activator.CreateInstance( assembly, // name of assembly classname, // fully qualified class name false, // class name is case-sensitive BindingFlags.Default, // no binding attributes null, // use default binder args, // arguments to constructor, null, // default culture null, // default activation attributes null // default security policy ); if (objHandle != null) { return(objHandle.Unwrap()); } #elif NETCORE //TODO: ALACHISOFT (Relection API has some changes in .Net Core thus code change was required) var obj = Activator.CreateInstance( assembly.GetType(), // type of assembly classname, // fully qualified class name false, // class name is case-sensitive BindingFlags.Default, // no binding attributes null, // use default binder args, // arguments to constructor, null, // default culture null, // default activation attributes null // default security policy ); return(obj); #endif } catch (Exception e) { Trace.error("Common.CreateObject()", e.ToString()); throw; } return(null); }
public static void Main(string[] args) { try { Console.WriteLine("The hash code of the default AppDomain is {0}.", AppDomain.CurrentDomain.GetHashCode()); Console.WriteLine(""); // Creates another AppDomain. AppDomain domain = AppDomain.CreateDomain("AnotherDomain", null, (AppDomainSetup)null); // Creates an instance of MyType defined in the assembly //called ObjectHandleAssembly. ObjectHandle obj = domain.CreateInstance("ObjectHandleAssembly", "MyType"); //FileNotFoundException // Unwrapps the proxy to the MyType object created in the other AppDomain. MyType testObj = (MyType)obj.Unwrap(); if (RemotingServices.IsTransparentProxy(testObj)) { Console.WriteLine("The unwrapped object is a proxy."); } else { Console.WriteLine("The unwrapped object is not a proxy!"); } Console.WriteLine(""); Console.Write("Calling a method on the object located in an AppDomain with the hash code "); Console.WriteLine(testObj.GetAppDomainHashCode()); } catch (Exception exc) { Console.WriteLine("error"); } finally { Console.ReadKey(true); } }