示例#1
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);
        }
示例#2
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Temporarily registers the specified file.
 /// </summary>
 /// <param name="fileName">Name of the file.</param>
 /// <param name="registerInHklm"><c>true</c> to register in HKLM, <c>false</c> to
 /// register in HKCU. Passing <c>false</c> has the same effect as calling
 /// regsvr32 with parameter /i:user.</param>
 /// <param name="registerTypeLib"><c>true</c> to also register tye type library.</param>
 /// ------------------------------------------------------------------------------------
 public bool Register(string fileName, bool registerInHklm, bool registerTypeLib)
 {
     SetDllDirectory(Path.GetDirectoryName(fileName));
     ApiInvokeDllInstall(m_Log, fileName, true, registerInHklm);
     try
     {
         if (registerInHklm && registerTypeLib)
         {
             ITypeLib typeLib        = LoadTypeLib(fileName);
             var      registerResult = RegisterTypeLib(typeLib, fileName, null);
             if (registerResult == 0)
             {
                 m_Log.LogMessage(MessageImportance.Low, "Registered {0} with result {1}",
                                  fileName, registerResult);
             }
             else
             {
                 m_Log.LogWarning("Registering {0} failed with result {1}", fileName,
                                  registerResult);
             }
         }
         else
         {
             m_Log.LogMessage(MessageImportance.Low, "Registered {0}", fileName);
         }
     }
     catch (Exception e)
     {
         m_Log.LogWarningFromException(e);
     }
     return(true);
 }
示例#3
0
        public static string GetTypeLibPath(ITypeLib typeLibrary)
        {
            if (typeLibrary == null)
            {
                throw new Exceptions.NullParameterException(typeof(ComInterop), "GetTypeLibPath", "typeLibrary");
            }

            System.IntPtr ptr = System.IntPtr.Zero;
            typeLibrary.GetLibAttr(out ptr);

            try
            {
                Win32.TLIBATTR libAttr = (Win32.TLIBATTR)Marshal.PtrToStructure(ptr, typeof(Win32.TLIBATTR));
                Debug.Assert(libAttr.guid != System.Guid.Empty, "libAttr.guid != Guid.Empty");

                string path = string.Empty;
                Win32.SafeNativeMethods.QueryPathOfRegTypeLib(ref libAttr.guid, libAttr.wMajorVerNum,
                                                              libAttr.wMinorVerNum, libAttr.lcid, ref path);
                return(path);
            }
            finally
            {
                typeLibrary.ReleaseTLibAttr(ptr);
            }
        }
示例#4
0
        private static string GetManagedTypeLibName(ITypeLib typeLib)
        {
            var typeLib2 = typeLib as ITypeLib2;

            if (typeLib2 != null)
            {
                // ReSharper disable EmptyGeneralCatchClause

                try
                {
                    var    guid = managedNameGuid;
                    object data;
                    typeLib2.GetCustData(ref guid, out data);

                    var name = data as string;
                    if (name != null)
                    {
                        name = name.Trim();
                        if (name.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) || name.EndsWith(".exe", StringComparison.OrdinalIgnoreCase))
                        {
                            return(name.Substring(0, name.Length - 4));
                        }

                        return(name);
                    }
                }
                catch (Exception)
                {
                }

                // ReSharper restore EmptyGeneralCatchClause
            }

            return(Marshal.GetTypeLibName(typeLib));
        }
示例#5
0
        public IntPtr GetTypeLibAttr(ITypeLib typeLib)
        {
            IntPtr ret;

            typeLib.GetLibAttr(out ret);
            return(ret);
        }
示例#6
0
        /*
         * Method:  ITypeLibImporterNotifySink.ResolveRef
         *
         * Implementation of ITypeLibImporterNotifySink.ResolveRef - this method is called by the NDP type lib converter
         * to resolve dependencies.
         * We should never return null here - it's not documented as the proper way of failing dependency resolution.
         * Instead, we use an exception to abort the conversion process.
         */
        Assembly ITypeLibImporterNotifySink.ResolveRef(object objTypeLib)
        {
            // get attributes for our dependent typelib
            ITypeLib typeLib = (ITypeLib)objTypeLib;

            ComReference.GetTypeLibAttrForTypeLib(ref typeLib, out TYPELIBATTR attr);

            // call our callback to do the dirty work for us
            if (!ResolverCallback.ResolveComClassicReference(attr, base.OutputDirectory, null, null, out ComReferenceWrapperInfo wrapperInfo))
            {
                if (!Silent)
                {
                    Log.LogWarningWithCodeFromResources("ResolveComReference.FailedToResolveDependentComReference", attr.guid, attr.wMajorVerNum, attr.wMinorVerNum);
                }

                throw new ComReferenceResolutionException();
            }

            Debug.Assert(wrapperInfo.assembly != null, "Successfully resolved assembly cannot be null!");
            if (wrapperInfo.assembly == null)
            {
                throw new ComReferenceResolutionException();
            }

            if (!Silent)
            {
                Log.LogMessageFromResources(MessageImportance.Low, "ResolveComReference.ResolvedDependentComReference",
                                            attr.guid, attr.wMajorVerNum, attr.wMinorVerNum, wrapperInfo.path);
            }

            Debug.Assert(wrapperInfo.assembly != null, "Expected a non-null wrapperInfo.assembly. It should have been loaded in GenerateWrapper if it was going to be necessary.");
            return(wrapperInfo.assembly);
        }
