/// <summary>
        /// This is an helper method to convert the VSCOMPONENTSELECTORDATA recieved by the
        /// implementer of IVsComponentUser into a ProjectElement that can be used to create
        /// an instance of this class.
        /// This should not be called for project reference or reference to managed assemblies.
        /// </summary>
        /// <returns>ProjectElement corresponding to the COM component passed in</returns>
        private ProjectElement GetProjectElementBasedOnInputFromComponentSelectorData()
        {
            ProjectElement element = new ProjectElement(this.ProjectMgr, this.typeName, ProjectFileConstants.COMReference);

            // Set the basic information regarding this COM component
            element.SetMetadata(ProjectFileConstants.Guid, this.typeGuid.ToString("B"));
            element.SetMetadata(ProjectFileConstants.VersionMajor, this.majorVersionNumber);
            element.SetMetadata(ProjectFileConstants.VersionMinor, this.minorVersionNumber);
            element.SetMetadata(ProjectFileConstants.Lcid, this.lcid);
            element.SetMetadata(ProjectFileConstants.Isolated, false.ToString());

            // See if a PIA exist for this component
            TypeLibConverter typelib = new TypeLibConverter();
            string           assemblyName;
            string           assemblyCodeBase;

            if (typelib.GetPrimaryInteropAssembly(this.typeGuid, Int32.Parse(this.majorVersionNumber, CultureInfo.InvariantCulture), Int32.Parse(this.minorVersionNumber, CultureInfo.InvariantCulture), Int32.Parse(this.lcid, CultureInfo.InvariantCulture), out assemblyName, out assemblyCodeBase))
            {
                element.SetMetadata(ProjectFileConstants.WrapperTool, WrapperToolAttributeValue.Primary.ToString().ToLower());
            }
            else
            {
                // MSBuild will have to generate an interop assembly
                element.SetMetadata(ProjectFileConstants.WrapperTool, WrapperToolAttributeValue.TlbImp.ToString().ToLower());
                element.SetMetadata(ProjectFileConstants.Private, true.ToString());
            }
            return(element);
        }
Esempio n. 2
0
        static int Main(string[] args)
        {
            if (args.Length < 2)
            {
                Console.WriteLine("Usage: tlb-convert <unmanaged COM DLL path> <managed wrapper path> [root namespace]");
                return(2);
            }

            try
            {
                string srcDll        = args[0];
                string outDll        = args[1];
                string rootNamespace = args.Length == 3 ? args[2] : null;

                Object typeLib;
                LoadTypeLibEx(srcDll, RegKind.RegKind_None, out typeLib);
                TypeLibConverter tlbConv = new TypeLibConverter();
                AssemblyBuilder  asm     = tlbConv.ConvertTypeLibToAssembly(typeLib, outDll, 0, new ConversionEventHandler(), null, null, rootNamespace, null);
                asm.Save(outDll);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception: {0}\n{1}", e.Message, e.StackTrace);
                return(1);
            }

            Console.WriteLine("\nConversion successful.");
            return(0);
        }
Esempio n. 3
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);
        }
Esempio n. 4
0
        private static ITypeLib DoExportAndRegister(Assembly asm, string strTypeLibName)
        {
            ITypeLibConverter typeLibConverter = new TypeLibConverter();
            ExporterCallback  notifySink       = new ExporterCallback();

            //RegAsm'ом используется только флаг OnlyReferenceRegistered если установлен registered
            //поскольку у нас это нигде не использовалось, параметр опущен
            ITypeLib        typeLib        = (ITypeLib)typeLibConverter.ConvertAssemblyToTypeLib(asm, strTypeLibName, TypeLibExporterFlags.None, notifySink);
            ICreateITypeLib createITypeLib = null;

            try
            {
                createITypeLib = (ICreateITypeLib)typeLib;
                createITypeLib.SaveAllChanges();
            }
            catch
            {
                throw;
            }
            finally
            {
                Marshal.FinalReleaseComObject(createITypeLib);
            }

            return(typeLib);
        }
