Holds AssemblyScanner.GetScannableAssemblies results. Contains list of errors and list of scannable assemblies.
        /// <summary>
        /// Traverses the specified base directory including all sub-directories, generating a list of assemblies that can be
        /// scanned for handlers, a list of skipped files, and a list of errors that occurred while scanning.
        /// Scanned files may be skipped when they're either not a .NET assembly, or if a reflection-only load of the .NET
        /// assembly reveals that it does not reference NServiceBus.
        /// </summary>
        public AssemblyScannerResults GetScannableAssemblies()
        {
            var results = new AssemblyScannerResults();
            var processed = new Dictionary<string, bool>(StringComparer.OrdinalIgnoreCase);

            if (assemblyToScan != null)
            {
                var assemblyPath = AssemblyPath(assemblyToScan);
                ScanAssembly(assemblyPath, results, processed);
                return results;
            }

            foreach (var assemblyFile in ScanDirectoryForAssemblyFiles(baseDirectoryToScan, ScanNestedDirectories))
            {
                ScanAssembly(assemblyFile.FullName, results, processed);
            }

            // This extra step is to ensure unobtrusive message types are included in the Types list.
            var list = GetHandlerMessageTypes(results.Types);
            results.Types.AddRange(list);

            results.RemoveDuplicates();

            return results;
        }
Beispiel #2
0
        /// <summary>
        /// Traverses the specified base directory including all sub-directories, generating a list of assemblies that can be
        /// scanned for handlers, a list of skipped files, and a list of errors that occurred while scanning.
        /// Scanned files may be skipped when they're either not a .NET assembly, or if a reflection-only load of the .NET
        /// assembly reveals that it does not reference NServiceBus.
        /// </summary>
        public AssemblyScannerResults GetScannableAssemblies()
        {
            var results   = new AssemblyScannerResults();
            var processed = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            if (assemblyToScan != null)
            {
                var assemblyPath = AssemblyPath(assemblyToScan);
                ScanAssembly(assemblyPath, results, processed);
                return(results);
            }

            foreach (var assemblyFile in ScanDirectoryForAssemblyFiles(baseDirectoryToScan, ScanNestedDirectories))
            {
                ScanAssembly(assemblyFile.FullName, results, processed);
            }

            // This extra step is to ensure unobtrusive message types are included in the Types list.
            var list = GetHandlerMessageTypes(results.Types);

            results.Types.AddRange(list);

            results.RemoveDuplicates();

            return(results);
        }
Beispiel #3
0
        /// <summary>
        /// Traverses the specified base directory including all sub-directories, generating a list of assemblies that can be
        /// scanned for handlers, a list of skipped files, and a list of errors that occurred while scanning.
        /// Scanned files may be skipped when they're either not a .NET assembly, or if a reflection-only load of the .NET
        /// assembly reveals that it does not reference NServiceBus.
        /// </summary>
        public AssemblyScannerResults GetScannableAssemblies()
        {
            var results = new AssemblyScannerResults();

            if (assemblyToScan != null)
            {
                var assemblyPath = AssemblyPath(assemblyToScan);
                ScanAssembly(assemblyPath, results);
                return(results);
            }

            if (IncludeAppDomainAssemblies)
            {
                var matchingAssembliesFromAppDomain = MatchingAssembliesFromAppDomain();

                foreach (var assembly in matchingAssembliesFromAppDomain)
                {
                    ScanAssembly(AssemblyPath(assembly), results);
                }
            }

            foreach (var assemblyFile in ScanDirectoryForAssemblyFiles())
            {
                ScanAssembly(assemblyFile.FullName, results);
            }

            // This extra step is to ensure unobtrusive message types are included in the Types list.
            var list = GetHandlerMessageTypes(results.Types).ToList();

            results.Types.AddRange(list);

            results.RemoveDuplicates();

            return(results);
        }