示例#7
0
        private static string GetManagedTypeInfoName(ITypeInfo typeInfo, ITypeLib typeLib)
        {
            var typeInfo2 = typeInfo as ITypeInfo2;

            if (typeInfo2 != null)
            {
                // ReSharper disable EmptyGeneralCatchClause

                try
                {
                    var    guid = managedNameGuid;
                    object data;
                    typeInfo2.GetCustData(ref guid, out data);

                    var name = data as string;
                    if (name != null)
                    {
                        return(name.Trim());
                    }
                }
                catch (Exception)
                {
                }

                // ReSharper restore EmptyGeneralCatchClause
            }

            return(GetManagedTypeLibName(typeLib) + "." + Marshal.GetTypeInfoName(typeInfo));
        }
        internal static AssemblyName GetAssemblyNameFromTypelib(object typeLib, string asmFileName, byte[] publicKey, StrongNameKeyPair keyPair, Version asmVersion, AssemblyNameFlags asmNameFlags)
        {
            string   strName       = null;
            string   strDocString  = null;
            int      dwHelpContext = 0;
            string   strHelpFile   = null;
            ITypeLib typeLibrary   = (ITypeLib)typeLib;

            typeLibrary.GetDocumentation(-1, out strName, out strDocString, out dwHelpContext, out strHelpFile);
            if (asmFileName == null)
            {
                asmFileName = strName;
            }
            else
            {
                string fileName  = Path.GetFileName(asmFileName);
                string extension = Path.GetExtension(asmFileName);
                if (!".dll".Equals(extension, StringComparison.OrdinalIgnoreCase))
                {
                    throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileExtension"));
                }
                asmFileName = fileName.Substring(0, fileName.Length - ".dll".Length);
            }
            if (asmVersion == null)
            {
                int num2;
                int num3;
                Marshal.GetTypeLibVersion(typeLibrary, out num2, out num3);
                asmVersion = new Version(num2, num3, 0, 0);
            }
            AssemblyName name = new AssemblyName();

            name.Init(asmFileName, publicKey, null, asmVersion, null, AssemblyHashAlgorithm.None, AssemblyVersionCompatibility.SameMachine, null, asmNameFlags, keyPair);
            return(name);
        }
        private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, object typeLib)
        {
            IntPtr   nULL         = Win32Native.NULL;
            ITypeLib lib          = (ITypeLib)typeLib;
            int      wMajorVerNum = 0;
            int      wMinorVerNum = 0;

            Type[]          types       = new Type[] { typeof(int), typeof(int) };
            ConstructorInfo constructor = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(types);

            try
            {
                lib.GetLibAttr(out nULL);
                System.Runtime.InteropServices.ComTypes.TYPELIBATTR typelibattr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(nULL, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                wMajorVerNum = typelibattr.wMajorVerNum;
                wMinorVerNum = typelibattr.wMinorVerNum;
            }
            finally
            {
                if (nULL != Win32Native.NULL)
                {
                    lib.ReleaseTLibAttr(nULL);
                }
            }
            object[] constructorArgs             = new object[] { wMajorVerNum, wMinorVerNum };
            CustomAttributeBuilder customBuilder = new CustomAttributeBuilder(constructor, constructorArgs);

            asmBldr.SetCustomAttribute(customBuilder);
        }
示例#10
0
        //private IEnumerable<string> GetImplementedInterfaceNames(TYPEATTR typeAttr, ITypeInfo info)
        //{
        //    for (var implIndex = 0; implIndex < typeAttr.cImplTypes; implIndex++)
        //    {
        //        int href;
        //        info.GetRefTypeOfImplType(implIndex, out href);

        //        ITypeInfo implTypeInfo;
        //        info.GetRefTypeInfo(href, out implTypeInfo);

        //        var implTypeName = GetTypeName(implTypeInfo);

        //        yield return implTypeName;
        //        //Debug.WriteLine(string.Format("\tImplements {0}", implTypeName));
        //    }
        //}

        private DeclarationType GetDeclarationType(ITypeLib typeLibrary, int i)
        {
            TYPEKIND typeKind;

            typeLibrary.GetTypeInfoType(i, out typeKind);

            DeclarationType typeDeclarationType = DeclarationType.Control; // todo: a better default

            if (typeKind == TYPEKIND.TKIND_ENUM)
            {
                typeDeclarationType = DeclarationType.Enumeration;
            }
            else if (typeKind == TYPEKIND.TKIND_COCLASS || typeKind == TYPEKIND.TKIND_INTERFACE ||
                     typeKind == TYPEKIND.TKIND_ALIAS || typeKind == TYPEKIND.TKIND_DISPATCH)
            {
                typeDeclarationType = DeclarationType.ClassModule;
            }
            else if (typeKind == TYPEKIND.TKIND_RECORD)
            {
                typeDeclarationType = DeclarationType.UserDefinedType;
            }
            else if (typeKind == TYPEKIND.TKIND_MODULE)
            {
                typeDeclarationType = DeclarationType.ProceduralModule;
            }
            return(typeDeclarationType);
        }
示例#11
0
        internal static string GetMetadataName(string strSrcTypeLib, ITypeLib TypeLib, out string strMetaFileRoot)
        {
            string typeLibName = "";

            strMetaFileRoot = "";
            if (TypeLib == null)
            {
                TypeLib = GetTypeLib(strSrcTypeLib);
                if (TypeLib == null)
                {
                    return(typeLibName);
                }
            }
            typeLibName     = Marshal.GetTypeLibName(TypeLib);
            strMetaFileRoot = typeLibName + ".dll";
            char[] anyOf      = new char[] { '/', '\\' };
            int    startIndex = strSrcTypeLib.LastIndexOfAny(anyOf) + 1;

            if (startIndex <= 0)
            {
                startIndex = 0;
            }
            if (strSrcTypeLib.Substring(startIndex, strSrcTypeLib.Length - startIndex).ToLower(CultureInfo.InvariantCulture) == strMetaFileRoot.ToLower(CultureInfo.InvariantCulture))
            {
                typeLibName     = typeLibName + "SoapLib";
                strMetaFileRoot = typeLibName + ".dll";
            }
            return(typeLibName);
        }
示例#12
0
 internal void AnalyzeTypeLibrary(ITypeLib typeLibrary)
 {
     try
     {
         int typeInfoCount = typeLibrary.GetTypeInfoCount();
         for (int i = 0; i < typeInfoCount; i++)
         {
             ITypeInfo ppTI = null;
             try
             {
                 typeLibrary.GetTypeInfo(i, out ppTI);
                 this.AnalyzeTypeInfo(ppTI);
             }
             finally
             {
                 if (ppTI != null)
                 {
                     this.marshalReleaseComObject(ppTI);
                 }
             }
         }
     }
     catch (COMException exception)
     {
         this.encounteredProblems.Add(exception);
     }
 }
示例#13
0
        private bool CanSkipType(ITypeInfo typeInfo, ITypeLib typeLib, System.Runtime.InteropServices.ComTypes.TYPEATTR typeAttributes, System.Runtime.InteropServices.ComTypes.TYPELIBATTR typeLibAttributes)
        {
            if (((typeAttributes.guid == Microsoft.Build.Tasks.NativeMethods.IID_IUnknown) || (typeAttributes.guid == Microsoft.Build.Tasks.NativeMethods.IID_IDispatch)) || (((typeAttributes.guid == Microsoft.Build.Tasks.NativeMethods.IID_IDispatchEx) || (typeAttributes.guid == Microsoft.Build.Tasks.NativeMethods.IID_IEnumVariant)) || (typeAttributes.guid == Microsoft.Build.Tasks.NativeMethods.IID_ITypeInfo)))
            {
                return(true);
            }
            if (typeLibAttributes.guid == Microsoft.Build.Tasks.NativeMethods.IID_StdOle)
            {
                string str;
                string str2;
                string str3;
                int    num;
                typeInfo.GetDocumentation(-1, out str, out str2, out num, out str3);
                if (string.CompareOrdinal(str, "GUID") == 0)
                {
                    return(true);
                }
            }
            ITypeLib2 lib = typeLib as ITypeLib2;

            if (lib != null)
            {
                object obj2;
                lib.GetCustData(ref Microsoft.Build.Tasks.NativeMethods.GUID_ExportedFromComPlus, out obj2);
                string str4 = obj2 as string;
                if (!string.IsNullOrEmpty(str4))
                {
                    return(true);
                }
            }
            return(false);
        }
示例#14
0
 public ComStruct(ITypeLib typeLib, ITypeInfo info, TYPEATTR attrib, int index)
     : base(typeLib, attrib, index)
 {
     _fields = new List <ComField>();
     Type    = DeclarationType.UserDefinedType;
     GetFields(info, attrib);
 }
示例#15
0
 public ComCoClass(ITypeLib typeLib, ITypeInfo info, TYPEATTR attrib, int index) : base(typeLib, attrib, index)
 {
     Type = DeclarationType.ClassModule;
     GetImplementedInterfaces(info, attrib);
     IsControl = attrib.wTypeFlags.HasFlag(TYPEFLAGS.TYPEFLAG_FCONTROL);
     Debug.Assert(attrib.cFuncs == 0);
 }
示例#16
0
        private static Assembly LoadPrimaryInteropAssembly(ITypeLib typeLib)
        {
            // ReSharper disable EmptyGeneralCatchClause

            try
            {
                IntPtr pAttr;
                typeLib.GetLibAttr(out pAttr);
                try
                {
                    var attr = (TYPELIBATTR)Marshal.PtrToStructure(pAttr, typeof(TYPELIBATTR));

                    string name;
                    string codeBase;
                    if (new TypeLibConverter().GetPrimaryInteropAssembly(attr.guid, attr.wMajorVerNum, attr.wMinorVerNum, attr.lcid, out name, out codeBase))
                    {
                        return(Assembly.Load(new AssemblyName(name)
                        {
                            CodeBase = codeBase
                        }));
                    }
                }
                finally
                {
                    typeLib.ReleaseTLibAttr(pAttr);
                }
            }
            catch (Exception)
            {
            }

            return(null);

            // ReSharper restore EmptyGeneralCatchClause
        }
示例#17
0
 public IntPtr GetTypeLibAttr(ITypeLib typeLib)
 {
     if (typeLib == null) throw new ArgumentNullException(nameof(typeLib));
     IntPtr ret;
     typeLib.GetLibAttr(out ret);
     return ret;
 }
        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());
        }
