Example #1
0
        public static string GetManagedWrapperForCOM(string fileName)
        {
            ITypeLib typeLib;

            if (LoadTypeLibEx(fileName, RegKind.None, out typeLib) != 0)
            {
                return(null);
            }
            if (typeLib == null)
            {
                return(null);
            }
            string fname = null;

            try
            {
                ConversionEventHandler eventHandler = new ConversionEventHandler();
                AssemblyBuilder        asm          = converter.ConvertTypeLibToAssembly(typeLib, System.IO.Path.Combine(ProjectFactory.Instance.ProjectDirectory, System.IO.Path.GetFileNameWithoutExtension(fileName) + ".dll"), 0, eventHandler, null, null, null, null);
                asm.Save(System.IO.Path.GetFileNameWithoutExtension(fileName) + ".dll");
                fname = System.IO.Path.GetFileNameWithoutExtension(fileName);
            }
            finally
            {
                Marshal.ReleaseComObject(typeLib);
            }
            return(fname);
        }
Example #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);
        }
            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);
            }
Example #4
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);
        }
            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);
            }
        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");
        }
        /// <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);
        }
Example #8
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");
    }
Example #9
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);
        }
Example #10
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);
        }
Example #11
0
        private Assembly GenerateAssemblyFromNativeTypeLibInternal(Guid iid, Guid typeLibraryID, ITypeLib typeLibrary)
        {
            Assembly asm = null;

            try
            {
                lock (this)
                {
                    TypelibraryAssembly.TryGetValue(typeLibraryID, out asm);
                    if (asm == null)
                    {
                        string assemblyName = "";
                        string notused1     = "";
                        string notused2     = "";
                        int    notused3;
                        string namespaceName;
                        typeLibrary.GetDocumentation(-1, out namespaceName, out notused1, out notused3, out notused2);
                        if (String.IsNullOrEmpty(namespaceName))
                        {
                            throw Fx.AssertAndThrowFatal("Assembly cannot be null");
                        }
                        assemblyName = String.Concat(namespaceName, GetRandomName(), ".dll");
                        asm          = TypelibraryConverter.ConvertTypeLibToAssembly(typeLibrary, assemblyName, TypeLibImporterFlags.SerializableValueClasses, new ConversionEventHandler(iid, typeLibraryID), null, null, namespaceName, null);
                        TypelibraryAssembly[typeLibraryID] = asm;
                    }
                }
            }
            catch (ReflectionTypeLoadException)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(SR.GetString(SR.FailedToConvertTypelibraryToAssembly)));
            }

            if (asm == null)
            {
                throw Fx.AssertAndThrowFatal("Assembly cannot be null");
            }
            return(asm);
        }
Example #12
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);
            }
        }
Example #13
0
        internal static Assembly generateAssemblyFromTypeLib(UCOMITypeLib typeLib, bool safeArrayAsArray, string asmFilePath, out bool foundPIAInstead)
        {
            foundPIAInstead = false;
            string typeLibName = Marshal.GetTypeLibName(typeLib);
            string asmDir, asmName, asmFullPath;

            if (asmFilePath == "")
            {
                // asmFilePath == "" means that user does not want the assembly saved in a file. A filename argument
                // is required by the conversion function, although no file is actually written by it. Therefore we
                // supply one in case it is truly necessary.
                asmName = "interop." + typeLibName + ".dll";
                asmDir  = "";
            }
            else
            {
                asmDir = System.IO.Path.GetDirectoryName(asmFilePath);
                if (asmDir == null)
                {
                    // asmFilePath was a root dir, like c:\.
                    string asmRoot = System.IO.Path.GetPathRoot(asmFilePath);
                    asmDir = asmRoot == null ? "" : asmRoot;
                }
                else
                {
                    asmDir = asmDir + System.IO.Path.DirectorySeparatorChar;
                }
                // M code ensures that if asmFilePath is a dir and not a filename it ends in \, so asmName will be ""
                // if it is a dir.
                asmName = System.IO.Path.GetFileName(asmFilePath);
                if (asmName == "")
                {
                    // asmFilePath was just a dir.
                    asmName = "interop." + typeLibName + ".dll";
                }
            }
            asmFullPath = asmDir + asmName;

            ImporterNotiferSink sink = new ImporterNotiferSink(safeArrayAsArray, asmDir);
            TypeLibConverter    tlc  = new TypeLibConverter();

            // Check for an existing PIA and use it if it exists.
            IntPtr pTLibAttr;

            typeLib.GetLibAttr(out pTLibAttr);
            TYPELIBATTR typeLibAttr = (TYPELIBATTR)Marshal.PtrToStructure(pTLibAttr, typeof(TYPELIBATTR));
            string      piaName, piaCodeBase;
            bool        piaExists = tlc.GetPrimaryInteropAssembly(typeLibAttr.guid, typeLibAttr.wMajorVerNum, typeLibAttr.wMinorVerNum,
                                                                  typeLibAttr.lcid, out piaName, out piaCodeBase);

            typeLib.ReleaseTLibAttr(pTLibAttr);
            if (piaExists)
            {
                Assembly pia = Assembly.LoadWithPartialName(piaName);
                if (pia != null)
                {
                    foundPIAInstead = true;
                    return(pia);
                }
            }

            TypeLoader.isBuildingDynamicAssembly = true;
            try {
                AssemblyBuilder asmBuilder = tlc.ConvertTypeLibToAssembly(typeLib, asmFullPath,
                                                                          safeArrayAsArray ? TypeLibImporterFlags.SafeArrayAsSystemArray : 0, sink, null, null, typeLibName, null);
                Type[] tt = asmBuilder.GetTypes();
                if (asmFilePath != "")
                {
                    asmBuilder.Save(asmName);
                }
                return(asmBuilder);
            } finally {
                TypeLoader.isBuildingDynamicAssembly = false;
            }
        }
