Esempio n. 1
0
        private static bool CanSkipType(ITypeInfo typeInfo, ITypeLib typeLib, TYPEATTR typeAttributes, TYPELIBATTR typeLibAttributes)
        {
            // Well known OLE type?
            if ((typeAttributes.guid == NativeMethods.IID_IUnknown) ||
                (typeAttributes.guid == NativeMethods.IID_IDispatch) ||
                (typeAttributes.guid == NativeMethods.IID_IDispatchEx) ||
                (typeAttributes.guid == NativeMethods.IID_IEnumVariant) ||
                (typeAttributes.guid == NativeMethods.IID_ITypeInfo))
            {
                return(true);
            }

            // Is this the Guid type? If so we should be using the corresponding .NET type.
            if (typeLibAttributes.guid == NativeMethods.IID_StdOle)
            {
                typeInfo.GetDocumentation(-1, out string typeName, out _, out _, out _);

                if (string.CompareOrdinal(typeName, "GUID") == 0)
                {
                    return(true);
                }
            }

            // Skip types exported from .NET assemblies
            if (typeLib is ITypeLib2 typeLib2)
            {
                typeLib2.GetCustData(ref NativeMethods.GUID_ExportedFromComPlus, out object exportedFromComPlusObj);

                string exportedFromComPlus = exportedFromComPlusObj as string;

                if (!string.IsNullOrEmpty(exportedFromComPlus))
                {
                    return(true);
                }
            }

            return(false);
        }
Esempio n. 2
0
            /// <summary>
            /// <para>Gets the TypeLibAttr corresponding to the TLB containing our ActiveX control.</para>
            /// </summary>
            private TYPELIBATTR GetTypeLibAttr()
            {
                string      controlKey = "CLSID\\" + clsid;
                RegistryKey key        = Registry.ClassesRoot.OpenSubKey(controlKey);

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

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

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

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

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

                    short majorVer;

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

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

                    object o = tlbKey.GetValue("");

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

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

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

                        pTLB = Oleaut32.LoadTypeLib(inprocServer);
                    }
                }

                key.Close();

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

                            return(typeLibraryAttributes);
                        }
                    }
                    finally
                    {
                        Marshal.ReleaseComObject(pTLB);
                    }
                }
                else
                {
                    throw new ArgumentException(string.Format(SR.AXNotRegistered, controlKey.ToString()));
                }
            }
Esempio n. 3
0
        /// <summary>
        /// Gets the name of given type library.
        /// </summary>
        internal static bool GetTypeLibNameForTypeLibAttrs(TaskLoggingHelper log, bool silent, TYPELIBATTR typeLibAttr, out string typeLibName)
        {
            typeLibName = "";
            ITypeLib typeLib = null;

            try
            {
                // load our type library
                try
                {
                    TYPELIBATTR attr = typeLibAttr;
                    typeLib = (ITypeLib)NativeMethods.LoadRegTypeLib(ref attr.guid, attr.wMajorVerNum, attr.wMinorVerNum, attr.lcid);
                }
                catch (COMException ex)
                {
                    if (!silent)
                    {
                        log.LogWarningWithCodeFromResources("ResolveComReference.CannotLoadTypeLib", typeLibAttr.guid, typeLibAttr.wMajorVerNum, typeLibAttr.wMinorVerNum, ex.Message);
                    }

                    return(false);
                }

                string typeLibId = log.FormatResourceString("ResolveComReference.TypeLibAttrId", typeLibAttr.guid.ToString(), typeLibAttr.wMajorVerNum, typeLibAttr.wMinorVerNum);

                return(GetTypeLibNameForITypeLib(log, silent, typeLib, typeLibId, out typeLibName));
            }
            finally
            {
                if (typeLib != null)
                {
                    Marshal.ReleaseComObject(typeLib);
                }
            }
        }