示例#19
0
        /// <summary>
        /// Exports the type library of the given assembly, then registers
        /// the type library. Will recursively export and register TLBs of
        /// referenced assemblies as needed.
        /// </summary>
        /// <param name="assembly"><see cref="System.Reflection.Assembly"/>
        /// to export. Cannot be <c>null</c>.</param>
        /// <param name="typeLibName">Full path to type library to export.
        /// Cannot be <c>null</c>, empty or equal to the path of
        /// <paramref name="assembly"/>.</param>
        /// <exception cref="ArgumentNullException"><paramref name="assembly"/>
        /// or <paramref name="typeLibName"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException"><paramref name="typeLibName"/>
        /// is <see cref="String.Empty"/>.
        ///
        /// OR
        ///
        /// <paramref name="typeLibName"/> is equal to the local path
        /// of <paramref name="assembly"/>.</exception>
        public void ExportAndRegisterTypeLibrary(Assembly assembly, string typeLibName)
        {
            // Validate input.
            if (assembly == null)
            {
                throw new ArgumentNullException("assembly");
            }
            if (typeLibName == null)
            {
                throw new ArgumentNullException("typeLibName");
            }
            if (typeLibName.Length == 0)
            {
                throw new ArgumentException("Type library name cannot be empty.", "typeLibName");
            }
            string assemblyName = AssemblyTools.GetAssemblyPath(assembly);

            if (String.Compare(assemblyName, typeLibName, true) == 0)
            {
                throw new ArgumentException("Type library cannot overwrite assembly.", "typeLibName");
            }

            // Export the type lib, then register it.
            ITypeLib tlb = ExportTypeLibrary(assembly, typeLibName);

            RegisterTypeLibrary(tlb, typeLibName);

            // Log normal message to tell we've registered the type lib.
            console.WriteLine("Type library \"{0}\" exported from assembly \"{1}\" " +
                              "and registered successfully.", assemblyName, typeLibName);
        }
