Beispiel #1
0
        /// <summary>
        /// Gets the full typename of an object
        /// In the case of .NET objects it is in the form 'Type.Namespace'.'Type.Name'
        /// In the case of COM objects it is in the form 'TypeLibName'.'TypeInfoName'
        /// </summary>
        /// <param name="obj">The object to get the full typename of</param>
        /// <returns>The full type name</returns>
        private string GetObjectFullTypeName(object obj)
        {
            if (Marshal.IsComObject(obj))
            {
                IDispatch dispatch = (IDispatch)obj;
                if (dispatch.GetTypeInfoCount() != 1)
                {
                    throw new Exception("Failed to get runtime type information");
                }

                ITypeInfo typeInfo = dispatch.GetTypeInfo(0, 0);

                ITypeLib typeLib;
                int      index;
                typeInfo.GetContainingTypeLib(out typeLib, out index);

                string typeLibName  = Marshal.GetTypeLibName(typeLib);
                string typeInfoName = Marshal.GetTypeInfoName(typeInfo);

                return(typeLibName + "." + typeInfoName);
            }
            else
            {
                Type typeObject = obj.GetType();
                return(typeObject.Namespace + "." + typeObject.Name);
            }
        }
        /// <summary>
        /// Tries to get the DISPID for the requested member name.
        /// </summary>
        /// <param name="dispatch">An object that implements IDispatch.</param>
        /// <param name="name">The name of a member to lookup.</param>
        /// <param name="dispId">If the method returns true, this holds the DISPID on output.
        /// If the method returns false, this value should be ignored.</param>
        /// <returns>True if the member was found and resolved to a DISPID.  False otherwise.</returns>
        private static bool tryGetDispId(IDispatch dispatch, string name, out int dispId)
        {
            requireReference(dispatch, "dispatch");
            requireReference(name, "name");

            bool result = false;

            // Members names aren't usually culture-aware for IDispatch, so we might as well
            // pass the default locale instead of looking up the current thread's LCID each time
            // (via CultureInfo.CurrentCulture.LCID).
            Guid iidNull = Guid.Empty;
            int  hr      = dispatch.GetIDsOfNames(ref iidNull, ref name, 1, LOCALE_SYSTEM_DEFAULT, out dispId);

            const int DISP_E_UNKNOWNNAME = unchecked ((int)0x80020006); //From WinError.h
            const int DISPID_UNKNOWN     = -1;                          //From OAIdl.idl

            if (hr == S_OK)
            {
                result = true;
            }
            else if (hr == DISP_E_UNKNOWNNAME && dispId == DISPID_UNKNOWN)
            {
                // This is the only supported "error" case because it means IDispatch
                // is saying it doesn't know the member we asked about.
                result = false;
            }
            else
            {
                // The other documented result codes are all errors.
                Marshal.ThrowExceptionForHR(hr);
            }

            return(result);
        }
Beispiel #3
0
        /// <summary>
        /// get the guid from type lib there is the type defined
        /// </summary>
        /// <param name="comProxy"></param>
        /// <returns></returns>
        private static Guid GetParentLibraryGuid(object comProxy)
        {
            IDispatch dispatcher = comProxy as IDispatch;

            COMTypes.ITypeInfo typeInfo      = dispatcher.GetTypeInfo(0, 0);
            COMTypes.ITypeLib  parentTypeLib = null;

            Guid typeGuid   = GetTypeGuid(typeInfo);
            Guid parentGuid = Guid.Empty;

            if (!_hostCache.TryGetValue(typeGuid, out parentGuid))
            {
                int i = 0;
                typeInfo.GetContainingTypeLib(out parentTypeLib, out i);

                IntPtr attributesPointer = IntPtr.Zero;
                parentTypeLib.GetLibAttr(out attributesPointer);

                COMTypes.TYPELIBATTR attributes = (COMTypes.TYPELIBATTR)Marshal.PtrToStructure(attributesPointer, typeof(COMTypes.TYPELIBATTR));
                parentGuid = attributes.guid;
                parentTypeLib.ReleaseTLibAttr(attributesPointer);
                Marshal.ReleaseComObject(parentTypeLib);

                _hostCache.Add(typeGuid, parentGuid);
            }

            Marshal.ReleaseComObject(typeInfo);

            return(parentGuid);
        }
Beispiel #4
0
        internal static ComTypeInfo GetDispatchTypeInfo(object comObject)
        {
            ComTypeInfo result = null;
            IDispatch   disp   = comObject as IDispatch;

            if (disp != null)
            {
                COM.ITypeInfo typeinfo = null;
                disp.GetTypeInfo(0, 0, out typeinfo);
                if (typeinfo != null)
                {
                    COM.TYPEATTR typeattr = GetTypeAttr(typeinfo);

                    if ((typeattr.typekind == COM.TYPEKIND.TKIND_INTERFACE))
                    {
                        //We have typeinfo for custom interface. Get typeinfo for Dispatch interface.
                        typeinfo = GetDispatchTypeInfoFromCustomInterfaceTypeInfo(typeinfo);
                    }

                    if ((typeattr.typekind == COM.TYPEKIND.TKIND_COCLASS))
                    {
                        //We have typeinfo for the COClass.  Find the default interface and get typeinfo for default interface.
                        typeinfo = GetDispatchTypeInfoFromCoClassTypeInfo(typeinfo);
                    }
                    result = new ComTypeInfo(typeinfo);
                }
            }
            return(result);
        }
Beispiel #5
0
        private string GetComObjectFullyQualifiedName(object o)
        {
            if (o == null)
            {
                throw new ArgumentNullException();
            }

            if (Marshal.IsComObject(o))
            {
                IDispatch dispatch = o as IDispatch;
                if (dispatch != null)
                {
                    ITypeLib  typeLib  = null;
                    ITypeInfo typeInfo = dispatch.GetTypeInfo(0, 0);
                    int       index    = 0;
                    typeInfo.GetContainingTypeLib(out typeLib, out index);

                    string typeLibName  = Marshal.GetTypeLibName(typeLib);
                    string typeInfoName = Marshal.GetTypeInfoName(typeInfo);

                    return(String.Format("{0}.{1}", typeLibName, typeInfoName));
                }
            }

            return(o.GetType().FullName);
        }