Esempio n. 5
0
        internal static UCOMITypeLib DoExportAndRegister(Assembly asm, String strTypeLibName)
        {
            // Create the TypeLibConverter.
            ITypeLibConverter TLBConv = new TypeLibConverter();

            // Convert the assembly.
            ExporterCallback callback = new ExporterCallback();
            UCOMITypeLib     Tlb      = (UCOMITypeLib)TLBConv.ConvertAssemblyToTypeLib(asm, strTypeLibName, s_Options.m_Flags, callback);

            // Persist the typelib.
            try
            {
                UCOMICreateITypeLib CreateTlb = (UCOMICreateITypeLib)Tlb;
                CreateTlb.SaveAllChanges();
            }
            catch (Exception e)
            {
                ThrowAppException(Resource.FormatString("Err_TypelibSaveFailed"), e);
            }

            // Register the typelib.
            try
            {
                RegisterTypeLib(Tlb, strTypeLibName, Path.GetDirectoryName(strTypeLibName));
            }
            catch (Exception e)
            {
                ThrowAppException(Resource.FormatString("Err_TypelibRegisterFailed"), e);
            }

            return(Tlb);
        }
            private Assembly ConvertTypeLib(NativeMethods.ITypeLib typeLib, string assemblyPath, string assemblyFile, string assemblyNamespace, Version assemblyVersion, TypeLibImporterFlags flags, byte[] publicKey, StrongNameKeyPair keyPair)
            {
                try
                {
                    this.RaiseMessage(string.Format("Converting '{0}'.", GetTypeLibName(typeLib)));

                    TypeLibConverter converter       = new TypeLibConverter();
                    AssemblyBuilder  assemblyBuilder = converter.ConvertTypeLibToAssembly(typeLib, Path.Combine(assemblyPath, assemblyFile), flags, this, publicKey, keyPair, assemblyNamespace, assemblyVersion);

                    this.RaiseMessage(string.Format("Saving '{0}'.", assemblyFile));

                    string currentDirectory = Environment.CurrentDirectory;
                    Environment.CurrentDirectory = assemblyPath;
                    assemblyBuilder.Save(assemblyFile);
                    Environment.CurrentDirectory = currentDirectory;

                    return(assemblyBuilder);
                }
                catch (COMException exception)
                {
                    this.RaiseError(exception.Message);
                }

                return(null);
            }
Esempio n. 7
0
        /// <summary>
        ///  Helper method - exports a type library for an assembly. Returns true if succeeded.
        /// </summary>
        private bool ExportTypeLib(Assembly asm, string typeLibFileName)
        {
            _typeLibExportFailed = false;
            ITypeLib convertedTypeLib = null;

            try
            {
                // Create a converter and run the conversion
                ITypeLibConverter tlbConverter = new TypeLibConverter();
                convertedTypeLib = (ITypeLib)tlbConverter.ConvertAssemblyToTypeLib(asm, typeLibFileName, 0, this);

                if (convertedTypeLib == null || _typeLibExportFailed)
                {
                    return(false);
                }

                // Persist the type library
                UCOMICreateITypeLib createTypeLib = (UCOMICreateITypeLib)convertedTypeLib;

                createTypeLib.SaveAllChanges();
            }
            finally
            {
                if (convertedTypeLib != null)
                {
                    Marshal.ReleaseComObject((ITypeLib)convertedTypeLib);
                }
            }

            return(!_typeLibExportFailed);
        }
Esempio n. 8
0
        public object ResolveRef(Assembly assembly)
        {
            var converter = new TypeLibConverter();
            var lib       = converter.ConvertAssemblyToTypeLib(assembly, assembly.GetName().Name,
                                                               TypeLibExporterFlags.None, this);

            return(lib);
        }
Esempio n. 9
0
        internal static ITypeLib GenerateTypeLib(Assembly asm, ref string strTlbName)
        {
            ITypeLibConverter converter  = new TypeLibConverter();
            ExporterCallback  notifySink = new ExporterCallback();
            ITypeLib          lib        = (ITypeLib)converter.ConvertAssemblyToTypeLib(asm, strTlbName, TypeLibExporterFlags.None, notifySink);

            ((ICreateITypeLib)lib).SaveAllChanges();
            return(lib);
        }