示例#20
0
        /*
         * Method:  GetTypeLibNameForTypeLibAttrs
         *
         * Gets the name of given type library.
         */
        internal static bool GetTypeLibNameForTypeLibAttrs(TaskLoggingHelper log, bool silent, TYPELIBATTR typeLibAttr, out string typeLibName)
        {
            typeLibName = "";
            ITypeLib typeLib = null;

            try
            {
                // load our type library
                try
                {
                    TYPELIBATTR attr = typeLibAttr;
                    typeLib = (ITypeLib)NativeMethods.LoadRegTypeLib(ref attr.guid, attr.wMajorVerNum, attr.wMinorVerNum, attr.lcid);
                }
                catch (COMException ex)
                {
                    if (!silent)
                    {
                        log.LogWarningWithCodeFromResources("ResolveComReference.CannotLoadTypeLib", typeLibAttr.guid, typeLibAttr.wMajorVerNum, typeLibAttr.wMinorVerNum, ex.Message);
                    }

                    return(false);
                }

                string typeLibId = log.FormatResourceString("ResolveComReference.TypeLibAttrId", typeLibAttr.guid.ToString(), typeLibAttr.wMajorVerNum, typeLibAttr.wMinorVerNum);

                return(GetTypeLibNameForITypeLib(log, silent, typeLib, typeLibId, out typeLibName));
            }
            finally
            {
                if (typeLib != null)
                {
                    Marshal.ReleaseComObject(typeLib);
                }
            }
        }
 internal void AnalyzeTypeLibrary(ITypeLib typeLibrary)
 {
     try
     {
         int typeInfoCount = typeLibrary.GetTypeInfoCount();
         for (int i = 0; i < typeInfoCount; i++)
         {
             ITypeInfo ppTI = null;
             try
             {
                 typeLibrary.GetTypeInfo(i, out ppTI);
                 this.AnalyzeTypeInfo(ppTI);
             }
             finally
             {
                 if (ppTI != null)
                 {
                     this.marshalReleaseComObject(ppTI);
                 }
             }
         }
     }
     catch (COMException exception)
     {
         this.encounteredProblems.Add(exception);
     }
 }
示例#22
0
        public Assembly Convert(ITypeLib tl)
        {
            tl.GetLibAttr(out IntPtr ipta);
            var ta = *(_TYPELIBATTR *)ipta;

            tl.ReleaseTLibAttr(ipta);
            var hash = Fnv1((byte *)&ta, sizeof(_TYPELIBATTR) - 2).ToString("x");

            tl.GetDocumentation(-1, out var tlName, out var tlDescription, out var _, out var _);
            var fileName = $"{tlName} {ta.wMajorVerNum}.{ta.wMinorVerNum} #{hash}.dll";
            var netPath  = saveDir + fileName;

            if (!s_converted.TryGetValue(fileName, out var asm) || !File.Exists(netPath))
            {
                Print($"Converted: {tlName} ({tlDescription}) to \"{fileName}\".");

                var converter = new TypeLibConverter();
                asm = converter.ConvertTypeLibToAssembly(tl, netPath,
                                                         TypeLibImporterFlags.ReflectionOnlyLoading | TypeLibImporterFlags.TransformDispRetVals | TypeLibImporterFlags.UnsafeInterfaces,
                                                         this, null, null, tlName, null);
                asm.Save(fileName);
                s_converted[fileName] = asm;
            }
            return(asm);
        }
        private static Assembly LoadPrimaryInteropAssembly(ITypeLib typeLib)
        {
            // ReSharper disable EmptyGeneralCatchClause

            if (typeLib == null)
            {
                return(null);
            }

            try
            {
                using (var attrScope = typeLib.CreateAttrScope())
                {
                    string name;
                    string codeBase;
                    if (GetPrimaryInteropAssembly(attrScope.Value.guid, attrScope.Value.wMajorVerNum, attrScope.Value.wMinorVerNum, out name, out codeBase))
                    {
                        return(Assembly.Load(new AssemblyName(name)
                        {
                            CodeBase = codeBase
                        }));
                    }
                }
            }
            catch (Exception)
            {
            }

            return(null);

            // ReSharper restore EmptyGeneralCatchClause
        }
 internal static string GetMetadataName(string strSrcTypeLib, ITypeLib TypeLib, out string strMetaFileRoot)
 {
     string typeLibName = "";
     strMetaFileRoot = "";
     if (TypeLib == null)
     {
         TypeLib = GetTypeLib(strSrcTypeLib);
         if (TypeLib == null)
         {
             return typeLibName;
         }
     }
     typeLibName = Marshal.GetTypeLibName(TypeLib);
     strMetaFileRoot = typeLibName + ".dll";
     char[] anyOf = new char[] { '/', '\\' };
     int startIndex = strSrcTypeLib.LastIndexOfAny(anyOf) + 1;
     if (startIndex <= 0)
     {
         startIndex = 0;
     }
     if (strSrcTypeLib.Substring(startIndex, strSrcTypeLib.Length - startIndex).ToLower(CultureInfo.InvariantCulture) == strMetaFileRoot.ToLower(CultureInfo.InvariantCulture))
     {
         typeLibName = typeLibName + "SoapLib";
         strMetaFileRoot = typeLibName + ".dll";
     }
     return typeLibName;
 }
