Example #1
0
        public int Run(String strTypeLibName,
                       String strAssemblyName,
                       String strAssemblyNamespace,
                       String strOutputDir,
                       byte[]               aPublicKey,
                       StrongNameKeyPair sKeyPair,
                       String strAssemblyRefList,
                       String strTypeLibRefList,
                       Version AssemblyVersion,
                       TypeLibImporterFlags flags,
                       bool bNoLogo,
                       bool bSilentMode,
                       System.Collections.Generic.List <int> silenceList,
                       bool bVerboseMode,
                       bool bStrictRef,
                       bool bStrictRefNoPia,
                       bool bSearchPathSucceeded,
                       String strProduct,
                       String strProductVersion,
                       String strCompany,
                       String strCopyright,
                       String strTrademark,
                       bool isVersion2,
                       bool isPreserveSig,
                       String ruleSetFileName)
        {
            TlbImpOptions options = new TlbImpOptions();

            options.m_strTypeLibName       = strTypeLibName;
            options.m_strAssemblyName      = strAssemblyName;
            options.m_strAssemblyNamespace = strAssemblyNamespace;
            options.m_strOutputDir         = strOutputDir;
            options.m_aPublicKey           = aPublicKey;
            options.m_sKeyPair             = sKeyPair;
            options.m_strAssemblyRefList   = strAssemblyRefList;
            options.m_strTypeLibRefList    = strTypeLibRefList;
            options.m_AssemblyVersion      = AssemblyVersion;
            options.m_flags                = flags;
            options.m_bNoLogo              = bNoLogo;
            options.m_bSilentMode          = bSilentMode;
            options.m_silenceList          = silenceList;
            options.m_bVerboseMode         = bVerboseMode;
            options.m_bStrictRef           = bStrictRef;
            options.m_bStrictRefNoPia      = bStrictRefNoPia;
            options.m_bSearchPathSucceeded = bSearchPathSucceeded;
            options.m_strProduct           = strProduct;
            options.m_strProductVersion    = strProductVersion;
            options.m_strCompany           = strCompany;
            options.m_strCopyright         = strCopyright;
            options.m_strTrademark         = strTrademark;
            options.m_isVersion2           = isVersion2;
            options.m_isPreserveSig        = isPreserveSig;
            options.m_ruleSetFileName      = ruleSetFileName;

            return(TlbImpCode.Run(options));
        }
Example #2
0
        public int Run(String               strTypeLibName,
            String               strAssemblyName,
            String               strAssemblyNamespace,
            String               strOutputDir,
            byte[]               aPublicKey,
            StrongNameKeyPair    sKeyPair,
            String               strAssemblyRefList,
            String               strTypeLibRefList,
            Version              AssemblyVersion,
            TypeLibImporterFlags flags,
            bool                 bNoLogo,
            bool                 bSilentMode,
            System.Collections.Generic.List<int> silenceList,
            bool                 bVerboseMode,
            bool                 bStrictRef,
            bool                 bStrictRefNoPia,
            bool                 bSearchPathSucceeded,
            String               strProduct,
            String               strProductVersion,
            String               strCompany,
            String               strCopyright,
            String               strTrademark,
            bool                 isVersion2,
            bool                 isPreserveSig,
            String               ruleSetFileName)
        {
            TlbImpOptions options = new TlbImpOptions();
            options.m_strTypeLibName = strTypeLibName;
            options.m_strAssemblyName = strAssemblyName;
            options.m_strAssemblyNamespace = strAssemblyNamespace;
            options.m_strOutputDir = strOutputDir;
            options.m_aPublicKey = aPublicKey;
            options.m_sKeyPair = sKeyPair;
            options.m_strAssemblyRefList = strAssemblyRefList;
            options.m_strTypeLibRefList = strTypeLibRefList;
            options.m_AssemblyVersion = AssemblyVersion;
            options.m_flags = flags;
            options.m_bNoLogo = bNoLogo;
            options.m_bSilentMode = bSilentMode;
            options.m_silenceList = silenceList;
            options.m_bVerboseMode = bVerboseMode;
            options.m_bStrictRef = bStrictRef;
            options.m_bStrictRefNoPia = bStrictRefNoPia;
            options.m_bSearchPathSucceeded = bSearchPathSucceeded;
            options.m_strProduct = strProduct;
            options.m_strProductVersion = strProductVersion;
            options.m_strCompany = strCompany;
            options.m_strCopyright = strCopyright;
            options.m_strTrademark = strTrademark;
            options.m_isVersion2 = isVersion2;
            options.m_isPreserveSig = isPreserveSig;
            options.m_ruleSetFileName = ruleSetFileName;

            return TlbImpCode.Run(options);
        }
