Beispiel #1
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
        }
Beispiel #2
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);
        }
        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);
        }
        internal void UnregisterTypeLib(Assembly asm)
        {
            IntPtr   zero   = IntPtr.Zero;
            object   pptlib = null;
            ITypeLib o      = null;

            try
            {
                Guid    typeLibGuidForAssembly = Marshal.GetTypeLibGuidForAssembly(asm);
                Version version = asm.GetName().Version;
                if ((version.Major == 0) && (version.Minor == 0))
                {
                    version = new Version(1, 0);
                }
                if (System.EnterpriseServices.Util.LoadRegTypeLib(typeLibGuidForAssembly, (short)version.Major, (short)version.Minor, 0, out pptlib) == 0)
                {
                    o = (ITypeLib)pptlib;
                    o.GetLibAttr(out zero);
                    System.Runtime.InteropServices.ComTypes.TYPELIBATTR typelibattr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(zero, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                    System.EnterpriseServices.Util.UnRegisterTypeLib(typelibattr.guid, typelibattr.wMajorVerNum, typelibattr.wMinorVerNum, typelibattr.lcid, typelibattr.syskind);
                }
            }
            finally
            {
                if ((o != null) && (zero != IntPtr.Zero))
                {
                    o.ReleaseTLibAttr(zero);
                }
                if (o != null)
                {
                    Marshal.ReleaseComObject(o);
                }
            }
        }
Beispiel #5
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);
            }
        }
Beispiel #6
0
        public IntPtr GetTypeLibAttr(ITypeLib typeLib)
        {
            IntPtr ret;

            typeLib.GetLibAttr(out ret);
            return(ret);
        }
        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);
        }
Beispiel #8
0
        private static IntPtr GetTypeLibAttr_Proxy(ITypeLib typeLib)
        {
            IntPtr libAttr;

            typeLib.GetLibAttr(out libAttr);
            return(libAttr);
        }
Beispiel #9
0
 public IntPtr GetTypeLibAttr(ITypeLib typeLib)
 {
     if (typeLib == null) throw new ArgumentNullException(nameof(typeLib));
     IntPtr ret;
     typeLib.GetLibAttr(out ret);
     return ret;
 }
Beispiel #10
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;
        }
Beispiel #11
0
        public ComTypeLibrary(ITypeLib typeLib)
        {
            _typeLib = typeLib;
            _typeLib.GetDocumentation(-1, out _name, out _description, out _helpContext, out _helpFile);
            _typeLibAttr = _typeLib.GetLibAttr();

            _fileName = NativeMethods.QueryPathOfRegTypeLib(_typeLibAttr.guid, _typeLibAttr.wMajorVerNum, _typeLibAttr.wMinorVerNum, _typeLibAttr.lcid);
            _fileName = _fileName.Trim(new [] { '\0' });

            _fileName = Path.GetFullPath(_fileName);
        }
Beispiel #12
0
        private void ProcessLibraryAttributes(ITypeLib typeLibrary)
        {
            try
            {
                IntPtr attribPtr;
                typeLibrary.GetLibAttr(out attribPtr);
                var typeAttr = (TYPELIBATTR)Marshal.PtrToStructure(attribPtr, typeof(TYPELIBATTR));

                MajorVersion = typeAttr.wMajorVerNum;
                MinorVersion = typeAttr.wMinorVerNum;
                _flags       = (TypeLibTypeFlags)typeAttr.wLibFlags;
                Guid         = typeAttr.guid;
            }
            catch (COMException) { }
        }
Beispiel #13
0
        public static Version GetVersion(this ITypeLib typeLib)
        {
            System.Runtime.InteropServices.ComTypes.TYPELIBATTR attr;
            IntPtr p = IntPtr.Zero;

            typeLib.GetLibAttr(out p);

            try
            {
                attr = p.ToStructure <System.Runtime.InteropServices.ComTypes.TYPELIBATTR>();
                return(new Version(attr.wMajorVerNum, attr.wMinorVerNum));
            }
            finally
            {
                typeLib.ReleaseTLibAttr(p);
            }
        }
Beispiel #14
0
        public static Guid GetGuid(this ITypeLib typeLib)
        {
            System.Runtime.InteropServices.ComTypes.TYPELIBATTR attr;
            IntPtr p = IntPtr.Zero;

            typeLib.GetLibAttr(out p);

            try
            {
                attr = p.ToStructure <System.Runtime.InteropServices.ComTypes.TYPELIBATTR>();
                return(attr.guid);
            }
            finally
            {
                typeLib.ReleaseTLibAttr(p);
            }
        }
        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);
            }
        }