Example #14
0
        /*
         * Method:  GenerateWrapper
         *
         * Generates a wrapper for this reference.
         */
        internal bool GenerateWrapper(out ComReferenceWrapperInfo wrapperInfo)
        {
            wrapperInfo = null;

            string rootNamespace            = ReferenceInfo.typeLibName;
            string wrapperPath              = GetWrapperPath();
            bool   generateWrapperSucceeded = true;

            if (ExecuteAsTool)
            {
                // delegate generation of the assembly to an instance of the TlbImp ToolTask. MUST
                // HAVE SET SDKTOOLSPATH TO THE TARGET SDK TO WORK
                var tlbImp = new ResolveComReference.TlbImp();

                tlbImp.BuildEngine          = BuildEngine;
                tlbImp.EnvironmentVariables = EnvironmentVariables;
                tlbImp.DelaySign            = DelaySign;
                tlbImp.KeyContainer         = KeyContainer;
                tlbImp.KeyFile                = KeyFile;
                tlbImp.OutputAssembly         = wrapperPath;
                tlbImp.ToolPath               = ToolPath;
                tlbImp.TypeLibName            = ReferenceInfo.fullTypeLibPath;
                tlbImp.AssemblyNamespace      = rootNamespace;
                tlbImp.AssemblyVersion        = null;
                tlbImp.PreventClassMembers    = _noClassMembers;
                tlbImp.SafeArrayAsSystemArray = true;
                tlbImp.Silent    = Silent;
                tlbImp.Transform = ResolveComReference.TlbImpTransformFlags.TransformDispRetVals;
                if (_referenceFiles != null)
                {
                    // Issue is that there may be reference dependencies that need to be passed in. It is possible
                    // that the set of references will also contain the file that is meant to be written here (when reference resolution
                    // found the file in the output folder). We need to filter out this case.
                    var fullPathToOutput = Path.GetFullPath(wrapperPath); // Current directory is the directory of the project file.
                    tlbImp.ReferenceFiles = _referenceFiles.Where(rf => String.Compare(fullPathToOutput, rf, StringComparison.OrdinalIgnoreCase) != 0).ToArray();
                }

                switch (_targetProcessorArchitecture)
                {
                case UtilitiesProcessorArchitecture.MSIL:
                    tlbImp.Machine = "Agnostic";
                    break;

                case UtilitiesProcessorArchitecture.AMD64:
                    tlbImp.Machine = "X64";
                    break;

                case UtilitiesProcessorArchitecture.IA64:
                    tlbImp.Machine = "Itanium";
                    break;

                case UtilitiesProcessorArchitecture.X86:
                    tlbImp.Machine = "X86";
                    break;

                case UtilitiesProcessorArchitecture.ARM:
                    tlbImp.Machine = "ARM";
                    break;

                case null:
                    break;

                default:
                    // Transmit the flag directly from the .targets files and rely on tlbimp.exe to produce a good error message.
                    tlbImp.Machine = _targetProcessorArchitecture;
                    break;
                }

                generateWrapperSucceeded = tlbImp.Execute();

                // store the wrapper info...
                wrapperInfo      = new ComReferenceWrapperInfo();
                wrapperInfo.path = (HasTemporaryWrapper) ? null : wrapperPath;
                // Changed to ReflectionOnlyLoadFrom, related to bug:
                //  RCR: Bad COM-interop assemblies being generated when using 64-bit MSBuild to build a project that is targeting 32-bit platform
                // The original call to UnsafeLoadFrom loads the assembly in preparation for execution. If the assembly is x86 and this is x64 msbuild.exe then we
                // have problems (UnsafeLoadFrom will fail). We only use this assembly for reference resolution so we don't need to be ready to execute the code.
                //
                // Its actually not clear to me that we even need to load the assembly at all. Reference resoluton is only used in the !ExecuteAsTool which is not
                // where we are right now.
                //
                // If we really do need to load it then:
                //
                //  wrapperInfo.assembly = Assembly.ReflectionOnlyLoadFrom(wrapperPath);
            }
            else
            {
                // use framework classes in-proc to generate the assembly
                TypeLibConverter converter = new TypeLibConverter();

                AssemblyBuilder   assemblyBuilder = null;
                StrongNameKeyPair keyPair;
                byte[]            publicKey;

                GetAndValidateStrongNameKey(out keyPair, out publicKey);

                try
                {
                    TypeLibImporterFlags flags = TypeLibImporterFlags.SafeArrayAsSystemArray | TypeLibImporterFlags.TransformDispRetVals;

                    if (_noClassMembers)
                    {
                        flags |= TypeLibImporterFlags.PreventClassMembers;
                    }

                    switch (_targetProcessorArchitecture)
                    {
                    case UtilitiesProcessorArchitecture.MSIL:
                        flags |= TypeLibImporterFlags.ImportAsAgnostic;
                        break;

                    case UtilitiesProcessorArchitecture.AMD64:
                        flags |= TypeLibImporterFlags.ImportAsX64;
                        break;

                    case UtilitiesProcessorArchitecture.IA64:
                        flags |= TypeLibImporterFlags.ImportAsItanium;
                        break;

                    case UtilitiesProcessorArchitecture.X86:
                        flags |= TypeLibImporterFlags.ImportAsX86;
                        break;

                    case UtilitiesProcessorArchitecture.ARM:
                        flags |= TypeLibImporterFlags.ImportAsArm;
                        break;

                    default:
                        // Let the type importer decide.
                        break;
                    }

                    // Start the conversion process. We'll get callbacks on ITypeLibImporterNotifySink to resolve dependent refs.
                    assemblyBuilder = converter.ConvertTypeLibToAssembly(ReferenceInfo.typeLibPointer, wrapperPath,
                                                                         flags, this, publicKey, keyPair, rootNamespace, null);
                }
                catch (COMException ex)
                {
                    if (!Silent)
                    {
                        Log.LogWarningWithCodeFromResources("ResolveComReference.ErrorCreatingWrapperAssembly", ItemName, ex.Message);
                    }

                    throw new ComReferenceResolutionException(ex);
                }

                // if we're done, and this is not a temporary wrapper, write it out to disk
                if (!HasTemporaryWrapper)
                {
                    WriteWrapperToDisk(assemblyBuilder, wrapperPath);
                }

                // store the wrapper info...
                wrapperInfo          = new ComReferenceWrapperInfo();
                wrapperInfo.path     = (HasTemporaryWrapper) ? null : wrapperPath;
                wrapperInfo.assembly = assemblyBuilder;
            }

            // ...and we're done!
            return(generateWrapperSucceeded);
        }
        internal bool GenerateWrapper(out ComReferenceWrapperInfo wrapperInfo)
        {
            wrapperInfo = null;
            string            typeLibName = this.ReferenceInfo.typeLibName;
            string            wrapperPath = base.GetWrapperPath();
            StrongNameKeyPair keyPair     = null;

            byte[] publicKey = null;
            StrongNameUtils.GetStrongNameKey(base.Log, base.KeyFile, base.KeyContainer, out keyPair, out publicKey);
            if (base.DelaySign)
            {
                keyPair = null;
                if (publicKey == null)
                {
                    base.Log.LogErrorWithCodeFromResources(null, this.ReferenceInfo.SourceItemSpec, 0, 0, 0, 0, "StrongNameUtils.NoPublicKeySpecified", new object[0]);
                    throw new StrongNameException();
                }
            }
            else
            {
                publicKey = null;
                if (keyPair == null)
                {
                    if ((base.KeyContainer != null) && (base.KeyContainer.Length > 0))
                    {
                        base.Log.LogErrorWithCodeFromResources(null, this.ReferenceInfo.SourceItemSpec, 0, 0, 0, 0, "ResolveComReference.StrongNameUtils.NoKeyPairInContainer", new object[] { base.KeyContainer });
                        throw new StrongNameException();
                    }
                    if ((base.KeyFile != null) && (base.KeyFile.Length > 0))
                    {
                        base.Log.LogErrorWithCodeFromResources(null, this.ReferenceInfo.SourceItemSpec, 0, 0, 0, 0, "ResolveComReference.StrongNameUtils.NoKeyPairInFile", new object[] { base.KeyFile });
                        throw new StrongNameException();
                    }
                }
            }
            bool flag = true;

            if (!base.ExecuteAsTool)
            {
                TypeLibConverter converter       = new TypeLibConverter();
                AssemblyBuilder  assemblyBuilder = null;
                try
                {
                    TypeLibImporterFlags flags = TypeLibImporterFlags.TransformDispRetVals | TypeLibImporterFlags.SafeArrayAsSystemArray;
                    if (this.noClassMembers)
                    {
                        flags |= TypeLibImporterFlags.PreventClassMembers;
                    }
                    string str4 = this.targetProcessorArchitecture;
                    if (str4 != null)
                    {
                        if (!(str4 == "MSIL"))
                        {
                            if (str4 == "AMD64")
                            {
                                goto Label_0323;
                            }
                            if (str4 == "IA64")
                            {
                                goto Label_032F;
                            }
                            if (str4 == "x86")
                            {
                                goto Label_033B;
                            }
                        }
                        else
                        {
                            flags |= TypeLibImporterFlags.ImportAsAgnostic;
                        }
                    }
                    goto Label_0345;
Label_0323:
                    flags |= TypeLibImporterFlags.ImportAsX64;
                    goto Label_0345;
Label_032F:
                    flags |= TypeLibImporterFlags.ImportAsItanium;
                    goto Label_0345;
Label_033B:
                    flags |= TypeLibImporterFlags.ImportAsX86;
Label_0345:
                    assemblyBuilder = converter.ConvertTypeLibToAssembly(this.ReferenceInfo.typeLibPointer, wrapperPath, flags, this, publicKey, keyPair, typeLibName, null);
                }
                catch (COMException exception)
                {
                    base.Log.LogWarningWithCodeFromResources("ResolveComReference.ErrorCreatingWrapperAssembly", new object[] { this.ItemName, exception.Message });
                    throw new ComReferenceResolutionException(exception);
                }
                if (!this.HasTemporaryWrapper)
                {
                    this.WriteWrapperToDisk(assemblyBuilder, wrapperPath);
                }
                wrapperInfo          = new ComReferenceWrapperInfo();
                wrapperInfo.path     = this.HasTemporaryWrapper ? null : wrapperPath;
                wrapperInfo.assembly = assemblyBuilder;
                return(flag);
            }
            ResolveComReference.TlbImp imp = new ResolveComReference.TlbImp {
                BuildEngine          = base.BuildEngine,
                EnvironmentVariables = base.EnvironmentVariables,
                DelaySign            = base.DelaySign,
                KeyContainer         = base.KeyContainer,
                KeyFile                = base.KeyFile,
                OutputAssembly         = wrapperPath,
                ToolPath               = base.ToolPath,
                TypeLibName            = this.ReferenceInfo.typeLibPath,
                AssemblyNamespace      = typeLibName,
                AssemblyVersion        = null,
                PreventClassMembers    = this.noClassMembers,
                SafeArrayAsSystemArray = true,
                Transform              = ResolveComReference.TlbImpTransformFlags.TransformDispRetVals
            };
            if (this.referenceFiles != null)
            {
                string fullPathToOutput = Path.GetFullPath(wrapperPath);
                imp.ReferenceFiles = (from rf in this.referenceFiles
                                      where string.Compare(fullPathToOutput, rf, StringComparison.OrdinalIgnoreCase) != 0
                                      select rf).ToArray <string>();
            }
            string targetProcessorArchitecture = this.targetProcessorArchitecture;

            if (targetProcessorArchitecture != null)
            {
                if (!(targetProcessorArchitecture == "MSIL"))
                {
                    if (targetProcessorArchitecture == "AMD64")
                    {
                        imp.Machine = "X64";
                    }
                    else if (targetProcessorArchitecture == "IA64")
                    {
                        imp.Machine = "Itanium";
                    }
                    else if (targetProcessorArchitecture == "x86")
                    {
                        imp.Machine = "X86";
                    }
                    else
                    {
                        imp.Machine = this.targetProcessorArchitecture;
                    }
                }
                else
                {
                    imp.Machine = "Agnostic";
                }
            }
            flag             = imp.Execute();
            wrapperInfo      = new ComReferenceWrapperInfo();
            wrapperInfo.path = this.HasTemporaryWrapper ? null : wrapperPath;
            return(flag);
        }
