Inheritance: MarshalByRefObject, IObjectHandle
Exemplo n.º 1
0
    static void Main()
    {
        //<snippet2>
        // Create an instance of the StringBuilder type using
        // Activator.CreateInstance.
        Object o = Activator.CreateInstance(typeof(StringBuilder));

        // Append a string into the StringBuilder object and display the
        // StringBuilder.
        StringBuilder sb = (StringBuilder)o;

        sb.Append("Hello, there.");
        Console.WriteLine(sb);
        //</snippet2>

        //<snippet3>
        // Create an instance of the SomeType class that is defined in this
        // assembly.
        System.Runtime.Remoting.ObjectHandle oh =
            Activator.CreateInstanceFrom(Assembly.GetEntryAssembly().CodeBase,
                                         typeof(SomeType).FullName);

        // Call an instance method defined by the SomeType type using this object.
        SomeType st = (SomeType)oh.Unwrap();

        st.DoSomething(5);
        //</snippet3>
    }
Exemplo n.º 2
0
    public List <SpellCreationSegment> GetPattern(ISpellGrid grid)
    {
        System.Runtime.Remoting.ObjectHandle handle = System.Activator.CreateInstance(null, pattern);
        ISpellPattern spellPattern = handle.Unwrap() as ISpellPattern;

        return(spellPattern.CreateSpellSegs(grid, damageMod));
    }
Exemplo n.º 3
0
    IProjectory GetProjectory()
    {
        System.Runtime.Remoting.ObjectHandle handle = System.Activator.CreateInstance(null, projectoryString);
        IProjectory projectory = handle.Unwrap() as IProjectory;

        return(projectory);
    }
Exemplo n.º 4
0
        public void GetExceptionMessage(ObjectHandle exception, out string message, out string errorTypeName) {
            ContractUtils.RequiresNotNull(exception, "exception");
            var exceptionObj = exception.Unwrap() as Exception;
            ContractUtils.Requires(exceptionObj != null, "exception", "ObjectHandle must be to Exception object");

            _context.GetExceptionMessage(exceptionObj, out message, out errorTypeName);
        }
Exemplo n.º 5
0
        public string FormatException(ObjectHandle exception) {
            ContractUtils.RequiresNotNull(exception, "exception");
            var exceptionObj = exception.Unwrap() as Exception;
            ContractUtils.Requires(exceptionObj != null, "exception", "ObjectHandle must be to Exception object");

            return _context.FormatException(exceptionObj);
        }
Exemplo n.º 6
0
    public void ReadXml(XmlReader reader, World world)
    {
        //reader.ReadToDescendant("ConstructionJobs");
        int count = 0;
        // ONLY USE THIS FOR SINGLE THREADED LOADING!!!!!!!
        Assembly         assembly     = new StackTrace().GetFrames().Last().GetMethod().Module.Assembly;
        HashSet <string> jobTypesRead = new HashSet <string>();

        if (reader.ReadToDescendant("Job"))
        {
            // We have at least one job to read
            do
            { // Read it while there are more jobs to read
                string className = reader.GetAttribute("Class");
                System.Runtime.Remoting.ObjectHandle oh = Activator.CreateInstanceFrom(assembly.CodeBase, className);
                Job job = (Job)Convert.ChangeType(oh.Unwrap(), Type.GetType(className));

                if (jobTypesRead.Contains(className))
                {
                    job.ReadXml(reader, world, this);
                }
                else
                {
                    job.ReadXml(reader, world, this, true);
                }

                jobTypesRead.Add(className);
                count++;
            } while (reader.ReadToNextSibling("Job"));
        }
    }
Exemplo n.º 7
0
        public bool HandleException(ObjectHandle exception) {
            ContractUtils.RequiresNotNull(exception, "exception");
            var exceptionObj = exception.Unwrap() as Exception;
            ContractUtils.Requires(exceptionObj != null, "exception", "ObjectHandle must be to Exception object");

            return false;
        }
 public object Create(string appId, string appPath)
 {
     object obj2;
     try
     {
         if (appPath[0] == '.')
         {
             FileInfo info = new FileInfo(appPath);
             appPath = info.FullName;
         }
         if (!StringUtil.StringEndsWith(appPath, '\\'))
         {
             appPath = appPath + @"\";
         }
         ISAPIApplicationHost appHost = new ISAPIApplicationHost(appId, appPath, false);
         ISAPIRuntime o = (ISAPIRuntime) this._appManager.CreateObjectInternal(appId, typeof(ISAPIRuntime), appHost, false, null);
         o.StartProcessing();
         obj2 = new ObjectHandle(o);
     }
     catch (Exception)
     {
         throw;
     }
     return obj2;
 }