Beispiel #6
0
        public static IEnumerable <object> ToCollection(object o)
        {
            IDispatch dispatchObject = null;

            dispatchObject = o as IDispatch;

            if (dispatchObject == null)
            {
                throw new ArgumentException("Object is not IDispatch");
            }

            try
            {
                int           len = Convert.ToInt32(GetProperty(dispatchObject, "length"));
                List <object> res = new List <object>(len);

                for (int i = 0; i < len; i++)
                {
                    res.Add(GetProperty(dispatchObject, i.ToString()));
                }
                return(res);
            }
            finally
            {
                Marshal.ReleaseComObject(dispatchObject);
            }
        }
Beispiel #7
0
        public unsafe void IDispatch_Invoke_Invoke_Success()
        {
            using var image = new Bitmap(16, 32);
            IPictureDisp picture  = SubAxHost.GetIPictureDispFromPicture(image);
            IDispatch    dispatch = (IDispatch)picture;

            Guid    riid       = Guid.Empty;
            var     dispParams = new DISPPARAMS();
            var     varResult  = new object[1];
            var     excepInfo  = new EXCEPINFO();
            uint    argErr     = 0;
            HRESULT hr         = dispatch.Invoke(
                (DispatchID)4,
                &riid,
                Kernel32.GetThreadLocale(),
                DISPATCH.PROPERTYGET,
                &dispParams,
                varResult,
                &excepInfo,
                &argErr
                );

            Assert.Equal(HRESULT.S_OK, hr);
            Assert.Equal(16, GdiHelper.HimetricToPixelY((int)varResult[0]));
            Assert.Equal(0u, argErr);
        }
Beispiel #8
0
        public unsafe void ITypeInfo_GetNames_Invoke_Success()
        {
            using var image = new Bitmap(16, 32);
            IPictureDisp picture  = MockAxHost.GetIPictureDispFromPicture(image);
            IDispatch    dispatch = (IDispatch)picture;
            ITypeInfo    typeInfo;
            HRESULT      hr = dispatch.GetTypeInfo(0, Kernel32.GetThreadLocale(), out typeInfo);

            using var typeInfoReleaser = new ComRefReleaser(typeInfo);
            Assert.Equal(HRESULT.S_OK, hr);

            BSTR *rgszNames = stackalloc BSTR[2];

            rgszNames[0] = new BSTR("Name1");
            rgszNames[1] = new BSTR("Name2");
            uint cNames = 0;

            hr = typeInfo.GetNames((DispatchID)4, rgszNames, 2u, &cNames);
            Assert.Equal(HRESULT.S_OK, hr);
            Assert.Equal("Width", rgszNames[0].String.ToString());
            Assert.Equal("Name2", rgszNames[1].String.ToString());
            Assert.Equal(1u, cNames);

            rgszNames[0].Dispose();
            rgszNames[1].Dispose();
        }
Beispiel #9
0
 public void Play()
 {
     if (!supportedDevice)
     {
         return;
     }
     if (dispatch == null)
     {
         dispatch = new MainDispatch();
         dispatch.Dispatch(Update, true);
     }
     if (preview == null)
     {
         int    width, height, rate = (int)device.GetFramerate(camera);
         string name = WebCamTexture.devices[camera].name;
         device.GetPreviewResolution(camera, out width, out height);
         rate    = rate == 0 ? 30 : rate;
         preview = width == 0 ?  new WebCamTexture(name) : new WebCamTexture(name, width, height, rate);
     }
     #if NATCAM_EXTENDED
     SetDetection(OnMetadata != null);
     #endif
     firstFrame = true;
     preview.Play();
 }
        /// <summary>
        /// Gets a Type that can be used with reflection.
        /// </summary>
        /// <param name="dispatch">An object that implements IDispatch.</param>
        /// <param name="throwIfNotFound">Whether an exception should be thrown if a Type can't be obtained.</param>
        /// <returns>A .NET Type that can be used with reflection.</returns>
        private static Type getType(IDispatch dispatch, bool throwIfNotFound)
        {
            requireReference(dispatch, "dispatch");

            Type result = null;
            int  typeInfoCount;
            int  hr = dispatch.GetTypeInfoCount(out typeInfoCount);

            if (hr == S_OK && typeInfoCount > 0)
            {
                // Type info isn't usually culture-aware for IDispatch, so we might as well pass
                // the default locale instead of looking up the current thread's LCID each time
                // (via CultureInfo.CurrentCulture.LCID).
                dispatch.GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, out result);
            }

            if (result == null && throwIfNotFound)
            {
                // If the GetTypeInfoCount called failed, throw an exception for that.
                Marshal.ThrowExceptionForHR(hr);

                // Otherwise, throw the same exception that Type.GetType would throw.
                throw new TypeLoadException();
            }

            return(result);
        }
Beispiel #11
0
        public unsafe void ITypeInfo_Invoke_Invoke_Success()
        {
            using var image = new Bitmap(16, 32);
            IPictureDisp picture  = MockAxHost.GetIPictureDispFromPicture(image);
            IDispatch    dispatch = (IDispatch)picture;
            ITypeInfo    typeInfo;
            HRESULT      hr = dispatch.GetTypeInfo(0, Kernel32.GetThreadLocale(), out typeInfo);

            using var typeInfoReleaser = new ComRefReleaser(typeInfo);
            Assert.Equal(HRESULT.S_OK, hr);

            var  dispParams = new DISPPARAMS();
            var  varResult  = new object[1];
            var  excepInfo  = new EXCEPINFO();
            uint argErr     = 0;

            hr = typeInfo.Invoke(
                picture,
                (DispatchID)4,
                DISPATCH.PROPERTYGET,
                &dispParams,
                varResult,
                &excepInfo,
                &argErr);
            Assert.Equal(HRESULT.DISP_E_MEMBERNOTFOUND, hr);
            Assert.Null(varResult[0]);
            Assert.Equal(0u, argErr);
        }