Esempio n. 4
0
            /// <summary>
            /// <para>Creates an instance of the ActiveX control. Calls VS7 project system
            /// to generate the wrappers if they are needed..</para>
            /// </summary>
            protected override IComponent[] CreateComponentsCore(IDesignerHost host)
            {
                Debug.Assert(host != null, "Designer host is null!!!");

                // Get the DTE References object
                //
                object references = GetReferences(host);

                if (references != null)
                {
                    try
                    {
                        TYPELIBATTR tlibAttr = GetTypeLibAttr();

                        object[] args = new object[5];
                        args[0] = "{" + tlibAttr.guid.ToString() + "}";
                        args[1] = (int)tlibAttr.wMajorVerNum;
                        args[2] = (int)tlibAttr.wMinorVerNum;
                        args[3] = tlibAttr.lcid;

                        args[4] = "";
                        object tlbRef = references.GetType().InvokeMember("AddActiveX", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, references, args, CultureInfo.InvariantCulture);
                        Debug.Assert(tlbRef != null, "Null reference returned by AddActiveX (tlbimp) by the project system for: " + clsid);

                        args[4] = "aximp";
                        object axRef = references.GetType().InvokeMember("AddActiveX", BindingFlags.InvokeMethod | BindingFlags.Public | BindingFlags.Instance, null, references, args, CultureInfo.InvariantCulture);
                        Debug.Assert(axRef != null, "Null reference returned by AddActiveX (aximp) by the project system for: " + clsid);

                        axctlType = GetAxTypeFromReference(axRef, host);
                    }
                    catch (TargetInvocationException tie)
                    {
                        Debug.WriteLineIf(AxToolSwitch.TraceVerbose, "Generating Ax References failed: " + tie.InnerException);
                        throw tie.InnerException;
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLineIf(AxToolSwitch.TraceVerbose, "Generating Ax References failed: " + e);
                        throw;
                    }
                }

                if (axctlType == null)
                {
                    IUIService uiSvc = (IUIService)host.GetService(typeof(IUIService));
                    if (uiSvc == null)
                    {
                        RTLAwareMessageBox.Show(null, SR.AxImportFailed, null, MessageBoxButtons.OK, MessageBoxIcon.Error,
                                                MessageBoxDefaultButton.Button1, 0);
                    }
                    else
                    {
                        uiSvc.ShowError(SR.AxImportFailed);
                    }

                    return(Array.Empty <IComponent>());
                }

                var comps = new IComponent[1];

                try
                {
                    comps[0] = host.CreateComponent(axctlType);
                }
                catch (Exception e)
                {
                    Debug.Fail("Could not create type: " + e);
                    throw;
                }

                Debug.Assert(comps[0] != null, "Could not create instance of ActiveX control wrappers!!!");
                return(comps);
            }
Esempio n. 5
0
 /*
  * Method:  UniqueKeyFromTypeLibAttr
  *
  * Given a TYPELIBATTR structure, generates a key that can be used in hashtables to identify it.
  */
 internal static string UniqueKeyFromTypeLibAttr(TYPELIBATTR attr)
 {
     return(String.Format(CultureInfo.InvariantCulture, @"{0}|{1}.{2}|{3}", attr.guid, attr.wMajorVerNum, attr.wMinorVerNum, attr.lcid));
 }
Esempio n. 6
0
 /// <summary>
 /// Given a TYPELIBATTR structure, generates a key that can be used in hashtables to identify it.
 /// </summary>
 internal static string UniqueKeyFromTypeLibAttr(TYPELIBATTR attr)
 {
     return($@"{attr.guid}|{attr.wMajorVerNum}.{attr.wMinorVerNum}|{attr.lcid}");
 }
Esempio n. 7
0
 /// <summary>
 /// Get all the dependencies of the processed libraries
 /// </summary>
 /// <returns></returns>
 internal TYPELIBATTR[] GetDependencies()
 {
     TYPELIBATTR[] returnArray = new TYPELIBATTR[_dependencies.Count];
     _dependencies.CopyTo(returnArray);
     return(returnArray);
 }
Esempio n. 8
0
 public static string GetFileOfTypeLib(ref TYPELIBATTR tlibattr)
 {
     throw new NotImplementedException();
 }
Esempio n. 9
0
 public TypeLibAttr(ITypeLib typelib)
 {
     m_typelib = typelib;
     m_ipAttr = TypeLibResourceManager.GetDaemon().GetTypeLibAttr(typelib);
     m_attr = (TYPELIBATTR)Marshal.PtrToStructure(m_ipAttr, typeof(TYPELIBATTR));
 }