示例#25
0
        public void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex)
        {
            _faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetContainingTypeLib);

            ppTLB  = _containingTypeLib;
            pIndex = _indexInContainingTypeLib;
        }
示例#26
0
        public TypeLibViewModel(ITypeLib typeLib)
        {
            _typeLib = typeLib;
            TYPELIBATTR attr = COMUtil.GetTypeLibAttr(typeLib);
            CLSID = attr.guid.ToString();
            MajorVersion = attr.wMajorVerNum;
            MinorVersion = attr.wMinorVerNum;
            LCID = attr.lcid;
            //Name = Marshal.GetTypeLibName(typeLib);
            string name, docString, helpFile;
            int helpContext;
            typeLib.GetDocumentation(-1,
                                     out name,
                                     out docString,
                                     out helpContext,
                                     out helpFile);

            Path = COMUtil.GetTypeLibPath(typeLib);
            Name = name;
            Description = docString;
            // Remove the null char
            HelpFilePath = helpFile == null ? string.Empty : helpFile.Substring(0, helpFile.Length - 1);

            string asmName, asmCodeBase;
            var converter = new TypeLibConverter();
            converter.GetPrimaryInteropAssembly(
                attr.guid, MajorVersion, MinorVersion, LCID, out asmName, out asmCodeBase);

            PIAName = asmName;
            PIACodeBase = asmCodeBase;
        }
示例#27
0
        private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, object typeLib)
        {
            IntPtr          ppTLibAttr  = IntPtr.Zero;
            ITypeLib        typeLib1    = (ITypeLib)typeLib;
            int             num1        = 0;
            int             num2        = 0;
            ConstructorInfo constructor = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(new Type[2] {
                typeof(int), typeof(int)
            });

            try
            {
                typeLib1.GetLibAttr(out ppTLibAttr);
                System.Runtime.InteropServices.ComTypes.TYPELIBATTR typelibattr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(ppTLibAttr, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                num1 = (int)typelibattr.wMajorVerNum;
                num2 = (int)typelibattr.wMinorVerNum;
            }
            finally
            {
                if (ppTLibAttr != IntPtr.Zero)
                {
                    typeLib1.ReleaseTLibAttr(ppTLibAttr);
                }
            }
            object[] constructorArgs = new object[2] {
                (object)num1, (object)num2
            };
            CustomAttributeBuilder customBuilder = new CustomAttributeBuilder(constructor, constructorArgs);

            asmBldr.SetCustomAttribute(customBuilder);
        }
示例#28
0
        /// <summary>
        /// Attempts to load the specified type lib and return it's parsed metadata.
        /// </summary>
        /// <param name="typeLibPath"></param>
        /// <returns></returns>
        bool TryLoadTypeLibFromPathInternal(string path, out TypeLibInfo info)
        {
            info = null;

            if (string.IsNullOrWhiteSpace(path))
            {
                return(false);
            }

            Log.LogMessage("TryLoadTypeLibFromPath: {0}", path);

            ITypeLib typeLib    = null;
            var      typeLibPtr = IntPtr.Zero;

            try
            {
                typeLib = LoadTypeLib(path);
                if (typeLib != null)
                {
                    typeLib.GetLibAttr(out typeLibPtr);
                    if (typeLibPtr != IntPtr.Zero)
                    {
                        // marshal pointer into struct
                        var ta = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(typeLibPtr, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));

                        // obtain information from typelib
                        typeLib.GetDocumentation(-1, out var name, out var docString, out var helpContext, out var helpFile);

                        // generate information
                        info = new TypeLibInfo()
                        {
                            Name            = name,
                            Description     = docString,
                            Guid            = ta.guid,
                            MajorVersion    = ta.wMajorVerNum,
                            MinorVersion    = ta.wMinorVerNum,
                            Lcid            = ta.lcid,
                            TypeLibPath     = NormalizePath(path),
                            TypeLibFilePath = GetTypeLibFilePath(path),
                        };

                        // success
                        return(true);
                    }
                }
            }
            catch (COMException e)
            {
                Log.LogMessage(MessageImportance.Low, "LoadTypeLib error: {0}; {1}", path, e.Message);
            }
            finally
            {
                if (typeLib != null && typeLibPtr != IntPtr.Zero)
                {
                    typeLib.ReleaseTLibAttr(typeLibPtr);
                }
            }

            return(false);
        }