Beispiel #12
0
        public static void SetProperty(this IDispatch dispatch, string name, params object[] args)
        {
            if (args.Length < 1)
            {
                throw new ArgumentException("Invalid argument count", nameof(args));
            }

            var dispid = dispatch.GetDispIDForName(name);

            using (var argVariantArrayBlock = new CoTaskMemVariantArgsBlock(args))
            {
                using (var namedArgDispidBlock = new CoTaskMemBlock(sizeof(int)))
                {
                    Marshal.WriteInt32(namedArgDispidBlock.Addr, SpecialDispIDs.PropertyPut);
                    var dispArgs = new DISPPARAMS {
                        cArgs = args.Length, rgvarg = argVariantArrayBlock.Addr, cNamedArgs = 1, rgdispidNamedArgs = namedArgDispidBlock.Addr
                    };

                    var result = dispatch.Invoke(dispid, ref iid, 0, DispatchFlags.PropertyPut | DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out _, out _);
                    if (result == HResult.DISP_E_MEMBERNOTFOUND)
                    {
                        // VBScript objects can be finicky about property-put dispatch flags

                        result = dispatch.Invoke(dispid, iid, 0, DispatchFlags.PropertyPut, ref dispArgs, IntPtr.Zero, out _, out _);
                        if (result == HResult.DISP_E_MEMBERNOTFOUND)
                        {
                            result = dispatch.Invoke(dispid, iid, 0, DispatchFlags.PropertyPutRef, ref dispArgs, IntPtr.Zero, out _, out _);
                        }
                    }

                    HResult.Check(result);
                }
            }
        }
Beispiel #13
0
        public unsafe void ITypeInfo_GetContainingTypeLib_Invoke_Success()
        {
            using var image = new Bitmap(16, 32);
            IPictureDisp picture  = MockAxHost.GetIPictureDispFromPicture(image);
            IDispatch    dispatch = (IDispatch)picture;
            ITypeInfo    typeInfo;
            HRESULT      hr = dispatch.GetTypeInfo(0, Kernel32.GetThreadLocale(), out typeInfo);

            using var typeInfoReleaser = new ComRefReleaser(typeInfo);
            Assert.Equal(HRESULT.S_OK, hr);

            IntPtr typeLib = (IntPtr)int.MaxValue;
            uint   index   = uint.MaxValue;

            hr = typeInfo.GetContainingTypeLib(&typeLib, &index);
            try
            {
                Assert.Equal(HRESULT.S_OK, hr);
                Assert.NotEqual(IntPtr.Zero, typeLib);
                Assert.NotEqual(0u, index);
            }
            finally
            {
                Runtime.InteropServices.Marshal.Release(typeLib);
            }
        }
Beispiel #14
0
        /// <summary>
        /// Look for typeinfo using IDispatch.GetTypeInfo
        /// </summary>
        /// <param name="dispatch"></param>
        /// <param name="throwIfMissingExpectedTypeInfo">
        /// Some COM objects just dont expose typeinfo. In these cases, this method will return null.
        /// Some COM objects do intend to expose typeinfo, but may not be able to do so if the type-library is not properly 
        /// registered. This will be considered as acceptable or as an error condition depending on throwIfMissingExpectedTypeInfo</param>
        /// <returns></returns>
        internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch, bool throwIfMissingExpectedTypeInfo) {
            uint typeCount;
            int hresult = dispatch.TryGetTypeInfoCount(out typeCount);
            Marshal.ThrowExceptionForHR(hresult);
            Debug.Assert(typeCount <= 1);
            if (typeCount == 0) {
                return null;
            }

            IntPtr typeInfoPtr = IntPtr.Zero;

            hresult = dispatch.TryGetTypeInfo(0, 0, out typeInfoPtr);
            if (!ComHresults.IsSuccess(hresult)) {
                CheckIfMissingTypeInfoIsExpected(hresult, throwIfMissingExpectedTypeInfo);
                return null;
            }
            if (typeInfoPtr == IntPtr.Zero) { // be defensive against components that return IntPtr.Zero
                if (throwIfMissingExpectedTypeInfo) {
                    Marshal.ThrowExceptionForHR(ComHresults.E_FAIL);
                }
                return null;
            }

            ComTypes.ITypeInfo typeInfo = null;
            try {
                typeInfo = Marshal.GetObjectForIUnknown(typeInfoPtr) as ComTypes.ITypeInfo;
            } finally {
                Marshal.Release(typeInfoPtr);
            }

            return typeInfo;
        }
 public void setup()
 {
     _dispatcher = Substitute.For<IDispatch<object>>();
     _queue = new InMemoryWorkQueue<object>();
     _subject = new DirectWorkerPool<object>();
     _subject.SetSource(_dispatcher, _queue);
 }
Beispiel #16
0
        internal static Type GetManagedType(object ob, Type t)
        {
            if (ob == null)
            {
                return(t);
            }

            if (!Marshal.IsComObject(ob))
            {
                return(t);
            }

            IDispatch disp = GetIDispatch(ob);

            if (disp == null)
            {
                return(t);
            }

            ITypeInfo ti = GetTypeInfo(disp);

            if (ti == null)
            {
                return(t);
            }

            Type managedType = GetCOMObjectType(ti);

            if (managedType == null)
            {
                return(t);
            }

            return(managedType);
        }
