Inheritance: ITypeLibConverter
コード例 #1
0
        public TypeLibViewModel(ITypeLib typeLib)
        {
            _typeLib = typeLib;
            TYPELIBATTR attr = COMUtil.GetTypeLibAttr(typeLib);
            CLSID = attr.guid.ToString();
            MajorVersion = attr.wMajorVerNum;
            MinorVersion = attr.wMinorVerNum;
            LCID = attr.lcid;
            //Name = Marshal.GetTypeLibName(typeLib);
            string name, docString, helpFile;
            int helpContext;
            typeLib.GetDocumentation(-1,
                                     out name,
                                     out docString,
                                     out helpContext,
                                     out helpFile);

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

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

            PIAName = asmName;
            PIACodeBase = asmCodeBase;
        }
コード例 #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;
        }
コード例 #3
0
 public Assembly ResolveEvent(object sender, ResolveEventArgs args)
 {
     try
     {
         TypeLibConverter.LoadInMemoryTypeByName(this.m_Module.GetNativeHandle(), args.Name);
         return(this.m_Module.Assembly);
     }
     catch (TypeLoadException ex)
     {
         if (ex.ResourceId != -2146233054)
         {
             throw;
         }
     }
     foreach (RuntimeAssembly runtimeAssembly in this.m_AsmList)
     {
         try
         {
             runtimeAssembly.GetType(args.Name, true, false);
             return(runtimeAssembly);
         }
         catch (TypeLoadException ex2)
         {
             if (ex2._HResult != -2146233054)
             {
                 throw;
             }
         }
     }
     return(null);
 }
コード例 #4
0
        public AssemblyBuilder ConvertTypeLibToAssembly([MarshalAs(UnmanagedType.Interface)] object typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte[] publicKey, StrongNameKeyPair keyPair, string asmNamespace, Version asmVersion)
        {
            if (typeLib == null)
            {
                throw new ArgumentNullException("typeLib");
            }
            if (asmFileName == null)
            {
                throw new ArgumentNullException("asmFileName");
            }
            if (notifySink == null)
            {
                throw new ArgumentNullException("notifySink");
            }
            if (string.Empty.Equals(asmFileName))
            {
                throw new ArgumentException(Environment.GetResourceString("Arg_InvalidFileName"), "asmFileName");
            }
            if (asmFileName.Length > 260)
            {
                throw new ArgumentException(Environment.GetResourceString("IO.PathTooLong"), asmFileName);
            }
            if ((flags & TypeLibImporterFlags.PrimaryInteropAssembly) != TypeLibImporterFlags.None && publicKey == null && keyPair == null)
            {
                throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_PIAMustBeStrongNamed"));
            }
            ArrayList         arrayList               = null;
            AssemblyNameFlags asmNameFlags            = AssemblyNameFlags.None;
            AssemblyName      assemblyNameFromTypelib = TypeLibConverter.GetAssemblyNameFromTypelib(typeLib, asmFileName, publicKey, keyPair, asmVersion, asmNameFlags);
            AssemblyBuilder   assemblyBuilder         = TypeLibConverter.CreateAssemblyForTypeLib(typeLib, asmFileName, assemblyNameFromTypelib, (flags & TypeLibImporterFlags.PrimaryInteropAssembly) > TypeLibImporterFlags.None, (flags & TypeLibImporterFlags.ReflectionOnlyLoading) > TypeLibImporterFlags.None, (flags & TypeLibImporterFlags.NoDefineVersionResource) > TypeLibImporterFlags.None);
            string            fileName      = Path.GetFileName(asmFileName);
            ModuleBuilder     moduleBuilder = assemblyBuilder.DefineDynamicModule(fileName, fileName);

            if (asmNamespace == null)
            {
                asmNamespace = assemblyNameFromTypelib.Name;
            }
            TypeLibConverter.TypeResolveHandler typeResolveHandler = new TypeLibConverter.TypeResolveHandler(moduleBuilder, notifySink);
            AppDomain           domain = Thread.GetDomain();
            ResolveEventHandler value  = new ResolveEventHandler(typeResolveHandler.ResolveEvent);
            ResolveEventHandler value2 = new ResolveEventHandler(typeResolveHandler.ResolveAsmEvent);
            ResolveEventHandler value3 = new ResolveEventHandler(typeResolveHandler.ResolveROAsmEvent);

            domain.TypeResolve     += value;
            domain.AssemblyResolve += value2;
            domain.ReflectionOnlyAssemblyResolve += value3;
            TypeLibConverter.nConvertTypeLibToMetadata(typeLib, assemblyBuilder.InternalAssembly, moduleBuilder.InternalModule, asmNamespace, flags, typeResolveHandler, out arrayList);
            TypeLibConverter.UpdateComTypesInAssembly(assemblyBuilder, moduleBuilder);
            if (arrayList.Count > 0)
            {
                new TCEAdapterGenerator().Process(moduleBuilder, arrayList);
            }
            domain.TypeResolve     -= value;
            domain.AssemblyResolve -= value2;
            domain.ReflectionOnlyAssemblyResolve -= value3;
            return(assemblyBuilder);
        }
 public Assembly ResolveRef(object TypeLib)
 {
     try
     {
         ITypeLibConverter converter = new TypeLibConverter();
         return converter.ConvertTypeLibToAssembly(TypeLib, Marshal.GetTypeLibName((ITypeLib) TypeLib) + ".dll", TypeLibImporterFlags.None, new ImporterCallback(), null, null, null, null);
     }
     catch (Exception)
     {
         return null;
     }
 }