Example #3
0
    private static bool ParseArguments(String []aArgs, ref TlbImpOptions Options, ref int ReturnCode)
    {
        Option opt;
        bool delaysign = false;

        // Create the options object that will be returned.
        Options = new TlbImpOptions();

        // Parse the command line arguments using the command line argument parser.
        var cmdLine = new CommandLine(aArgs, new String[] { "*out", "*publickey", "*keyfile", "*keycontainer", "delaysign", "*reference",
            "unsafe", "nologo", "silent", "verbose", "+strictref", "primary", "*namespace", 
            "*asmversion", "sysarray", "*transform", "?", "help", "*tlbreference",
            "noclassmembers", "*machine", "*silence", "*product", "*productversion", 
            "*company", "*copyright", "*trademark", "v2", "preservesig", "*config" });

        // Make sure there is at least one argument.
        if ((cmdLine.NumArgs + cmdLine.NumOpts) < 1)
        {
            PrintUsage();
            ReturnCode = SuccessReturnCode;
            return false;
        }

        var assemblyRefList = new List<string>();
        var typeLibRefList = new List<string>();

        // Get the name of the COM typelib.
        Options.m_strTypeLibName = cmdLine.GetNextArg();

        // Go through the list of options.
        while ((opt = cmdLine.GetNextOption()) != null)
        {
            // Determine which option was specified.
            if (opt.Name.Equals("out"))
            {
                Options.m_strAssemblyName = opt.Value;
            }
            else if (opt.Name.Equals("namespace"))
            {
                Options.m_strAssemblyNamespace = opt.Value;
            }
            else if (opt.Name.Equals("asmversion"))
            {
                try
                {
                    Options.m_AssemblyVersion = new Version(opt.Value);
                }
                catch(Exception)
                {
                    throw new TlbImpGeneralException(Resource.FormatString("Err_InvalidVersion"), ErrorCode.Err_InvalidVersion, true);
                }
            }
            else if (opt.Name.Equals("reference"))
            {
                string FullPath = GetFullPath(opt.Value, false);
                
                if (FullPath == null)
                {
                    ReturnCode = ErrorReturnCode;
                    return false;
                }

                if (Options.m_strAssemblyRefList == null)
                {
                    assemblyRefList.Clear();
                    assemblyRefList.Add(FullPath.ToLower());
                    Options.m_strAssemblyRefList = FullPath;
                }
                else
                {
                    if (!assemblyRefList.Contains(FullPath.ToLower())) {
                        assemblyRefList.Add(FullPath.ToLower());
                        Options.m_strAssemblyRefList =
                            Options.m_strAssemblyRefList + ";" + FullPath;
                    }
                }
            }
            else if (opt.Name.Equals("tlbreference"))
            {
                string FullPath = GetFullPath(opt.Value, false);
                if (FullPath == null)
                {
                    ReturnCode = ErrorReturnCode;
                    return false;
                }

                if (Options.m_strTypeLibRefList == null) {
                    typeLibRefList.Clear();
                    typeLibRefList.Add(FullPath.ToLower());
                    Options.m_strTypeLibRefList = FullPath;
                }
                else
                {
                    if (!typeLibRefList.Contains(FullPath.ToLower()))
                    {
                        typeLibRefList.Add(FullPath.ToLower());
                        Options.m_strTypeLibRefList =
                            Options.m_strTypeLibRefList + ";" + FullPath;
                    }
                }
            }
            else if (opt.Name.Equals("delaysign"))
            {
                delaysign = true;
            }
            else if (opt.Name.Equals("publickey"))
            {
                if (Options.m_sKeyPair != null || Options.m_aPublicKey != null)
                {
                    throw new TlbImpGeneralException(Resource.FormatString("Err_TooManyKeys"), ErrorCode.Err_TooManyKeys, true);
                }
                // Read data from binary file into byte array.
                byte[] aData;
                FileStream fs = null;
                try
                {
                    fs = new FileStream(opt.Value, FileMode.Open, FileAccess.Read, FileShare.Read);
                    int iLength = (int)fs.Length;
                    aData = new byte[iLength];
                    fs.Read(aData, 0, iLength);
                }
                catch (Exception ex)
                {
                    throw new TlbImpGeneralException(Resource.FormatString("Err_ErrorWhileOpenningFile", new object[] { opt.Value, ex.GetType().ToString(), ex.Message }), ErrorCode.Err_ErrorWhileOpenningFile, true);
                }
                finally
                {
                    if (fs != null)
                        fs.Close();
                }
                Options.m_aPublicKey = aData;
            }
            else if (opt.Name.Equals("keyfile"))
            {
                if (Options.m_sKeyPair != null || Options.m_aPublicKey != null)
                {
                    throw new TlbImpGeneralException(Resource.FormatString("Err_TooManyKeys"), ErrorCode.Err_TooManyKeys, true);
                }
                
                // Read data from binary file into byte array.
                byte[] aData;
                FileStream fs = null;
                try
                {
                    fs = new FileStream(opt.Value, FileMode.Open, FileAccess.Read, FileShare.Read);
                    int iLength = (int)fs.Length;
                    aData = new byte[iLength];
                    fs.Read(aData, 0, iLength);
                }
                catch (Exception ex)
                {
                    throw new TlbImpGeneralException(Resource.FormatString("Err_ErrorWhileOpenningFile", new object[] { opt.Value, ex.GetType().ToString(), ex.Message }), ErrorCode.Err_ErrorWhileOpenningFile, true);
                }
                finally
                {
                    if (fs != null)
                        fs.Close();
                }
                Options.m_sKeyPair = new StrongNameKeyPair(aData);
            }
            else if (opt.Name.Equals("keycontainer"))
            {
                if ((Options.m_sKeyPair != null) || (Options.m_aPublicKey != null))
                {
                    throw new TlbImpGeneralException(Resource.FormatString("Err_TooManyKeys"), ErrorCode.Err_TooManyKeys, true);
                }
                Options.m_sKeyPair = new StrongNameKeyPair(opt.Value);
            }
            else if (opt.Name.Equals("unsafe"))
            {
                Options.m_flags |= TypeLibImporterFlags.UnsafeInterfaces;
            }
            else if (opt.Name.Equals("primary"))
            {
                Options.m_flags |= TypeLibImporterFlags.PrimaryInteropAssembly;
            }
            else if (opt.Name.Equals("sysarray"))
            {
                Options.m_flags |= TypeLibImporterFlags.SafeArrayAsSystemArray;
            }
            else if (opt.Name.Equals("nologo"))
            {
                Options.m_bNoLogo = true;
            }
            else if (opt.Name.Equals("silent"))
            {
                Output.SetSilent(true);
                Options.m_bSilentMode = true;
            }
            else if (opt.Name.Equals("silence"))
            {
                int warningNumber = int.Parse(opt.Value, System.Globalization.NumberStyles.HexNumber);
                Output.Silence(warningNumber);
                Options.m_silenceList.Add(warningNumber);
            }
            else if (opt.Name.Equals("verbose"))
            {
                Options.m_bVerboseMode = true;
            }
            else if (opt.Name.Equals("noclassmembers"))
            {
                Options.m_flags |= TypeLibImporterFlags.PreventClassMembers;
            }
            else if (opt.Name.Equals("strictref"))
            {
                if (opt.Value != null)
                {
                    if (String.Compare(opt.Value, "nopia", true) == 0)
                    {
                        Options.m_bStrictRefNoPia = true;
                    }
                    else
                    {
                        throw new TlbImpGeneralException(Resource.FormatString("Err_UnknownStrictRefOpt", opt.Value), ErrorCode.Err_UnknownStrictRefOpt, true);
                    }
                }
                else
                    Options.m_bStrictRef = true;
            }
            else if (opt.Name.Equals("transform"))
            {
                if (opt.Value.ToLower(CultureInfo.InvariantCulture) == "dispret")
                {
                    Options.m_flags |= TypeLibImporterFlags.TransformDispRetVals;
                }
                else if (opt.Value.ToLower(CultureInfo.InvariantCulture) == "serializablevalueclasses")
                {
                    Options.m_flags |= TypeLibImporterFlags.SerializableValueClasses;
                }
                else
                {
                    throw new TlbImpGeneralException(Resource.FormatString("Err_InvalidTransform", opt.Value), ErrorCode.Err_InvalidTransform, true);
                }
            }
            else if (opt.Name.Equals("machine"))
            {
                if (opt.Value.ToLower(CultureInfo.InvariantCulture) == "itanium")
                {
                    Options.m_flags |= TypeLibImporterFlags.ImportAsItanium;
                }
                else if (opt.Value.ToLower(CultureInfo.InvariantCulture) == "x64")
                {
                    Options.m_flags |= TypeLibImporterFlags.ImportAsX64;
                }
                else if (opt.Value.ToLower(CultureInfo.InvariantCulture) == "x86")
                {
                    Options.m_flags |= TypeLibImporterFlags.ImportAsX86;
                }
                else if (opt.Value.ToLower(CultureInfo.InvariantCulture) == "agnostic")
                {
                    Options.m_flags |= TypeLibImporterFlags.ImportAsAgnostic;
                }
                else
                {
                    throw new TlbImpGeneralException(Resource.FormatString("Err_InvalidMachine", opt.Value), ErrorCode.Err_InvalidMachine, true);
                }
            }
            else if (opt.Name.Equals("product"))
            {
                Options.m_strProduct = opt.Value;
            }
            else if (opt.Name.Equals("productversion"))
            {
                Options.m_strProductVersion = opt.Value;
            }
            else if (opt.Name.Equals("company"))
            {
                Options.m_strCompany = opt.Value;
            }
            else if (opt.Name.Equals("copyright"))
            {
                Options.m_strCopyright = opt.Value;
            }
            else if (opt.Name.Equals("trademark"))
            {
                Options.m_strTrademark = opt.Value;
            }
            else if (opt.Name.Equals("?") || opt.Name.Equals("help"))
            {
                PrintUsage();
                ReturnCode = SuccessReturnCode;
                return false;
            }
            else if (opt.Name.Equals("v2"))
            {
                Options.m_isVersion2 = true;
            }
            else if (opt.Name.Equals("preservesig"))
            {
                Options.m_isPreserveSig = true;
            }
            else if (opt.Name.Equals("config"))
            {
                Options.m_ruleSetFileName = opt.Value;
            }
        }

        // Validate that the typelib name has been specified.
        if (Options.m_strTypeLibName == null)
        {
            throw new TlbImpGeneralException(Resource.FormatString("Err_NoInputFile"), ErrorCode.Err_NoInputFile, true);
        }

        // Gather information needed for strong naming the assembly (if
        // the user desires this).
        if ((Options.m_sKeyPair != null) && (Options.m_aPublicKey == null))
        {
            try
            {
                Options.m_aPublicKey = Options.m_sKeyPair.PublicKey;
            }
            catch
            {
                throw new TlbImpGeneralException(Resource.FormatString("Err_InvalidStrongName"), ErrorCode.Err_InvalidStrongName, true);
            }
        }

        if (delaysign && Options.m_sKeyPair != null)
            Options.m_sKeyPair = null;

        // To be able to generate a PIA, we must also be strong naming the assembly.
        if ((Options.m_flags & TypeLibImporterFlags.PrimaryInteropAssembly) != 0)
        {
            if (Options.m_aPublicKey == null && Options.m_sKeyPair == null)
            {
                throw new TlbImpGeneralException(Resource.FormatString("Err_PIAMustBeStrongNamed"), ErrorCode.Err_PIAMustBeStrongNamed, true);
            }
        }

        return true;
    }