Beispiel #4
0
        bool TryLoadScannableAssembly(string assemblyPath, AssemblyScannerResults results, Dictionary <string, bool> processed, out Assembly assembly)
        {
            assembly = null;
            if (!IsIncluded(Path.GetFileNameWithoutExtension(assemblyPath)))
            {
                var skippedFile = new SkippedFile(assemblyPath, "File was explicitly excluded from scanning.");
                results.SkippedFiles.Add(skippedFile);
                return(false);
            }

            var compilationMode = Image.GetCompilationMode(assemblyPath);

            if (compilationMode == Image.CompilationMode.NativeOrInvalid)
            {
                var skippedFile = new SkippedFile(assemblyPath, "File is not a .NET assembly.");
                results.SkippedFiles.Add(skippedFile);
                return(false);
            }

            if (!Environment.Is64BitProcess && compilationMode == Image.CompilationMode.CLRx64)
            {
                var skippedFile = new SkippedFile(assemblyPath, "x64 .NET assembly can't be loaded by a 32Bit process.");
                results.SkippedFiles.Add(skippedFile);
                return(false);
            }

            try
            {
                if (!ReferencesNServiceBus(assemblyPath, processed, CoreAssemblyName))
                {
                    var skippedFile = new SkippedFile(assemblyPath, "Assembly does not reference at least one of the must referenced assemblies.");
                    results.SkippedFiles.Add(skippedFile);
                    return(false);
                }

                var loadedAssembly = Assembly.LoadFrom(assemblyPath);

                if (results.Assemblies.Contains(loadedAssembly))
                {
                    return(false);
                }

                assembly = loadedAssembly;
                return(true);
            }
            catch (Exception ex) when(ex is BadImageFormatException || ex is FileLoadException)
            {
                results.ErrorsThrownDuringScanning = true;

                if (ThrowExceptions)
                {
                    var errorMessage = $"Could not load '{assemblyPath}'. Consider excluding that assembly from the scanning.";
                    throw new Exception(errorMessage, ex);
                }
                return(false);
            }
        }
Beispiel #5
0
        public static AssemblyScannerResults GetScannableAssemblies()
        {
            var baseDir       = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            var assemblyFiles = baseDir.GetFiles("*.dll", SearchOption.AllDirectories)
                                .Union(baseDir.GetFiles("*.exe", SearchOption.AllDirectories));
            var results = new AssemblyScannerResults();

            foreach (var assemblyFile in assemblyFiles)
            {
                Assembly assembly;

                try
                {
                    assembly = Assembly.LoadFrom(assemblyFile.FullName);
                }
                catch (BadImageFormatException bif)
                {
                    var error = new ErrorWhileScanningAssemblies(bif, "Could not load " + assemblyFile.FullName +
                                                                 ". Consider using 'Configure.With(AllAssemblies.Except(\"" + assemblyFile.Name + "\"))' to tell NServiceBus not to load this file.");
                    results.Errors.Add(error);
                    continue;
                }

                try
                {
                    //will throw if assembly cannot be loaded
                    assembly.GetTypes();
                }
                catch (ReflectionTypeLoadException e)
                {
                    var sb = new StringBuilder();
                    sb.Append(string.Format("Could not scan assembly: {0}. Exception message {1}.", assemblyFile.FullName, e));
                    if (e.LoaderExceptions.Any())
                    {
                        sb.Append(Environment.NewLine + "Scanned type errors: ");
                        foreach (var ex in e.LoaderExceptions)
                        {
                            sb.Append(Environment.NewLine + ex.Message);
                        }
                    }
                    var error = new ErrorWhileScanningAssemblies(e, sb.ToString());
                    results.Errors.Add(error);
                    continue;
                }

                results.Assemblies.Add(assembly);
            }

            return(results);
        }