Exemplo n.º 9
0
        public IList<DynamicStackFrame> GetStackFrames(ObjectHandle exception) {
            ContractUtils.RequiresNotNull(exception, "exception");
            var exceptionObj = exception.Unwrap() as Exception;
            ContractUtils.Requires(exceptionObj != null, "exception", "ObjectHandle must be to Exception object");

            return _context.GetStackFrames(exceptionObj);
        }
Exemplo n.º 10
0
 public IronPythonTypeWrapper(ScriptEngine engine, string name, PythonType pythonType, ObjectHandle classHandle)
 {
     Name = name;
     PythonType = pythonType;
     _engine = engine;
     _classHandle = classHandle;
 }
Exemplo n.º 11
0
    static void Main()
    {
        // Construct a path to the current assembly.
        string assemblyPath = Environment.CurrentDirectory + "\\" +
                              typeof(MarshalableExample).Assembly.GetName().Name + ".exe";

        AppDomain ad = AppDomain.CreateDomain("MyDomain");

        System.Runtime.Remoting.ObjectHandle oh =
            ad.CreateInstanceFrom(assemblyPath, "MarshalableExample");

        object obj = oh.Unwrap();

        // Three ways to use the newly created object, depending on how
        // much is known about the type: Late bound, early bound through
        // a mutually known interface, or early binding of a known type.
        //
        obj.GetType().InvokeMember("Test",
                                   System.Reflection.BindingFlags.InvokeMethod,
                                   Type.DefaultBinder, obj, new object[] { "Hello" });

        ITest it = (ITest)obj;

        it.Test("Hi");

        MarshalableExample ex = (MarshalableExample)obj;

        ex.Test("Goodbye");
    }
Exemplo n.º 12
0
    private void PushPhase(string phaseID)
    {
        System.Runtime.Remoting.ObjectHandle handle = System.Activator.CreateInstance(_appProxyConfig.m_assemblyPrimary, phaseID);
        IPhase phase = handle.Unwrap() as IPhase;

        if (LoggingManager.Instance.Filter(LoggingManager.Domain.Phases))
        {
            Debug.Log("(AppManager) Entering phase: " + phaseID + " (" + _phases.Count + ")");
        }
        _phases.Add(phase);
        phase.Setup(this);
    }
Exemplo n.º 13
0
    public SpellCollisionEffect.SpellCollisionBehaviour GetOnSpellCollisionEffect()
    {
        if (onCollisionEffectName == "" || onCollisionEffectName == null)
        {
            return(DefaultSpellCollisionBehaviour);
        }

        System.Runtime.Remoting.ObjectHandle handle = System.Activator.CreateInstance(null, onCollisionEffectName);
        SpellCollisionEffect onCollision            = handle.Unwrap() as SpellCollisionEffect;

        return(onCollision.SpellCollisionEffectBehaviour());
    }
Exemplo n.º 14
0
    public OnHitEffect.DamageBehaviour GetOnHitEffect()
    {
        /// Debug.LogError(onHitEffectName);
        if (onHitEffectName == "" || onHitEffectName == null)
        {
            return(DefaultDamageBehaviour);
        }

        System.Runtime.Remoting.ObjectHandle handle = System.Activator.CreateInstance(null, onHitEffectName);
        OnHitEffect onHitEffect = handle.Unwrap() as OnHitEffect;

        return(onHitEffect.GetOnHitEffectBehaviour());
    }
Exemplo n.º 15
0
        void GotNewAppDomain(ObjectHandle oh)
        {
            Invariant.Assert(PresentationAppDomainManager.SaveAppDomain);

            // In stress situations or with a corrupt application store, ClickOnce may fail to return us
            // an AppDomain, without throwing an exception. This might also happen if something goes wrong
            // with ApplicationActivator's use of our custom AppDomainManager (Dev10.581515).
            if (oh != null)
            {
                AppDomain newDomain = (AppDomain)oh.Unwrap();
                if (newDomain != null)
                {
                    PresentationAppDomainManager.NewAppDomain = newDomain;
                    return;
                }
            }
            // Note that DocObjHost enables the unhandled exception page just before trying to run the
            // application, so this exception message should be displayed to the user (except if we are
            // trying direct activation, in which case the exception is caught and we fall back to the full
            // IPHM activation).
            throw new ApplicationException(SR.Get(SRID.AppActivationException));
        }