Beispiel #17
0
        public unsafe void ITypeInfo_GetVarDesc_Invoke_Success()
        {
            using var image = new Bitmap(16, 32);
            IPictureDisp picture  = MockAxHost.GetIPictureDispFromPicture(image);
            IDispatch    dispatch = (IDispatch)picture;
            ITypeInfo    typeInfo;
            HRESULT      hr = dispatch.GetTypeInfo(0, Kernel32.GetThreadLocale(), out typeInfo);

            using var typeInfoReleaser = new ComRefReleaser(typeInfo);
            Assert.Equal(HRESULT.S_OK, hr);

            VARDESC *pVarDesc = null;

            try
            {
                hr = typeInfo.GetVarDesc(3, &pVarDesc);
                Assert.Equal(HRESULT.S_OK, hr);
                Assert.Equal((DispatchID)4, pVarDesc->memid);
                Assert.Equal(IntPtr.Zero, pVarDesc->lpstrSchema);
                Assert.Equal(IntPtr.Zero, pVarDesc->unionMember);
                Assert.Equal(VARENUM.USERDEFINED, pVarDesc->elemdescVar.tdesc.vt);
                Assert.NotEqual(IntPtr.Zero, pVarDesc->elemdescVar.tdesc.union.lpadesc);
                Assert.Equal(IntPtr.Zero, pVarDesc->elemdescVar.paramdesc.pparamdescex);
                Assert.Equal(PARAMFLAG.NONE, pVarDesc->elemdescVar.paramdesc.wParamFlags);
                Assert.Equal(VARFLAGS.FREADONLY, pVarDesc->wVarFlags);
                Assert.Equal(VARKIND.DISPATCH, pVarDesc->varkind);
            }
            finally
            {
                typeInfo.ReleaseVarDesc(pVarDesc);
            }
        }
        public static Type GetInteropType(this System.Object o)
        {
            if (o == null)
            {
                throw new ArgumentNullException();
            }

            if (Marshal.IsComObject(o))
            {
                IDispatch dispatch = o as IDispatch;
                if (dispatch != null)
                {
                    ITypeLib  typeLib  = null;
                    ITypeInfo typeInfo = dispatch.GetTypeInfo(0, 0);
                    int       index    = 0;
                    typeInfo.GetContainingTypeLib(out typeLib, out index);

                    string typeLibName  = Marshal.GetTypeLibName(typeLib);
                    string typeInfoName = Marshal.GetTypeInfoName(typeInfo);
                    string typeFullName = String.Format("{0}.{1}", typeLibName, typeInfoName);

                    System.Reflection.Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
                    System.Reflection.Assembly   assembly   = assemblies.FirstOrDefault(x => x.GetType(typeFullName) != null);

                    if (assembly != null)
                    {
                        return(assembly.GetType(typeFullName));
                    }
                }
            }

            return(o.GetType());
        }
        /// <summary>
        /// Gets the TypeName for objects implementing IDispatch.
        /// </summary>
        /// <param name="obj">The object for which to get the TypeName</param>
        /// <returns>String</returns>
        public static string GetIDispatchTypeName(IDispatch obj)
        {
            ITypeInfo t;

            obj.GetTypeInfo(0, 0, out t);

            return(Marshal.GetTypeInfoName(t));
        }
 private void Control_VisibleChanged(object sender, EventArgs e)
 {
     _site = GetClientSiteDispatch(this);
     if (_site != null && !_timer.Enabled)
     {
         _timer.Start();
     }
 }
        /// <summary>
        /// Gets the TypeName for objects implementing IDispatch.
        /// </summary>
        /// <param name="obj">The object for which to get the TypeName</param>
        /// <returns>String</returns>
        public static string GetIDispatchTypeName(IDispatch obj)
        {
            ITypeInfo t;

            obj.GetTypeInfo(0, 0, out t);

            return Marshal.GetTypeInfoName(t);
        }
Beispiel #22
0
        public static int InvokePropertySet(this IDispatch dispatch, int dispid, object value)
        {
            int hr = NativeMethods.S_OK;

            var  guid       = Guid.Empty;
            var  lcid       = NativeMethods.LOCALE_SYSTEM_DEFAULT;
            var  flags      = System.Runtime.InteropServices.ComTypes.INVOKEKIND.INVOKE_PROPERTYPUT;
            var  pExcepInfo = default(System.Runtime.InteropServices.ComTypes.EXCEPINFO);
            uint pArgErr    = 0;

            Variant       pVarResult = default(Variant);
            VariantArgPtr va         = new VariantArgPtr(1);

            var dp = new System.Runtime.InteropServices.ComTypes.DISPPARAMS()
            {
                cArgs             = va.Count,
                rgvarg            = va,
                cNamedArgs        = 1,
                rgdispidNamedArgs = Marshal.AllocCoTaskMem(Marshal.SizeOf(typeof(int)))
            };

            Marshal.WriteInt32(dp.rgdispidNamedArgs, (int)NativeMethods.DISPID_PROPERTYPUT);

            if (value is VariantWrapper)
            {
                Variant variant = new Variant((VariantWrapper)value);
                Marshal.StructureToPtr(variant, va[0], false);
            }
            else
            {
                Marshal.GetNativeVariantForObject(value, va[0]);
            }

            try
            {
                hr = dispatch.Invoke(
                    dispid,
                    ref guid,
                    lcid,
                    flags,
                    ref dp,
                    out pVarResult,
                    ref pExcepInfo,
                    out pArgErr
                    );
            }
            catch
            {
                GlobalExceptionHandler.HandleException();
            }
            finally
            {
                Marshal.FreeCoTaskMem(dp.rgdispidNamedArgs);
                va.Dispose();
            }

            return(hr);
        }
Beispiel #23
0
 public void once(string eventType, IDispatch listener)
 {
     LambdaListener list = data =>
     {
         removeListener(eventType, listener);
         applyIDispatch(listener, data);
     };
     on(eventType, list, listener);
 }
Beispiel #24
0
        private void InitializeRunner(string pattern, SearchOptions options)
        {
            if (options == SearchOptions.Unknown)
                options = SelectTheBestOption(pattern);

            IPreProcess preProcess = new PreProcessFactory().GetInstance(options);
            IProcessText processText = new ProcessTextFactory().GetInstance(options);
            _searchRunner = new SearchDispatch(processText, preProcess, pattern);
        }