コード例 #6
0
 public Assembly ResolveRef(object TypeLib)
 {
     try
     {
         ITypeLibConverter converter = new TypeLibConverter();
         return(converter.ConvertTypeLibToAssembly(TypeLib, Marshal.GetTypeLibName((ITypeLib)TypeLib) + ".dll", TypeLibImporterFlags.None, new ImporterCallback(), null, null, null, null));
     }
     catch (Exception)
     {
         return(null);
     }
 }
コード例 #7
0
        private static AssemblyBuilder CreateAssemblyForTypeLib(object typeLib, string asmFileName, AssemblyName asmName, bool bPrimaryInteropAssembly, bool bReflectionOnly, bool bNoDefineVersionResource)
        {
            AppDomain domain = Thread.GetDomain();
            string    text   = null;

            if (asmFileName != null)
            {
                text = Path.GetDirectoryName(asmFileName);
                if (string.IsNullOrEmpty(text))
                {
                    text = null;
                }
            }
            AssemblyBuilderAccess access;

            if (bReflectionOnly)
            {
                access = AssemblyBuilderAccess.ReflectionOnly;
            }
            else
            {
                access = AssemblyBuilderAccess.RunAndSave;
            }
            List <CustomAttributeBuilder> list = new List <CustomAttributeBuilder>();
            ConstructorInfo constructor        = typeof(SecurityRulesAttribute).GetConstructor(new Type[]
            {
                typeof(SecurityRuleSet)
            });
            CustomAttributeBuilder item = new CustomAttributeBuilder(constructor, new object[]
            {
                SecurityRuleSet.Level2
            });

            list.Add(item);
            AssemblyBuilder assemblyBuilder = domain.DefineDynamicAssembly(asmName, access, text, false, list);

            TypeLibConverter.SetGuidAttributeOnAssembly(assemblyBuilder, typeLib);
            TypeLibConverter.SetImportedFromTypeLibAttrOnAssembly(assemblyBuilder, typeLib);
            if (bNoDefineVersionResource)
            {
                TypeLibConverter.SetTypeLibVersionAttribute(assemblyBuilder, typeLib);
            }
            else
            {
                TypeLibConverter.SetVersionInformation(assemblyBuilder, typeLib, asmName);
            }
            if (bPrimaryInteropAssembly)
            {
                TypeLibConverter.SetPIAAttributeOnAssembly(assemblyBuilder, typeLib);
            }
            return(assemblyBuilder);
        }