Example #16
0
            Assembly ITypeLibImporterNotifySink.ResolveRef(Object typeLib)
            {
                try {
                    string assem = importer.GetComReference((UCOMITypeLib)typeLib);
                    if (assem != null)
                    {
                        importer.AddReferencedAssembly(assem);
                    }

                    Assembly a = importer.FindRCW((UCOMITypeLib)typeLib);
                    if (a != null)
                    {
                        return(a);
                    }

                    // Generate the RCW for the typelib. We have to go through the motions of this anyway,
                    // because there is no easy way to find the dependent references for this typelib.
                    //
                    try {
                        string tlbName = Marshal.GetTypeLibName((UCOMITypeLib)typeLib);
                        string rcwName = Path.Combine(options.outputDirectory, tlbName + ".dll");

                        Debug.WriteLineIf(AxWrapperGen.AxWrapper.Enabled, "\tConverting recursive TypeLib Name: " + tlbName + " in " + rcwName);

                        if (importer.GetReferencedAssembly(rcwName) != null)
                        {
                            Debug.WriteLineIf(AxWrapperGen.AxWrapper.Enabled, "\t\tFound RCW in referenced assembly list at " + rcwName);
                            return(importer.GetCopiedAssembly(rcwName, false, false));
                        }

                        // Create the TypeLibConverter.
                        TypeLibConverter tlbConv = new TypeLibConverter();

                        // Try to locate the primary interop assembly first.
                        //
                        a = importer.GetPrimaryInteropAssembly((UCOMITypeLib)typeLib, tlbConv);
                        if (a != null)
                        {
                            return(a);
                        }
                        else
                        {
                            // Convert the typelib.
                            AssemblyBuilder asmBldr = tlbConv.ConvertTypeLibToAssembly(typeLib,
                                                                                       rcwName,
                                                                                       (TypeLibImporterFlags)0,
                                                                                       new ImporterCallback(importer),
                                                                                       options.publicKey,
                                                                                       options.keyPair,
                                                                                       null,
                                                                                       null);

                            if (assem == null)
                            {
                                // Save the assembly to the disk only if we did not find it already on the reference list.
                                //
                                Debug.WriteLineIf(AxWrapperGen.AxWrapper.Enabled, "\t\tGenerated RCW at " + rcwName);
                                string rcwAssem = importer.SaveAssemblyBuilder((UCOMITypeLib)typeLib, asmBldr, rcwName);
                                importer.AddRCW((UCOMITypeLib)typeLib, asmBldr);
                                return(asmBldr);
                            }
                            else
                            {
                                Debug.WriteLineIf(AxWrapperGen.AxWrapper.Enabled, "\t\tFound COM Reference at " + assem);
                                return(importer.GetCopiedAssembly(assem, false, false));
                            }
                        }
                    }
                    catch (Exception) {
                        return(null);
                    }
                }
                finally {
                    Marshal.ReleaseComObject(typeLib);
                }
            }