Beispiel #25
0
        /// <summary>
        /// Look for typeinfo using IDispatch.GetTypeInfo.
        /// </summary>
        /// <param name="dispatch">IDispatch object</param>
        /// <remarks>
        /// Some COM objects just dont expose typeinfo. In these cases, this method will return null.
        /// Some COM objects do intend to expose typeinfo, but may not be able to do so if the type-library is not properly
        /// registered. This will be considered as acceptable or as an error condition depending on throwIfMissingExpectedTypeInfo
        /// </remarks>
        /// <returns>Type info</returns>
        internal static ComTypes.ITypeInfo GetITypeInfoFromIDispatch(IDispatch dispatch)
        {
            int hresult = dispatch.TryGetTypeInfoCount(out uint typeCount);

            if (hresult == ComHresults.E_NOTIMPL || hresult == ComHresults.E_NOINTERFACE)
            {
                // Allow the dynamic binding to continue using the original binder.
                return(null);
            }
            else
            {
                Marshal.ThrowExceptionForHR(hresult);
            }

            Debug.Assert(typeCount <= 1);
            if (typeCount == 0)
            {
                return(null);
            }

            IntPtr typeInfoPtr;

            hresult = dispatch.TryGetTypeInfo(0, 0, out typeInfoPtr);
            if (!ComHresults.IsSuccess(hresult))
            {
                // Word.Basic always returns this because of an incorrect implementation of IDispatch.GetTypeInfo
                // Any implementation that returns E_NOINTERFACE is likely to do so in all environments
                if (hresult == ComHresults.E_NOINTERFACE)
                {
                    return(null);
                }

                // This assert is potentially over-restrictive since COM components can behave in quite unexpected ways.
                // However, asserting the common expected cases ensures that we find out about the unexpected scenarios, and
                // can investigate the scenarios to ensure that there is no bug in our own code.
                Debug.Assert(hresult == ComHresults.TYPE_E_LIBNOTREGISTERED);

                Marshal.ThrowExceptionForHR(hresult);
            }

            if (typeInfoPtr == IntPtr.Zero)
            {
                Marshal.ThrowExceptionForHR(ComHresults.E_FAIL);
            }

            ComTypes.ITypeInfo typeInfo = null;
            try
            {
                typeInfo = Marshal.GetObjectForIUnknown(typeInfoPtr) as ComTypes.ITypeInfo;
            }
            finally
            {
                Marshal.Release(typeInfoPtr);
            }

            return(typeInfo);
        }
        public ComTypeInfo FromIDispatch(IDispatch dispatch)
        {
            if (dispatch == null)
            {
                return(null);
            }

            return(FromITypeInfo(dispatch.GetTypeInfo()));
        }
Beispiel #27
0
        public void start()
        {
            dispatch = ServiceManager.get<IDispatch>(netplug.Services.Dispatch);

            IConfiguration configuration = ServiceManager.get<IConfiguration>(netplug.Services.Configuration);
            this.rootDirectory = configuration.getProperty("documentRoot");

            serverTask = Task.Run(() => run());
        }
Beispiel #28
0
 // Async implementation
 /* public void get(string url, IDispatch success, IDispatch failure) */
 /* { */
 /*     var client = new WebClient(); */
 /*     var task   = client.DownloadStringTaskAsync(url); */
 /*     task.ContinueWith(t => */
 /*     { */
 /*         if (t.Exception != null) */
 /*         { */
 /*             t.Exception.Handle(e => { */
 /*                     // TODO: send meaningful parameters on failure */
 /*                     applyIDispatch(failure, "TODO"); */
 /*                     return true; */
 /*                 }); */
 /*         } */
 /*         else { */
 /*             applyIDispatch(success, t.Result); */
 /*         } */
 /*     }); */
 /* } */
 // Based on:
 // http://bytes.com/topic/c-sharp/answers/655563-handling-javascript-functions-closures-passed-into-c-function
 private void applyIDispatch(IDispatch func, string data)
 {
     func.GetType().InvokeMember(
             "",
             BindingFlags.InvokeMethod,
             null,
             func,
             new object[] { data });
 }
 public void setup()
 {
     _actionCalled = false;
     _dispatcher = Substitute.For<IDispatch<object>>();
     _dispatcher.MaximumInflight().Returns(1);
     _queue = Substitute.For<IWorkQueue<object>>();
     _subject = new ThreadedWorkerPool<object>("name", 1);
     _subject.SetSource(_dispatcher, _queue);
 }
Beispiel #30
0
        public void start()
        {
            dispatch = ServiceManager.get <IDispatch>(netplug.Services.Dispatch);

            IConfiguration configuration = ServiceManager.get <IConfiguration>(netplug.Services.Configuration);

            this.rootDirectory = configuration.getProperty("documentRoot");

            serverTask = Task.Run(() => run());
        }
        public static TContract GetProxy(IDispatch dispatcher)
        {
            var proxy = Create <TContract, ServiceProxy <TContract> >();

            var adjustableProxy = proxy as ServiceProxy <TContract>;

            adjustableProxy._dispatcher = dispatcher;

            return(proxy);
        }
Beispiel #32
0
        public static ComTypeLibrary FromIDispatch(IDispatch dispatch)
        {
            ITypeLib  typeLib  = null;
            ITypeInfo typeInfo = dispatch.GetTypeInfo();
            int       index    = 0;

            typeInfo.GetContainingTypeLib(out typeLib, out index);

            return(new ComTypeLibrary(typeLib));
        }
        public JqueryObject Next()
        {
            IDispatch jObj = InvokeMember <IDispatch>("next");

            if (jObj == null)
            {
                return(null);
            }
            return(new JqueryObject(jObj));
        }
        public JqueryObject Prev()
        {
            IDispatch jObj = InvokeMember <IDispatch>("prev");

            if (jObj == null)
            {
                return(null);
            }
            return(new JqueryObject(jObj));
        }
Beispiel #35
0
        public HTTPServer(IParser parser, IWebsite website, IError error, IResponse responseGenrate, IDispatch dispatch, IRequest request)
        {
            _parser  = parser;
            _website = website;
            _error   = error;

            _responseGenrate = responseGenrate;
            _dispatch        = dispatch;
            _request         = request;
        }
Beispiel #36
0
        static object GetProperty(IDispatch dispatchObject, string property)
        {
            int dispId = GetDispId(dispatchObject, property);

            if (dispId < 0)
            {
                return(null);
            }
            return(InvokePropertyGetter(dispatchObject, dispId));
        }
