ConvertTypeLibToAssembly() private method

private ConvertTypeLibToAssembly ( [ typeLib, string asmFileName, TypeLibImporterFlags flags, ITypeLibImporterNotifySink notifySink, byte publicKey, StrongNameKeyPair keyPair, string asmNamespace, System.Version asmVersion ) : AssemblyBuilder
typeLib [
asmFileName string
flags TypeLibImporterFlags
notifySink ITypeLibImporterNotifySink
publicKey byte
keyPair System.Reflection.StrongNameKeyPair
asmNamespace string
asmVersion System.Version
return System.Reflection.Emit.AssemblyBuilder
コード例 #1
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;
        }
コード例 #2
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);
     }
 }
 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;
     }
 }
        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");
        }
コード例 #5
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;
        }
コード例 #6
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;
        }
コード例 #7
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;
        }
コード例 #8
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;
            }
        }
コード例 #9
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;
        }
コード例 #10
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();
			}
		}
コード例 #11
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;
 }
コード例 #12
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;
 }
コード例 #13
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;
 }
コード例 #14
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;
        }