Exemplo n.º 16
0
        public void TryGetVariableGenericT_MultipleCases()
        {
            ScriptScopeDictionary global = new ScriptScopeDictionary();
            // Populate with some test data
            string[] key = { "test1", "test2", "test3" };
            int tExpectedVal1 = 1111;
            global[key[0]] = tExpectedVal1; // case 1

            // Get default scope with set values
            ScriptScope TestScope = _testEng.CreateScope(new ObjectDictionaryExpando(global));
            // out value;
            int value = -1;

            ObjectHandle objHVal = new ObjectHandle(value);

            // Case 1
            //int outV;
            Assert.IsTrue(TestScope.TryGetVariable<int>(key[0], out value));
            Assert.IsTrue(value == tExpectedVal1);

            // reset
            value = -1;
            // Case 2 - Not sure about this
            Assert.IsFalse(TestScope.TryGetVariable<int>(key[1], out value));
            Assert.IsTrue(value == 0);

            //@TODO - Add Case 3 - HOW CAN I TEST THIS CASE need more info.
        }
Exemplo n.º 17
0
 public override string FormatException(ObjectHandle exception)
 {
     return _engine.GetService<ExceptionOperations>().FormatException(exception);
 }
Exemplo n.º 18
0
 protected override string[] GetObjectMemberNames(ObjectHandle obj, string startsWith)
 {
     try {
         return FilterNames(_engine.Operations.GetMemberNames(obj), startsWith);
     } catch {
         // TODO: Log error?
         return new string[0];
     }
 }
Exemplo n.º 19
0
 protected void OutputResult(object result, ObjectHandle exception)
 {
     if (exception != null) {
         WriteException(exception);
     } else if (result != null) {
         ScopeForLastResult.SetVariable("_", result);
         WriteObject(result, _engine.Operations.Format(result));
     }
 }
Exemplo n.º 20
0
        private bool ExecuteTextInScopeWorker(string text, ScriptScope scope, SourceCodeKind kind, Action<ObjectHandle, ObjectHandle> completionFunction)
        {
            var source = _engine.CreateScriptSourceFromString(text, kind);
            var errors = new DlrErrorListener();
            var command = source.Compile(CompilerOptions, errors);
            if (command == null) {
                if (errors.Errors.Count > 0) {
                    WriteException(new ObjectHandle(errors.Errors[0]));
                }
                return false;
            }
            // Allow re-entrant execution.

            Dispatcher.BeginInvoke(new Action(() => {
                ObjectHandle result = null;
                ObjectHandle exception = null;
                try {
                    result = command.ExecuteAndWrap(scope, out exception);
                } catch (ThreadAbortException e) {
                    if (e.ExceptionState != null) {
                        exception = new ObjectHandle(e.ExceptionState);
                    } else {
                        exception = new ObjectHandle(e);
                    }
                    if ((Thread.CurrentThread.ThreadState & System.Threading.ThreadState.AbortRequested) != 0) {
                        Thread.ResetAbort();
                    }
                } catch (RemotingException) {
                    WriteLine("Communication with the remote process has been disconnected.");
                } catch (Exception e) {
                    exception = new ObjectHandle(e);
                }
                if (completionFunction != null) {
                    completionFunction(result, exception);
                }
            }));

            return true;
        }
Exemplo n.º 21
0
 /// <summary>
 /// Gets the overloads available for the provided remote object if it is invokable.
 /// </summary>
 public ICollection<OverloadDoc> GetOverloads(ObjectHandle value)
 {
     return _provider.GetOverloads(value.Unwrap());
 }
Exemplo n.º 22
0
 /// <summary>
 /// Gets the available members on the provided remote object.
 /// </summary>
 public ICollection<MemberDoc> GetMembers(ObjectHandle value)
 {
     return _provider.GetMembers(value.Unwrap());
 }