コード例 #8
0
        private static void SetVersionInformation(AssemblyBuilder asmBldr, object typeLib, AssemblyName asmName)
        {
            string strName       = (string)null;
            string strDocString  = (string)null;
            int    dwHelpContext = 0;
            string strHelpFile   = (string)null;

            ((ITypeLib)typeLib).GetDocumentation(-1, out strName, out strDocString, out dwHelpContext, out strHelpFile);
            string product = string.Format((IFormatProvider)CultureInfo.InvariantCulture, Environment.GetResourceString("TypeLibConverter_ImportedTypeLibProductName"), (object)strName);

            asmBldr.DefineVersionInfoResource(product, asmName.Version.ToString(), (string)null, (string)null, (string)null);
            TypeLibConverter.SetTypeLibVersionAttribute(asmBldr, typeLib);
        }
        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");
        }
コード例 #10
0
        private static void SetVersionInformation(AssemblyBuilder asmBldr, object typeLib, AssemblyName asmName)
        {
            string   arg      = null;
            string   text     = null;
            int      num      = 0;
            string   text2    = null;
            ITypeLib typeLib2 = (ITypeLib)typeLib;

            typeLib2.GetDocumentation(-1, out arg, out text, out num, out text2);
            string product = string.Format(CultureInfo.InvariantCulture, Environment.GetResourceString("TypeLibConverter_ImportedTypeLibProductName"), arg);

            asmBldr.DefineVersionInfoResource(product, asmName.Version.ToString(), null, null, null);
            TypeLibConverter.SetTypeLibVersionAttribute(asmBldr, typeLib);
        }
コード例 #11
0
        public object ConvertAssemblyToTypeLib(Assembly assembly, string strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink)
        {
            AssemblyBuilder assemblyBuilder = assembly as AssemblyBuilder;

            RuntimeAssembly assembly2;

            if (assemblyBuilder != null)
            {
                assembly2 = assemblyBuilder.InternalAssembly;
            }
            else
            {
                assembly2 = (assembly as RuntimeAssembly);
            }
            return(TypeLibConverter.nConvertAssemblyToTypeLib(assembly2, strTypeLibName, flags, notifySink));
        }
コード例 #12
0
        private static AssemblyBuilder CreateAssemblyForTypeLib(object typeLib, string asmFileName, AssemblyName asmName, bool bPrimaryInteropAssembly, bool bReflectionOnly, bool bNoDefineVersionResource)
        {
            AppDomain domain = Thread.GetDomain();
            string    dir    = (string)null;

            if (asmFileName != null)
            {
                dir = Path.GetDirectoryName(asmFileName);
                if (string.IsNullOrEmpty(dir))
                {
                    dir = (string)null;
                }
            }
            AssemblyBuilderAccess access  = !bReflectionOnly ? AssemblyBuilderAccess.RunAndSave : AssemblyBuilderAccess.ReflectionOnly;
            AssemblyBuilder       asmBldr = domain.DefineDynamicAssembly(asmName, access, dir, false, (System.Collections.Generic.IEnumerable <CustomAttributeBuilder>) new List <CustomAttributeBuilder>()
            {
                new CustomAttributeBuilder(typeof(SecurityRulesAttribute).GetConstructor(new Type[1] {
                    typeof(SecurityRuleSet)
                }), new object[1] {
                    (object)SecurityRuleSet.Level2
                })
            });

            TypeLibConverter.SetGuidAttributeOnAssembly(asmBldr, typeLib);
            TypeLibConverter.SetImportedFromTypeLibAttrOnAssembly(asmBldr, typeLib);
            if (bNoDefineVersionResource)
            {
                TypeLibConverter.SetTypeLibVersionAttribute(asmBldr, typeLib);
            }
            else
            {
                TypeLibConverter.SetVersionInformation(asmBldr, typeLib, asmName);
            }
            if (bPrimaryInteropAssembly)
            {
                TypeLibConverter.SetPIAAttributeOnAssembly(asmBldr, typeLib);
            }
            return(asmBldr);
        }