Example #4
0
        //**************************************************************************
        // Entry point called on the typelib importer in the proper app domain.
        //**************************************************************************
        public static int Run(TlbImpOptions options)
        {
            if (options == null) throw new ArgumentNullException(nameof(options));
            s_Options = options;

            Output.SetSilent(options.m_bSilentMode);
            Output.Silence(options.m_silenceList);

            System.Runtime.InteropServices.ComTypes.ITypeLib TypeLib = null;
            String strPIAName = null;
            String strPIACodeBase = null;

            s_RK = REGKIND.REGKIND_NONE;

            if (Environment.OSVersion.Platform != PlatformID.Win32Windows)
            {
            if (IsImportingToItanium(options.m_flags) || IsImportingToX64(options.m_flags))
            {
                s_RK |= REGKIND.REGKIND_LOAD_TLB_AS_64BIT;
            }
            else if (IsImportingToX86(options.m_flags))
            {
                s_RK |= REGKIND.REGKIND_LOAD_TLB_AS_32BIT;
            }
            }

            //----------------------------------------------------------------------
            // Load the typelib.
            try
            {
            LoadTypeLibEx(s_Options.m_strTypeLibName, s_RK, out TypeLib);
            s_RefTypeLibraries.Add(s_Options.m_strTypeLibName, TypeLib);
            }
            catch (COMException e)
            {
            if (!s_Options.m_bSearchPathSucceeded)
            {
                // We failed to search for the typelib and we failed to load it.
                // This means that the input typelib is not available.
                Output.WriteError(Resource.FormatString("Err_InputFileNotFound", s_Options.m_strTypeLibName), ErrorCode.Err_InputFileNotFound);
            }
            else
            {
                if (e.ErrorCode == unchecked((int)0x80029C4A))
                {
                    Output.WriteError(Resource.FormatString("Err_InputFileNotValidTypeLib", s_Options.m_strTypeLibName), ErrorCode.Err_InputFileNotValidTypeLib);
                }
                else
                {
                    Output.WriteError(Resource.FormatString("Err_TypeLibLoad", e), ErrorCode.Err_TypeLibLoad);
                }
            }
            return ErrorReturnCode;
            }
            catch (Exception e)
            {
            Output.WriteError(Resource.FormatString("Err_TypeLibLoad", e), ErrorCode.Err_TypeLibLoad);
            return ErrorReturnCode;
            }

            //----------------------------------------------------------------------
            // Check to see if there already exists a primary interop assembly for
            // this typelib.

            if (TlbImpCode.GetPrimaryInteropAssembly(TypeLib, out strPIAName, out strPIACodeBase))
            {
            Output.WriteWarning(Resource.FormatString("Wrn_PIARegisteredForTlb", strPIAName, s_Options.m_strTypeLibName), WarningCode.Wrn_PIARegisteredForTlb);
            }

            //----------------------------------------------------------------------
            // Retrieve the name of output assembly if it was not explicitly set.

            if (s_Options.m_strAssemblyName == null)
            {
            s_Options.m_strAssemblyName = Marshal.GetTypeLibName(TypeLib) + ".dll";
            }

            //----------------------------------------------------------------------
            // Do some verification on the output assembly.

            String strFileNameNoPath = Path.GetFileName(s_Options.m_strAssemblyName);
            String strExtension = Path.GetExtension(s_Options.m_strAssemblyName);

            // Validate that the extension is valid.
            bool bExtensionValid = ".dll".Equals(strExtension.ToLower(CultureInfo.InvariantCulture));

            // If the extension is not valid then tell the user and quit.
            if (!bExtensionValid)
            {
            Output.WriteError(Resource.FormatString("Err_InvalidExtension"), ErrorCode.Err_InvalidExtension);
            return ErrorReturnCode;
            }

            // Make sure the output file will not overwrite the input file.
            String strInputFilePath = (new FileInfo(s_Options.m_strTypeLibName)).FullName.ToLower(CultureInfo.InvariantCulture);
            String strOutputFilePath;
            try
            {
            strOutputFilePath = (new FileInfo(s_Options.m_strAssemblyName)).FullName.ToLower(CultureInfo.InvariantCulture);
            }
            catch (System.IO.PathTooLongException)
            {
            Output.WriteError(Resource.FormatString("Err_OutputFileNameTooLong", s_Options.m_strAssemblyName), ErrorCode.Err_OutputFileNameTooLong);
            return ErrorReturnCode;
            }

            if (strInputFilePath.Equals(strOutputFilePath))
            {
            Output.WriteError(Resource.FormatString("Err_OutputWouldOverwriteInput"), ErrorCode.Err_OutputWouldOverwriteInput);
            return ErrorReturnCode;
            }

            //-------------------------------------------------------------------------
            // Load all assemblies provided as explicit references on the command line.
            if (s_Options.m_strAssemblyRefList != null)
            {
            String[] asmPaths = s_Options.m_strAssemblyRefList.Split(';');

            foreach (String asmPath in asmPaths)
            {
                if (!LoadAssemblyRef(asmPath))
                    return ErrorReturnCode;
            }
            }

            //-------------------------------------------------------------------------
            // And the same for type library references.
            if (s_Options.m_strTypeLibRefList != null)
            {
            String[] tlbPaths = s_Options.m_strTypeLibRefList.Split(';');

            foreach (String tlbPath in tlbPaths)
            {
                if (!LoadTypeLibRef(tlbPath))
                    return ErrorReturnCode;
            }
            }

            //-------------------------------------------------------------------------
            // Before we attempt the import, verify the references first
            if (!VerifyTypeLibReferences(s_Options.m_strTypeLibName))
            return ErrorReturnCode;

            //----------------------------------------------------------------------
            // Attempt the import.

            try
            {
            try
            {
                // Import the typelib to an assembly.
                AssemblyBuilder AsmBldr = DoImport(TypeLib, s_Options.m_strAssemblyName, s_Options.m_strAssemblyNamespace,
                    s_Options.m_AssemblyVersion, s_Options.m_aPublicKey, s_Options.m_sKeyPair, s_Options.m_strProduct,
                    s_Options.m_strProductVersion, s_Options.m_strCompany, s_Options.m_strCopyright, s_Options.m_strTrademark,
                    s_Options.m_flags, s_Options.m_isVersion2, s_Options.m_isPreserveSig, s_Options.m_ruleSetFileName);
                if (AsmBldr == null)
                    return ErrorReturnCode;
            }
            catch (TlbImpResolveRefFailWrapperException ex)
            {
                // Throw out the inner exception instead
                throw ex.InnerException;
            }
            }
            catch (ReflectionTypeLoadException e)
            {
            Output.WriteError(Resource.FormatString("Err_TypeLoadExceptions"), ErrorCode.Err_TypeLoadExceptions);
            Exception[] exceptions = e.LoaderExceptions;
            for (int i = 0; i < exceptions.Length; i++)
            {
                try
                {
                    Output.WriteInfo(Resource.FormatString("Msg_DisplayException", new object[] { i, exceptions[i].GetType().ToString(), exceptions[i].Message }), MessageCode.Msg_DisplayException);
                }
                catch (Exception ex)
                {
                    Output.WriteInfo(Resource.FormatString("Msg_DisplayNestedException", new object [] { i, ex.GetType().ToString(), ex.Message }), MessageCode.Msg_DisplayNestedException);
                }
            }
            return ErrorReturnCode;
            }
            catch (TlbImpGeneralException tge)
            {
            Output.WriteTlbimpGeneralException(tge);
            return ErrorReturnCode;
            }
            catch (COMException ex)
            {
            if ((uint)ex.ErrorCode == HResults.TYPE_E_CANTLOADLIBRARY)
            {
                // Give a more specific message
                Output.WriteError(Resource.FormatString("Err_RefTlbCantLoad"), ErrorCode.Err_RefTlbCantLoad);
            }
            else
            {
                // TlbImp COM exception
                string msg = Resource.FormatString(
                    "Err_UnexpectedException",
                    ex.GetType().ToString(),
                    ex.Message
                    );
                Output.WriteError(msg, ErrorCode.Err_UnexpectedException);
            }

            return ErrorReturnCode;
            }
            catch (TlbImpInvalidTypeConversionException ex)
            {
            // This usually means that a type conversion has failed outside normal conversion process...
            string name = null;
            try
            {
                name = ex.Type.GetDocumentation();
            }
            catch(Exception)
            {
            }

            if (name != null)
                Output.WriteError(Resource.FormatString("Err_FatalErrorInConversion_Named", name), ErrorCode.Err_FatalErrorInConversion_Named);
            else
                Output.WriteError(Resource.FormatString("Err_FatalErrorInConversion_Unnamed"), ErrorCode.Err_FatalErrorInConversion_Unnamed);

            return ErrorReturnCode;
            }
            catch (SecurityException ex)
            {
            // Only treat SecurityException with PermissionType != null as permission issue
            if (ex.PermissionType == null)
            {
                string msg = Resource.FormatString(
                    "Err_UnexpectedException",
                    ex.GetType().ToString(),
                    ex.Message
                    );
                Output.WriteError(msg, ErrorCode.Err_UnexpectedException);
            }
            else
            {
                Output.WriteError(Resource.GetString("Err_PermissionException"), ErrorCode.Err_PermissionException);
            }

            return ErrorReturnCode;
            }
            catch (Exception ex)
            {
            string msg = Resource.FormatString(
                "Err_UnexpectedException",
                ex.GetType().ToString(),
                ex.Message
                );
            Output.WriteError(msg, ErrorCode.Err_UnexpectedException);

            return ErrorReturnCode;
            }

            Output.WriteInfo(Resource.FormatString("Msg_TypeLibImported", s_Options.m_strAssemblyName), MessageCode.Msg_TypeLibImported);

            return SuccessReturnCode;
        }