示例#29
0
            /// <summary>
            /// Resolves a reference during the exporting process. This means that the
            /// type library references the type library in another assembly. We must
            /// call back our <see cref="TypeLibHelper"/> to do this.
            /// </summary>
            /// <param name="assembly">Assembly to resolve.</param>
            /// <returns>Type library for the specified <paramref name="assembly"/>.
            /// Must implement the <see cref="ITypeLib"/> interface.</returns>
            /// <exception cref="ArgumentNullException"><paramref name="assembly"/>
            /// is <c>null</c>.</exception>
            public object ResolveRef(Assembly assembly)
            {
                ITypeLib tlb = null;

                // Validate input.
                if (assembly == null)
                {
                    throw new ArgumentNullException("assembly");
                }

                // We'll export the type lib next to the assembly.
                string assemblyName = assembly.GetName().Name;
                string typeLibName  = Path.ChangeExtension(Path.Combine(Path.GetDirectoryName(
                                                                            AssemblyTools.GetAssemblyPath(assembly)), assemblyName), ".tlb");

                // Log recursive references in verbose mode.
                parent.console.Verbose.WriteLine("Recursively exporting and registering type " +
                                                 "library of assembly \"{0}\" to \"{1}\".", assemblyName, typeLibName);

                // Call back parent to export and register the type lib.
                tlb = parent.ExportTypeLibrary(assembly, typeLibName);
                parent.RegisterTypeLibrary(tlb, typeLibName);

                Debug.Assert(tlb != null);
                return(tlb);
            }
示例#30
0
        /// <summary>
        /// The main entry point to the dependency walker
        /// </summary>
        /// <param name="typeLibrary">type library to be analyzed</param>
        internal void AnalyzeTypeLibrary(ITypeLib typeLibrary)
        {
            try
            {
                int typeInfoCount = typeLibrary.GetTypeInfoCount();

                for (int i = 0; i < typeInfoCount; i++)
                {
                    ITypeInfo typeInfo = null;

                    try
                    {
                        typeLibrary.GetTypeInfo(i, out typeInfo);
                        AnalyzeTypeInfo(typeInfo);
                    }
                    finally
                    {
                        if (typeInfo != null)
                        {
                            _marshalReleaseComObject(typeInfo);
                        }
                    }
                }
            }
            // This is the only catch block in this class, meaning that once a type library throws it's game over for it.
            // I've tried using a finer grained approach but experiments with COM objects on my machine have shown that if
            // a type library is broken, it's broken in several places (e.g. dependencies on a type lib that's not
            // registered properly). Trying to recover from errors and continue with scanning dependencies only meant
            // that we got lots of exceptions thrown which was not only not very useful for the end user, but also horribly slow.
            catch (COMException ex)
            {
                EncounteredProblems.Add(ex);
            }
        }
示例#31
0
 private void DisposeInternal()
 {
     if (m_typeLib != null)
     {
         Marshal.ReleaseComObject(m_typeLib);
         m_typeLib = null;
     }
 }
示例#32
0
        internal TypeLibraryBrowserInfo(string filePath, ITypeLib typeLibrary, ComBrowserManager manager)
        {
            Debug.Assert(typeLibrary != null && manager != null, "typeLibrary != null && manager != null");

            m_filePath    = filePath;
            m_typeLibrary = new ComLibWrapper(typeLibrary);
            m_manager     = manager;
        }
示例#33
0
 public ComDocumentation(ITypeLib typeLib, int index)
 {
     typeLib.GetDocumentation(index, out string name, out string docString, out int helpContext, out string helpFile);
     Name        = name;
     DocString   = docString;
     HelpContext = helpContext;
     HelpFile    = helpFile?.Trim('\0');
 }
示例#34
0
 /// <summary>
 /// Release the COM ITypeLib pointer for this reference
 /// </summary>
 internal void ReleaseTypeLibPtr()
 {
     if (typeLibPointer != null)
     {
         Marshal.ReleaseComObject(typeLibPointer);
         typeLibPointer = null;
     }
 }
示例#35
0
        public static TYPELIBATTR GetTypeLibAttr(ITypeLib typeLib)
        {
            IntPtr ppTLibAttr;
            typeLib.GetLibAttr(out ppTLibAttr);
            TYPELIBATTR tlibattr = (TYPELIBATTR)Marshal.PtrToStructure(ppTLibAttr, typeof(TYPELIBATTR));
            typeLib.ReleaseTLibAttr(ppTLibAttr);

            return tlibattr;
        }
示例#36
0
 public static IList<string> GetProgIds(ITypeLib typeLib)
 {
     var typeInfos = GetTypeInfos(typeLib);
     return typeInfos
         .Select(GetTypeAttr)
         .Where(attr => attr.typekind == TYPEKIND.TKIND_COCLASS)
         .Select(ProgIdFromTypeAttr)
         .ToList();
 }
 internal ComReferenceInfo(ComReferenceInfo copyFrom)
 {
     this.attr = copyFrom.attr;
     this.typeLibName = copyFrom.typeLibName;
     this.typeLibPath = copyFrom.typeLibPath;
     this.typeLibPointer = copyFrom.typeLibPointer;
     this.primaryOfAxImpRef = copyFrom.primaryOfAxImpRef;
     this.resolvedWrapper = copyFrom.resolvedWrapper;
     this.taskItem = new TaskItem(copyFrom.taskItem);
     this.dependentWrapperPaths = copyFrom.dependentWrapperPaths;
     this.referencePathItem = copyFrom.referencePathItem;
 }