Beispiel #6
0
        bool TryLoadScannableAssembly(string assemblyPath, AssemblyScannerResults results, out Assembly assembly)
        {
            assembly = null;

            if (IsExcluded(Path.GetFileNameWithoutExtension(assemblyPath)))
            {
                var skippedFile = new SkippedFile(assemblyPath, "File was explicitly excluded from scanning.");
                results.SkippedFiles.Add(skippedFile);

                return(false);
            }

            assemblyValidator.ValidateAssemblyFile(assemblyPath, out var shouldLoad, out var reason);

            if (!shouldLoad)
            {
                var skippedFile = new SkippedFile(assemblyPath, reason);
                results.SkippedFiles.Add(skippedFile);

                return(false);
            }

            try
            {
#if NETCOREAPP
                var context = AssemblyLoadContext.GetLoadContext(Assembly.GetExecutingAssembly());
                assembly = context.LoadFromAssemblyPath(assemblyPath);
#else
                assembly = Assembly.LoadFrom(assemblyPath);
#endif
                return(true);
            }
            catch (Exception ex) when(ex is BadImageFormatException || ex is FileLoadException)
            {
                results.ErrorsThrownDuringScanning = true;

                if (ThrowExceptions)
                {
                    var errorMessage = $"Could not load '{assemblyPath}'. Consider excluding that assembly from the scanning.";
                    throw new Exception(errorMessage, ex);
                }

                var skippedFile = new SkippedFile(assemblyPath, ex.Message);

                results.SkippedFiles.Add(skippedFile);

                return(false);
            }
        }
        bool TryLoadScannableAssembly(string assemblyPath, AssemblyScannerResults results, out Assembly assembly)
        {
            assembly = null;

            if (IsExcluded(Path.GetFileNameWithoutExtension(assemblyPath)))
            {
                var skippedFile = new SkippedFile(assemblyPath, "File was explicitly excluded from scanning.");
                results.SkippedFiles.Add(skippedFile);

                return(false);
            }

            assemblyValidator.ValidateAssemblyFile(assemblyPath, out var shouldLoad, out var reason);

            if (!shouldLoad)
            {
                var skippedFile = new SkippedFile(assemblyPath, reason);
                results.SkippedFiles.Add(skippedFile);

                return(false);
            }

            try
            {
                Console.WriteLine($"Loading {assemblyPath}");
                assembly = Assembly.LoadFrom(assemblyPath);

                Console.WriteLine($"{assembly.FullName} loaded from location {assembly.Location}");

                return(true);
            }
            catch (Exception ex) when(ex is BadImageFormatException || ex is FileLoadException)
            {
                results.ErrorsThrownDuringScanning = true;

                if (ThrowExceptions)
                {
                    var errorMessage = $"Could not load '{assemblyPath}'. Consider excluding that assembly from the scanning.";
                    throw new Exception(errorMessage, ex);
                }

                var skippedFile = new SkippedFile(assemblyPath, ex.Message);

                results.SkippedFiles.Add(skippedFile);

                return(false);
            }
        }
Beispiel #8
0
        public static AssemblyScannerResults GetScannableAssemblies()
        {
            var baseDir = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
            var assemblyFiles = baseDir.GetFiles("*.dll", SearchOption.AllDirectories)
                .Union(baseDir.GetFiles("*.exe", SearchOption.AllDirectories));
            var results = new AssemblyScannerResults();

            foreach (var assemblyFile in assemblyFiles)
            {
                Assembly assembly;

                try
                {
                    assembly = Assembly.LoadFrom(assemblyFile.FullName);
                }
                catch (BadImageFormatException bif)
                {
                    var error = new ErrorWhileScanningAssemblies(bif, "Could not load " + assemblyFile.FullName +
                        ". Consider using 'Configure.With(AllAssemblies.Except(\"" + assemblyFile.Name + "\"))' to tell NServiceBus not to load this file.");
                    results.Errors.Add(error);
                    continue;
                }

                try
                {
                    //will throw if assembly cannot be loaded
                    assembly.GetTypes();
                }
                catch (ReflectionTypeLoadException e)
                {
                    var sb = new StringBuilder();
                    sb.Append(string.Format("Could not scan assembly: {0}. Exception message {1}.", assemblyFile.FullName, e));
                    if (e.LoaderExceptions.Any())
                    {
                        sb.Append(Environment.NewLine + "Scanned type errors: ");
                        foreach (var ex in e.LoaderExceptions)
                            sb.Append(Environment.NewLine + ex.Message);
                    }
                    var error = new ErrorWhileScanningAssemblies(e, sb.ToString());
                    results.Errors.Add(error);
                    continue;
                }

                results.Assemblies.Add(assembly);
            }

            return results;
        }
Beispiel #9
0
        /// <summary>
        /// Traverses the specified base directory including all sub-directories, generating a list of assemblies that can be
        /// scanned for handlers, a list of skipped files, and a list of errors that occurred while scanning.
        /// Scanned files may be skipped when they're either not a .NET assembly, or if a reflection-only load of the .NET
        /// assembly reveals that it does not reference NServiceBus.
        /// </summary>
        public AssemblyScannerResults GetScannableAssemblies()
        {
            var results = new AssemblyScannerResults();

            if (assemblyToScan != null)
            {
                ScanAssembly(assemblyToScan, results);
                return(results);
            }

            if (ScanAppDomainAssemblies)
            {
                var appDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies();
                foreach (var assembly in appDomainAssemblies)
                {
                    if (!assembly.IsDynamic)
                    {
                        ScanAssembly(assembly, results);
                    }
                }
            }

            var processed = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            foreach (var assemblyFile in ScanDirectoryForAssemblyFiles(baseDirectoryToScan, ScanNestedDirectories))
            {
                Assembly assembly;
                if (TryLoadScannableAssembly(assemblyFile.FullName, results, processed, out assembly))
                {
                    ScanAssembly(assembly, results);
                }
            }

            // This extra step is to ensure unobtrusive message types are included in the Types list.
            var list = GetHandlerMessageTypes(results.Types);

            results.Types.AddRange(list);

            results.RemoveDuplicates();

            return(results);
        }