Exemplo n.º 23
0
        public override string FormatException(ObjectHandle exception)
        {
            if (_factory.IsDisconnected) {
                Restart();
            }

            return base.FormatException(exception);
        }
Exemplo n.º 24
0
 protected void WriteException(ObjectHandle exception)
 {
     WriteObject(exception, FormatException(exception));
 }
Exemplo n.º 25
0
        public void TryGetVariableAsHandle_MultipleCases()
        {
            ScriptScopeDictionary global = new ScriptScopeDictionary();
            // Populate with some test data
            string[] key = { "test1", "test2", "test3" };
            int tExpectedVal1 = 1111;
            global[key[0]] = tExpectedVal1; // case 1

            ScriptScope TestScope = _testEng.CreateScope(new ObjectDictionaryExpando(global));
            // out value;
            int value = -1;

            ObjectHandle objHVal = new ObjectHandle(value);

            // Case 1
            Assert.IsTrue(TestScope.TryGetVariableHandle(key[0], out objHVal));
            Assert.IsTrue((int)(objHVal.Unwrap()) == tExpectedVal1);

            // reset
            value = -1;
            objHVal = new ObjectHandle(value);
            // Case 2
            Assert.IsFalse(TestScope.TryGetVariableHandle(key[1], out objHVal));
            Assert.IsNull(objHVal);
        }
Exemplo n.º 26
0
        private void FinishExecution(ObjectHandle result, ObjectHandle exception, Action<bool, ObjectHandle> completionFunction)
        {
            _output.Flush();
            if (exception != null) {
                OutputResult(null, exception);
            }

            if (completionFunction != null) {
                completionFunction(exception == null, exception);
            }
        }