示例#38
0
        public static ITypeInfo[] GetTypeInfos(ITypeLib typeLib)
        {
            var infoCount = typeLib.GetTypeInfoCount();
            var infos = new ITypeInfo[infoCount];

            for (int i = 0; i < infoCount; i++)
            {
                ITypeInfo info;
                typeLib.GetTypeInfo(i, out info);
                infos[i] = info;
            }

            return infos;
        }
        internal static Assembly GenerateAssemblyFromNativeTypeLibrary(Guid iid, Guid typeLibraryID, ITypeLib typeLibrary)
        {
            TypeLibraryHelper helper = GetHelperInstance();
            try
            {
                return helper.GenerateAssemblyFromNativeTypeLibInternal(iid, typeLibraryID, typeLibrary);

            }
            finally
            {
                ReleaseHelperInstance();
            }


        }
示例#40
0
        public TypeViewModel(ITypeLib typeLib, int index)
        {
            Members = new List<MemberViewModel>();
            ITypeInfo typeInfo;
            typeLib.GetTypeInfo(index, out typeInfo);

            string strName, strDocString, strHelpFile;
            int dwHelpContext;
            typeLib.GetDocumentation(index, out strName, out strDocString, out dwHelpContext, out strHelpFile);

            Name = strName;

            // This sometimes throws a COMException
            var attr = COMUtil.GetTypeAttr(typeInfo);

            Kind = attr.typekind;

            // Get the functions
            for (int i = 0; i < attr.cFuncs; i++)
            {
                // TODO: Figure out why this throws an AccessViolationException for the groove type library
                IntPtr ppFuncDesc;
                typeInfo.GetFuncDesc(i, out ppFuncDesc);

                FUNCDESC funcdesc = (FUNCDESC)Marshal.PtrToStructure(ppFuncDesc, typeof(FUNCDESC));
                typeInfo.ReleaseFuncDesc(ppFuncDesc);

                typeInfo.GetDocumentation(funcdesc.memid, out strName, out strDocString, out dwHelpContext, out strHelpFile);
                var member = new MemberViewModel(strName);
                Members.Add(member);
            }

            // Get the vars
            for (int i = 0; i < attr.cVars; i++)
            {
                IntPtr ppVarDesc;
                typeInfo.GetVarDesc(i, out ppVarDesc);

                VARDESC vardesc = (VARDESC)Marshal.PtrToStructure(ppVarDesc, typeof(VARDESC));
                typeInfo.ReleaseVarDesc(ppVarDesc);

                typeInfo.GetDocumentation(vardesc.memid, out strName, out strDocString, out dwHelpContext, out strHelpFile);
                var member = new MemberViewModel(strName);
                Members.Add(member);
            }
        }
 internal bool InitializeWithPath(TaskLoggingHelper log, string path, ITaskItem originalTaskItem, string targetProcessorArchitecture)
 {
     Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentNull(path, "path");
     this.taskItem = originalTaskItem;
     this.typeLibPath = ComReference.StripTypeLibNumberFromPath(path, new Microsoft.Build.Shared.FileExists(File.Exists));
     string str = targetProcessorArchitecture;
     if (str != null)
     {
         if (!(str == "AMD64") && !(str == "IA64"))
         {
             if (str == "x86")
             {
                 this.typeLibPointer = (ITypeLib) Microsoft.Build.Tasks.NativeMethods.LoadTypeLibEx(path, 0x20);
                 goto Label_00A2;
             }
             if (str == "MSIL")
             {
             }
         }
         else
         {
             this.typeLibPointer = (ITypeLib) Microsoft.Build.Tasks.NativeMethods.LoadTypeLibEx(path, 0x40);
             goto Label_00A2;
         }
     }
     this.typeLibPointer = (ITypeLib) Microsoft.Build.Tasks.NativeMethods.LoadTypeLibEx(path, 2);
 Label_00A2:
     try
     {
         ComReference.GetTypeLibAttrForTypeLib(ref this.typeLibPointer, out this.attr);
         if (!ComReference.GetTypeLibNameForITypeLib(log, this.typeLibPointer, this.GetTypeLibId(log), out this.typeLibName))
         {
             this.ReleaseTypeLibPtr();
             return false;
         }
     }
     catch (COMException)
     {
         this.ReleaseTypeLibPtr();
         throw;
     }
     return true;
 }
示例#42
0
 public static string GetTypeLibPath(ITypeLib typeLib)
 {
     var attr = GetTypeLibAttr(typeLib);
     return GetTypeLibPath(attr.guid, attr.wMajorVerNum, attr.wMinorVerNum, attr.lcid);
 }
示例#43
0
        static extern int LoadTypeLibEx([MarshalAs(UnmanagedType.BStr)] string szFile,
		                                RegKind regkind,
		                                out ITypeLib pptlib);
示例#44
0
        static extern int LoadRegTypeLib(
			ref Guid rguid,
			short wVerMajor,
			short wVerMinor,
			int lcid,
			out ITypeLib pptlib);