Beispiel #10
0
        /// <summary>
        ///     Traverses the specified base directory including all sub-directories, generating a list of assemblies that can be
        ///     scanned for handlers, a list of skipped files, and a list of errors that occurred while scanning.
        ///     Scanned files may be skipped when they're either not a .NET assembly, or if a reflection-only load of the .NET
        ///     assembly reveals that it does not reference NServiceBus.
        /// </summary>
        public AssemblyScannerResults GetScannableAssemblies()
        {
            var results = new AssemblyScannerResults();

            if (IncludeAppDomainAssemblies)
            {
                var matchingAssembliesFromAppDomain = AppDomain.CurrentDomain
                                                      .GetAssemblies()
                                                      .Where(assembly => IsIncluded(assembly.GetName().Name));

                results.Assemblies.AddRange(matchingAssembliesFromAppDomain);
            }

            foreach (var assemblyFile in ScanDirectoryForAssemblyFiles())
            {
                ScanAssembly(assemblyFile.FullName, results);
            }

            return(results);
        }
Beispiel #11
0
        /// <summary>
        ///     Traverses the specified base directory including all sub-directories, generating a list of assemblies that can be
        ///     scanned for handlers, a list of skipped files, and a list of errors that occurred while scanning.
        ///     Scanned files may be skipped when they're either not a .NET assembly, or if a reflection-only load of the .NET
        ///     assembly reveals that it does not reference NServiceBus.
        /// </summary>
        public AssemblyScannerResults GetScannableAssemblies()
        {
            var results = new AssemblyScannerResults();

            if (IncludeAppDomainAssemblies)
            {
                var matchingAssembliesFromAppDomain = AppDomain.CurrentDomain
                                                               .GetAssemblies()
                                                               .Where(assembly => IsIncluded(assembly.GetName().Name));

                results.Assemblies.AddRange(matchingAssembliesFromAppDomain);
            }

            foreach (var assemblyFile in ScanDirectoryForAssemblyFiles())
            {
                ScanAssembly(assemblyFile.FullName, results);
            }

            return results;
        }
Beispiel #12
0
        void AddTypesToResult(Assembly assembly, AssemblyScannerResults results)
        {
            try
            {
                //will throw if assembly cannot be loaded
                results.Types.AddRange(assembly.GetTypes().Where(IsAllowedType));
            }
            catch (ReflectionTypeLoadException e)
            {
                results.ErrorsThrownDuringScanning = true;

                var errorMessage = FormatReflectionTypeLoadException(assembly.FullName, e);
                if (ThrowExceptions)
                {
                    throw new Exception(errorMessage);
                }

                LogManager.GetLogger <AssemblyScanner>().Warn(errorMessage);
                results.Types.AddRange(e.Types.Where(IsAllowedType));
            }
            results.Assemblies.Add(assembly);
        }