コード例 #13
0
ファイル: TlbReference.cs プロジェクト: cameron314/msbuild
        /*
         * 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;
        }
コード例 #14
0
 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 path = null;
             if (this.options.ignoreRegisteredOcx)
             {
                 path = this.typeLibName;
             }
             else
             {
                 path = GetFileOfTypeLib((System.Runtime.InteropServices.ComTypes.ITypeLib) typeLib);
             }
             DateTime tlbTimeStamp = (path == null) ? DateTime.Now : File.GetLastWriteTime(path);
             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, this.options.ignoreRegisteredOcx, 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;
 }
コード例 #15
0
        private DLLModel convertDLLToManaged(DLLModel dLLModel)
        {
            Object typeLib;
            LoadTypeLibEx(dLLModel.getFullyQualifiedPath(), RegKind.RegKind_None, out typeLib);

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

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

            string newDllName = dLLModel.getDllFileName()
                + "_converted.dll";
            AssemblyBuilder asm = converter.ConvertTypeLibToAssembly(typeLib, newDllName, 0, eventHandler, null, null, null, null);

            asm.Save(newDllName);
            DLLModel newdLLModel = new DLLModel(AppDomain.CurrentDomain.BaseDirectory + newDllName);
            return newdLLModel;
        }
コード例 #16
0
        private static Assembly ConvertTypeLibToAssembly(ITypeLib typeLib)
        {
            if (m_typelibs == null)
            {
                LoadTypeLibAssemblies();
            }

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

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

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

                Assembly a = Assembly.LoadFile(strAssemblyPath);

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

                return a;
            }
        }
コード例 #17
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());
            }
        }
コード例 #18
0
 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;
 }
コード例 #19
0
		// This translates the type library into an assembly
		internal void TranslateTypeLib()
		{
			TraceUtil.WriteLineInfo(this, "TranslateTypeLib");
			// Already associated with an assembly
			if (_assy != null)
				return;
			ReadTypeLibFile();
			if (_iTypeLib == null)
				throw new Exception("Failed to open file: " + _fileName);
			// If this is present, we can't translate the assembly,
			// we just have to try and load it using this name.  This 
			// is the case for things like mscorlib.tlb 
			if (_translatedAssyFullName != null) {
				Assembly assy = null;
				try {
					String fileName;
					// We will have the file name if we are coming through
					// here after the type library has been opened previously
					// (when it is being restored from the registry).
					if (_assyInfo._fileName != null)
						fileName = _assyInfo._fileName;
					else
						fileName = _translatedAssyFullName;
					TraceUtil.WriteLineInfo
						(null,
						"TypeLib - translated assy looking for: " 
						+ fileName);
					assy = Assembly.Load(fileName);
				} catch (FileNotFoundException) {
					// Don't ask the user if we have already asked
					// the user
					if (!_dontFindAssy)
						assy = FindAssemblyFile();
				}
			
				TraceUtil.WriteLineInfo(null,
										"TypeLib - source assy is: "
										+ assy
										+ " for translated lib "
										+ _translatedAssyFullName);
				RecordTranslatedAssy(assy);
				return;
			}
			CheckForPrimaryInteropAssy();
			if (_primaryInteropAssyName != null)
				return;
			// Only create the versioned names if the primary interop assy
			// is not used, since that's not versioned.
			CreateAssyNames();
			TraceUtil.WriteLineIf(null, TraceLevel.Info,
								 "TypeLib - converting - url: " 
								 + _assyInfo._url
								 + " file: " + _assyInfo._fileName);
			String dir = ComponentInspectorProperties.ConvertedAssemblyDirectory;
			Directory.CreateDirectory(dir);
			Directory.SetCurrentDirectory(dir);
			if (IsAssyCurrent(_assyInfo._fileName, _fileName)) {
				// See if there is a translated version already present.
				// We don't know if there should be an Ax version or not,
				// try the normal one and if it succeeds, try the Ax version.
				// If the normal version succeeds however, we can consider
				// that we are done.
				RecordTranslatedAssy(Assembly.LoadFrom(_assyInfo._url));
				TraceUtil.WriteLineInfo(null,
										"TypeLib - found previous xlated "
										+ _assyInfo._name);
				try {
					RecordTranslatedAssy(Assembly.LoadFrom(_axAssyInfo._url));
				} catch {
					// Ignore
				}
				return;
			}
			// Convert the type library to an assembly
				
			// The assembly load event happens in here, it is going to
			// be unable to add the assembly to the registry since there
			// is no CodeBase associated with a dynamically created 
			// assembly, but that's not a problem since we add it below
			// when adding the GUID for the typelib
			ProgressDialog progress = new ProgressDialog();
			progress.Setup("Converting " + GetName() 
						   + " to .NET Assembly",
						  "Please wait while I convert " 
						  + GetName()
						   + " to a .NET Assembly",
						  ProgressDialog.NO_PROGRESS_BAR,
						   !ProgressDialog.HAS_PROGRESS_TEXT,
						  ProgressDialog.FINAL);
			progress.ShowIfNotDone();
			try {
				TypeLibConverter converter = new TypeLibConverter();
				AssemblyBuilder asm = converter.ConvertTypeLibToAssembly
					(_iTypeLib, 
					_assyInfo._fileName,
					// Can't do this because we can't strong name these
					 //TypeLibImporterFlags.PrimaryInteropAssembly, 
					0,
					this,
					null, null, null, null);
				// For the problem associated with Q316653
				//FixEventSinkHelpers(asm);
				asm.Save(_assyInfo._fileName);
				RecordTranslatedAssy(Assembly.LoadFrom(_assyInfo._url));
				// Generate the ActiveX wrapper for the typelib, 
				// if that's necessary
				AxImporter.Options impOptions = new AxImporter.Options();
				impOptions.outputDirectory = dir;
				impOptions.outputName = _axAssyInfo._fileName;
				impOptions.references = this;
				impOptions.genSources = true;
				AxImporter axImport = new AxImporter(impOptions);
				try {
					// This converts the type library and generates the
					// wrapper for any ActiveX controls.  It produces 
					// a list of the assemblies that it created.  If there
					// are no ActiveX controls this will throw.
					String wrapper = axImport.
						GenerateFromTypeLibrary(_iTypeLib);
				} catch (Exception ex) {
					if (ex.Message.StartsWith("Did not find a")) {
						TraceUtil.WriteLineInfo(this, 
												"TypeLib - no controls found");
						return;
					}
					TraceUtil.WriteLineWarning(this, 
											  "TypeLib - AxImporter error "
											  + _assyInfo._url + " " 
											  + ex);
					throw new Exception("Error in AxImporter for: "
										+ _assyInfo._url, ex);
				}
				foreach (String aname in axImport.GeneratedAssemblies) {
					TraceUtil.WriteLineInfo(this, "TypeLib - AX gen assy: " 
											+ aname);
				}
				foreach (String sname in axImport.GeneratedSources) {
					TraceUtil.WriteLineInfo(this, "TypeLib - AX gen source: " 
											+ sname);
				}
				RecordTranslatedAssy(Assembly.LoadFrom(_axAssyInfo._url));
				TraceUtil.WriteLineIf(null, TraceLevel.Info,
									 "TypeLib - conversion done: "
									 + _assyInfo._url);
			} finally {
				progress.Finished();
			}
		}
コード例 #20
0
 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;
 }
コード例 #21
0
        public object ConvertAssemblyToTypeLib(Assembly assembly, string strTypeLibName, TypeLibExporterFlags flags, ITypeLibExporterNotifySink notifySink)
        {
            AssemblyBuilder assemblyBuilder = assembly as AssemblyBuilder;

            return(TypeLibConverter.nConvertAssemblyToTypeLib(!((Assembly)assemblyBuilder != (Assembly)null) ? assembly as RuntimeAssembly : (RuntimeAssembly)assemblyBuilder.InternalAssembly, strTypeLibName, flags, notifySink));
        }
コード例 #22
0
ファイル: MyTypeLibExporter.cs プロジェクト: rojac07/COM
        /// <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;
        }
コード例 #23
0
        public static string GenerateAssemblyFromTypeLib(UCOMITypeLib typLib)
        {
            // Need a sink for the TypeLibConverter.
            var 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.
            var tlc = new TypeLibConverter();

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

            // Now make the assembly based on COM type information.
            var asmBuilder = tlc.ConvertTypeLibToAssembly(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;
        }
コード例 #24
0
 internal Assembly GetPrimaryInteropAssembly(System.Runtime.InteropServices.ComTypes.ITypeLib typeLib, TypeLibConverter tlbConverter)
 {
     Assembly assem = this.FindRCW(typeLib);
     if (assem == null)
     {
         IntPtr invalidIntPtr = System.Design.NativeMethods.InvalidIntPtr;
         typeLib.GetLibAttr(out invalidIntPtr);
         if (!(invalidIntPtr != System.Design.NativeMethods.InvalidIntPtr))
         {
             return assem;
         }
         System.Runtime.InteropServices.TYPELIBATTR typelibattr = (System.Runtime.InteropServices.TYPELIBATTR) Marshal.PtrToStructure(invalidIntPtr, typeof(System.Runtime.InteropServices.TYPELIBATTR));
         string asmName = null;
         string asmCodeBase = null;
         try
         {
             tlbConverter.GetPrimaryInteropAssembly(typelibattr.guid, typelibattr.wMajorVerNum, typelibattr.wMinorVerNum, typelibattr.lcid, out asmName, out asmCodeBase);
             if ((asmName != null) && (asmCodeBase == null))
             {
                 try
                 {
                     assem = Assembly.ReflectionOnlyLoad(asmName);
                     asmCodeBase = this.GetLocalPath(assem.EscapedCodeBase);
                 }
                 catch (Exception)
                 {
                 }
             }
             else if (asmCodeBase != null)
             {
                 asmCodeBase = this.GetLocalPath(asmCodeBase);
                 assem = Assembly.ReflectionOnlyLoadFrom(asmCodeBase);
             }
             if (assem != null)
             {
                 this.AddRCW(typeLib, assem);
                 this.AddReferencedAssembly(asmCodeBase);
             }
         }
         finally
         {
             typeLib.ReleaseTLibAttr(invalidIntPtr);
         }
     }
     return assem;
 }
コード例 #25
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;
        }
 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;
 }
 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;
 }
コード例 #28
0
        private static Type GetInterfaceForTypeInfo(ICallerContext context, IntPtr typeInfoPtr)
        {
            Debug.Assert(typeInfoPtr != IntPtr.Zero);

            ComTypes.TYPEATTR typeInfoAttr = GetITypeInfoAttr(typeInfoPtr);
            Guid typeInfoGuid = typeInfoAttr.guid;

            // Have we seen the GUID before in a previously-loaded assembly?

            Type interfaceType = null;
            if (ComTypeCache.TryGetValue(typeInfoGuid, out interfaceType))
                return interfaceType;

            // Try to find a registered Primary Interop Assembly (PIA)

            TypeLibConverter tlc = new TypeLibConverter();
            string asmName = null, asmCodeBase = null;
            if (tlc.GetPrimaryInteropAssembly(
                    typeInfoGuid,
                    typeInfoAttr.wMajorVerNum,
                    typeInfoAttr.wMinorVerNum,
                    0,
                    out asmName,
                    out asmCodeBase)) {
                try {
                    Assembly interopAssembly = Assembly.Load(asmName);
                    context.SystemState.TopPackage.LoadAssembly(context.SystemState, interopAssembly, true);
                    Debug.Assert(ComTypeCache.ContainsKey(typeInfoGuid));
                    if (!ComTypeCache.ContainsKey(typeInfoGuid))
                        throw new COMException("TypeLib " + asmName + " does not contain COM interface + " + typeInfoGuid);
                    return ComTypeCache[typeInfoGuid];
                } catch (FileNotFoundException) { }
            }

            #if COM_GAC_CRAWLER
            Assembly interopAssembly = SearchForInteropAssemblyInGAC(typeInfoGuid, typeInfoAttr.wMajorVerNum, typeInfoAttr.wMinorVerNum);
            if (interopAssembly != null) {
                context.SystemState.TopPackage.LoadAssembly(context.SystemState, interopAssembly, false);
                Debug.Assert(ComTypeCache.ContainsKey(typeInfoGuid));
                if (!ComTypeCache.ContainsKey(typeInfoGuid))
                    throw new COMException("TypeLib " + interopAssebly + " does not contain COM interface + " + typeInfoGuid);
                return ComTypeCache[typeInfoGuid];
            }
            #endif
            // Try creating an Interop assembly on the fly
            return ConvertTypeLibToAssembly(context, typeInfoPtr, typeInfoGuid);
        }
コード例 #29
0
        public string Import(ProjectReference refinfo, Project project)
        {
            RegistryKey root = Registry.ClassesRoot;
            RegistryKey typelibsKey = root.OpenSubKey("TypeLib");
            int index = refinfo.Reference.LastIndexOf("{");
            if (index < 0) {
                return null;
            }
            RegistryKey typelibKey = typelibsKey.OpenSubKey(refinfo.Reference.Substring(index, refinfo.Reference.Length - index));
            if (typelibKey == null) {
                return null;
            }
            string[] versions = typelibKey.GetSubKeyNames();

            if (versions.Length <= 0) {
                return null;
            }
            // Use the last version
            string version = versions[versions.Length - 1];
            RegistryKey versionKey = typelibKey.OpenSubKey(version);

            string tlbname = (string)versionKey.GetValue(null);

            string tlpath = GetTypelibPath(versionKey);
            if (tlpath == null) {
                return null;
            }
            string proxyfilename = "Interop." + Path.GetFileNameWithoutExtension(tlpath) + ".dll";

            AbstractProjectConfiguration ac = (AbstractProjectConfiguration)project.ActiveConfiguration;
            string fullpath = Path.Combine(ac.OutputDirectory,proxyfilename);

            if (!File.Exists(fullpath)) {
                string saveCurrDir = Directory.GetCurrentDirectory();
                if (!Directory.Exists(ac.OutputDirectory)) {
                    Directory.CreateDirectory(ac.OutputDirectory);
                }
                Directory.SetCurrentDirectory(ac.OutputDirectory);
                if (!ImportTypelibUsingTlbImpCode(tlpath, ac.OutputDirectory, proxyfilename)) {

                    MessageBox.Show("Cannot import type library using .Net SDK 1.0. Some, but not all type libraries can succesfully be imported without it. ",
                                        ".Net SDK 1.0 not present ?",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Warning,
                                        MessageBoxDefaultButton.Button1);

                    Object typeLib;
                    LoadTypeLibEx(tlpath, RegKind.RegKind_None, out typeLib);

                    if( typeLib == null ) {
                        throw new System.Exception("LoadTypeLibEx failed.");
                    }

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

                    AssemblyBuilder asm = converter.ConvertTypeLibToAssembly( typeLib,
                                                                             proxyfilename, 0, eventHandler, null, null,
                                                                             Marshal.GetTypeLibName((UCOMITypeLib)typeLib), null );

                    asm.Save( proxyfilename );

                }
                Directory.SetCurrentDirectory(saveCurrDir);
            }
            return fullpath;
        }
コード例 #30
0
ファイル: PiaReference.cs プロジェクト: cameron314/msbuild
        /*
         * Method:  Resolve
         * 
         * Gets the resolved assembly path for the typelib wrapper.
         */
        internal override bool FindExistingWrapper(out ComReferenceWrapperInfo wrapperInfo, DateTime componentTimestamp)
        {
            wrapperInfo = null;

            // Let NDP do the dirty work...
            TypeLibConverter converter = new TypeLibConverter();
            string asmName, asmCodeBase;

            if (!converter.GetPrimaryInteropAssembly(ReferenceInfo.attr.guid, ReferenceInfo.attr.wMajorVerNum, ReferenceInfo.attr.wMinorVerNum, ReferenceInfo.attr.lcid,
                out asmName, out asmCodeBase))
            {
                return false;
            }

            // let's try to load the assembly to determine its path and if it's there
            try
            {
                if (asmCodeBase != null && asmCodeBase.Length > 0)
                {
                    Uri uri = new Uri(asmCodeBase);

                    // make sure the PIA can be loaded
                    Assembly assembly = Assembly.UnsafeLoadFrom(uri.LocalPath);

                    // got here? then assembly must have been loaded successfully.
                    wrapperInfo = new ComReferenceWrapperInfo();
                    wrapperInfo.path = uri.LocalPath;
                    wrapperInfo.assembly = assembly;

                    // We need to remember the original assembly name of this PIA in case it gets redirected to a newer 
                    // version and other COM components use that name to reference the PIA. assembly.FullName wouldn't
                    // work here since we'd get the redirected assembly name.
                    wrapperInfo.originalPiaName = new AssemblyNameExtension(AssemblyName.GetAssemblyName(uri.LocalPath));
                }
                else
                {
                    Assembly assembly = Assembly.Load(asmName);

                    // got here? then assembly must have been loaded successfully.
                    wrapperInfo = new ComReferenceWrapperInfo();
                    wrapperInfo.path = assembly.Location;
                    wrapperInfo.assembly = assembly;

                    // We need to remember the original assembly name of this PIA in case it gets redirected to a newer 
                    // version and other COM components use that name to reference the PIA. 
                    wrapperInfo.originalPiaName = new AssemblyNameExtension(asmName, true);
                }
            }
            catch (FileNotFoundException)
            {
                // This means that assembly file cannot be found.
                // We don't need to do anything here; wrapperInfo is not set 
                // and we'll assume that the assembly doesn't exist.
            }
            catch (BadImageFormatException)
            {
                // Similar case as above, except we should additionally warn the user that the assembly file 
                // is not really a valid assembly file.
                if (!Silent)
                {
                    Log.LogWarningWithCodeFromResources("ResolveComReference.BadAssemblyImage", asmName);
                }
            }

            // have we found the wrapper?
            if (wrapperInfo != null)
            {
                return true;
            }

            return false;
        }
コード例 #31
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());
     }
 }
コード例 #32
0
        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().ToLowerInvariant());
            }
            else
            {
                // MSBuild will have to generate an interop assembly
                element.SetMetadata(ProjectFileConstants.WrapperTool, WrapperToolAttributeValue.TlbImp.ToString().ToLowerInvariant());
                element.SetMetadata(ProjectFileConstants.Private, true.ToString());
            }
            return element;
        }
コード例 #33
0
ファイル: ObjectTranslator.cs プロジェクト: viticm/pap2
        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;
        }