Beispiel #37
0
        private static object DynamicInvoke(IDispatch dispatch, int dispID, object[] parameters, ComTypes.INVOKEKIND invokeKind)
        {
            Array.Reverse(parameters);
            IntPtr paramsPtr = Marshal.AllocCoTaskMem(parameters.Length * SizeOfVariant);

            ComTypes.DISPPARAMS[] dispParams = new ComTypes.DISPPARAMS[1];
            if (IsSet(invokeKind))
            {
                dispParams[0].cNamedArgs        = 1;
                dispParams[0].rgdispidNamedArgs = Marshal.AllocCoTaskMem(SizeOfVariant);
                Marshal.Copy(new int[] { DISPID_PROPERTYPUT }, 0, dispParams[0].rgdispidNamedArgs, 1);
            }
            else
            {
                dispParams[0].cNamedArgs        = 0;
                dispParams[0].rgdispidNamedArgs = IntPtr.Zero;
            }
            dispParams[0].cArgs  = parameters.Length;
            dispParams[0].rgvarg = paramsPtr;
            try
            {
                int ptr = paramsPtr.ToInt32();
                foreach (object parameter in parameters)
                {
                    Marshal.GetNativeVariantForObject(parameter, new IntPtr(ptr));
                    ptr += SizeOfVariant;
                }
                Guid     guid   = Guid.Empty;
                object[] result = new object[] { null };
                Marshal.ThrowExceptionForHR(dispatch.Invoke(
                                                dispID,
                                                ref guid,
                                                CultureInfo.CurrentCulture.LCID,
                                                (short)invokeKind,
                                                dispParams,
                                                result,
                                                null,
                                                null));
                return(result[0]);
            }
            finally
            {
                if (dispParams[0].rgdispidNamedArgs != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(dispParams[0].rgdispidNamedArgs);
                    dispParams[0].rgdispidNamedArgs = IntPtr.Zero;
                }
                if (dispParams[0].rgvarg != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(dispParams[0].rgvarg);
                    dispParams[0].rgvarg = IntPtr.Zero;
                }
                paramsPtr = IntPtr.Zero;
            }
        }