Beispiel #13
0
        void ScanAssembly(Assembly assembly, AssemblyScannerResults results)
        {
            if (assembly == null)
            {
                return;
            }

            if (IsRuntimeAssembly(assembly.GetName()))
            {
                return;
            }
            if (!IsIncluded(assembly.GetName().Name))
            {
                return;
            }

            try
            {
                //will throw if assembly cannot be loaded
                results.Types.AddRange(assembly.GetTypes().Where(IsAllowedType));
            }
            catch (ReflectionTypeLoadException e)
            {
                results.ErrorsThrownDuringScanning = true;

                var errorMessage = FormatReflectionTypeLoadException(assembly.FullName, e);
                if (ThrowExceptions)
                {
                    throw new Exception(errorMessage);
                }

                LogManager.GetLogger <AssemblyScanner>().Warn(errorMessage);
                results.Types.AddRange(e.Types.Where(IsAllowedType));
            }

            results.Assemblies.Add(assembly);
        }
        void ScanAssembly(string assemblyPath, AssemblyScannerResults results, Dictionary<string, bool> processed)
        {
            Assembly assembly;

            if (!IsIncluded(Path.GetFileNameWithoutExtension(assemblyPath)))
            {
                var skippedFile = new SkippedFile(assemblyPath, "File was explicitly excluded from scanning.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            var compilationMode = Image.GetCompilationMode(assemblyPath);
            if (compilationMode == Image.CompilationMode.NativeOrInvalid)
            {
                var skippedFile = new SkippedFile(assemblyPath, "File is not a .NET assembly.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            if (!Environment.Is64BitProcess && compilationMode == Image.CompilationMode.CLRx64)
            {
                var skippedFile = new SkippedFile(assemblyPath, "x64 .NET assembly can't be loaded by a 32Bit process.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            try
            {
                if (!ReferencesNServiceBus(assemblyPath, processed, CoreAssemblyName))
                {
                    var skippedFile = new SkippedFile(assemblyPath, "Assembly does not reference at least one of the must referenced assemblies.");
                    results.SkippedFiles.Add(skippedFile);
                    return;
                }

                assembly = Assembly.LoadFrom(assemblyPath);

                if (results.Assemblies.Contains(assembly))
                {
                    return;
                }
            }
            catch (Exception ex) when (ex is BadImageFormatException || ex is FileLoadException)
            {
                assembly = null;
                results.ErrorsThrownDuringScanning = true;

                if (ThrowExceptions)
                {
                    var errorMessage = $"Could not load '{assemblyPath}'. Consider excluding that assembly from the scanning.";
                    throw new Exception(errorMessage, ex);
                }
            }

            if (assembly == null)
            {
                return;
            }

            try
            {
                //will throw if assembly cannot be loaded
                results.Types.AddRange(assembly.GetTypes().Where(IsAllowedType));
            }
            catch (ReflectionTypeLoadException e)
            {
                results.ErrorsThrownDuringScanning = true;

                var errorMessage = FormatReflectionTypeLoadException(assemblyPath, e);
                if (ThrowExceptions)
                {
                    throw new Exception(errorMessage);
                }

                LogManager.GetLogger<AssemblyScanner>().Warn(errorMessage);
                results.Types.AddRange(e.Types.Where(IsAllowedType));
            }

            results.Assemblies.Add(assembly);
        }
Beispiel #15
0
        void ScanAssembly(string assemblyPath, AssemblyScannerResults results, Dictionary <string, bool> processed)
        {
            Assembly assembly;

            if (!IsIncluded(Path.GetFileNameWithoutExtension(assemblyPath)))
            {
                var skippedFile = new SkippedFile(assemblyPath, "File was explicitly excluded from scanning.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            var compilationMode = Image.GetCompilationMode(assemblyPath);

            if (compilationMode == Image.CompilationMode.NativeOrInvalid)
            {
                var skippedFile = new SkippedFile(assemblyPath, "File is not a .NET assembly.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            if (!Environment.Is64BitProcess && compilationMode == Image.CompilationMode.CLRx64)
            {
                var skippedFile = new SkippedFile(assemblyPath, "x64 .NET assembly can't be loaded by a 32Bit process.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            try
            {
                if (!ReferencesNServiceBus(assemblyPath, processed, CoreAssemblyName))
                {
                    var skippedFile = new SkippedFile(assemblyPath, "Assembly does not reference at least one of the must referenced assemblies.");
                    results.SkippedFiles.Add(skippedFile);
                    return;
                }

                assembly = Assembly.LoadFrom(assemblyPath);

                if (results.Assemblies.Contains(assembly))
                {
                    return;
                }
            }
            catch (Exception ex) when(ex is BadImageFormatException || ex is FileLoadException)
            {
                assembly = null;
                results.ErrorsThrownDuringScanning = true;

                if (ThrowExceptions)
                {
                    var errorMessage = $"Could not load '{assemblyPath}'. Consider excluding that assembly from the scanning.";
                    throw new Exception(errorMessage, ex);
                }
            }

            if (assembly == null)
            {
                return;
            }

            try
            {
                //will throw if assembly cannot be loaded
                results.Types.AddRange(assembly.GetTypes().Where(IsAllowedType));
            }
            catch (ReflectionTypeLoadException e)
            {
                results.ErrorsThrownDuringScanning = true;

                var errorMessage = FormatReflectionTypeLoadException(assemblyPath, e);
                if (ThrowExceptions)
                {
                    throw new Exception(errorMessage);
                }

                LogManager.GetLogger <AssemblyScanner>().Warn(errorMessage);
                results.Types.AddRange(e.Types.Where(IsAllowedType));
            }

            results.Assemblies.Add(assembly);
        }
Beispiel #16
0
        void ScanAssembly(string assemblyPath, AssemblyScannerResults results)
        {
            Assembly assembly;

            if (!IsIncluded(Path.GetFileNameWithoutExtension(assemblyPath)))
            {
                var skippedFile = new SkippedFile(assemblyPath, "File was explicitly excluded from scanning.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            var compilationMode = Image.GetCompilationMode(assemblyPath);

            if (compilationMode == Image.CompilationMode.NativeOrInvalid)
            {
                var skippedFile = new SkippedFile(assemblyPath, "File is not a .NET assembly.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            if (!Environment.Is64BitProcess && compilationMode == Image.CompilationMode.CLRx64)
            {
                var skippedFile = new SkippedFile(assemblyPath, "x64 .NET assembly can't be loaded by a 32Bit process.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            try
            {
                //TODO: re-enable when we make message scanning lazy #1617
                //if (!AssemblyPassesReferencesTest(assemblyPath))
                //{
                //    var skippedFile = new SkippedFile(assemblyPath, "Assembly does not reference at least one of the must referenced assemblies.");
                //    results.SkippedFiles.Add(skippedFile);
                //    return;
                //}
                if (IsRuntimeAssembly(assemblyPath))
                {
                    var skippedFile = new SkippedFile(assemblyPath, "Assembly .net runtime assembly.");
                    results.SkippedFiles.Add(skippedFile);
                    return;
                }

                assembly = Assembly.LoadFrom(assemblyPath);
                if (results.Assemblies.Contains(assembly))
                {
                    return;
                }
            }
            catch (BadImageFormatException)
            {
                var errorMessage = String.Format("Could not load '{0}'. Consider excluding that assembly from the scanning.", assemblyPath);
                results.Errors.Add(errorMessage);
                return;
            }

            try
            {
                //will throw if assembly cannot be loaded
                assembly.GetTypes();
            }
            catch (ReflectionTypeLoadException e)
            {
                var errorMessage = FormatReflectionTypeLoadException(assemblyPath, e);
                results.Errors.Add(errorMessage);
                return;
            }

            results.Assemblies.Add(assembly);
        }
Beispiel #17
0
        void ScanAssembly(string assemblyPath, AssemblyScannerResults results)
        {
            Assembly assembly;

            if (!IsIncluded(Path.GetFileNameWithoutExtension(assemblyPath)))
            {
                var skippedFile = new SkippedFile(assemblyPath, "File was explicitly excluded from scanning.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            var compilationMode = Image.GetCompilationMode(assemblyPath);
            if (compilationMode == Image.CompilationMode.NativeOrInvalid)
            {
                var skippedFile = new SkippedFile(assemblyPath, "File is not a .NET assembly.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            if (!Environment.Is64BitProcess && compilationMode == Image.CompilationMode.CLRx64)
            {
                var skippedFile = new SkippedFile(assemblyPath, "x64 .NET assembly can't be loaded by a 32Bit process.");
                results.SkippedFiles.Add(skippedFile);
                return;
            }

            try
            {
                //TODO: re-enable when we make message scanning lazy #1617
                //if (!AssemblyPassesReferencesTest(assemblyPath))
                //{
                //    var skippedFile = new SkippedFile(assemblyPath, "Assembly does not reference at least one of the must referenced assemblies.");
                //    results.SkippedFiles.Add(skippedFile);
                //    return;
                //}
                if (IsRuntimeAssembly(assemblyPath))
                {
                    var skippedFile = new SkippedFile(assemblyPath, "Assembly .net runtime assembly.");
                    results.SkippedFiles.Add(skippedFile);
                    return;
                }

                assembly = Assembly.LoadFrom(assemblyPath);

                if (results.Assemblies.Contains(assembly))
                {
                    return;
                }
            }
            catch (BadImageFormatException ex)
            {
                assembly = null;
                results.ErrorsThrownDuringScanning = true;

                if (ThrowExceptions)
                {
                    var errorMessage = String.Format("Could not load '{0}'. Consider excluding that assembly from the scanning.", assemblyPath);
                    throw new Exception(errorMessage, ex);
                }
            }

            if (assembly == null)
            {
                return;
            }

            try
            {
                //will throw if assembly cannot be loaded
                assembly.GetTypes();
            }
            catch (ReflectionTypeLoadException e)
            {
                results.ErrorsThrownDuringScanning = true;

                if (ThrowExceptions)
                {
                    var errorMessage = FormatReflectionTypeLoadException(assemblyPath, e);
                    throw new Exception(errorMessage);
                }

                return;
            }

            results.Assemblies.Add(assembly);
        }
Beispiel #18
0
        /// <summary>
        /// Traverses the specified base directory including all sub-directories, generating a list of assemblies that should be
        /// scanned for handlers, a list of skipped files, and a list of errors that occurred while scanning.
        /// </summary>
        public AssemblyScannerResults GetScannableAssemblies()
        {
            var results   = new AssemblyScannerResults();
            var processed = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            if (assemblyToScan != null)
            {
                if (ScanAssembly(assemblyToScan, processed))
                {
                    AddTypesToResult(assemblyToScan, results);
                }

                return(results);
            }

            if (ScanAppDomainAssemblies)
            {
                var appDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies();

                foreach (var assembly in appDomainAssemblies)
                {
                    if (ScanAssembly(assembly, processed))
                    {
                        AddTypesToResult(assembly, results);
                    }
                }
            }

            var assemblies = new List <Assembly>();

            foreach (var assemblyFile in ScanDirectoryForAssemblyFiles(baseDirectoryToScan, ScanNestedDirectories))
            {
                if (TryLoadScannableAssembly(assemblyFile.FullName, results, out var assembly))
                {
                    assemblies.Add(assembly);
                }
            }

            var platformAssembliesString = (string)AppDomain.CurrentDomain.GetData("TRUSTED_PLATFORM_ASSEMBLIES");

            if (platformAssembliesString != null)
            {
                var platformAssemblies = platformAssembliesString.Split(Path.PathSeparator);

                foreach (var platformAssembly in platformAssemblies)
                {
                    if (TryLoadScannableAssembly(platformAssembly, results, out var assembly))
                    {
                        assemblies.Add(assembly);
                    }
                }
            }

            foreach (var assembly in assemblies)
            {
                if (ScanAssembly(assembly, processed))
                {
                    AddTypesToResult(assembly, results);
                }
            }

            results.RemoveDuplicates();

            return(results);
        }
Beispiel #19
0
        /// <summary>
        /// Traverses the specified base directory including all sub-directories, generating a list of assemblies that should be
        /// scanned for handlers, a list of skipped files, and a list of errors that occurred while scanning.
        /// </summary>
        public AssemblyScannerResults GetScannableAssemblies()
        {
            var results   = new AssemblyScannerResults();
            var processed = new Dictionary <string, bool>(StringComparer.OrdinalIgnoreCase);

            if (assemblyToScan != null)
            {
                if (ScanAssembly(assemblyToScan, processed))
                {
                    AddTypesToResult(assemblyToScan, results);
                }

                return(results);
            }

            if (ScanAppDomainAssemblies)
            {
                var appDomainAssemblies = AppDomain.CurrentDomain.GetAssemblies();

                foreach (var assembly in appDomainAssemblies)
                {
                    if (ScanAssembly(assembly, processed))
                    {
                        AddTypesToResult(assembly, results);
                    }
                }
            }

            var assemblies = new List <Assembly>();

            ScanAssembliesInDirectory(baseDirectoryToScan, assemblies, results);

            if (!string.IsNullOrWhiteSpace(AdditionalAssemblyScanningPath))
            {
                ScanAssembliesInDirectory(AdditionalAssemblyScanningPath, assemblies, results);
            }

            var platformAssembliesString = (string)AppDomain.CurrentDomain.GetData("TRUSTED_PLATFORM_ASSEMBLIES");

            if (!string.IsNullOrEmpty(platformAssembliesString))
            {
                var platformAssemblies = platformAssembliesString.Split(Path.PathSeparator);

                foreach (var platformAssembly in platformAssemblies)
                {
                    if (TryLoadScannableAssembly(platformAssembly, results, out var assembly))
                    {
                        assemblies.Add(assembly);
                    }
                }
            }

            foreach (var assembly in assemblies)
            {
                if (ScanAssembly(assembly, processed))
                {
                    AddTypesToResult(assembly, results);
                }
            }

            results.RemoveDuplicates();

            return(results);
        }
Beispiel #20
0
        static void Main(string[] args)
        {
            Parser.Args commandLineArguments = Parser.ParseArgs(args);
            var arguments = new HostArguments(commandLineArguments);

            if (arguments.Help != null)
            {
                DisplayHelpContent();

                return;
            }
            assemblyScannerResults = AssemblyScanner.GetScannableAssemblies();
            var endpointConfigurationType = GetEndpointConfigurationType(arguments);

            if (endpointConfigurationType == null)
            {
                if (arguments.InstallInfrastructure == null)
                    throw new InvalidOperationException("No endpoint configuration found in scanned assemblies. " +
                        "This usually happens when NServiceBus fails to load your assembly containing IConfigureThisEndpoint." +
                        " Try specifying the type explicitly in the NServiceBus.Host.exe.config using the appsetting key: EndpointConfigurationType, " +
                        "Scanned path: " + AppDomain.CurrentDomain.BaseDirectory);

                Console.WriteLine("Running infrastructure installers and exiting (ignoring other command line parameters if exist).");
                InstallInfrastructure();
                return;
            }

            AssertThatEndpointConfigurationTypeHasDefaultConstructor(endpointConfigurationType);
            string endpointConfigurationFile = GetEndpointConfigurationFile(endpointConfigurationType);

            var endpointName = GetEndpointName(endpointConfigurationType, arguments);
            var endpointVersion = GetEndpointVersion(endpointConfigurationType);

            var serviceName = endpointName;

            if (arguments.ServiceName != null)
                serviceName = arguments.ServiceName.Value;

            var displayName = serviceName + "-" + endpointVersion;

            if (arguments.SideBySide != null)
            {
                serviceName += "-" + endpointVersion;

                displayName += " (SideBySide)";
            }

            //Add the endpoint name so that the new appdomain can get it
            if (arguments.EndpointName == null)
                args = args.Concat(new[] { "/endpointName:" + endpointName }).ToArray();

            //Add the ScannedAssemblies name so that the new appdomain can get it
            if (arguments.ScannedAssemblies == null)
                args = args.Concat(new[] { "/scannedassemblies:" + string.Join(";", assemblyScannerResults.Assemblies.Select(s => s.ToString()).ToArray()) }).ToArray();

            //Add the endpointConfigurationType name so that the new appdomain can get it
            if (arguments.EndpointConfigurationType == null)
                args = args.Concat(new[] { "/endpointConfigurationType:" + endpointConfigurationType.AssemblyQualifiedName }).ToArray();

            AppDomain.CurrentDomain.SetupInformation.AppDomainInitializerArguments = args;
            if ((commandLineArguments.Install) || (arguments.InstallInfrastructure != null))
                WindowsInstaller.Install(args, endpointConfigurationFile);

            IRunConfiguration cfg = RunnerConfigurator.New(x =>
                                                               {
                                                                   x.ConfigureServiceInIsolation<WindowsHost>(endpointConfigurationType.AssemblyQualifiedName, c =>
                                                                                                                                                                   {
                                                                                                                                                                       c.ConfigurationFile(endpointConfigurationFile);
                                                                                                                                                                       c.CommandLineArguments(args, () => SetHostServiceLocatorArgs);
                                                                                                                                                                       c.WhenStarted(service => service.Start());
                                                                                                                                                                       c.WhenStopped(service => service.Stop());
                                                                                                                                                                       c.CreateServiceLocator(() => new HostServiceLocator());
                                                                                                                                                                   });

                                                                   if (arguments.Username != null && arguments.Password != null)
                                                                   {
                                                                       x.RunAs(arguments.Username.Value, arguments.Password.Value);
                                                                   }
                                                                   else
                                                                   {
                                                                       x.RunAsLocalSystem();
                                                                   }

                                                                   if (arguments.StartManually != null)
                                                                   {
                                                                       x.DoNotStartAutomatically();
                                                                   }

                                                                   x.SetDisplayName(arguments.DisplayName != null ? arguments.DisplayName.Value : displayName);
                                                                   x.SetServiceName(serviceName);
                                                                   x.SetDescription(arguments.Description != null ? arguments.Description.Value : "NServiceBus Message Endpoint Host Service for " + displayName);

                                                                   var serviceCommandLine = commandLineArguments.CustomArguments.AsCommandLine();
                                                                   serviceCommandLine += " /serviceName:\"" + serviceName + "\"";
                                                                   serviceCommandLine += " /endpointName:\"" + endpointName + "\"";

                                                                   x.SetServiceCommandLine(serviceCommandLine);

                                                                   if (arguments.DependsOn == null)
                                                                       x.DependencyOnMsmq();
                                                                   else
                                                                       foreach (var dependency in arguments.DependsOn.Value.Split(','))
                                                                           x.DependsOn(dependency);
                                                               });

            Runner.Host(cfg, args);
        }
Beispiel #21
0
 void ScanAssembliesInDirectory(string directoryToScan, List <Assembly> assemblies, AssemblyScannerResults results)
 {
     foreach (var assemblyFile in ScanDirectoryForAssemblyFiles(directoryToScan, ScanNestedDirectories))
     {
         if (TryLoadScannableAssembly(assemblyFile.FullName, results, out var assembly))
         {
             assemblies.Add(assembly);
         }
     }
 }