Esempio n. 10
0
        public ComImporter(string path, OutputMessageCollection outputMessages, string outputDisplayName)
        {
            _outputMessages    = outputMessages;
            _outputDisplayName = outputDisplayName;

            if (NativeMethods.SfcIsFileProtected(IntPtr.Zero, path) != 0)
            {
                outputMessages.AddWarningMessage("GenerateManifest.ComImport", outputDisplayName, _resources.GetString("ComImporter.ProtectedFile"));
            }

            object obj = null;

            try { NativeMethods.LoadTypeLibEx(path, NativeMethods.RegKind.RegKind_None, out obj); }
            catch (COMException) { }

#pragma warning disable 618
            UCOMITypeLib tlib = (UCOMITypeLib)obj;
            if (tlib != null)
            {
                IntPtr typeLibAttrPtr = IntPtr.Zero;
                tlib.GetLibAttr(out typeLibAttrPtr);
                TYPELIBATTR typeLibAttr = (TYPELIBATTR)Marshal.PtrToStructure(typeLibAttrPtr, typeof(TYPELIBATTR));
                tlib.ReleaseTLibAttr(typeLibAttrPtr);
                Guid tlbid = typeLibAttr.guid;

                string name, docString, helpFile;
                int    helpContext;
                tlib.GetDocumentation(-1, out name, out docString, out helpContext, out helpFile);
                string helpdir = Util.FilterNonprintableChars(helpFile); //Path.GetDirectoryName(helpFile);

                _typeLib = new TypeLib(tlbid, new Version(typeLibAttr.wMajorVerNum, typeLibAttr.wMinorVerNum), helpdir, typeLibAttr.lcid, Convert.ToInt32(typeLibAttr.wLibFlags, CultureInfo.InvariantCulture));

                List <ComClass> comClassList = new List <ComClass>();
                int             count        = tlib.GetTypeInfoCount();
                for (int i = 0; i < count; ++i)
                {
                    TYPEKIND tkind;
                    tlib.GetTypeInfoType(i, out tkind);
                    if (tkind == TYPEKIND.TKIND_COCLASS)
                    {
                        UCOMITypeInfo tinfo;
                        tlib.GetTypeInfo(i, out tinfo);

                        IntPtr tinfoAttrPtr = IntPtr.Zero;
                        tinfo.GetTypeAttr(out tinfoAttrPtr);
                        TYPEATTR tinfoAttr = (TYPEATTR)Marshal.PtrToStructure(tinfoAttrPtr, typeof(TYPEATTR));
                        tinfo.ReleaseTypeAttr(tinfoAttrPtr);
                        Guid   clsid  = tinfoAttr.guid;
                        string sclsid = clsid.ToString("B");

                        tlib.GetDocumentation(i, out name, out docString, out helpContext, out helpFile);
                        string description = Util.FilterNonprintableChars(docString);

                        ClassInfo info = GetRegisteredClassInfo(clsid);
                        if (info == null)
                        {
                            continue;
                        }

                        comClassList.Add(new ComClass(tlbid, clsid, info.Progid, info.ThreadingModel, description));
                    }
                }
                if (comClassList.Count > 0)
                {
                    _comClasses = comClassList.ToArray();
                    _success    = true;
                }
                else
                {
                    outputMessages.AddErrorMessage("GenerateManifest.ComImport", outputDisplayName, _resources.GetString("ComImporter.NoRegisteredClasses"));
                    _success = false;
                }
            }
            else
            {
                outputMessages.AddErrorMessage("GenerateManifest.ComImport", outputDisplayName, _resources.GetString("ComImporter.TypeLibraryLoadFailure"));
                _success = false;
            }
#pragma warning restore 618
        }