Beispiel #38
0
        public static object InvokeScript(IHTMLDocument doc, string scriptName, object[] args)
        {
            object result = null;

            NativeMethods.tagDISPPARAMS tagDISPPARAMS = new NativeMethods.tagDISPPARAMS();
            tagDISPPARAMS.rgvarg = IntPtr.Zero;
            try
            {
                IDispatch dispatch = doc.Script as IDispatch;
                if (dispatch != null)
                {
                    Guid     empty     = Guid.Empty;
                    string[] rgszNames = new string[]
                    {
                        scriptName
                    };
                    int[] array = new int[]
                    {
                        -1
                    };
                    int iDsOfNames = dispatch.GetIDsOfNames(ref empty, rgszNames, 1, SafeNativeMethods.GetThreadLCID(), array);
                    if (SafeNativeMethods.Succeeded(iDsOfNames) && array[0] != -1)
                    {
                        if (args != null)
                        {
                            Array.Reverse(args);
                        }
                        tagDISPPARAMS.rgvarg            = ((args == null) ? IntPtr.Zero : SafeNativeMethods.ArrayToVARIANTVector(args));
                        tagDISPPARAMS.cArgs             = ((args == null) ? 0 : args.Length);
                        tagDISPPARAMS.rgdispidNamedArgs = IntPtr.Zero;
                        tagDISPPARAMS.cNamedArgs        = 0;
                        object[] array2 = new object[1];
                        if (dispatch.Invoke(array[0], ref empty, SafeNativeMethods.GetThreadLCID(), 1, tagDISPPARAMS, array2, new NativeMethods.tagEXCEPINFO(), null) == 0)
                        {
                            result = array2[0];
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                if (ClientUtils.IsSecurityOrCriticalException(ex))
                {
                    throw;
                }
            }
            finally
            {
                if (tagDISPPARAMS.rgvarg != IntPtr.Zero)
                {
                    SafeNativeMethods.FreeVARIANTVector(tagDISPPARAMS.rgvarg, args.Length);
                }
            }
            return(result);
        }
Beispiel #39
0
 public void setup()
 {
     _calls = 0;
     _subject = Dispatch<object>.CreateDefaultMultithreaded("test");
     _subject.Exceptions += (s,e) => {
         if (_calls++ < 2)
         {
             e.WorkItem.Cancel();
         }
         // if we don't cancel, the work item will be finished by default.
     };
 }
Beispiel #40
0
 public void get(string url, IDispatch success, IDispatch failure)
 {
     var client = new WebClient();
     try
     {
         var data = client.DownloadString(url);
         applyIDispatch(success, data);
     }
     catch (Exception e)
     {
         // TODO: send meaningful parameters on failure
         applyIDispatch(failure, "TODO");
     }
 }
		public void setup()
		{
			_messagingBase = Substitute.For<IMessagingBase>();
			_sleeper = Substitute.For<ISleepWrapper>();
			_dispatcher = Substitute.For<IDispatch<byte[]>>();
			_dispatcherFactory = Substitute.For<IDispatcherFactory>();
			_dispatcherFactory.Create(Arg.Any<IWorkQueue<byte[]>>(), Arg.Any<IWorkerPool<byte[]>>()).Returns(_dispatcher);

			_queueFactory = Substitute.For<IOutgoingQueueFactory>();

			_eventHook1 = Substitute.For<IEventHook>();
			_eventHook2 = Substitute.For<IEventHook>();
			ObjectFactory.Configure(map => {
				map.For<IEventHook>().Use(_eventHook1);
				map.For<IEventHook>().Use(_eventHook2);
			});

			_subject = new SenderNode(_messagingBase, _dispatcherFactory, _sleeper,_queueFactory);
		}
Beispiel #42
0
        public Handler(Server server, IDispatch dispatcher, TcpClient tcpClient)
            : base()
        {
            handlerUsage++;
            handlerId = (++handlerCounter);

            //Console.WriteLine("Started Handler: " + handlerId + " (usage: " + handlerUsage + ")");

            this.dispatcher = dispatcher;
            this.tcpClient = tcpClient;

            this.documentRoot = server.getRootDirectory();

            typeMap["html"] = "text/html; charset=utf-8";
            typeMap["txt"] = "text/text; charset=utf-8";
            typeMap["js"] = "text/javascript; charset=utf-8";
            typeMap["css"] = "text/css; charset=utf-8";
            typeMap["png"] = "image/png";
            typeMap["ico"] = "image/ico";
        }
Beispiel #43
0
 internal DispCallable(IDispatch dispatch, ComMethodDesc methodDesc) {
     _dispatch = dispatch;
     _methodDesc = methodDesc;
 }
Beispiel #44
0
 public void on(string eventType, IDispatch listener)
 {
     LambdaListener list = fromIDispatch(listener);
     on(eventType, list, listener);
 }
 public static DispCallable CreateDispCallable(IDispatch dispatch, ComMethodDesc method) {
     return new DispCallable(dispatch, method);
 }
Beispiel #46
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="from"></param>
 /// <returns></returns>
 IDispatch GetTo(IDispatch from)
 {
     if (from == _d1)
         return _d2;
     if (from == _d2)
         return _d1;
     throw new InvalidOperationException("from");
 }
Beispiel #47
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="from"></param>
 void Dispatch(IDispatch from)
 {
     if (this.Enable)
     {
         IDispatch to = GetTo(from);
         if (to != null)
         {
             //to.Write(from.ReceivedBytes);
         }
     }
 }
Beispiel #48
0
 public static extern int AccessibleObjectFromWindow(int hwnd, uint dwObjectID, byte[] riid, out IDispatch ptr);
Beispiel #49
0
 /// <summary>
 /// 
 /// </summary>
 private void RegisterEvents(IDispatch d )
 {
     //d.ReceivedEvent += new EventHandler(d_ReceivedEvent);
 }
Beispiel #50
0
 internal IDispatchComObject(IDispatch rcw)
     : base(rcw) {
     _dispatchObject = rcw;
 }
Beispiel #51
0
        public static IntPtr GetIdsOfNamedParameters(IDispatch dispatch, string[] names, int methodDispId, out GCHandle pinningHandle) {
            pinningHandle = GCHandle.Alloc(null, GCHandleType.Pinned);
            int[] dispIds = new int[names.Length];
            Guid empty = Guid.Empty;
            int hresult = dispatch.TryGetIDsOfNames(ref empty, names, (uint)names.Length, 0, dispIds);
            if (hresult < 0) {
                Marshal.ThrowExceptionForHR(hresult);
            }

            if (methodDispId != dispIds[0]) {
                throw Error.GetIDsOfNamesInvalid(names[0]);
            }

            int[] keywordArgDispIds = dispIds.RemoveFirst(); // Remove the dispId of the method name

            pinningHandle.Target = keywordArgDispIds;
            return Marshal.UnsafeAddrOfPinnedArrayElement(keywordArgDispIds, 0);
        }
Beispiel #52
0
        static int Invoke(IDispatch dispatch, int memberDispId, out object result) {
            Guid emtpyRiid = Guid.Empty;
            ComTypes.DISPPARAMS dispParams = new ComTypes.DISPPARAMS();
            ComTypes.EXCEPINFO excepInfo = new ComTypes.EXCEPINFO();
            uint argErr;
            int hresult = dispatch.TryInvoke(
                memberDispId,
                ref emtpyRiid,
                0,
                ComTypes.INVOKEKIND.INVOKE_PROPERTYGET,
                ref dispParams,
                out result,
                out excepInfo,
                out argErr);

            return hresult;
        }
Beispiel #53
0
        private static int GetIDsOfNames(IDispatch dispatch, string name, out int dispId) {
            int[] dispIds = new int[1];
            Guid emtpyRiid = Guid.Empty;
            int hresult = dispatch.TryGetIDsOfNames(
                ref emtpyRiid,
                new string[] { name },
                1,
                0,
                dispIds);

            dispId = dispIds[0];
            return hresult;
        }
Beispiel #54
0
        /// <summary>
        /// Invoke the COM member
        /// </summary>
        /// <param name="target">IDispatch object</param>
        /// <param name="dispId">Dispatch identifier that identifies the member</param>
        /// <param name="args">Arguments passed in</param>
        /// <param name="byRef">Boolean array that indicates by-Ref parameters</param>
        /// <param name="invokeKind">Invocation kind</param>
        /// <returns></returns>
        internal static object Invoke(IDispatch target, int dispId, object[] args, bool[] byRef, COM.INVOKEKIND invokeKind)
        {
            Diagnostics.Assert(target != null, "Caller makes sure an IDispatch object passed in.");
            Diagnostics.Assert(args == null || byRef == null || args.Length == byRef.Length,
                "If 'args' and 'byRef' are not null, then they should be one-on-one mapping.");

            int argCount = args != null ? args.Length : 0;
            int refCount = byRef != null ? byRef.Count(c => c) : 0;
            IntPtr variantArgArray = IntPtr.Zero, dispIdArray = IntPtr.Zero, tmpVariants = IntPtr.Zero;

            try
            {
                // Package arguments
                if (argCount > 0)
                {
                    variantArgArray = NewVariantArray(argCount);

                    int refIndex = 0;
                    for (int i = 0; i < argCount; i++)
                    {
                        // !! The arguments should be in REVERSED order!!
                        int actualIndex = argCount - i - 1;
                        IntPtr varArgPtr = variantArgArray + s_variantSize * actualIndex;

                        // If need to pass by ref, create a by-ref variant 
                        if (byRef != null && byRef[i])
                        {
                            // Allocate memory for temporary VARIANTs used in by-ref marshalling
                            if (tmpVariants == IntPtr.Zero)
                            {
                                tmpVariants = NewVariantArray(refCount);
                            }

                            // Create a VARIANT that the by-ref VARIANT points to
                            IntPtr tmpVarPtr = tmpVariants + s_variantSize * refIndex;
                            Marshal.GetNativeVariantForObject(args[i], tmpVarPtr);

                            // Create the by-ref VARIANT
                            MakeByRefVariant(tmpVarPtr, varArgPtr);
                            refIndex++;
                        }
                        else
                        {
                            Marshal.GetNativeVariantForObject(args[i], varArgPtr);
                        }
                    }
                }

                var paramArray = new COM.DISPPARAMS[1];
                paramArray[0].rgvarg = variantArgArray;
                paramArray[0].cArgs = argCount;

                if (invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUT || invokeKind == COM.INVOKEKIND.INVOKE_PROPERTYPUTREF)
                {
                    // For property putters, the first DISPID argument needs to be DISPID_PROPERTYPUT
                    dispIdArray = Marshal.AllocCoTaskMem(4); // Allocate 4 bytes to hold a 32-bit signed integer
                    Marshal.WriteInt32(dispIdArray, DISPID_PROPERTYPUT);

                    paramArray[0].cNamedArgs = 1;
                    paramArray[0].rgdispidNamedArgs = dispIdArray;
                }
                else
                {
                    // Otherwise, no named parameters are necessary since powershell parser doesn't support named parameter
                    paramArray[0].cNamedArgs = 0;
                    paramArray[0].rgdispidNamedArgs = IntPtr.Zero;
                }

                // Make the call
                EXCEPINFO info = default(EXCEPINFO);
                object result = null;

                try
                {
                    // 'puArgErr' is set when IDispatch.Invoke fails with error code 'DISP_E_PARAMNOTFOUND' and 'DISP_E_TYPEMISMATCH'.
                    // Appropriate exceptions will be thrown in such cases, but FullCLR doesn't use 'puArgErr' in the exception handling, so we also ignore it.
                    uint puArgErrNotUsed = 0;
                    target.Invoke(dispId, s_IID_NULL, LCID_DEFAULT, invokeKind, paramArray, out result, out info, out puArgErrNotUsed);
                }
                catch (Exception innerException)
                {
                    // When 'IDispatch.Invoke' returns error code, CLR will raise exception based on internal HR-to-Exception mapping.
                    // Description of the return code can be found at https://msdn.microsoft.com/en-us/library/windows/desktop/ms221479(v=vs.85).aspx
                    // According to CoreCLR team (yzha), the exception needs to be wrapped as an inner exception of TargetInvocationException.

                    string exceptionMsg = null;
                    if (innerException.HResult == DISP_E_EXCEPTION)
                    {
                        // Invoke was successful but the actual underlying method failed. 
                        // In this case, we use EXCEPINFO to get additional error info.

                        // Use EXCEPINFO.scode or EXCEPINFO.wCode as HR to construct the correct exception.
                        int code = info.scode != 0 ? info.scode : info.wCode;
                        innerException = Marshal.GetExceptionForHR(code, IntPtr.Zero) ?? innerException;

                        // Get the richer error description if it's available.
                        if (info.bstrDescription != IntPtr.Zero)
                        {
                            exceptionMsg = Marshal.PtrToStringBSTR(info.bstrDescription);
                            Marshal.FreeBSTR(info.bstrDescription);
                        }

                        // Free the BSTRs
                        if (info.bstrSource != IntPtr.Zero)
                        {
                            Marshal.FreeBSTR(info.bstrSource);
                        }
                        if (info.bstrHelpFile != IntPtr.Zero)
                        {
                            Marshal.FreeBSTR(info.bstrHelpFile);
                        }
                    }

                    var outerException = exceptionMsg == null
                                              ? new TargetInvocationException(innerException)
                                              : new TargetInvocationException(exceptionMsg, innerException);
                    throw outerException;
                }

                // Now back propagate the by-ref arguments
                if (refCount > 0)
                {
                    for (int i = 0; i < argCount; i++)
                    {
                        // !! The arguments should be in REVERSED order!!
                        int actualIndex = argCount - i - 1;

                        // If need to pass by ref, back propagate 
                        if (byRef != null && byRef[i])
                        {
                            args[i] = Marshal.GetObjectForNativeVariant(variantArgArray + s_variantSize * actualIndex);
                        }
                    }
                }

                return result;
            }
            finally
            {
                // Free the variant argument array
                if (variantArgArray != IntPtr.Zero)
                {
                    for (int i = 0; i < argCount; i++)
                    {
                        VariantClear(variantArgArray + s_variantSize * i);
                    }
                    Marshal.FreeCoTaskMem(variantArgArray);
                }

                // Free the dispId array
                if (dispIdArray != IntPtr.Zero)
                {
                    Marshal.FreeCoTaskMem(dispIdArray);
                }

                // Free the temporary variants created when handling by-Ref arguments
                if (tmpVariants != IntPtr.Zero)
                {
                    for (int i = 0; i < refCount; i++)
                    {
                        VariantClear(tmpVariants + s_variantSize * i);
                    }
                    Marshal.FreeCoTaskMem(tmpVariants);
                }
            }
        }
Beispiel #55
0
 private LambdaListener fromIDispatch(IDispatch listener)
 {
     return data =>
     {
         applyIDispatch(listener, data);
     };
 }
Beispiel #56
0
 private void on(string eventType, LambdaListener lambdaList, IDispatch dispList)
 {
     Listener list = Tuple.Create<IDispatch, LambdaListener>(dispList, lambdaList);
     if (!listeners.ContainsKey(eventType))
     {
         listeners[eventType] = new List<Listener>();
     }
     var lists = listeners[eventType];
     lists.Add(list);
 }
Beispiel #57
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="d"></param>
 void UnregisterEvents(IDispatch d)
 {
     //d.ReceivedEvent -= new EventHandler(d_ReceivedEvent);
 }
Beispiel #58
0
        public void removeListener(string eventType, IDispatch listener)
        {
            if (!listeners.ContainsKey(eventType)) { return; }

            var lists = listeners[eventType];
            listeners[eventType] =
                new List<Listener>(lists.Where(l =>
                            l.Item1 != null && l.Item1 != listener));
        }
Beispiel #59
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="d1"></param>
 /// <param name="d2"></param>
 public Dispatcher(IDispatch d1, IDispatch d2)
 {
     D1 = d1;
     D2 = d2;
 }
Beispiel #60
0
 public PatternFinder(string[] keys)
 {
     _searchRunner = new SetSearchDispatch(keys);
 }