Example #5
0
 public int Run(TlbImpOptions s_options)
 {
     return(TlbImpCode.Run(s_options));
 }
Example #6
0
        //**************************************************************************
        // Entry point called on the typelib importer in the proper app domain.
        //**************************************************************************
        public static int Run(TlbImpOptions options)
        {
            s_Options = options;

            UCOMITypeLib TypeLib        = null;
            String       strPIAName     = null;
            String       strPIACodeBase = null;

            //----------------------------------------------------------------------
            // Load the typelib.
            try
            {
                LoadTypeLibEx(s_Options.m_strTypeLibName, REGKIND.REGKIND_NONE, out TypeLib);
            }
            catch (COMException e)
            {
                if (!s_Options.m_bSearchPathSucceeded)
                {
                    // We failed to search for the typelib and we failed to load it.
                    // This means that the input typelib is not available.
                    WriteErrorMsg(Resource.FormatString("Err_InputFileNotFound", s_Options.m_strTypeLibName));
                }
                else
                {
                    if (e.ErrorCode == unchecked ((int)0x80029C4A))
                    {
                        WriteErrorMsg(Resource.FormatString("Err_InputFileNotValidTypeLib", s_Options.m_strTypeLibName));
                    }
                    else
                    {
                        WriteErrorMsg(Resource.FormatString("Err_TypeLibLoad", e));
                    }
                }
                return(ErrorReturnCode);
            }
            catch (Exception e)
            {
                WriteErrorMsg(Resource.FormatString("Err_TypeLibLoad", e));
            }

            //----------------------------------------------------------------------
            // Check to see if there already exists a primary interop assembly for
            // this typelib.

            if (TlbImpCode.GetPrimaryInteropAssembly(TypeLib, out strPIAName, out strPIACodeBase))
            {
                WriteWarningMsg(Resource.FormatString("Wrn_PIARegisteredForTlb", strPIAName, s_Options.m_strTypeLibName));
            }

            //----------------------------------------------------------------------
            // Retrieve the name of output assembly if it was not explicitly set.

            if (s_Options.m_strAssemblyName == null)
            {
                s_Options.m_strAssemblyName = Marshal.GetTypeLibName(TypeLib) + ".dll";
            }

            //----------------------------------------------------------------------
            // If no extension is provided, append a .dll to the assembly name.

            if ("".Equals(Path.GetExtension(s_Options.m_strAssemblyName)))
            {
                s_Options.m_strAssemblyName = s_Options.m_strAssemblyName + ".dll";
            }

            //----------------------------------------------------------------------
            // Do some verification on the output assembly.

            String strFileNameNoPath = Path.GetFileName(s_Options.m_strAssemblyName);
            String strExtension      = Path.GetExtension(s_Options.m_strAssemblyName);

            // Validate that the extension is valid.
            bool bExtensionValid = ".dll".Equals(strExtension.ToLower(CultureInfo.InvariantCulture));

            // If the extension is not valid then tell the user and quit.
            if (!bExtensionValid)
            {
                WriteErrorMsg(Resource.FormatString("Err_InvalidExtension"));
                return(ErrorReturnCode);
            }

            // Make sure the output file will not overwrite the input file.
            String strInputFilePath = (new FileInfo(s_Options.m_strTypeLibName)).FullName.ToLower(CultureInfo.InvariantCulture);
            String strOutputFilePath;

            try
            {
                strOutputFilePath = (new FileInfo(s_Options.m_strAssemblyName)).FullName.ToLower(CultureInfo.InvariantCulture);
            }
            catch (System.IO.PathTooLongException)
            {
                WriteErrorMsg(Resource.FormatString("Err_OutputFileNameTooLong", s_Options.m_strAssemblyName));
                return(ErrorReturnCode);
            }
            if (strInputFilePath.Equals(strOutputFilePath))
            {
                WriteErrorMsg(Resource.FormatString("Err_OutputWouldOverwriteInput"));
                return(ErrorReturnCode);
            }

            // Check to see if the output directory is valid.
            if (!Directory.Exists(Path.GetDirectoryName(strOutputFilePath)))
            {
                WriteErrorMsg(Resource.FormatString("Err_InvalidOutputDirectory"));
                return(ErrorReturnCode);
            }

            //----------------------------------------------------------------------
            // Attempt the import.

            try
            {
                // Import the typelib to an assembly.
                AssemblyBuilder AsmBldr = DoImport(TypeLib, s_Options.m_strAssemblyName, s_Options.m_strAssemblyNamespace, s_Options.m_AssemblyVersion, s_Options.m_aPublicKey, s_Options.m_sKeyPair, s_Options.m_flags);
                if (AsmBldr == null)
                {
                    return(ErrorReturnCode);
                }
            }
            catch (ReflectionTypeLoadException e)
            {
                int         i;
                Exception[] exceptions;
                WriteErrorMsg(Resource.FormatString("Err_TypeLoadExceptions"));
                exceptions = e.LoaderExceptions;
                for (i = 0; i < exceptions.Length; i++)
                {
                    try
                    {
                        Console.Error.WriteLine(Resource.FormatString("Msg_DisplayException", i, exceptions[i]));
                    }
                    catch (Exception ex)
                    {
                        Console.Error.WriteLine(Resource.FormatString("Msg_DisplayNestedException", i, ex));
                    }
                }
                return(ErrorReturnCode);
            }
            catch (Exception e)
            {
                WriteErrorMsg(null, e);
                return(ErrorReturnCode);
            }

            //----------------------------------------------------------------------
            // Display the success message unless silent mode is enabled.

            if (!s_Options.m_bSilentMode)
            {
                Console.WriteLine(Resource.FormatString("Msg_TypeLibImported", s_Options.m_strAssemblyName));
            }

            return(SuccessReturnCode);
        }