Esempio n. 11
0
        public ComImporter(string path, OutputMessageCollection outputMessages, string outputDisplayName)
        {
            this.outputMessages    = outputMessages;
            this.outputDisplayName = outputDisplayName;
            if (Microsoft.Build.Tasks.Deployment.ManifestUtilities.NativeMethods.SfcIsFileProtected(IntPtr.Zero, path) != 0)
            {
                outputMessages.AddWarningMessage("GenerateManifest.ComImport", new string[] { outputDisplayName, this.resources.GetString("ComImporter.ProtectedFile") });
            }
            object typeLib = null;

            try
            {
                Microsoft.Build.Tasks.Deployment.ManifestUtilities.NativeMethods.LoadTypeLibEx(path, Microsoft.Build.Tasks.Deployment.ManifestUtilities.NativeMethods.RegKind.RegKind_None, out typeLib);
            }
            catch (COMException)
            {
            }
            UCOMITypeLib lib = (UCOMITypeLib)typeLib;

            if (lib != null)
            {
                string str;
                string str2;
                string str3;
                int    num;
                IntPtr zero = IntPtr.Zero;
                lib.GetLibAttr(out zero);
                TYPELIBATTR typelibattr = (TYPELIBATTR)Marshal.PtrToStructure(zero, typeof(TYPELIBATTR));
                lib.ReleaseTLibAttr(zero);
                Guid tlbId = typelibattr.guid;
                lib.GetDocumentation(-1, out str, out str2, out num, out str3);
                string helpDirectory = Microsoft.Build.Tasks.Deployment.ManifestUtilities.Util.FilterNonprintableChars(str3);
                this.typeLib = new Microsoft.Build.Tasks.Deployment.ManifestUtilities.TypeLib(tlbId, new Version(typelibattr.wMajorVerNum, typelibattr.wMinorVerNum), helpDirectory, typelibattr.lcid, Convert.ToInt32(typelibattr.wLibFlags, CultureInfo.InvariantCulture));
                List <ComClass> list          = new List <ComClass>();
                int             typeInfoCount = lib.GetTypeInfoCount();
                for (int i = 0; i < typeInfoCount; i++)
                {
                    TYPEKIND typekind;
                    lib.GetTypeInfoType(i, out typekind);
                    if (typekind == TYPEKIND.TKIND_COCLASS)
                    {
                        UCOMITypeInfo info;
                        lib.GetTypeInfo(i, out info);
                        IntPtr ppTypeAttr = IntPtr.Zero;
                        info.GetTypeAttr(out ppTypeAttr);
                        TYPEATTR typeattr = (TYPEATTR)Marshal.PtrToStructure(ppTypeAttr, typeof(TYPEATTR));
                        info.ReleaseTypeAttr(ppTypeAttr);
                        Guid guid = typeattr.guid;
                        guid.ToString("B");
                        lib.GetDocumentation(i, out str, out str2, out num, out str3);
                        string    description         = Microsoft.Build.Tasks.Deployment.ManifestUtilities.Util.FilterNonprintableChars(str2);
                        ClassInfo registeredClassInfo = this.GetRegisteredClassInfo(guid);
                        if (registeredClassInfo != null)
                        {
                            list.Add(new ComClass(tlbId, guid, registeredClassInfo.Progid, registeredClassInfo.ThreadingModel, description));
                        }
                    }
                }
                if (list.Count > 0)
                {
                    this.comClasses = list.ToArray();
                    this.success    = true;
                }
                else
                {
                    outputMessages.AddErrorMessage("GenerateManifest.ComImport", new string[] { outputDisplayName, this.resources.GetString("ComImporter.NoRegisteredClasses") });
                    this.success = false;
                }
            }
            else
            {
                outputMessages.AddErrorMessage("GenerateManifest.ComImport", new string[] { outputDisplayName, this.resources.GetString("ComImporter.TypeLibraryLoadFailure") });
                this.success = false;
            }
        }
Esempio n. 12
0
 public static string GetFileOfTypeLib(ref TYPELIBATTR tlibattr)
 {
     throw null;
 }
Esempio n. 13
0
        /// <include file='doc\AxImporter.uex' path='docs/doc[@for="AxImporter.GetFileOfTypeLib"]/*' />
        /// <devdoc>
        /// <para>Gets the file name corresponding to the given TypelibAttribute. </para>
        /// </devdoc>
        public static string GetFileOfTypeLib(ref TYPELIBATTR tlibattr)
        {
            // Get which file the type library resides in.  If the appropriate
            // file cannot be found then a blank string is returned.

            string returnedPath = null;

            // Get the path from the registry
            returnedPath = NativeMethods.QueryPathOfRegTypeLib(ref tlibattr.guid, tlibattr.wMajorVerNum, tlibattr.wMinorVerNum, tlibattr.lcid);

            if (returnedPath.Length > 0)
            {
                // Remove the '\0' characters at the end of the string, so File.Exists()
                // does not get confused.
                int nullTerminate = returnedPath.IndexOf('\0');
                if (nullTerminate > -1)
                {
                    returnedPath = returnedPath.Substring(0, nullTerminate);
                }

                // If we got a path then it might have a type library number appended to
                // it.  If so, then we need to strip it.
                if (!File.Exists(returnedPath))
                {
                    // Strip the type library number
                    //
                    int lastSlash = returnedPath.LastIndexOf(Path.DirectorySeparatorChar);
                    if (lastSlash != -1)
                    {
                        bool allNumbers = true;
                        for (int i = lastSlash + 1; i < returnedPath.Length; i++)
                        {
                            // We have to check for NULL here because QueryPathOfRegTypeLib() returns
                            // a BSTR with a NULL character appended to it.
                            if (returnedPath[i] != '\0' && !Char.IsDigit(returnedPath[i]))
                            {
                                allNumbers = false;
                                break;
                            }
                        }

                        // If we had all numbers past the last slash then we're OK to strip
                        // the type library number
                        if (allNumbers)
                        {
                            returnedPath = returnedPath.Substring(0, lastSlash);
                            if (!File.Exists(returnedPath))
                            {
                                returnedPath = null;
                            }
                        }
                        else
                        {
                            returnedPath = null;
                        }
                    }
                    else
                    {
                        returnedPath = null;
                    }
                }
            }

            return(returnedPath);
        }