Exemplo n.º 27
0
        static internal ObjectHandle CreateInstance(String assemblyName, 
                                                    String typeName, 
                                                    bool ignoreCase,
                                                    BindingFlags bindingAttr, 
                                                    Binder binder,
                                                    Object[] args,
                                                    CultureInfo culture,
                                                    Object[] activationAttributes,
                                                    Evidence securityInfo,
                                                    ref StackCrawlMark stackMark)
        {
            Assembly assembly;
            if(assemblyName == null)
                assembly = Assembly.nGetExecutingAssembly(ref stackMark);
            else
                assembly = Assembly.InternalLoad(assemblyName, securityInfo, ref stackMark);

            Log(assembly != null, "CreateInstance:: ", "Loaded " + assembly.FullName, "Failed to Load: " + assemblyName);
            if(assembly == null) return null;

            Type t = assembly.GetTypeInternal(typeName, true, ignoreCase, false);
            
            Object o = Activator.CreateInstance(t,
                                                bindingAttr,
                                                binder,
                                                args,
                                                culture,
                                                activationAttributes);

            Log(o != null, "CreateInstance:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
            if(o == null)
                return null;
            else {
                ObjectHandle Handle = new ObjectHandle(o);
                return Handle;
            }
        }
Exemplo n.º 28
0
 public object Activator()
 {
     _instanceHandle = _engine.Operations.Invoke(_classHandle, new object[] {});
     _instance = _engine.Operations.Unwrap<object>(_instanceHandle);
     return _instance;
 }
Exemplo n.º 29
0
        /// <include file='doc\Activator.uex' path='docs/doc[@for="Activator.CreateInstanceFrom2"]/*' />
        static public ObjectHandle CreateInstanceFrom(String assemblyFile,
                                                      String typeName, 
                                                      bool ignoreCase,
                                                      BindingFlags bindingAttr, 
                                                      Binder binder,
                                                      Object[] args,
                                                      CultureInfo culture,
                                                      Object[] activationAttributes,
                                                      Evidence securityInfo)
                                               
        {
            Assembly assembly = Assembly.LoadFrom(assemblyFile, securityInfo);
            Type t = assembly.GetTypeInternal(typeName, true, ignoreCase, false);
            
            Object o = Activator.CreateInstance(t,
                                                bindingAttr,
                                                binder,
                                                args,
                                                culture,
                                                activationAttributes);

            Log(o != null, "CreateInstanceFrom:: ", "Created Instance of class " + typeName, "Failed to create instance of class " + typeName);
            if(o == null)
                return null;
            else {
                ObjectHandle Handle = new ObjectHandle(o);
                return Handle;
            }
        }
Exemplo n.º 30
0
 public ObjectHandle GetSetCommandDispatcher(ObjectHandle dispatcher) {
     var res = _context.GetSetCommandDispatcher((Action<Action>)dispatcher.Unwrap());
     if (res != null) {
         return new ObjectHandle(res);
     }
                 
     return null;
 }
Exemplo n.º 31
0
 public virtual string FormatException(ObjectHandle exception)
 {
     return exception.ToString();
 }
Exemplo n.º 32
0
 protected virtual string[] GetObjectMemberNames(ObjectHandle obj, string startsWith)
 {
     return ArrayUtils.EmptyStrings;
 }
Exemplo n.º 33
0
        public void StartApplication(String appId, String appPath, out Object runtimeInterface)
        {
            try {
                if (appId == null)
                    throw new ArgumentNullException("appId");
                if (appPath == null)
                    throw new ArgumentNullException("appPath");

                Debug.Assert(_functions != null, "_functions != null");

                runtimeInterface = null;

                PipelineRuntime runtime = null;

                //
                //  Fill app a Dictionary with 'binding rules' -- name value string pairs
                //  for app domain creation
                //

                // 


                if (appPath[0] == '.') {
                    System.IO.FileInfo file = new System.IO.FileInfo(appPath);
                    appPath = file.FullName;
                }

                if (!StringUtil.StringEndsWith(appPath, '\\')) {
                    appPath = appPath + "\\";
                }

                // Create new app host of a consistent type
                IApplicationHost appHost = CreateAppHost(appId, appPath);


                //
                // Create the AppDomain and a registered object in it
                //
                LockableAppDomainContext ac = _appManager.GetLockableAppDomainContext(appId);

                lock (ac) {
                    // #1 WOS 1690249: ASP.Net v2.0: ASP.NET stress: 2nd chance exception: Attempted to access an unloaded AppDomain.
                    // if an old AppDomain exists with a PipelineRuntime, remove it from
                    // AppManager._appDomains so that a new AppDomain will be created
                    // #2 WOS 1977425: ASP.NET apps continue recycling after touching machine.config once - this used to initiate shutdown,
                    // but that can cause us to recycle the app repeatedly if we initiate shutdown before IIS initiates shutdown of the
                    // previous app.

                    _appManager.RemoveFromTableIfRuntimeExists(appId, typeof(PipelineRuntime));


                    // Preload (if required) the App Domain before letting the first request to be processed
                    PreloadApplicationIfRequired(appId, appHost, null, ac);

                    try {
                        runtime = (PipelineRuntime)_appManager.CreateObjectInternal(
                            appId,
                            typeof(PipelineRuntime),
                            appHost,
                            true /* failIfExists */,
                            null /* default */ );
                    }
                    catch (AppDomainUnloadedException) {
                        // munch it so we can retry again
                    }

                    if (null != runtime) {
                        runtime.SetThisAppDomainsIsapiAppId(appId);
                        runtime.StartProcessing();
                        runtimeInterface = new ObjectHandle(runtime);
                    }
                }
            }
            catch (Exception e) {
                using (new ProcessImpersonationContext()) {
                    Misc.ReportUnhandledException(e, new string[] {
                                              SR.GetString(SR.Failure_Start_Integrated_App)} );
                }
                throw;
            }
        }
Exemplo n.º 34
0
        public void GetVariableGenericT_ExistingVarGenericTypeCheck()
        {
            ScriptScopeDictionary global = new ScriptScopeDictionary();
            // Populate with some test data
            string[] key = { "test1", "test2", "test3" };
            int tExpectedVal1 = 1111;
            global[key[0]] = tExpectedVal1; // case 1
            int tExpectedVal2 = 2222;
            global[key[1]] = tExpectedVal2;

            ScriptScope TestScope = _testEng.CreateScope(new ObjectDictionaryExpando(global));
            // ScriptScope TestNullScope = null;
            object obj = new object();
            // What is ObjectHandle used for?
            ObjectHandle oResult = new ObjectHandle(obj);
            int val = TestScope.GetVariable<int>(key[0]);

            // Check return type and value
            Assert.IsTrue(val.GetType() == tExpectedVal1.GetType());
            Assert.IsTrue(val == tExpectedVal1);
        }