Example #17
0
        /// <include file='doc\AxImporter.uex' path='docs/doc[@for="AxImporter.GenerateFromTypeLibrary1"]/*' />
        /// <devdoc>
        ///    <para>
        ///       Generates a wrapper for an ActiveX control for use in the design-time
        ///       environment.
        ///    </para>
        /// </devdoc>
        public string GenerateFromTypeLibrary(UCOMITypeLib typeLib, Guid clsid)
        {
            string   axWFW     = null;
            string   axctlType = null;
            Assembly rcw       = null;

            // Look to see if we can find the AxWrapper also for this typeLib.
            //
            axWFW = GetAxReference(typeLib);

            if (axWFW != null && clsid != Guid.Empty)
            {
                axctlType = GetAxTypeFromAssembly(axWFW, clsid);
            }

            if (axWFW == null)
            {
                string tlbName = Marshal.GetTypeLibName(typeLib);
                string rcwName = Path.Combine(options.outputDirectory, tlbName + ".dll");
                Debug.WriteLineIf(AxWrapperGen.AxWrapper.Enabled, "Converting TypeLib Name: " + tlbName + " in " + rcwName);

                AddReferencedAssembly(GetManagedReference("System.Windows.Forms"));
                AddReferencedAssembly(GetManagedReference("System.Drawing"));
                AddReferencedAssembly(GetManagedReference("System"));

                string rcwAssem = GetComReference(typeLib);
                if (rcwAssem != null)
                {
                    AddReferencedAssembly(rcwAssem);
                    rcw = GetCopiedAssembly(rcwAssem, false, false);
                    AddDependentAssemblies(rcw);
                }
                else
                {
                    TypeLibConverter tlbConverter = new TypeLibConverter();

                    // Try to locate the primary interop assembly first.
                    //
                    rcw = GetPrimaryInteropAssembly(typeLib, tlbConverter);

                    if (rcw != null)
                    {
                        rcwAssem = GetLocalPath(rcw.EscapedCodeBase);
                        AddDependentAssemblies(rcw);
                    }
                    else
                    {
                        AssemblyBuilder asmBldr = tlbConverter.ConvertTypeLibToAssembly(typeLib,
                                                                                        rcwName,
                                                                                        (TypeLibImporterFlags)0,
                                                                                        new ImporterCallback(this),
                                                                                        options.publicKey,
                                                                                        options.keyPair,
                                                                                        null,
                                                                                        null);

                        if (rcwAssem == null)
                        {
                            // Save the assembly to the disk only if we did not find it already on the reference list.
                            //
                            rcwAssem = SaveAssemblyBuilder(typeLib, asmBldr, rcwName);
                            rcw      = GetCopiedAssembly(rcwAssem, false, false);
                        }
                    }
                }
                Debug.Assert(rcw != null, "No assembly obtained from: " + rcwAssem);

                // Create a list of the referenced assemblies and create the WFW Wrapper for the AxControl.
                //
                int      i         = 0;
                string[] refAssems = new string[this.refAssems.Count];
                foreach (string assem in this.refAssems)
                {
                    string name = assem;

                    name = name.Replace("%20", " ");
                    Debug.WriteLineIf(AxWrapperGen.AxWrapper.Enabled, "Adding " + name + " to the wrapper reference list...");
                    refAssems[i++] = name;
                }

                if (axctlType == null)
                {
                    string   file         = GetFileOfTypeLib(typeLib);
                    DateTime tlbTimeStamp = (file == null) ? DateTime.Now : File.GetLastWriteTime(file);

                    // Hook up the type resolution events for the appdomain so we can delay load
                    // any assemblies/types users gave us in the /i option.
                    //
                    ResolveEventHandler assemblyResolveEventHandler = new ResolveEventHandler(OnAssemblyResolve);
                    AppDomain.CurrentDomain.AssemblyResolve += assemblyResolveEventHandler;

                    try {
                        if (options.genSources)
                        {
                            AxWrapperGen.GeneratedSources = new ArrayList();
                        }

                        if (options.outputName == null)
                        {
                            options.outputName = "Ax" + tlbName + ".dll";
                        }

                        axctlType = AxWrapperGen.GenerateWrappers(this, clsid, rcw, refAssems, tlbTimeStamp, out axWFW);

                        if (options.genSources)
                        {
                            generatedSources = AxWrapperGen.GeneratedSources;
                        }
                    }
                    finally {
                        AppDomain.CurrentDomain.AssemblyResolve -= assemblyResolveEventHandler;
                    }

                    if (axctlType == null)
                    {
                        throw new Exception(SR.GetString(SR.AXNoActiveXControls, ((typeLibName != null) ? typeLibName : tlbName)));
                    }
                }

                if (axctlType != null)
                {
                    // Add the WFW assembly to the references list.
                    //
                    Debug.Assert(axWFW != null && axWFW.Length > 0, "Invalid output assembly name");
                    AddReferencedAssembly(axWFW);
                    AddTypeLibAttr(typeLib);
                    AddGeneratedAssembly(axWFW);
                }
            }

            return(axctlType);
        }