Esempio n. 10
0
        internal Assembly GetPrimaryInteropAssembly(UCOMITypeLib typeLib, TypeLibConverter tlbConverter)
        {
            Assembly pia = FindRCW(typeLib);

            if (pia != null)
            {
                return(pia);
            }

            IntPtr typeLibAttr = NativeMethods.InvalidIntPtr;

            typeLib.GetLibAttr(out typeLibAttr);

            if (typeLibAttr != NativeMethods.InvalidIntPtr)
            {
                // Marshal the returned int as a TLibAttr structure
                //
                TYPELIBATTR tlbAttr     = (TYPELIBATTR)Marshal.PtrToStructure(typeLibAttr, typeof(TYPELIBATTR));
                string      asmName     = null;
                string      asmCodeBase = null;

                try {
                    tlbConverter.GetPrimaryInteropAssembly(tlbAttr.guid, tlbAttr.wMajorVerNum, tlbAttr.wMinorVerNum, tlbAttr.lcid,
                                                           out asmName, out asmCodeBase);

                    if (asmName != null && asmCodeBase == null)
                    {
                        // We found the PIA in the GAC... we need a codebase for this
                        // so we can pass this to the compiler.
                        //
                        try {
                            pia         = Assembly.Load(asmName);
                            asmCodeBase = GetLocalPath(pia.EscapedCodeBase);
                        }
                        catch (Exception e) {
                            Debug.WriteLineIf(AxWrapperGen.AxWrapper.Enabled, "Could load assembly from GAC " + asmName + " Exception " + e.Message);
                        }
                    }
                    else if (asmCodeBase != null)
                    {
                        asmCodeBase = GetLocalPath(asmCodeBase);
                        pia         = Assembly.LoadFrom(asmCodeBase);
                    }

                    if (pia != null)
                    {
                        AddRCW(typeLib, pia);
                        AddReferencedAssembly(asmCodeBase);
                    }
                }
                finally {
                    typeLib.ReleaseTLibAttr(typeLibAttr);
                }
            }

            return(pia);
        }
        static bool PerformTypeLibCreationAndRegistration(string strTargetAssemblyFilePath)
        {
            try
            {
                string strTargetAssemblyDirectory = Path.GetDirectoryName(strTargetAssemblyFilePath);
                string strTargetAssemblyFileNameWithoutExtension = Path.GetFileNameWithoutExtension(strTargetAssemblyFilePath);
                string strTargetTypeLibFullPath = strTargetAssemblyDirectory + "\\" + strTargetAssemblyFileNameWithoutExtension + ".tlb";

                TypeLibConverter     converter = new TypeLibConverter();
                Assembly             assembly  = Assembly.LoadFrom(strTargetAssemblyFilePath);
                TypeLibExporterFlags flags;

                if (Is32Bits())
                {
                    flags = TypeLibExporterFlags.ExportAs32Bit;
                }
                else if (Is64Bits())
                {
                    flags = TypeLibExporterFlags.ExportAs64Bit;
                }
                else
                {
                    Console.WriteLine(string.Format("Unknown bit-ness."));
                    return(false);
                }

                ICreateTypeLib create_typeLib = (ICreateTypeLib)(converter.ConvertAssemblyToTypeLib
                                                                     (assembly, strTargetTypeLibFullPath, flags, m_pITypeLibExporterNotifySink));

                // SaveAllChanges() will create the TypeLib physical file
                // based on strTargetTypeLibFullPath.
                create_typeLib.SaveAllChanges();

                ITypeLib typelib = (ITypeLib)create_typeLib;

                UInt32 uiRetTemp = RegisterTypeLib(typelib, strTargetTypeLibFullPath, null);

                if (uiRetTemp == 0)
                {
                    Console.WriteLine(string.Format("TypeLib File [{0:S}] registered.", strTargetTypeLibFullPath));
                }
                else
                {
                    Console.WriteLine(string.Format("Failed to register TypeLib File [{0:S}]. Error code : [{1:D}]",
                                                    strTargetTypeLibFullPath, uiRetTemp));
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(string.Format("An exception occurred. Exception description : [{0:S}].", ex.Message));
                return(false);
            }
        }
Esempio n. 12
0
    public static void Main()
    {
        Assembly               asm          = Assembly.LoadFrom("MyAssembly.dll");
        TypeLibConverter       converter    = new TypeLibConverter();
        ConversionEventHandler eventHandler = new ConversionEventHandler();

        UCOMICreateITypeLib typeLib = (UCOMICreateITypeLib)converter.ConvertAssemblyToTypeLib(asm, "MyTypeLib.dll", 0, eventHandler);

        typeLib.SaveAllChanges();
    }
Esempio n. 13
0
        /// <summary>
        /// Try to search the GAC for an assembly that seems to match the given type GUID
        /// </summary>
        private static Assembly SearchForInteropAssembly(Guid typeInfoGuid)
        {
            Assembly assembly = null;

            try {
                string      typelibPath = @"Interface\{" + typeInfoGuid + @"}\TypeLib";
                RegistryKey typelibKey  = Registry.ClassesRoot.OpenSubKey(typelibPath);
                if (typelibKey == null)
                {
                    return(null);
                }

                // Read HKCR\Interface\{<typeInfoGuid>}\TypeLib\(Default)"
                Guid typelibGuid = new Guid(typelibKey.GetValue(null, null) as string);

                // Read HKCR\Interface\{<typeInfoGuid>}\TypeLib\Version"
                string typelibVersion = typelibKey.GetValue("Version") as String;
                if (typelibVersion == null)
                {
                    return(null);
                }

                string[] versionSplit = typelibVersion.Split('.');
                int      major        = int.Parse(versionSplit[0]);
                int      minor        = int.Parse(versionSplit[1]);

                // Try using TypeLibConverter
                TypeLibConverter tlc = new TypeLibConverter();
                string           asmName = null, asmCodeBase = null;
                tlc.GetPrimaryInteropAssembly(typelibGuid, major, minor, 0, out asmName, out asmCodeBase);

                if (asmName != null)
                {
                    assembly = Assembly.Load(asmName);
                }

                if (assembly != null)
                {
                    return(assembly);
                }

                // Next, try looking up the GAC
                assembly = SearchForInteropAssemblyInGAC(typeInfoGuid, major, minor);
            } catch (Exception e) {
                if (IronPython.Hosting.PythonEngine.options.EngineDebug)
                {
                    throw e;
                }
            }

            return(assembly);
        }
            Assembly ITypeLibImporterNotifySink.ResolveRef(object typeLib)
            {
                Assembly assembly2;

                try
                {
                    string comReference = this.importer.GetComReference((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib);
                    if (comReference != null)
                    {
                        this.importer.AddReferencedAssembly(comReference);
                    }
                    Assembly primaryInteropAssembly = this.importer.FindRCW((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib);
                    if (primaryInteropAssembly != null)
                    {
                        assembly2 = primaryInteropAssembly;
                    }
                    else
                    {
                        try
                        {
                            string assemName = Path.Combine(this.options.outputDirectory, Marshal.GetTypeLibName((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib) + ".dll");
                            if (this.importer.GetReferencedAssembly(assemName) != null)
                            {
                                return(this.importer.GetCopiedAssembly(assemName, false, false));
                            }
                            TypeLibConverter tlbConverter = new TypeLibConverter();
                            primaryInteropAssembly = this.importer.GetPrimaryInteropAssembly((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib, tlbConverter);
                            if (primaryInteropAssembly != null)
                            {
                                return(primaryInteropAssembly);
                            }
                            AssemblyBuilder asmBldr = tlbConverter.ConvertTypeLibToAssembly(typeLib, assemName, TypeLibImporterFlags.None, new AxImporter.ImporterCallback(this.importer), this.options.publicKey, this.options.keyPair, null, null);
                            if (comReference == null)
                            {
                                this.importer.SaveAssemblyBuilder((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib, asmBldr, assemName);
                                this.importer.AddRCW((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib, asmBldr);
                                return(asmBldr);
                            }
                            assembly2 = this.importer.GetCopiedAssembly(comReference, false, false);
                        }
                        catch
                        {
                            assembly2 = null;
                        }
                    }
                }
                finally
                {
                    Marshal.ReleaseComObject(typeLib);
                }
                return(assembly2);
            }
Esempio n. 15
0
        internal static UCOMITypeLib GenerateTypeLib(Assembly asm, ref String strTlbName)
        {
            ITypeLibConverter tlbConv = new TypeLibConverter();

            ExporterCallback callback = new ExporterCallback();
            UCOMITypeLib     tlb      = (UCOMITypeLib)tlbConv.ConvertAssemblyToTypeLib(asm, strTlbName, 0, callback);

            // Persist the typelib.
            UCOMICreateITypeLib createTlb = (UCOMICreateITypeLib)tlb;

            createTlb.SaveAllChanges();

            return(tlb);
        }
Esempio n. 16
0
        public string GenerateIdl(Assembly assembly)
        {
            var converter = new TypeLibConverter();
            var sink      = new TypeLibExporterNotifySink();
            var lib       = (ITypeLib)converter.ConvertAssemblyToTypeLib(assembly, assembly.GetName().Name,
                                                                         TypeLibExporterFlags.None, sink);
            var formatter = new PlainIDLFormatter();
            var owLib     = new OWTypeLib(lib);

            owLib.Listeners.Add(new IdlListener());

            owLib.BuildIDLInto(formatter);
            return(formatter.ToString());
        }
        public void BuildLib(string targetFolder)
        {
            NativeMethods.LoadTypeLibEx(VBoxWrapper.COMInterface.VBoxComUtils.GetVirtualBoxComTypeLib(), NativeMethods.RegKind.RegKind_None, out _typeLibInMemory);
            if (_typeLibInMemory == null)
            {
                throw new DllNotFoundException("Could not load Virtualbox-Typelibrary.");
            }


            TypeLibConverter       converter = new TypeLibConverter();
            ConversionEventHandler handler   = new ConversionEventHandler();

            AssemblyBuilder asm = converter.ConvertTypeLibToAssembly(_typeLibInMemory, "Interop.VirtualBox.dll", TypeLibImporterFlags.SafeArrayAsSystemArray, handler, null, null, "VirtualBox", null); //using assembly name "VirtualBox" and SafeArrayAsSystemArray to be compatible to VisualStudio-Generated Interop-Assembly

            asm.Save("Interop.VirtualBox.dll");
        }
Esempio n. 18
0
        /// <summary>
        /// Gets an assembly used to interop with the objects defined in the type
        /// library.
        /// </summary>
        /// <param name="typeLibraryName">
        ///		Name of the type library such as SHDocVw.dll
        /// </param>
        /// <returns>
        ///		Returns the assembly if found/created otherwise null.
        /// </returns>
        public static Assembly GetAssemblyForTypeLib(string typeLibraryName)
        {
            object typeLib = null;

            LoadTypeLibEx(typeLibraryName, RegKind.RegKind_None, out typeLib);

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

            TypeLibConverter       converter    = new TypeLibConverter();
            ConversionEventHandler eventHandler = new ConversionEventHandler();
            AssemblyBuilder        asm          = converter.ConvertTypeLibToAssembly(typeLib, "Interop." + typeLibraryName, 0, eventHandler, null, null, null, null);

            return(asm);
        }
Esempio n. 19
0
    public static void Main()
    {
        Object typeLib;

        LoadTypeLibEx("SHDocVw.dll", RegKind.RegKind_None, out typeLib);

        if (typeLib == null)
        {
            Console.WriteLine("LoadTypeLibEx failed.");
            return;
        }

        TypeLibConverter       converter    = new TypeLibConverter();
        ConversionEventHandler eventHandler = new ConversionEventHandler();
        AssemblyBuilder        asm          = converter.ConvertTypeLibToAssembly(typeLib, "ExplorerLib.dll", 0, eventHandler, null, null, null, null);

        asm.Save("ExplorerLib.dll");
    }
Esempio n. 20
0
        public static string GenerateAssemblyFromTypeLib(UCOMITypeLib typLib)
        {
            // Need a sink for the TypeLibConverter.
            ImporterNotiferSink sink = new ImporterNotiferSink();

            #region Notes on Strong Name...

            /* Don't need a *.snk file if you are not building a primary interop asm.
             * Just send in nulls to the ConvertTypeLibToAssembly() method.
             * But if you have a valid *.snk file, you can use it as so:
             *
             * // Object representation of *.snk file.
             * FileStream fs = File.Open(@"D:\APress Books\InteropBook\MyTypeLibImporter\bin\Debug\theKey.snk",
             *                          FileMode.Open);
             * System.Reflection.StrongNameKeyPair keyPair = new StrongNameKeyPair(fs);
             */
            #endregion

            // This class will covert COM type info into
            // .NET metadata and vice-versa.
            TypeLibConverter tlc = new TypeLibConverter();

            // Generate name of the assembly.
            string typeLibName = Marshal.GetTypeLibName(typLib);
            string asmName     = "interop." + typeLibName + ".dll";

            // Now make the assembly based on COM type information.
            AssemblyBuilder asmBuilder = tlc.ConvertTypeLibToAssembly((UCOMITypeLib)typLib,
                                                                      asmName,
                                                                      TypeLibImporterFlags.SafeArrayAsSystemArray,
                                                                      sink,
                                                                      null,        // If you have a strong name: keyPair.PublicKey,
                                                                      null,        // If you have a strong name: keyPair
                                                                      typeLibName, // Namespace name is same as file name.
                                                                      null);       // null = (typeLibMajor.typeLibMinor.0.0)

            // Save the assembly in the app directory!
            asmBuilder.Save(asmName);

            // return Assembly ref to call.
            return(asmName);
        }
Esempio n. 21
0
        internal override bool FindExistingWrapper(out ComReferenceWrapperInfo wrapperInfo, DateTime componentTimestamp)
        {
            string str;
            string str2;

            wrapperInfo = null;
            TypeLibConverter converter = new TypeLibConverter();

            if (!converter.GetPrimaryInteropAssembly(this.ReferenceInfo.attr.guid, this.ReferenceInfo.attr.wMajorVerNum, this.ReferenceInfo.attr.wMinorVerNum, this.ReferenceInfo.attr.lcid, out str, out str2))
            {
                return(false);
            }
            try
            {
                if ((str2 != null) && (str2.Length > 0))
                {
                    Uri      uri      = new Uri(str2);
                    Assembly assembly = Assembly.UnsafeLoadFrom(uri.LocalPath);
                    wrapperInfo                 = new ComReferenceWrapperInfo();
                    wrapperInfo.path            = uri.LocalPath;
                    wrapperInfo.assembly        = assembly;
                    wrapperInfo.originalPiaName = new AssemblyNameExtension(AssemblyName.GetAssemblyName(uri.LocalPath));
                }
                else
                {
                    Assembly assembly2 = Assembly.Load(str);
                    wrapperInfo                 = new ComReferenceWrapperInfo();
                    wrapperInfo.path            = assembly2.Location;
                    wrapperInfo.assembly        = assembly2;
                    wrapperInfo.originalPiaName = new AssemblyNameExtension(str, true);
                }
            }
            catch (FileNotFoundException)
            {
            }
            catch (BadImageFormatException)
            {
                base.Log.LogWarningWithCodeFromResources("ResolveComReference.BadAssemblyImage", new object[] { str });
            }
            return(wrapperInfo != null);
        }
Esempio n. 22
0
        public void RegisterAsnetMmcAssembly(int doReg, string typeName, string binaryDirectory, out IntPtr exception)
        {
            exception = IntPtr.Zero;

            try
            {
                Assembly             webAssembly = Assembly.GetAssembly(Type.GetType(typeName, true));
                RegistrationServices rs          = new RegistrationServices();

                if (doReg != 0)
                {
                    if (!rs.RegisterAssembly(webAssembly, AssemblyRegistrationFlags.None))
                    {
                        exception = Marshal.StringToBSTR((new Exception(SR.GetString(SR.Unable_To_Register_Assembly, webAssembly.FullName))).ToString());
                    }
                    TypeLibConverter    converter    = new TypeLibConverter();
                    ConversionEventSink eventHandler = new ConversionEventSink();

                    IRegisterCreateITypeLib typeLib = (IRegisterCreateITypeLib)converter.ConvertAssemblyToTypeLib(webAssembly, System.IO.Path.Combine(binaryDirectory, "AspNetMMCExt.tlb"), 0, eventHandler);
                    typeLib.SaveAllChanges();
                }
                else
                {
                    // Consider deleting tlb file
                    if (!rs.UnregisterAssembly(webAssembly))
                    {
                        exception = Marshal.StringToBSTR((new Exception(SR.GetString(SR.Unable_To_UnRegister_Assembly, webAssembly.FullName))).ToString());
                    }

                    try {
                        File.Delete(System.IO.Path.Combine(binaryDirectory, "AspNetMMCExt.tlb"));
                    }
                    catch {
                    }
                }
            }
            catch (Exception e)
            {
                exception = Marshal.StringToBSTR(e.ToString());
            }
        }
Esempio n. 23
0
        public Assembly Import(string InteropFileName, string path, string name, TlbImp parent)
        {
            ITypeLib typeLib;

            AsmPath = Path.GetDirectoryName(InteropFileName);
            LoadTypeLibEx(path, RegKind.RegKind_None, out typeLib);

            if (typeLib == null)
            {
                return(null);
            }
            TypeLibConverter       converter    = new TypeLibConverter();
            ConversionEventHandler eventHandler = new ConversionEventHandler(parent == null?this:parent);
            AssemblyBuilder        asm          =
                converter.ConvertTypeLibToAssembly(typeLib, Path.GetFileName(InteropFileName), TypeLibImporterFlags.None, eventHandler, null, null, name, null);
            string outputFolder = Path.GetDirectoryName(InteropFileName);
            string interopFName = Path.Combine(outputFolder, String.Concat("Interop.", name, ".dll"));

            asm.Save(Path.GetFileName(interopFName));
            Marshal.ReleaseComObject(typeLib);
            return(asm as Assembly);
        }
Esempio n. 24
0
        public static UCOMITypeLib DoExport(Assembly asm, String strTypeLibName)
        {
            // Create the TypeLibConverter.
            ITypeLibConverter TLBConv = new TypeLibConverter();

            // Convert the assembly.
            ExporterCallback callback = new ExporterCallback();
            UCOMITypeLib     Tlb      = (UCOMITypeLib)TLBConv.ConvertAssemblyToTypeLib(asm, strTypeLibName, 0, callback);

            // Persist the typelib.
            try
            {
                UCOMICreateITypeLib CreateTlb = (UCOMICreateITypeLib)Tlb;
                CreateTlb.SaveAllChanges();
            }
            catch (Exception e)
            {
                ThrowAppException(Resource.FormatString("Err_ErrorSavingTypeLib"), e);
            }

            return(Tlb);
        }
        internal static object GenerateTypeLibrary(Assembly asm, string tlb, Report report)
        {
            object obj3;

            try
            {
                TypeLibConverter converter = new TypeLibConverter();
                RegistrationExporterNotifySink notifySink = new RegistrationExporterNotifySink(tlb, report);
                object obj2 = converter.ConvertAssemblyToTypeLib(asm, tlb, TypeLibExporterFlags.OnlyReferenceRegistered, notifySink);
                ((ICreateTypeLib)obj2).SaveAllChanges();
                RegisterTypeLibrary(tlb);
                obj3 = obj2;
            }
            catch (Exception exception)
            {
                if ((exception is NullReferenceException) || (exception is SEHException))
                {
                    throw;
                }
                throw new RegistrationException(Resource.FormatString("Reg_TypeLibGenErr", tlb, asm), exception);
            }
            return(obj3);
        }
Esempio n. 26
0
 public void RegisterAsnetMmcAssembly(int doReg, string typeName, string binaryDirectory, out IntPtr exception)
 {
     exception = IntPtr.Zero;
     try
     {
         Assembly             assembly = Assembly.GetAssembly(Type.GetType(typeName, true));
         RegistrationServices services = new RegistrationServices();
         if (doReg != 0)
         {
             if (!services.RegisterAssembly(assembly, AssemblyRegistrationFlags.None))
             {
                 exception = Marshal.StringToBSTR(new Exception(System.Web.SR.GetString("Unable_To_Register_Assembly", new object[] { assembly.FullName })).ToString());
             }
             TypeLibConverter    converter  = new TypeLibConverter();
             ConversionEventSink notifySink = new ConversionEventSink();
             ((IRegisterCreateITypeLib)converter.ConvertAssemblyToTypeLib(assembly, Path.Combine(binaryDirectory, "AspNetMMCExt.tlb"), TypeLibExporterFlags.None, notifySink)).SaveAllChanges();
         }
         else
         {
             if (!services.UnregisterAssembly(assembly))
             {
                 exception = Marshal.StringToBSTR(new Exception(System.Web.SR.GetString("Unable_To_UnRegister_Assembly", new object[] { assembly.FullName })).ToString());
             }
             try
             {
                 File.Delete(Path.Combine(binaryDirectory, "AspNetMMCExt.tlb"));
             }
             catch
             {
             }
         }
     }
     catch (Exception exception2)
     {
         exception = Marshal.StringToBSTR(exception2.ToString());
     }
 }
Esempio n. 27
0
        public 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;

                lock (m_typelibsname)
                {
                    m_typelibsname[a.FullName] = a;
                }

                RegisterTypeInterfaces(a);

                return(a);
            }
        }
Esempio n. 28
0
        /// <summary>
        /// This method creates (and saves) a COM type library given a .NET
        /// assembly.
        /// </summary>
        public static UCOMITypeLib GenerateTLBFromAsm(string pathToAssmebly)
        {
            UCOMITypeLib        managedITypeLib = null;
            ExporterNotiferSink sink            = new ExporterNotiferSink();

            // Load the assembly to convert.
            Assembly asm = Assembly.LoadFrom(pathToAssmebly);

            if (asm != null)
            {
                try
                {
                    // Create name of type library based on .NET assembly.
                    string tlbname = asm.GetName().Name + ".tlb";

                    // Convert the assembly.
                    ITypeLibConverter TLBConv = new TypeLibConverter();
                    managedITypeLib = (UCOMITypeLib)TLBConv.ConvertAssemblyToTypeLib(asm, tlbname, 0, sink);
                    try
                    {
                        UCOMICreateTypeLib managedICreateITypeLib = (UCOMICreateTypeLib)managedITypeLib;
                        managedICreateITypeLib.SaveAllChanges();
                    }
                    catch (COMException e)
                    {
                        throw new Exception("Error saving the typeLib : "
                                            + e.ErrorCode.ToString("x"));
                    }
                }
                catch (Exception e)
                {
                    throw new Exception("Error Converting assembly" + e);
                }
            }
            return(managedITypeLib);
        }
Esempio n. 29
0
        private bool ExportTypeLib(Assembly asm, string typeLibFileName)
        {
            this.typeLibExportFailed = false;
            ITypeLib o = null;

            try
            {
                ITypeLibConverter converter = new TypeLibConverter();
                o = (ITypeLib)converter.ConvertAssemblyToTypeLib(asm, typeLibFileName, TypeLibExporterFlags.None, this);
                if ((o == null) || this.typeLibExportFailed)
                {
                    return(false);
                }
                ((UCOMICreateITypeLib)o).SaveAllChanges();
            }
            finally
            {
                if (o != null)
                {
                    Marshal.ReleaseComObject(o);
                }
            }
            return(!this.typeLibExportFailed);
        }
Esempio n. 30
0
        /// <summary>
        /// Exports the type library of the given assembly to the given path.
        /// 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>
        /// <returns>Type library reference.</returns>
        /// <exception cref="CLRegAsmException">Failed to save type library
        /// <paramref name="typeLibName"/> to disk.</exception>
        private ITypeLib ExportTypeLibrary(Assembly assembly, string typeLibName)
        {
            Debug.Assert(assembly != null);
            Debug.Assert(!String.IsNullOrEmpty(typeLibName));
            Debug.Assert(String.Compare(AssemblyTools.GetAssemblyPath(assembly), typeLibName, true) != 0);

            // Create type lib converter and export the type lib.
            // This will call us back recursively if referenced assemblies'
            // type libs need to be exported and registered also.
            TypeLibConverter tlbConverter = new TypeLibConverter();
            ITypeLib         tlb          = (ITypeLib)tlbConverter.ConvertAssemblyToTypeLib(assembly,
                                                                                            typeLibName, flags, new ConverterCallback(this));

            // Save all changes, which will save the data to disk.
            try {
                (tlb as ICreateTypeLib).SaveAllChanges();
            } catch (Exception e) {
                throw new CLRegAsmException(String.Format("Could not save type library \"{0}\" to disk",
                                                          typeLibName), e);
            }

            Debug.Assert(tlb != null);
            return(tlb);
        }
Esempio n. 31
0
            private bool InitializeTDxInputWrapper()
            {
                bool bReturn = false;
                Object typeLib = null;
                try
                {
                    //get Com-Server from Registry
                    RegistryKey regKey
                       = Registry.LocalMachine.OpenSubKey("Software\\Classes\\CLSID\\{82C5AB54-C92C-4D52-AAC5-27E25E22604C}\\InprocServer32", false);

                          if (regKey != null)
                          {
                              string strTypeLibName = regKey.GetValue("").ToString();
                              regKey.Close();

                              LoadTypeLibEx(strTypeLibName
                                                 , RegKind.RegKind_None
                                                 , out typeLib);
                          }
                          else
                          {
                              // --- No registry set, there must be no 3DConnexion ---
                              return false;
                          }
                }
                catch (Exception)
                {
                }

                if (typeLib == null)
                {
                    Console.WriteLine("LoadTypeLibEx failed.");
                    throw new NotSupportedException("Com- Server not found.");
                }

                TypeLibConverter converter = new TypeLibConverter();
                ConversionEventHandler eventHandler = new ConversionEventHandler();
                m_Assembly = converter.ConvertTypeLibToAssembly(typeLib, "Import3DxInputAssembly.dll", 0, eventHandler, null, null, null, null);

                //Type[] ExpTypes = m_Assembly.GetTypes();
                try
                {
                    m_OSimpleDevice = m_Assembly.CreateInstance("Import3DxInputAssembly.DeviceClass");
                }
                catch
                {
                    //int nTest;
                }

                if (m_OSimpleDevice != null)
                {
                    Type TheType = m_OSimpleDevice.GetType();
                    //MethodInfo[] TheMethods = TheType.GetMethods();
                    MethodInfo method = TheType.GetMethod("get_Sensor");
                    m_OSensor = method.Invoke(m_OSimpleDevice, null);  // kein Parameter

                    method = TheType.GetMethod("get_Keyboard");
                    m_OKeyboard = method.Invoke(m_OSimpleDevice, null);

                    TheType = m_OKeyboard.GetType();
                    //TheMethods = TheType.GetMethods();
                    bReturn = true;
                }

                return bReturn;
            }