Beispiel #16
0
            Assembly ITypeLibImporterNotifySink.ResolveRef(object typeLib)
            {
                ITypeLib tlb = typeLib as ITypeLib;
                IntPtr   ptr = IntPtr.Zero;

                try
                {
                    tlb.GetLibAttr(out ptr);
                    System.Runtime.InteropServices.ComTypes.TYPELIBATTR attr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(ptr, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                    return(TypeLibraryHelper.GenerateAssemblyFromNativeTypeLibrary(iid, attr.guid, typeLib as ITypeLib));
                }
                finally
                {
                    if ((ptr != IntPtr.Zero) && (tlb != null))
                    {
                        tlb.ReleaseTLibAttr(ptr);
                    }
                }
            }
Beispiel #17
0
            Assembly ITypeLibImporterNotifySink.ResolveRef(object typeLib)
            {
                Assembly assembly;
                ITypeLib lib  = typeLib as ITypeLib;
                IntPtr   zero = IntPtr.Zero;

                try
                {
                    lib.GetLibAttr(out zero);
                    System.Runtime.InteropServices.ComTypes.TYPELIBATTR typelibattr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(zero, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                    assembly = TypeLibraryHelper.GenerateAssemblyFromNativeTypeLibrary(this.iid, typelibattr.guid, typeLib as ITypeLib);
                }
                finally
                {
                    if ((zero != IntPtr.Zero) && (lib != null))
                    {
                        lib.ReleaseTLibAttr(zero);
                    }
                }
                return(assembly);
            }
Beispiel #18
0
        public Assembly ResolveRef(object typeLib)
        {
            ITypeLib tLib = typeLib as ITypeLib;
            string   tLibname;
            string   outputFolder = "";
            string   interopFileName;
            string   asmPath;

            try
            {
                tLibname = Marshal.GetTypeLibName(tLib);
                IntPtr ppTlibAttri = IntPtr.Zero;
                tLib.GetLibAttr(out ppTlibAttri);
                System.Runtime.InteropServices.ComTypes.TYPELIBATTR tLibAttri = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(ppTlibAttri, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                string           guid        = tLibAttri.guid.ToString();
                RegistryKey      typeLibsKey = Registry.ClassesRoot.OpenSubKey("TypeLib\\{" + guid + "}");
                TypeLibrary      typeLibrary = TypeLibrary.Create(typeLibsKey);
                Converter.TlbImp importer    = new Converter.TlbImp(Parent.References);
                outputFolder    = Path.GetDirectoryName(this.Parent.AsmPath);
                interopFileName = Path.Combine(outputFolder, String.Concat("Interop.", typeLibrary.Name, ".dll"));

                asmPath = interopFileName;
                //asm.Save(Path.GetFileName(asmPath));
                //Call ResolveRefEventArgs to notify extra assembly imported as depenedencies
                ResolveRefEventArgs t = new ResolveRefEventArgs("Reference Interop '" + Path.GetFileName(asmPath) + "' created succesfully.");
                Parent.InvokeResolveRef(t);
                Parent.References.Add(new ComReferenceProjectItem(ScriptControl.GetProject(), typeLibrary));
                return(importer.Import(interopFileName, typeLibrary.Path, typeLibrary.Name, this.Parent));
            }
            catch (Exception Ex)
            {
                ResolveRefEventArgs t = new ResolveRefEventArgs(Ex.Message);
                Parent.InvokeResolveRef(t);
                return(null);
            }
            finally
            {
                Marshal.ReleaseComObject(tLib);
            }
        }
Beispiel #19
0
        [System.Security.SecurityCritical]  // auto-generated
        private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, Object typeLib)
        {
            IntPtr       pAttr = IntPtr.Zero;
            _TYPELIBATTR Attr;
            ITypeLib     pTLB  = (ITypeLib)typeLib;
            int          Major = 0;
            int          Minor = 0;

            // Retrieve the PrimaryInteropAssemblyAttribute constructor.
            Type [] aConsParams = new Type[2] {
                typeof(int), typeof(int)
            };
            ConstructorInfo PIAAttrCons = typeof(PrimaryInteropAssemblyAttribute).GetConstructor(aConsParams);

            // Retrieve the major and minor version from the typelib.
            try
            {
                pTLB.GetLibAttr(out pAttr);
                Attr  = (_TYPELIBATTR)Marshal.PtrToStructure(pAttr, typeof(_TYPELIBATTR));
                Major = Attr.wMajorVerNum;
                Minor = Attr.wMinorVerNum;
            }
            finally
            {
                // Release the typelib attributes.
                if (pAttr != IntPtr.Zero)
                {
                    pTLB.ReleaseTLibAttr(pAttr);
                }
            }

            // Create an instance of the custom attribute builder.
            Object[] aArgs = new Object[2] {
                Major, Minor
            };
            CustomAttributeBuilder PIACABuilder = new CustomAttributeBuilder(PIAAttrCons, aArgs);

            // Set the PrimaryInteropAssemblyAttribute on the assembly builder.
            asmBldr.SetCustomAttribute(PIACABuilder);
        }
Beispiel #20
0
        /// <summary>
        /// Helper method for retrieving type lib attributes for the given type lib
        /// </summary>
        /// <param name="typeLib"></param>
        /// <param name="typeLibAttr"></param>
        /// <returns></returns>
        internal static void GetTypeLibAttrForTypeLib(ref ITypeLib typeLib, out TYPELIBATTR typeLibAttr)
        {
            IntPtr pAttrs = IntPtr.Zero;

            typeLib.GetLibAttr(out pAttrs);

            // GetLibAttr should never return null, this is just to be safe
            if (pAttrs == IntPtr.Zero)
            {
                throw new COMException(
                          ResourceUtilities.FormatResourceString("ResolveComReference.CannotGetTypeLibAttrForTypeLib"));
            }

            try
            {
                typeLibAttr = (TYPELIBATTR)Marshal.PtrToStructure(pAttrs, typeof(TYPELIBATTR));
            }
            finally
            {
                typeLib.ReleaseTLibAttr(pAttrs);
            }
        }
Beispiel #21
0
        private static void SetPIAAttributeOnAssembly(AssemblyBuilder asmBldr, object typeLib)
        {
            IntPtr   zero     = IntPtr.Zero;
            ITypeLib typeLib2 = (ITypeLib)typeLib;
            int      num      = 0;
            int      num2     = 0;

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

            try
            {
                typeLib2.GetLibAttr(out zero);
                TYPELIBATTR typelibattr = (TYPELIBATTR)Marshal.PtrToStructure(zero, typeof(TYPELIBATTR));
                num  = (int)typelibattr.wMajorVerNum;
                num2 = (int)typelibattr.wMinorVerNum;
            }
            finally
            {
                if (zero != IntPtr.Zero)
                {
                    typeLib2.ReleaseTLibAttr(zero);
                }
            }
            object[] constructorArgs = new object[]
            {
                num,
                num2
            };
            CustomAttributeBuilder customAttribute = new CustomAttributeBuilder(constructor, constructorArgs);

            asmBldr.SetCustomAttribute(customAttribute);
        }
Beispiel #22
0
        private static void UnRegisterMainTypeLib(FileInfo asmFile)
        {
            ITypeLib typeLib = null;
            IntPtr   intPtr  = (IntPtr)0;

            try
            {
                LoadTypeLibEx(asmFile.FullName, REGKIND.REGKIND_REGISTER, out typeLib);
                typeLib.GetLibAttr(out intPtr);
                System.Runtime.InteropServices.ComTypes.TYPELIBATTR tYPELIBATTR = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(intPtr, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                UnRegisterTypeLib(ref tYPELIBATTR.guid, tYPELIBATTR.wMajorVerNum, tYPELIBATTR.wMinorVerNum, tYPELIBATTR.lcid, tYPELIBATTR.syskind);
            }
            catch
            {
                throw;
            }
            finally
            {
                if (intPtr != (IntPtr)0)
                {
                    typeLib.ReleaseTLibAttr(intPtr);
                }
            }
        }
Beispiel #23
0
 private static IntPtr GetTypeLibAttr_Proxy(ITypeLib typeLib)
 {
     IntPtr libAttr;
     typeLib.GetLibAttr(out libAttr);
     return libAttr;
 }
        private bool Unregister(string assemblyPath, string typeLibPath)
        {
            Microsoft.Build.Shared.ErrorUtilities.VerifyThrowArgumentNull(typeLibPath, "typeLibPath");
            base.Log.LogMessageFromResources(MessageImportance.Low, "UnregisterAssembly.UnregisteringAssembly", new object[] { assemblyPath });
            if (File.Exists(assemblyPath))
            {
                try
                {
                    Assembly             assembly = Assembly.UnsafeLoadFrom(assemblyPath);
                    RegistrationServices services = new RegistrationServices();
                    try
                    {
                        unregisteringLock.WaitOne();
                        if (!services.UnregisterAssembly(assembly))
                        {
                            base.Log.LogWarningWithCodeFromResources("UnregisterAssembly.NoValidTypes", new object[] { assemblyPath });
                        }
                    }
                    finally
                    {
                        unregisteringLock.ReleaseMutex();
                    }
                    goto Label_0237;
                }
                catch (ArgumentNullException exception)
                {
                    base.Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", new object[] { assemblyPath, exception.Message });
                    return(false);
                }
                catch (InvalidOperationException exception2)
                {
                    base.Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", new object[] { assemblyPath, exception2.Message });
                    return(false);
                }
                catch (TargetInvocationException exception3)
                {
                    base.Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", new object[] { assemblyPath, exception3.Message });
                    return(false);
                }
                catch (IOException exception4)
                {
                    base.Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", new object[] { assemblyPath, exception4.Message });
                    return(false);
                }
                catch (TypeLoadException exception5)
                {
                    base.Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", new object[] { assemblyPath, exception5.Message });
                    return(false);
                }
                catch (UnauthorizedAccessException exception6)
                {
                    base.Log.LogErrorWithCodeFromResources("UnregisterAssembly.UnauthorizedAccess", new object[] { assemblyPath, exception6.Message });
                    return(false);
                }
                catch (BadImageFormatException)
                {
                    base.Log.LogErrorWithCodeFromResources("General.InvalidAssembly", new object[] { assemblyPath });
                    return(false);
                }
                catch (SecurityException exception7)
                {
                    base.Log.LogErrorWithCodeFromResources("UnregisterAssembly.UnauthorizedAccess", new object[] { assemblyPath, exception7.Message });
                    return(false);
                }
            }
            base.Log.LogWarningWithCodeFromResources("UnregisterAssembly.UnregisterAsmFileDoesNotExist", new object[] { assemblyPath });
            Label_0237 :;
            base.Log.LogMessageFromResources(MessageImportance.Low, "UnregisterAssembly.UnregisteringTypeLib", new object[] { typeLibPath });
            if (File.Exists(typeLibPath))
            {
                try
                {
                    ITypeLib o    = (ITypeLib)Microsoft.Build.Tasks.NativeMethods.LoadTypeLibEx(typeLibPath, 2);
                    IntPtr   zero = IntPtr.Zero;
                    try
                    {
                        o.GetLibAttr(out zero);
                        if (zero != IntPtr.Zero)
                        {
                            System.Runtime.InteropServices.ComTypes.TYPELIBATTR typelibattr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(zero, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                            Microsoft.Build.Tasks.NativeMethods.UnregisterTypeLib(ref typelibattr.guid, typelibattr.wMajorVerNum, typelibattr.wMinorVerNum, typelibattr.lcid, typelibattr.syskind);
                        }
                    }
                    finally
                    {
                        o.ReleaseTLibAttr(zero);
                        Marshal.ReleaseComObject(o);
                    }
                    goto Label_036E;
                }
                catch (COMException exception8)
                {
                    if (exception8.ErrorCode != -2147319780)
                    {
                        if (exception8.ErrorCode != -2147312566)
                        {
                            throw;
                        }
                        base.Log.LogErrorWithCodeFromResources("UnregisterAssembly.UnregisterTlbCantLoadFile", new object[] { typeLibPath });
                        return(false);
                    }
                    base.Log.LogWarningWithCodeFromResources("UnregisterAssembly.UnregisterTlbFileNotRegistered", new object[] { typeLibPath });
                    goto Label_036E;
                }
            }
            base.Log.LogMessageFromResources(MessageImportance.Low, "UnregisterAssembly.UnregisterTlbFileDoesNotExist", new object[] { typeLibPath });
Label_036E:
            return(true);
        }
        /// <summary>
        /// Helper unregistration method
        /// </summary>
        private bool Unregister(string assemblyPath, string typeLibPath)
        {
            ErrorUtilities.VerifyThrowArgumentNull(typeLibPath, "typeLibPath");

            Log.LogMessageFromResources(MessageImportance.Low, "UnregisterAssembly.UnregisteringAssembly", assemblyPath);

            if (File.Exists(assemblyPath))
            {
                try
                {
                    // Load the specified assembly.
                    Assembly asm = Assembly.UnsafeLoadFrom(assemblyPath);

                    var comRegistrar = new RegistrationServices();

                    try
                    {
                        s_unregisteringLock.WaitOne();

                        // Unregister the assembly
                        if (!comRegistrar.UnregisterAssembly(asm))
                        {
                            // If the assembly doesn't contain any types that could be registered for COM interop,
                            // warn the user about it
                            Log.LogWarningWithCodeFromResources("UnregisterAssembly.NoValidTypes", assemblyPath);
                        }
                    }
                    finally
                    {
                        s_unregisteringLock.ReleaseMutex();
                    }
                }
                catch (ArgumentNullException e)
                {
                    Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", assemblyPath, e.Message);
                    return(false);
                }
                catch (InvalidOperationException e)
                {
                    Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", assemblyPath, e.Message);
                    return(false);
                }
                catch (TargetInvocationException e)
                {
                    Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", assemblyPath, e.Message);
                    return(false);
                }
                catch (IOException e)
                {
                    Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", assemblyPath, e.Message);
                    return(false);
                }
                catch (TypeLoadException e)
                {
                    Log.LogErrorWithCodeFromResources("UnregisterAssembly.CantUnregisterAssembly", assemblyPath, e.Message);
                    return(false);
                }
                catch (UnauthorizedAccessException e)
                {
                    Log.LogErrorWithCodeFromResources("UnregisterAssembly.UnauthorizedAccess", assemblyPath, e.Message);
                    return(false);
                }
                catch (BadImageFormatException)
                {
                    Log.LogErrorWithCodeFromResources("General.InvalidAssembly", assemblyPath);
                    return(false);
                }
                catch (SecurityException e) // running as normal user
                {
                    Log.LogErrorWithCodeFromResources("UnregisterAssembly.UnauthorizedAccess", assemblyPath, e.Message);
                    return(false);
                }
            }
            else
            {
                Log.LogWarningWithCodeFromResources("UnregisterAssembly.UnregisterAsmFileDoesNotExist", assemblyPath);
            }

            Log.LogMessageFromResources(MessageImportance.Low, "UnregisterAssembly.UnregisteringTypeLib", typeLibPath);

            if (File.Exists(typeLibPath))
            {
                try
                {
                    ITypeLib typeLibrary = (ITypeLib)NativeMethods.LoadTypeLibEx(typeLibPath, (int)NativeMethods.REGKIND.REGKIND_NONE);

                    // Get the library attributes so we can unregister it
                    IntPtr pTlibAttr = IntPtr.Zero;

                    try
                    {
                        typeLibrary.GetLibAttr(out pTlibAttr);
                        if (pTlibAttr != IntPtr.Zero)
                        {
                            // Unregister the type library
                            System.Runtime.InteropServices.ComTypes.TYPELIBATTR tlibattr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)Marshal.PtrToStructure(pTlibAttr, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
                            NativeMethods.UnregisterTypeLib(ref tlibattr.guid, tlibattr.wMajorVerNum, tlibattr.wMinorVerNum, tlibattr.lcid, tlibattr.syskind);
                        }
                    }
                    finally
                    {
                        typeLibrary.ReleaseTLibAttr(pTlibAttr);
                        Marshal.ReleaseComObject(typeLibrary);
                    }
                }
                catch (COMException ex)
                {
                    // if the typelib to be unregistered is not registered, then we don't have anything left to do
                    if (ex.ErrorCode == NativeMethods.TYPE_E_REGISTRYACCESS)
                    {
                        Log.LogWarningWithCodeFromResources("UnregisterAssembly.UnregisterTlbFileNotRegistered", typeLibPath);
                    }
                    // if the typelib can't be loaded (say because it's not a valid typelib file) we should report an error
                    else if (ex.ErrorCode == NativeMethods.TYPE_E_CANTLOADLIBRARY)
                    {
                        Log.LogErrorWithCodeFromResources("UnregisterAssembly.UnregisterTlbCantLoadFile", typeLibPath);
                        return(false);
                    }

                    // rethrow other exceptions
                    else
                    {
#if _DEBUG
                        Debug.Assert(false, "Unexpected exception in UnregisterAssembly.DoExecute. " +
                                     "Please log a MSBuild bug specifying the steps to reproduce the problem.");
#endif
                        throw;
                    }
                }
            }
            else
            {
                Log.LogMessageFromResources(MessageImportance.Low, "UnregisterAssembly.UnregisterTlbFileDoesNotExist", typeLibPath);
            }

            return(true);
        }
        static void Main(string[] args)
        {
            Usage();
            if (args.Length != 1)
            {
                Console.WriteLine("Invalid args");
                return;
            }
            // Download repo
            var repoZIP        = "TLB_REPO.zip";
            var outputRepoPath = ".";

            if (!File.Exists(repoZIP))
            {
                Console.WriteLine("Downloading repo...");
                ServicePointManager.Expect100Continue = true;
                ServicePointManager.SecurityProtocol  = SecurityProtocolType.Tls12;
                using (var client = new WebClient())
                {
                    client.DownloadFile(TLB_REPO_URL, repoZIP);
                }
                Console.WriteLine("Extracting ...");
                using (ZipFile zip = ZipFile.Read(repoZIP))
                {
                    zip.ExtractAll(outputRepoPath);
                }
            }
            Console.WriteLine("Loading TLB infos");
            var tlbs = new List <TypeLibInfo>();

            foreach (var file in Directory.GetFiles(outputRepoPath, "*.tlb", SearchOption.AllDirectories))
            {
                ITypeLib typeLib = null;

                try
                {
                    LoadTypeLibEx(file, RegKind.RegKind_Default, out typeLib);
                    IntPtr ppTLibAttr;
                    typeLib.GetLibAttr(out ppTLibAttr);
                    TYPELIBATTR tlibattr = (TYPELIBATTR)Marshal.PtrToStructure(ppTLibAttr, typeof(TYPELIBATTR));
                    typeLib.ReleaseTLibAttr(ppTLibAttr);
                    tlbs.Add(
                        new TypeLibInfo()
                    {
                        File  = file,
                        GUID  = tlibattr.guid.ToString("B").ToUpper(),
                        Major = tlibattr.wMajorVerNum,
                        Minor = tlibattr.wMinorVerNum
                    });
                }
                catch
                { }
                finally
                {
                    if (typeLib != null)
                    {
                        Marshal.ReleaseComObject(typeLib);
                    }
                }
            }
            var       inputFile = args[0];
            XDocument solution;

            using (var f = System.IO.File.OpenRead(inputFile))
            {
                solution = XDocument.Load(f);
            }
            foreach (var reference in solution.Element("VBUpgradeSolution").Elements("ExternalReference"))
            {
                var guid = reference.Attribute("Guid").Value.ToUpper();
                int.TryParse(reference.Attribute("MinorVersion").Value, out var minor);
                int.TryParse(reference.Attribute("MajorVersion").Value, out var major);
                var refInTlbs = tlbs.Find(x => (x.GUID == guid && x.Minor == minor && x.Major == major));
                if (refInTlbs != null)
                {
                    Console.WriteLine($"Mapping {reference.Attribute("FriendlyName")} using TLB {refInTlbs.File} ");
                    reference.Attribute("AbsolutePath").Value = Path.GetFullPath(refInTlbs.File);
                }
            }
            solution.Save(inputFile);
            Console.WriteLine("Solution file updated");
        }
Beispiel #27
0
        public static void ParseTypeLib(string filePath)
        {
            string   fileNameOnly = Path.GetFileNameWithoutExtension(filePath);
            ITypeLib typeLib      = LoadTypeLib(filePath);

            int count = typeLib.GetTypeInfoCount();

            Console.WriteLine($"typeLib count is {count}");
            IntPtr ipLibAtt = IntPtr.Zero;

            typeLib.GetLibAttr(out ipLibAtt);

            var typeLibAttr = (System.Runtime.InteropServices.ComTypes.TYPELIBATTR)
                              Marshal.PtrToStructure(ipLibAtt, typeof(System.Runtime.InteropServices.ComTypes.TYPELIBATTR));
            Guid tlbId = typeLibAttr.guid;

            for (int i = 0; i < count; i++)
            {
                ITypeInfo typeInfo = null;
                typeLib.GetTypeInfo(i, out typeInfo);

                //figure out what guids, typekind, and names of the thing we're dealing with
                IntPtr ipTypeAttr = IntPtr.Zero;
                typeInfo.GetTypeAttr(out ipTypeAttr);

                //unmarshal the pointer into a structure into something we can read
                var typeattr = (System.Runtime.InteropServices.ComTypes.TYPEATTR)
                               Marshal.PtrToStructure(ipTypeAttr, typeof(System.Runtime.InteropServices.ComTypes.TYPEATTR));

                System.Runtime.InteropServices.ComTypes.TYPEKIND typeKind = typeattr.typekind;
                Guid typeId = typeattr.guid;

                //get the name of the type
                string strName, strDocString, strHelpFile;
                int    dwHelpContext;
                typeLib.GetDocumentation(i, out strName, out strDocString, out dwHelpContext, out strHelpFile);


                if (typeKind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_COCLASS)
                {
                    string xmlComClassFormat = "<comClass clsid=\"{0}\" tlbid=\"{1}\" description=\"{2}\" progid=\"{3}.{4}\"></comClass>";
                    string comClassXml       = String.Format(xmlComClassFormat,
                                                             typeId.ToString("B").ToUpper(),
                                                             tlbId.ToString("B").ToUpper(),
                                                             strDocString,
                                                             fileNameOnly, strName
                                                             );
                    Console.WriteLine(comClassXml);
                }
                else if (typeKind == System.Runtime.InteropServices.ComTypes.TYPEKIND.TKIND_INTERFACE)
                {
                    string xmlProxyStubFormat = "<comInterfaceExternalProxyStub name=\"{0}\" iid=\"{1}\" tlbid=\"{2}\" proxyStubClsid32=\"{3}\"></comInterfaceExternalProxyStub>";
                    string proxyStubXml       = String.Format(xmlProxyStubFormat,
                                                              strName,
                                                              typeId.ToString("B").ToUpper(),
                                                              tlbId.ToString("B").ToUpper(),
                                                              "{00020424-0000-0000-C000-000000000046}"
                                                              );
                    Console.WriteLine(proxyStubXml);
                }
            }

            return;
        }
Beispiel #28
0
        /// <summary>
        /// Helper method for retrieving type lib attributes for the given type lib
        /// </summary>
        /// <param name="typeLib"></param>
        /// <param name="typeLibAttr"></param>
        /// <returns></returns>
        internal static void GetTypeLibAttrForTypeLib(ref ITypeLib typeLib, out TYPELIBATTR typeLibAttr)
        {
            IntPtr pAttrs = IntPtr.Zero;
            typeLib.GetLibAttr(out pAttrs);

            // GetLibAttr should never return null, this is just to be safe
            if (pAttrs == IntPtr.Zero)
            {
                throw new COMException(
                    ResourceUtilities.FormatResourceString("ResolveComReference.CannotGetTypeLibAttrForTypeLib"));
            }

            try
            {
                typeLibAttr = (TYPELIBATTR)Marshal.PtrToStructure(pAttrs, typeof(TYPELIBATTR));
            }
            finally
            {
                typeLib.ReleaseTLibAttr(pAttrs);
            }
        }
Beispiel #29
0
 public TypeLibAttr(ITypeLib typelib)
 {
     m_typelib = typelib;
     typelib.GetLibAttr(out m_ipAttr);
     m_attr = (TYPELIBATTR)Marshal.PtrToStructure(m_ipAttr, typeof(TYPELIBATTR));
 }
Beispiel #30
0
        /// ------------------------------------------------------------------------------------
        /// <summary>
        /// Creates the entries for the type library and all classes defined in this type
        /// library. We can get the necessary information for the file element (file name and
        /// size) directly from the file. We get the information for the type library from
        /// the type library itself.
        /// </summary>
        /// <param name="parent">The parent node.</param>
        /// <param name="fileName">Name (and path) of the file.</param>
        /// ------------------------------------------------------------------------------------
        public void ProcessTypeLibrary(XmlElement parent, string fileName)
        {
            _baseDirectory = Path.GetDirectoryName(fileName);
            _fileName      = fileName.ToLower();

            try
            {
                XmlNode  oldChild;
                ITypeLib typeLib = Tasks.RegHelper.LoadTypeLib(_fileName);
                IntPtr   pLibAttr;
                typeLib.GetLibAttr(out pLibAttr);
                var libAttr = (TYPELIBATTR)
                              Marshal.PtrToStructure(pLibAttr, typeof(TYPELIBATTR));
                typeLib.ReleaseTLibAttr(pLibAttr);

                string flags = string.Empty;
                if ((libAttr.wLibFlags & LIBFLAGS.LIBFLAG_FHASDISKIMAGE) == LIBFLAGS.LIBFLAG_FHASDISKIMAGE)
                {
                    flags = "HASDISKIMAGE";
                }

                // <file name="FwKernel.dll" asmv2:size="1507328">
                var file = GetOrCreateFileNode(parent, fileName);

                // <typelib tlbid="{2f0fccc0-c160-11d3-8da2-005004defec4}" version="1.0" helpdir=""
                //		resourceid="0" flags="HASDISKIMAGE" />
                if (_tlbGuids.ContainsKey(libAttr.guid))
                {
                    _log.LogWarning("Type library with GUID {0} is defined in {1} and {2}",
                                    libAttr.guid, _tlbGuids[libAttr.guid], Path.GetFileName(fileName));
                }
                else
                {
                    _tlbGuids.Add(libAttr.guid, Path.GetFileName(fileName));
                    XmlElement elem = _doc.CreateElement("typelib", UrnAsmv1);
                    elem.SetAttribute("tlbid", libAttr.guid.ToString("B"));
                    elem.SetAttribute("version", string.Format("{0}.{1}", libAttr.wMajorVerNum,
                                                               libAttr.wMinorVerNum));
                    elem.SetAttribute("helpdir", string.Empty);
                    elem.SetAttribute("resourceid", "0");
                    elem.SetAttribute("flags", flags);
                    oldChild = file.SelectSingleNode(string.Format("typelib[tlbid='{0}']",
                                                                   libAttr.guid.ToString("B")));
                    if (oldChild != null)
                    {
                        file.ReplaceChild(elem, oldChild);
                    }
                    else
                    {
                        file.AppendChild(elem);
                    }
                }

                Debug.WriteLine(string.Format(@"typelib tlbid=""{0}"" version=""{1}.{2}"" helpdir="""" resourceid=""0"" flags=""{3}""",
                                              libAttr.guid, libAttr.wMajorVerNum, libAttr.wMinorVerNum, flags));

                int count = typeLib.GetTypeInfoCount();
                for (int i = 0; i < count; i++)
                {
                    ITypeInfo typeInfo;
                    typeLib.GetTypeInfo(i, out typeInfo);

                    ProcessTypeInfo(parent, libAttr.guid, typeInfo);
                }

                oldChild = parent.SelectSingleNode(string.Format("file[name='{0}']",
                                                                 Path.GetFileName(fileName)));
                if (oldChild != null)
                {
                    parent.ReplaceChild(file, oldChild);
                }
                else
                {
                    parent.AppendChild(file);
                }
            }
            catch (Exception)
            {
                // just ignore if this isn't a type library
                _log.LogMessage(MessageImportance.Normal, "Can't load type library {0}", fileName);
            }
        }
Beispiel #31
0
            /// <summary>
            /// <para>Gets the TypeLibAttr corresponding to the TLB containing our ActiveX control.</para>
            /// </summary>
            private TYPELIBATTR GetTypeLibAttr()
            {
                string      controlKey = "CLSID\\" + clsid;
                RegistryKey key        = Registry.ClassesRoot.OpenSubKey(controlKey);

                if (key == null)
                {
                    if (AxToolSwitch.TraceVerbose)
                    {
                        Debug.WriteLine("No registry key found for: " + controlKey);
                    }
                    throw new ArgumentException(string.Format(SR.AXNotRegistered, controlKey.ToString()));
                }

                // Load the typelib into memory.
                //
                ITypeLib pTLB = null;

                // Open the key for the TypeLib
                //
                RegistryKey tlbKey = key.OpenSubKey("TypeLib");

                if (tlbKey != null)
                {
                    // Get the major and minor version numbers.
                    //
                    RegistryKey verKey = key.OpenSubKey("Version");
                    Debug.Assert(verKey != null, "No version registry key found for: " + controlKey);

                    string ver = (string)verKey.GetValue("");
                    int    dot = ver.IndexOf('.');

                    short majorVer;

                    short minorVer;
                    if (dot == -1)
                    {
                        majorVer = short.Parse(ver, CultureInfo.InvariantCulture);
                        minorVer = 0;
                    }
                    else
                    {
                        majorVer = short.Parse(ver.Substring(0, dot), CultureInfo.InvariantCulture);
                        minorVer = short.Parse(ver.Substring(dot + 1, ver.Length - dot - 1), CultureInfo.InvariantCulture);
                    }

                    Debug.Assert(majorVer > 0 && minorVer >= 0, "No Major version number found for: " + controlKey);
                    verKey.Close();

                    object o = tlbKey.GetValue("");

                    // Try to get the TypeLib's Guid.
                    //
                    var tlbGuid = new Guid((string)o);
                    Debug.Assert(!tlbGuid.Equals(Guid.Empty), "No valid Guid found for: " + controlKey);
                    tlbKey.Close();

                    try
                    {
                        pTLB = Oleaut32.LoadRegTypeLib(ref tlbGuid, majorVer, minorVer, Application.CurrentCulture.LCID);
                    }
                    catch (Exception e)
                    {
                        if (ClientUtils.IsCriticalException(e))
                        {
                            throw;
                        }
                    }
                }

                // Try to load the TLB directly from the InprocServer32.
                //
                // If that fails, try to load the TLB based on the TypeLib guid key.
                //
                if (pTLB == null)
                {
                    RegistryKey inprocServerKey = key.OpenSubKey("InprocServer32");
                    if (inprocServerKey != null)
                    {
                        string inprocServer = (string)inprocServerKey.GetValue("");
                        Debug.Assert(inprocServer != null, "No valid InprocServer32 found for: " + controlKey);
                        inprocServerKey.Close();

                        pTLB = Oleaut32.LoadTypeLib(inprocServer);
                    }
                }

                key.Close();

                if (pTLB != null)
                {
                    try
                    {
                        IntPtr pTlibAttr = NativeMethods.InvalidIntPtr;
                        pTLB.GetLibAttr(out pTlibAttr);
                        if (pTlibAttr == NativeMethods.InvalidIntPtr)
                        {
                            throw new ArgumentException(string.Format(SR.AXNotRegistered, controlKey.ToString()));
                        }
                        else
                        {
                            // Marshal the returned int as a TLibAttr structure
                            //
                            TYPELIBATTR typeLibraryAttributes = (TYPELIBATTR)Marshal.PtrToStructure(pTlibAttr, typeof(TYPELIBATTR));
                            pTLB.ReleaseTLibAttr(pTlibAttr);

                            return(typeLibraryAttributes);
                        }
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(pTLB);
                    }
                }
                else
                {
                    throw new ArgumentException(string.Format(SR.AXNotRegistered, controlKey.ToString()));
                }
            }
 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);
     }
 }