Example #18
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;
            }
        // public static TypeLibInfo CreateDll_1(FileInfo file, DirectoryInfo outputDir, string Namespace)
        // {
        //     var task = Task.Factory.StartNew(() => TlbConverter.CreateDllTask(file, outputDir, Namespace ));

        //     var result = task.Result;
        //     task = null;

        //     System.GC.Collect();
        //     GC.WaitForPendingFinalizers();
        //     return result;
        // }

        // public static TypeLibInfo CreateDll(FileInfo file, DirectoryInfo outputDir, string Namespace)
        // {
        //     TypeLibInfo i = null;
        //     var thread  = new System.Threading.Thread(() => {
        //         i = TlbConverter.CreateDllTask(file, outputDir, Namespace);
        //     });

        //     thread.IsBackground = true;

        //     thread.Start();
        //     thread.Join();

        //     thread = null;

        //     System.GC.Collect();
        //     GC.WaitForPendingFinalizers();

        //     return i;
        // }

        public static TypeLibInfo CreateDll(FileInfo file, DirectoryInfo outputDir, string Namespace)
        {
            Console.WriteLine($"-----------------File: {file.Name} is now processing-------------------");

            if (file.Name == "InfTypeLib.tlb")
            {
                // Console.ReadLine();
            }

            var typeLibInfo = new TypeLibInfo()
            {
                OriginalName = file.Name,
                path         = outputDir.FullName
            };

            AssemblyBuilder asm = null;

            var tlc = new TypeLibConverter();

            External.LoadTypeLibEx(file.FullName, External.RegKind.RegKind_None, out ITypeLib typeLib);

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

            typeLibInfo.TlbName = Marshal.GetTypeLibName(typeLib);
            typeLibInfo.AsmName = typeLibInfo.TlbName + ".dll";


            Console.WriteLine(typeLibInfo.GetFileinfo());

            if (typeLibInfo.Exists)
            {
                Console.WriteLine($"AsmName {typeLibInfo.AsmName} exists, no need to convert");
                return(typeLibInfo);
            }

            TypeLibConverter tlbConv = new TypeLibConverter();

            ConversionEventHandler eventHandler = new ConversionEventHandler(typeLibInfo);

            try
            {
                asm = tlbConv.ConvertTypeLibToAssembly(typeLib, typeLibInfo.AsmName, TypeLibImporterFlags.SafeArrayAsSystemArray, eventHandler, null, null, Namespace + typeLibInfo.TlbName, null);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to convert, trying again", e.Message, e.StackTrace);
                Console.WriteLine($"OriginalName {typeLibInfo.OriginalName}");
                Console.WriteLine($"TlbName {typeLibInfo.TlbName}");
                Console.WriteLine($"AsmName {typeLibInfo.AsmName}");
                return(null);
            }

            try
            {
                asm.Save(typeLibInfo.AsmName);
            }
            catch (Exception e)
            {
                Console.WriteLine("Failed to save, trying again", e.Message, e.StackTrace);
                Console.WriteLine($"OriginalName {typeLibInfo.OriginalName}");
                Console.WriteLine($"TlbName {typeLibInfo.TlbName}");
                Console.WriteLine($"AsmName {typeLibInfo.AsmName}");
                return(null);
            }
            return(typeLibInfo);
        }
        public string GenerateFromTypeLibrary(UCOMITypeLib typeLib, Guid clsid)
        {
            string   fileName           = null;
            string   axTypeFromAssembly = null;
            Assembly assem = null;

            fileName = this.GetAxReference((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib);
            if ((fileName != null) && (clsid != Guid.Empty))
            {
                axTypeFromAssembly = this.GetAxTypeFromAssembly(fileName, clsid);
            }
            if (fileName == null)
            {
                string typeLibName = Marshal.GetTypeLibName((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib);
                string asmFileName = Path.Combine(this.options.outputDirectory, typeLibName + ".dll");
                this.AddReferencedAssembly(this.GetManagedReference("System.Windows.Forms"));
                this.AddReferencedAssembly(this.GetManagedReference("System.Drawing"));
                this.AddReferencedAssembly(this.GetManagedReference("System"));
                string comReference = this.GetComReference((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib);
                if (comReference != null)
                {
                    this.AddReferencedAssembly(comReference);
                    assem = this.GetCopiedAssembly(comReference, false, false);
                    this.AddDependentAssemblies(assem, comReference);
                }
                else
                {
                    TypeLibConverter tlbConverter = new TypeLibConverter();
                    assem = this.GetPrimaryInteropAssembly((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib, tlbConverter);
                    if (assem != null)
                    {
                        comReference = this.GetLocalPath(assem.EscapedCodeBase);
                        this.AddDependentAssemblies(assem, comReference);
                    }
                    else
                    {
                        AssemblyBuilder asmBldr = tlbConverter.ConvertTypeLibToAssembly((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib, asmFileName, TypeLibImporterFlags.None, new ImporterCallback(this), this.options.publicKey, this.options.keyPair, null, null);
                        if (comReference == null)
                        {
                            comReference = this.SaveAssemblyBuilder((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib, asmBldr, asmFileName);
                            assem        = asmBldr;
                        }
                    }
                }
                int      num           = 0;
                string[] refAssemblies = new string[this.refAssems.Count];
                foreach (string str6 in this.refAssems)
                {
                    string str7 = str6;
                    str7 = str7.Replace("%20", " ");
                    refAssemblies[num++] = str7;
                }
                if (axTypeFromAssembly == null)
                {
                    string              fileOfTypeLib = GetFileOfTypeLib((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib);
                    DateTime            tlbTimeStamp  = (fileOfTypeLib == null) ? DateTime.Now : File.GetLastWriteTime(fileOfTypeLib);
                    ResolveEventHandler handler       = new ResolveEventHandler(this.OnAssemblyResolve);
                    AppDomain.CurrentDomain.AssemblyResolve += handler;
                    AppDomain.CurrentDomain.TypeResolve     += new ResolveEventHandler(this.OnTypeResolve);
                    try
                    {
                        if (this.options.genSources)
                        {
                            AxWrapperGen.GeneratedSources = new ArrayList();
                        }
                        if (this.options.outputName == null)
                        {
                            this.options.outputName = "Ax" + typeLibName + ".dll";
                        }
                        axTypeFromAssembly = AxWrapperGen.GenerateWrappers(this, clsid, assem, refAssemblies, tlbTimeStamp, out fileName);
                        if (this.options.genSources)
                        {
                            this.generatedSources = AxWrapperGen.GeneratedSources;
                        }
                    }
                    finally
                    {
                        AppDomain.CurrentDomain.AssemblyResolve -= handler;
                        AppDomain.CurrentDomain.TypeResolve     -= new ResolveEventHandler(this.OnTypeResolve);
                    }
                    if (axTypeFromAssembly == null)
                    {
                        string message = System.Design.SR.GetString("AXNoActiveXControls", new object[] { (this.typeLibName != null) ? this.typeLibName : typeLibName });
                        if (this.options.msBuildErrors)
                        {
                            message = "AxImp: error aximp000: " + message;
                        }
                        throw new Exception(message);
                    }
                }
                if (axTypeFromAssembly != null)
                {
                    this.AddReferencedAssembly(fileName);
                    this.AddTypeLibAttr((System.Runtime.InteropServices.ComTypes.ITypeLib)typeLib);
                    this.AddGeneratedAssembly(fileName);
                }
            }
            return(axTypeFromAssembly);
        }
        private Assembly loadComAssembly(string fileName)
        {
            string strPath = Path.GetDirectoryName(fileName) + "\\";

            if (Path.GetDirectoryName(fileName).Length <= 0)
            {
                strPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\";
            }

            //if (Path.GetDirectoryName(fileName).Length <= 0)
            //    strPath = string.Empty;

            string strSrcFileName = strPath + Path.GetFileName(fileName);

            if (!File.Exists(strSrcFileName))
            {
                return(null);
            }

            //RegComDll(m_mapComAssembly[assembly.FullName].ToString());
            RegComDll(strSrcFileName); //每次自动注册com dll

            string strDstFileName     = "interop." + Path.GetFileName(fileName);
            string strDetFullFileName = strPath + strDstFileName;
            string strNameSpace       = Path.GetFileNameWithoutExtension(fileName);//文件名作为命名空间

            //如果interop.dll的时间比dll时间早,则需要重新生成
            bool bNeedGenrate = false;

            if (File.Exists(strDetFullFileName))
            {
                DateTime dtInteropTime = File.GetLastWriteTime(strDetFullFileName);
                DateTime dtSrcTime     = File.GetLastWriteTime(strSrcFileName);
                if (dtSrcTime >= dtInteropTime)
                {
                    bNeedGenrate = true;
                }
            }
            else
            {
                bNeedGenrate = true;
            }

            if (bNeedGenrate)
            {
                Object typeLib;
                LoadTypeLibEx(fileName, RegKind.RegKind_None, out typeLib);

                if (typeLib == null)
                {
                    //throw new Exception("载入失败!");
                    return(null);
                }

                TypeLibConverter       converter    = new TypeLibConverter();
                ConversionEventHandler eventHandler = new ConversionEventHandler();
                AssemblyBuilder        ab           = converter.ConvertTypeLibToAssembly(typeLib, strDetFullFileName, 0,
                                                                                         eventHandler, null, null, strNameSpace, null);
                ab.Save(strDstFileName);
            }
            Assembly asm = Assembly.LoadFile(strDetFullFileName);//Application.StartupPath + @"\" + strDstFileName);

            //Type t = asm.GetType("interop.test.tcls1"); //old
            //Type t = asm.GetType("Prj2.tcls1"); //new, comdll=Prj2.dll
            if (asm != null)
            {
                m_mapComAssembly[asm.FullName] = strSrcFileName;
            }
            return(asm);
        }
Example #22
0
        public string GenerateMetaData(string strSrcTypeLib, string outPath, byte[] PublicKey, StrongNameKeyPair KeyPair)
        {
            string str2;

            try
            {
                new SecurityPermission(SecurityPermissionFlag.UnmanagedCode).Demand();
            }
            catch (Exception exception)
            {
                if ((exception is NullReferenceException) || (exception is SEHException))
                {
                    throw;
                }
                ComSoapPublishError.Report(exception.ToString());
                throw;
            }
            string str = "";

            if ((0 >= strSrcTypeLib.Length) || (0 >= outPath.Length))
            {
                return(str);
            }
            if (!outPath.EndsWith("/", StringComparison.Ordinal) && !outPath.EndsWith(@"\", StringComparison.Ordinal))
            {
                outPath = outPath + @"\";
            }
            ITypeLib typeLib = null;

            typeLib = CacheInfo.GetTypeLib(strSrcTypeLib);
            if (typeLib == null)
            {
                return(str);
            }
            str = CacheInfo.GetMetadataName(strSrcTypeLib, typeLib, out str2);
            if (str.Length == 0)
            {
                return(str);
            }
            if (this._nameonly)
            {
                return(str);
            }
            string assemblyPath = outPath + str2;

            if (this._signed)
            {
                try
                {
                    AssemblyManager manager = new AssemblyManager();
                    if (manager.CompareToCache(assemblyPath, strSrcTypeLib))
                    {
                        new Publish().GacInstall(assemblyPath);
                        return(str);
                    }
                    if (manager.GetFromCache(assemblyPath, strSrcTypeLib))
                    {
                        new Publish().GacInstall(assemblyPath);
                        return(str);
                    }
                    goto Label_0133;
                }
                catch (Exception exception2)
                {
                    if ((exception2 is NullReferenceException) || (exception2 is SEHException))
                    {
                        throw;
                    }
                    ComSoapPublishError.Report(exception2.ToString());
                    goto Label_0133;
                }
            }
            if (File.Exists(assemblyPath))
            {
                return(str);
            }
Label_0133:
            try
            {
                ITypeLibConverter converter  = new TypeLibConverter();
                ImporterCallback  notifySink = new ImporterCallback {
                    OutputDir = outPath
                };
                AssemblyBuilder builder = converter.ConvertTypeLibToAssembly(typeLib, assemblyPath, TypeLibImporterFlags.UnsafeInterfaces, notifySink, PublicKey, KeyPair, null, null);
                FileInfo        info    = new FileInfo(assemblyPath);
                builder.Save(info.Name);
                if (this._signed)
                {
                    new AssemblyManager().CopyToCache(assemblyPath, strSrcTypeLib);
                    new Publish().GacInstall(assemblyPath);
                }
            }
            catch (ReflectionTypeLoadException exception3)
            {
                Exception[] loaderExceptions = exception3.LoaderExceptions;
                for (int i = 0; i < loaderExceptions.Length; i++)
                {
                    try
                    {
                        ComSoapPublishError.Report(loaderExceptions[i].ToString());
                    }
                    catch (Exception exception4)
                    {
                        if ((exception4 is NullReferenceException) || (exception4 is SEHException))
                        {
                            throw;
                        }
                        ComSoapPublishError.Report(exception3.ToString());
                    }
                }
                return(string.Empty);
            }
            catch (Exception exception5)
            {
                if ((exception5 is NullReferenceException) || (exception5 is SEHException))
                {
                    throw;
                }
                ComSoapPublishError.Report(exception5.ToString());
                return(string.Empty);
            }
            return(str);
        }