Esempio n. 14
0
        /// <summary>
        /// Register a COM type library
        /// </summary>
        /// <param name="path"></param>
        private void RegisterTypelib(string path)
        {
            IntPtr Typelib = new IntPtr(0);
            int    error   = 0;

            // Load typelib
            int result = LoadTypeLib(path, ref Typelib);

            error = Marshal.GetLastWin32Error();

            if (error != 0 || result != 0)
            {
                int win32error = (error != 0) ? error : result;
                throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                       "Error loading typelib '{0}' ({1}: {2}).", path, win32error,
                                                       GetWin32ErrorMessage(win32error)), Location);
            }

            try {
                if (Unregister)
                {
                    UCOMITypeLib typeLib = null;

                    try {
                        typeLib = (UCOMITypeLib)Marshal.GetTypedObjectForIUnknown(
                            Typelib, typeof(UCOMITypeLib));
                        // check for for win32 error
                        error = Marshal.GetLastWin32Error();
                        if (error != 0)
                        {
                            throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                                   "Error retrieving information from typelib '{0}' ({1}: {2}).",
                                                                   path, error, GetWin32ErrorMessage(error)), Location);
                        }

                        IntPtr libAttrPtr = new IntPtr(0);
                        typeLib.GetLibAttr(out libAttrPtr);
                        TYPELIBATTR typeLibAttr = (TYPELIBATTR)
                                                  Marshal.PtrToStructure(libAttrPtr, typeof(TYPELIBATTR));

                        // unregister type library
                        UnRegisterTypeLib(ref typeLibAttr.guid, typeLibAttr.wMajorVerNum,
                                          typeLibAttr.wMinorVerNum, typeLibAttr.lcid, typeLibAttr.syskind);
                        // check for for win32 error
                        error = Marshal.GetLastWin32Error();
                        // release the TYPELIBATTR
                        typeLib.ReleaseTLibAttr(libAttrPtr);
                        if (error != 0)
                        {
                            // signal error
                            throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                                   "Typelib '{0}' could not be unregistered ({1}: {2}).",
                                                                   path, error, GetWin32ErrorMessage(error)), Location);
                        }
                    } finally {
                        if (typeLib != null)
                        {
                            Marshal.ReleaseComObject(typeLib);
                        }
                    }
                }
                else
                {
                    //Perform registration
                    RegisterTypeLib(Typelib, path, null);
                    error = Marshal.GetLastWin32Error();

                    if (error != 0)
                    {
                        throw new BuildException(string.Format(CultureInfo.InvariantCulture,
                                                               "Error registering typelib '{0}' ({1}: {2}).", path,
                                                               error, GetWin32ErrorMessage(error)), Location);
                    }
                }
            } finally {
                Marshal.Release(Typelib);
            }
        }
Esempio n. 15
0
        internal static Assembly generateAssemblyFromTypeLib(UCOMITypeLib typeLib, bool safeArrayAsArray, string asmFilePath, out bool foundPIAInstead)
        {
            foundPIAInstead = false;
            string typeLibName = Marshal.GetTypeLibName(typeLib);
            string asmDir, asmName, asmFullPath;

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

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

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

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

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

            TypeLoader.isBuildingDynamicAssembly = true;
            try {
                AssemblyBuilder asmBuilder = tlc.ConvertTypeLibToAssembly(typeLib, asmFullPath,
                                                                          safeArrayAsArray ? TypeLibImporterFlags.SafeArrayAsSystemArray : 0, sink, null, null, typeLibName, null);
                Type[] tt = asmBuilder.GetTypes();
                if (asmFilePath != "")
                {
                    asmBuilder.Save(asmName);
                }
                return(asmBuilder);
            } finally {
                TypeLoader.isBuildingDynamicAssembly = false;
            }
        }