示例#45
0
文件: Marshal.cs 项目: rabink/mono
		public static string GetTypeLibName (ITypeLib typelib)
		{
			throw new NotImplementedException ();
		}
 internal static bool GetTypeLibNameForITypeLib(TaskLoggingHelper log, ITypeLib typeLib, string typeLibId, out string typeLibName)
 {
     typeLibName = "";
     ITypeLib2 lib = typeLib as ITypeLib2;
     if (lib == null)
     {
         typeLibName = Marshal.GetTypeLibName(typeLib);
         return true;
     }
     try
     {
         object pVarVal = null;
         lib.GetCustData(ref Microsoft.Build.Tasks.NativeMethods.GUID_TYPELIB_NAMESPACE, out pVarVal);
         if ((pVarVal == null) || (string.Compare(pVarVal.GetType().ToString(), "system.string", StringComparison.OrdinalIgnoreCase) != 0))
         {
             typeLibName = Marshal.GetTypeLibName(typeLib);
             return true;
         }
         typeLibName = (string) pVarVal;
         if ((typeLibName.Length >= 4) && (string.Compare(typeLibName.Substring(typeLibName.Length - 4), ".dll", StringComparison.OrdinalIgnoreCase) == 0))
         {
             typeLibName = typeLibName.Substring(0, typeLibName.Length - 4);
         }
     }
     catch (COMException exception)
     {
         log.LogWarningWithCodeFromResources("ResolveComReference.CannotAccessTypeLibName", new object[] { typeLibId, exception.Message });
         typeLibName = Marshal.GetTypeLibName(typeLib);
         return true;
     }
     return true;
 }
 private static extern void LoadTypeLibEx(string strTypeLibName, REGKIND regKind, out ITypeLib TypeLib);
示例#48
0
        private static Assembly ConvertTypeLibToAssembly(ITypeLib typeLib)
        {
            if (m_typelibs == null)
            {
                LoadTypeLibAssemblies();
            }

            if (m_typelibs.ContainsKey(Marshal.GetTypeLibGuid(typeLib)))
            {
                return m_typelibs[Marshal.GetTypeLibGuid(typeLib)];
            }
            else
            {
                string strAssemblyPath = GetTypeLibDirectory();

                strAssemblyPath = Path.Combine(strAssemblyPath, Marshal.GetTypeLibName(typeLib) + ".dll");

                TypeLibConverter conv = new TypeLibConverter();
                AssemblyBuilder asm = conv.ConvertTypeLibToAssembly(typeLib, strAssemblyPath, TypeLibImporterFlags.ReflectionOnlyLoading,
                                        new TypeLibCallback(), null, null, null, null);
                asm.Save(Path.GetFileName(strAssemblyPath));

                Assembly a = Assembly.LoadFile(strAssemblyPath);

                m_typelibs[Marshal.GetTypeLibGuid(typeLib)] = a;
                RegisterTypeInterfaces(a);

                return a;
            }
        }
 public static Guid GetTypeLibGuid(ITypeLib! typelib) {
   CodeContract.Requires(typelib != null);
 //
 // Summary:
 //     Retrieves the library identifier (LIBID) of a type library.
 //
 // Parameters:
 //   pTLB:
 //     A System.Runtime.InteropServices.UCOMITypeLib that represents an ITypeLib
 //     pointer.
 //
 // Returns:
 //     The LIBID (that is, the System.Guid) of the type library pointed to by the
 //     pTLB parameter.
   return default(Guid);
 }
 public static string GetTypeLibName(ITypeLib! typelib) {
    CodeContract.Requires(typelib != null);
 //
 // Summary:
 //     Retrieves the name of a type library.
 //
 // Parameters:
 //   pTLB:
 //     A System.Runtime.InteropServices.UCOMITypeLib that represents an ITypeLib
 //     pointer.
 //
 // Returns:
 //     The name of the type library pointed to by the pTLB parameter.
   return default(string);
 }
示例#51
0
		private static extern int RegisterTypeLib(ITypeLib typeLib, string fullPath, string helpDir);
示例#52
0
		public static extern int LoadTypeLib(string szFile, out ITypeLib typeLib);
示例#53
0
 public static extern HRESULT LoadTypeLib([MarshalAs(UnmanagedType.LPWStr)] string fileName, out ITypeLib typeLib);
示例#54
0
 public TypeLib(ITypeLib typelib)
 {
     m_typelib = typelib;
     m_typeLib2 = typelib as ITypeLib2;
 }
示例#55
0
 public static unsafe extern int LoadTypeLib([MarshalAs(UnmanagedType.BStr)] string strFile, out ITypeLib ppTypeLib);
示例#56
0
        public void GetContainingTypeLib(out ITypeLib ppTLB, out int pIndex)
        {
            _faultInjector.FailurePointThrow(MockTypeLibrariesFailurePoints.ITypeInfo_GetContainingTypeLib);

            ppTLB = _containingTypeLib;
            pIndex = _indexInContainingTypeLib;
        }
示例#57
0
文件: Marshal.cs 项目: rabink/mono
		public static Guid GetTypeLibGuid (ITypeLib typelib)
		{
			throw new NotImplementedException ();
		}
示例#58
0
文件: Marshal.cs 项目: rabink/mono
		public static int GetTypeLibLcid (ITypeLib typelib)
		{
			throw new NotImplementedException ();
		}
示例#59
0
 public void ReleaseTypeLibAttr(ITypeLib typeLib, IntPtr typeLibAttr)
 {
     if (typeLib == null) throw new ArgumentNullException(nameof(typeLib));
     typeLib.ReleaseTLibAttr(typeLibAttr);
 }
 internal static void GetTypeLibAttrForTypeLib(ref ITypeLib typeLib, out System.Runtime.InteropServices.ComTypes.TYPELIBATTR typeLibAttr)
 {
     IntPtr zero = IntPtr.Zero;
     typeLib.GetLibAttr(out zero);
     if (zero == IntPtr.Zero)
     {
         throw new COMException(Microsoft.Build.Shared.ResourceUtilities.FormatResourceString("ResolveComReference.CannotGetTypeLibAttrForTypeLib", new object[0]));
     }
     try
     {
         typeLibAttr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR) Marshal.PtrToStructure(zero, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
     }
     finally
     {
         typeLib.ReleaseTLibAttr(zero);
     }
 }