ICyclicWorker CyclicWorkerContexts(DependencyContext context)
        {
            if (typeof(IOptionsDialogWatcher).IsAssignableFrom(context.ImplementationType))
                return _container.GetInstance<CyclicBackgroundWorker>();

            return _container.GetInstance<CyclicWorker>();
        }
 public JObject Save(DependencyContext dependencyContext)
 {
     using (var memoryStream = new MemoryStream())
     {
         new DependencyContextWriter().Write(dependencyContext, memoryStream);
         using (var readStream = new MemoryStream(memoryStream.ToArray()))
         {
             using (var textReader = new StreamReader(readStream))
             {
                 using (var reader = new JsonTextReader(textReader))
                 {
                     return JObject.Load(reader);
                 }
             }
         }
     }
 }
        public void GetRuntimeAssemblyNamesExtractsCorrectAssemblyName(string path, string expected)
        {
            var context = new DependencyContext(new TargetInfo(".NETStandard,Version=v1.3", string.Empty, string.Empty, true),
                compilationOptions: CompilationOptions.Default,
                compileLibraries: new CompilationLibrary[] { },
                runtimeLibraries: new[] {
                    new RuntimeLibrary("package", "System.Banana", "1.0.0", "hash",
                        new [] {
                            new RuntimeAssetGroup(string.Empty, Path.Combine("lib", path))
                        },
                        new RuntimeAssetGroup[] { },
                        new ResourceAssembly[] { },
                        new Dependency[] { },
                        serviceable: false)
                },
                runtimeGraph: new RuntimeFallbacks[] { });

            var assets = context.GetDefaultAssemblyNames();
            assets.Should().OnlyContain(a => a.Name == expected);
        }
        private static IEnumerable <Assembly> LoadAdditionalApplicationParts(
            Assembly entryAssembly,
            DependencyContext dependencyContext,
            IReadOnlyDictionary <string, AssemblyPart> existingAssemblyParts,
            IEnumerable <IAssemblyDiscoveryRule> rules
            )
        {
            var assemblyPartsToAdd = new Dictionary <string, AssemblyPart>();
            var context            = new AssemblyDiscoveryRuleContext(entryAssembly);

            var candidateLibraries = dependencyContext
                                     .RuntimeLibraries
                                     .Where(l => !existingAssemblyParts.ContainsKey(l.Name) && rules.Any(r => r.CanInclude(l, context)));

            foreach (var assembly in candidateLibraries
                     .SelectMany(l => l.GetDefaultAssemblyNames(dependencyContext))
                     .Select(Assembly.Load))
            {
                yield return(assembly);
            }
        }
Exemple #5
0
        private List <Assembly> GetAssemblies(NacosSdkOptions options)
        {
            var assemblies = new List <Assembly>();

            if (options.ConfigFilterAssemblies == null || !options.ConfigFilterAssemblies.Any())
            {
                return(assemblies);
            }

            DependencyContext context = DependencyContext.Default;

            var libs = context.CompileLibraries.Where(lib => options.ConfigFilterAssemblies.Contains(lib.Name));

            foreach (var lib in libs)
            {
                var assembly = Assembly.Load(new AssemblyName(lib.Name));
                assemblies.Add(assembly);
            }

            return(assemblies);
        }
        public override IEnumerable <PPtr <Object> > FetchDependencies(DependencyContext context)
        {
            foreach (PPtr <Object> asset in base.FetchDependencies(context))
            {
                yield return(asset);
            }

            yield return(context.FetchDependency(SkyboxMaterial, SkyboxMaterialName));

            yield return(context.FetchDependency(HaloTexture, HaloTextureName));

            yield return(context.FetchDependency(SpotCookie, SpotCookieName));

            yield return(context.FetchDependency(CustomReflection, CustomReflectionName));

            if (IsReadGeneratedSkyboxReflection(context.Version, context.Flags))
            {
                yield return(context.FetchDependency(GeneratedSkyboxReflection, GeneratedSkyboxReflectionName));
            }
            yield return(context.FetchDependency(Sun, SunName));
        }
Exemple #7
0
        public void Build()
        {
            var dependencyContext            = DependencyContext.Load(Assembly.GetEntryAssembly());
            IEnumerable <Assembly> assemblys = dependencyContext.RuntimeLibraries
                                               .SelectMany(p => p.GetDefaultAssemblyNames(dependencyContext))
                                               .Select(Assembly.Load);
            var types = assemblys.SelectMany(p => p.GetTypes());

            foreach (var type in types)
            {
                if (!typeof(IDomainService).GetTypeInfo().IsAssignableFrom(type))
                {
                    continue;
                }
                if (!type.GetTypeInfo().IsClass)
                {
                    continue;
                }
                this._services.AddSingleton(type);
            }
        }
Exemple #8
0
        public CustomAssemblyResolver(string assemblyDirectory)
        {
            RemoveSearchDirectory(".");
            RemoveSearchDirectory("bin");

            AddSearchDirectory(assemblyDirectory);

            _dependencyContext = DepsJsonUtils.LoadDependencyContext(assemblyDirectory);

            var runtimeConfigPath = Directory.GetFiles(assemblyDirectory, "*.runtimeconfig.dev.json", SearchOption.TopDirectoryOnly)
                                    .FirstOrDefault();

            if (runtimeConfigPath != null)
            {
                var runtimeConfigContent = File.ReadAllText(runtimeConfigPath);
                foreach (var path in DepsJsonUtils.GetAdditionalPaths(runtimeConfigContent))
                {
                    AddSearchDirectory(path);
                }
            }
        }
Exemple #9
0
        private void ResolveDenpendency()
        {
            var assemblies = new DirectoryInfo(new FileInfo(CurrentAssembly.Location).DirectoryName).GetFiles("*.dll");

            foreach (var item in assemblies)
            {
                if (item.FullName == CurrentAssembly.Location)
                {
                    continue;
                }

                var assembly = LoadFromAssemblyPath(item.FullName);
                if (!DependencyContext.Default.CompileLibraries.Any(m => m.Name == assembly.GetName().Name))
                {
                    DependencyAssemblies.Add(assembly);
                }
            }
            string currentName = CurrentAssembly.GetName().Name;

            DependencyCompilationLibrary = DependencyContext.Load(CurrentAssembly).CompileLibraries.Where(de => de.Name != currentName && !DependencyContext.Default.CompileLibraries.Any(m => m.Name == de.Name)).ToList();
        }
Exemple #10
0
        public void WriteDoesNotDisposeStream()
        {
            DependencyContext context = Create(
                "Target",
                "Target/runtime",
                runtimeGraph: new[]
            {
                new RuntimeFallbacks("win7-x64", new [] { "win6", "win5" }),
                new RuntimeFallbacks("win8-x64", new [] { "win7-x64" }),
            });

            DisposeAwareMemoryStream stream = new DisposeAwareMemoryStream();

            using (stream)
            {
                new DependencyContextWriter().Write(context, stream);
                Assert.False(stream.IsDisposed);
            }

            Assert.True(stream.IsDisposed);
        }
Exemple #11
0
        public static IEnumerable <Assembly> GetCandidateAssemblies(params string[] tagAssemblies)
        {
            if (tagAssemblies == null)
            {
                throw new ArgumentNullException(nameof(tagAssemblies));
            }
            if (tagAssemblies.Length == 0)
            {
                throw new ArgumentException("At least one tag assembly name must be specified.", nameof(tagAssemblies));
            }

            var context     = DependencyContext.Load(Assembly.GetEntryAssembly());
            var loadContext = AssemblyLoadContext.Default;

            var referenceAssemblies = new HashSet <string>(tagAssemblies, StringComparer.OrdinalIgnoreCase);

            return(context.RuntimeLibraries
                   .Where(x => x.Dependencies.Any(d => referenceAssemblies.Contains(d.Name)))
                   .SelectMany(x => x.GetDefaultAssemblyNames(context))
                   .Select(x => loadContext.LoadFromAssemblyName(x)));
        }
        public void GetRuntimeAssemblyNamesExtractsCorrectAssemblyName(string path, string expected)
        {
            var context = new DependencyContext(new TargetInfo(".NETStandard,Version=v1.3", string.Empty, string.Empty, true),
                                                compilationOptions: CompilationOptions.Default,
                                                compileLibraries: new CompilationLibrary[] { },
                                                runtimeLibraries: new[] {
                new RuntimeLibrary("package", "System.Banana", "1.0.0", "hash",
                                   new [] {
                    new RuntimeAssetGroup(string.Empty, Path.Combine("lib", path))
                },
                                   new RuntimeAssetGroup[] { },
                                   new ResourceAssembly[] { },
                                   new Dependency[] { },
                                   serviceable: false)
            },
                                                runtimeGraph: new RuntimeFallbacks[] { });

            var assets = context.GetDefaultAssemblyNames();

            assets.Should().OnlyContain(a => a.Name == expected);
        }
Exemple #13
0
        private void ExecuteCore()
        {
            DependencyContext context;

            using (var depsStream = File.OpenRead(DepsFilePath))
            {
                context = new DependencyContextJsonReader().Read(depsStream);
            }

            LockFile lockFile = LockFileUtilities.GetLockFile(AssetsFilePath, NullLogger.Instance);

            if (lockFile == null)
            {
                throw new ArgumentException($"Could not load a LockFile at '{AssetsFilePath}'.", nameof(AssetsFilePath));
            }

            var manager       = new RuntimeGraphManager();
            var graph         = manager.Collect(lockFile);
            var expandedGraph = manager.Expand(graph, Runtime);

            var trimmedRuntimeLibraries = context.RuntimeLibraries;

            if (PackagesToRemove != null && PackagesToRemove.Any())
            {
                trimmedRuntimeLibraries = RuntimeReference.RemoveReferences(context.RuntimeLibraries, PackagesToRemove);
            }

            context = new DependencyContext(
                context.Target,
                context.CompilationOptions,
                context.CompileLibraries,
                trimmedRuntimeLibraries,
                expandedGraph
                );

            using (var depsStream = File.Create(DepsFilePath))
            {
                new DependencyContextWriter().Write(context, depsStream);
            }
        }
        public void PopulateFeature(IEnumerable <ApplicationPart> parts, MetadataReferenceFeature feature)
        {
            var libraryPaths = new HashSet <string>(StringComparer.OrdinalIgnoreCase);

            foreach (var assemblyPart in parts.OfType <AssemblyPart>())
            {
                var dependencyContext = DependencyContext.Load(assemblyPart.Assembly);
                if (dependencyContext != null)
                {
                    foreach (var library in dependencyContext.CompileLibraries)
                    {
                        if (string.Equals("reference", library.Type, StringComparison.OrdinalIgnoreCase))
                        {
                            foreach (var libraryAssembly in library.Assemblies)
                            {
                                libraryPaths.Add(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, libraryAssembly));
                            }
                        }
                        else
                        {
                            try
                            {
                                foreach (var path in library.ResolveReferencePaths())
                                {
                                    libraryPaths.Add(path);
                                }
                            }
                            catch (InvalidOperationException)
                            {
                                if (PluginManagerService.GetPluginManager().PluginLoaded(library.Name + ".dll",
                                                                                         out int version, out string module))
                                {
                                    libraryPaths.Add(module);
                                }
                                else
                                {
                                    throw;
                                }
                            }
                        }
        /// <summary>
        /// Configure the Application Blocks and <see cref="Container">composition root</see>
        /// and build the application's <see cref="ConsoleApplicationContext" />.
        /// </summary>
        /// <param name="dependencyContext">
        /// Optional: A <see cref="DependencyContext" /> to use for all registration
        /// discovery.
        /// </param>
        /// <returns>
        /// The <see cref="ConsoleApplicationContext" /> that will serve as the run context of
        /// your console application
        /// </returns>
        public ConsoleApplicationContext Build <TAppConfigInterface, TAppConfigImplementation>(
            DependencyContext dependencyContext = null
            )
            where TAppConfigInterface : class, IApplicationConfiguration
            where TAppConfigImplementation : class, TAppConfigInterface
        {
            var container = new Container();

            container.Options.DefaultLifestyle       = defaultLifestyle;
            container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();

            var frameworkConfiguration = frameworkConfigurationBuilder.Build();

            container
            .AddApplicationConfiguration <TAppConfigInterface, TAppConfigImplementation>(frameworkConfiguration, hostingEnvironment)
            .AddEventLogging(defaultLifestyle)
            .AddCommands(defaultLifestyle, dependencyContext)
            .AddBootstrappers(dependencyContext);

            foreach (var module in modules)
            {
                module.RegisterServices(container);
            }

            container.Verify();

            if (container.GetRegistration(typeof(IEnumerable <IBootstrapper>)) != null)
            {
                using (AsyncScopedLifestyle.BeginScope(container))
                {
                    // Resolve and run IBootstrappers
                    foreach (var bootstrapper in container.GetAllInstances <IBootstrapper>())
                    {
                        bootstrapper.Bootstrap();
                    }
                }
            }

            return(new ConsoleApplicationContext(container));
        }
Exemple #16
0
        static List <IRunnerReporter> GetAvailableRunnerReporters()
        {
            var result          = new List <IRunnerReporter>();
            var dependencyModel = DependencyContext.Load(typeof(Program).GetTypeInfo().Assembly);
            var assemblyNames   = new List <RuntimeAssembly>(dependencyModel.RuntimeLibraries.SelectMany(r => r.Assemblies));

            foreach (var assemblyName in assemblyNames)
            {
                Assembly assembly;
                try
                {
                    assembly = Assembly.Load(assemblyName.Name);
                }
                catch
                {
                    continue;
                }

                foreach (var type in assembly.DefinedTypes)
                {
                    if (type == null || type.IsAbstract || type == typeof(DefaultRunnerReporter).GetTypeInfo() || type.ImplementedInterfaces.All(i => i != typeof(IRunnerReporter)))
                    {
                        continue;
                    }

                    var ctor = type.DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Length == 0);
                    if (ctor == null)
                    {
                        Console.ForegroundColor = ConsoleColor.Yellow;
                        Console.WriteLine($"Type {type.FullName} in assembly {assembly} appears to be a runner reporter, but does not have an empty constructor.");
                        Console.ResetColor();
                        continue;
                    }

                    result.Add((IRunnerReporter)ctor.Invoke(new object[0]));
                }
            }

            return(result);
        }
Exemple #17
0
        private IEnumerable <PluginDependency> GetPluginDependencies(DependencyContext pluginDependencyContext)
        {
            var dependencies    = new List <PluginDependency>();
            var runtimeId       = GetCorrectRuntimeIdentifier();
            var dependencyGraph = DependencyContext.Default.RuntimeGraph.FirstOrDefault(g => g.Runtime == runtimeId);
            // List of supported runtimes, includes the default runtime and the fallbacks for this dependency context
            var runtimes = new List <string> {
                dependencyGraph?.Runtime
            }.AddRangeToList <string>(dependencyGraph?.Fallbacks);

            foreach (var runtimeLibrary in pluginDependencyContext.RuntimeLibraries)
            {
                var assets = runtimeLibrary.RuntimeAssemblyGroups.GetDefaultAssets();

                foreach (var runtime in runtimes)
                {
                    var runtimeSpecificGroup = runtimeLibrary.RuntimeAssemblyGroups.FirstOrDefault(g => g.Runtime == runtime);
                    if (runtimeSpecificGroup != null)
                    {
                        assets = runtimeSpecificGroup.AssetPaths;
                        break;
                    }
                }
                foreach (var asset in assets)
                {
                    var path = asset.StartsWith("lib/")
                            ? Path.GetFileName(asset)
                            : asset;

                    dependencies.Add(new PluginDependency
                    {
                        DependencyNameWithoutExtension = Path.GetFileNameWithoutExtension(asset),
                        SemVer         = ParseSemVer(runtimeLibrary.Version),
                        DependencyPath = path,
                        ProbingPath    = Path.Combine(runtimeLibrary.Name.ToLowerInvariant(), runtimeLibrary.Version, path)
                    });
                }
            }
            return(dependencies);
        }
Exemple #18
0
        public void Register(DependencyContext context)
        {
            var builder = context.ContainerBuilder;
            var config  = context.AppConfig as ServiceConfiguration;

            //web helper
            builder.RegisterType <WebHelper>().As <IWebHelper>().InstancePerLifetimeScope();

            if (config.CachingEnabled)
            {
                //cache manager
                builder.RegisterType <PerRequestCacheManager>().As <ICacheManager>().InstancePerLifetimeScope();
                builder.RegisterType <MemoryCacheManager>().As <IStaticCacheManager>().SingleInstance();
            }
            else
            {
                //null logger
                builder.RegisterType <NullCacheManager>().As <ICacheManager>().SingleInstance();
            }

            //logging
            if (config.LoggingEnabled)
            {
                //default logger
                builder.RegisterType <DefaultLogger>().As <ILogger>().InstancePerLifetimeScope();
            }
            else
            {
                //null logger
                builder.RegisterType <NullLogger>().As <ILogger>().InstancePerLifetimeScope();
            }

            //dapper data context
            builder.Register(c => ProviderFactory.GetProvider(config.DatabaseProviderName)).As <IDataProvider>().SingleInstance();
            builder.Register(c => c.Resolve <IDataProvider>().CreateConnection(config.ConnectionString)).InstancePerLifetimeScope();
            builder.Register(c => new DataContext(c.Resolve <IDataProvider>(), c.Resolve <IDbConnection>())).As <IDataContext>().InstancePerLifetimeScope();

            //providers
            builder.RegisterType <PictureProvider>().As <IPictureProvider>().InstancePerLifetimeScope();
        }
        private List <TypeInfo> GetTypeInfos(CrontabOptions options)
        {
            HashSet <Assembly> assemblys = new HashSet <Assembly>();

            if (options.ScanAllAssembly)
            {
                var entryAssembly     = Assembly.GetEntryAssembly();
                var dependencyContext = DependencyContext.Load(entryAssembly);
                if (dependencyContext == null)
                {
                    assemblys.Add(entryAssembly);
                }
                else
                {
                    var assName  = Assembly.GetExecutingAssembly().GetName().Name;
                    var libs     = dependencyContext.RuntimeLibraries.Where(lib => lib.Dependencies.Any(dep => string.Equals(assName, dep.Name, StringComparison.Ordinal)));
                    var assNames = libs.SelectMany(lib => lib.GetDefaultAssemblyNames(dependencyContext));
                    foreach (var name in assNames)
                    {
                        var assembly = Assembly.Load(new AssemblyName(name.Name));
                        assemblys.Add(assembly);
                    }
                }
            }
            if (options.Assemblies != null && options.Assemblies.Count > 0)
            {
                foreach (var assembly in options.Assemblies)
                {
                    assemblys.Add(assembly);
                }
            }
            if (assemblys.Count == 0)
            {
                assemblys.Add(Assembly.GetEntryAssembly());
            }

            var types = assemblys.SelectMany(a => a.DefinedTypes.Where(y => y.GetCustomAttribute <CrontabJobAttribute>() != null)).ToList();

            return(types);
        }
Exemple #20
0
        public override IEnumerable <PPtr <Object> > FetchDependencies(DependencyContext context)
        {
            foreach (PPtr <Object> asset in base.FetchDependencies(context))
            {
                yield return(asset);
            }

            MonoBehaviourLayout layout = context.Layout.MonoBehaviour;

#if UNIVERSAL
            yield return(context.FetchDependency(GeneratorAsset, layout.GeneratorAssetName));
#endif
            yield return(context.FetchDependency(Script, layout.ScriptName));

            if (Structure != null)
            {
                foreach (PPtr <Object> asset in context.FetchDependencies(Structure, Structure.Type.Name))
                {
                    yield return(asset);
                }
            }
        }
Exemple #21
0
 private static List <AssemblyData> ResolveAssemblies(DependencyContext dependencyContext)
 {
     return(dependencyContext.CompileLibraries
            .SelectMany(l =>
     {
         try
         {
             var paths = l.ResolveReferencePaths();
             return paths.Select(p => new AssemblyData
             {
                 Library = l,
                 AssemblyFullPath = p,
                 AssemblyFileName = Path.GetFileNameWithoutExtension(p)
             });
         }
         catch (Exception)
         {
             return Enumerable.Empty <AssemblyData>();
         }
     })
            .ToList());
 }
        public override bool Execute()
        {
            LoadConflicts();

            DependencyContext sourceDeps;

            using (var sourceStream = File.Open(DepsFilePath, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete))
            {
                sourceDeps = new DependencyContextJsonReader().Read(sourceStream);
            }

            DependencyContext trimmedDeps = TrimConflicts(sourceDeps);

            var writer = new DependencyContextWriter();

            using (var fileStream = File.Create(DepsFilePath))
            {
                writer.Write(trimmedDeps, fileStream);
            }

            return(!Log.HasLoggedErrors);
        }
Exemple #23
0
        public AssemblyResolver()
        {
            _resolverDependencyContext = DependencyContext.Load(typeof(AssemblyResolver).Assembly);
            var codeGenPath = Path.GetDirectoryName(new Uri(typeof(AssemblyResolver).Assembly.CodeBase).LocalPath);

            _assemblyResolver = new CompositeCompilationAssemblyResolver(
                new ICompilationAssemblyResolver[]
            {
                new AppBaseCompilationAssemblyResolver(codeGenPath),
                new ReferenceAssemblyPathResolver(),
                new PackageCompilationAssemblyResolver()
            });

            AppDomain.CurrentDomain.AssemblyResolve += ResolveAssembly;

            _loadContext            = AssemblyLoadContext.GetLoadContext(typeof(AssemblyResolver).Assembly);
            _loadContext.Resolving += AssemblyLoadContextResolving;
            if (_loadContext != AssemblyLoadContext.Default)
            {
                AssemblyLoadContext.Default.Resolving += AssemblyLoadContextResolving;
            }
        }
 public IEnumerable <PPtr <Object> > FetchDependencies(DependencyContext context)
 {
     if (Type == PrimitiveType.Complex)
     {
         if (IsArray)
         {
             ISerializableStructure[] structures = (ISerializableStructure[])Value;
             foreach (PPtr <Object> asset in context.FetchDependencies(structures, Name))
             {
                 yield return(asset);
             }
         }
         else
         {
             ISerializableStructure structure = (ISerializableStructure)Value;
             foreach (PPtr <Object> asset in context.FetchDependencies(structure, Name))
             {
                 yield return(asset);
             }
         }
     }
 }
Exemple #25
0
        public IEnumerable <PPtr <Object> > FetchDependencies(DependencyContext context)
        {
            if (HasTerrainLayers(context.Version))
            {
                foreach (PPtr <Object> asset in context.FetchDependencies(TerrainLayers, TerrainLayersName))
                {
                    yield return(asset);
                }
            }
            else
            {
                foreach (PPtr <Object> asset in context.FetchDependencies(Splats, SplatsName))
                {
                    yield return(asset);
                }
            }

            foreach (PPtr <Object> asset in context.FetchDependencies(AlphaTextures, AlphaTexturesName))
            {
                yield return(asset);
            }
        }
        protected override Assembly[] FindAllItems()
        {
            string[] filters =
            {
                "System",
                "Microsoft",
                "netstandard",
                "dotnet",
                "Window",
                "mscorlib"
            };
            DependencyContext context = DependencyContext.Default;
            List <string>     names   = new List <string>();

            string[] dllNames = context.CompileLibraries.SelectMany(m => m.Assemblies).Distinct().Select(m => m.Replace(".dll", "")).ToArray();
            names = (from name in dllNames
                     let i = name.LastIndexOf('/') + 1
                             select name.Substring(i, name.Length - i)).Where(c => !filters.Any(c.StartsWith))
                    .Distinct()
                    .ToList();
            return(LoadFiles(names));
        }
Exemple #27
0
        static List <IRunnerReporter> GetAvailableRunnerReporters()
        {
            var result          = new List <IRunnerReporter>();
            var dependencyModel = DependencyContext.Load(typeof(Program).GetTypeInfo().Assembly);

            foreach (var assemblyName in dependencyModel.GetRuntimeAssemblyNames(RuntimeEnvironment.GetRuntimeIdentifier()))
            {
                try
                {
                    var assembly = Assembly.Load(assemblyName);
                    foreach (var type in assembly.DefinedTypes)
                    {
#pragma warning disable CS0618
                        if (type == null || type.IsAbstract || type == typeof(DefaultRunnerReporter).GetTypeInfo() || type == typeof(DefaultRunnerReporterWithTypes).GetTypeInfo() || type.ImplementedInterfaces.All(i => i != typeof(IRunnerReporter)))
                        {
                            continue;
                        }
#pragma warning restore CS0618

                        var ctor = type.DeclaredConstructors.FirstOrDefault(c => c.GetParameters().Length == 0);
                        if (ctor == null)
                        {
                            Console.ForegroundColor = ConsoleColor.Yellow;
                            Console.WriteLine($"Type {type.FullName} in assembly {assembly} appears to be a runner reporter, but does not have an empty constructor.");
                            Console.ResetColor();
                            continue;
                        }

                        result.Add((IRunnerReporter)ctor.Invoke(new object[0]));
                    }
                }
                catch
                {
                    continue;
                }
            }

            return(result);
        }
Exemple #28
0
        public void GetCandidateLibraries_ReturnsLibrariesReferencingAnyMvcAssembly()
        {
            // Arrange
            var dependencyContext = new DependencyContext(
                new TargetInfo("framework", "runtime", "signature", isPortable: true),
                CompilationOptions.Default,
                new CompilationLibrary[0],
                new[]
            {
                GetLibrary("Foo", "Microsoft.AspNetCore.Mvc.Core"),
                GetLibrary("Bar", "Microsoft.AspNetCore.Mvc"),
                GetLibrary("Qux", "Not.Mvc.Assembly", "Unofficial.Microsoft.AspNetCore.Mvc"),
                GetLibrary("Baz", "Microsoft.AspNetCore.Mvc.Abstractions"),
            },
                Enumerable.Empty <RuntimeFallbacks>());

            // Act
            var candidates = DefaultAssemblyPartDiscoveryProvider.GetCandidateLibraries(dependencyContext);

            // Assert
            Assert.Equal(new[] { "Foo", "Bar", "Baz" }, candidates.Select(a => a.Name));
        }
Exemple #29
0
        public static Assembly LoadPlugin(string path)
        {
            Assembly assembly = AssemblyLoadContext.Default.LoadFromAssemblyPath(path);

            _dependencyContext = DependencyContext.Load(assembly);

            _assemblyResolver = new CompositeCompilationAssemblyResolver(new ICompilationAssemblyResolver[]
            {
                new AppBaseCompilationAssemblyResolver(Path.GetDirectoryName(path)),
                new ReferenceAssemblyPathResolver(),
                new PackageCompilationAssemblyResolver()
            });

            _loadContext = AssemblyLoadContext.GetLoadContext(assembly);

            if (_loadContext != null)
            {
                _loadContext.Resolving += OnResolving;
            }

            return(assembly);
        }
Exemple #30
0
        //private Assembly AssemblyResolving(AssemblyLoadContext arg1, AssemblyName arg2)
        //{
        //    if (arg2.FullName == CurrentAssembly.FullName)
        //    {
        //        return CurrentAssembly;
        //    }
        //    var deps = DependencyContext.Default;
        //    if (deps.CompileLibraries.Any(d => d.Name == arg2.Name))
        //    {
        //        return Assembly.Load(arg2);
        //    }

        //    foreach (var item in DependencyAssemblies)
        //    {
        //        if (item.FullName == arg2.FullName)
        //        {
        //            return item;
        //        }
        //    }
        //    return null;
        //}
        private void ResolveDenpendency(Assembly assembly)
        {
            string currentName = assembly.GetName().Name;
            List <CompilationLibrary> dependencyCompilationLibrary = DependencyContext.Load(assembly)
                                                                     .CompileLibraries.Where(de => de.Name != currentName && !DependencyContext.Default.CompileLibraries.Any(m => m.Name == de.Name))
                                                                     .ToList();

            dependencyCompilationLibrary.Each(libaray =>
            {
                foreach (var item in libaray.ResolveReferencePaths(new DependencyAssemblyResolver(Path.GetDirectoryName(assembly.Location))))
                {
                    DependencyAssemblies.Add(AssemblyLoadContext.Default.LoadFromAssemblyPath(item));
                }
            });

            PluginDescriptor plugin = null;

            foreach (var typeInfo in assembly.DefinedTypes)
            {
                if (typeInfo.IsAbstract || typeInfo.IsInterface)
                {
                    continue;
                }

                if (PluginTypeInfo.IsAssignableFrom(typeInfo))
                {
                    plugin                   = new PluginDescriptor();
                    plugin.PluginType        = typeInfo.AsType();
                    plugin.Assembly          = assembly;
                    plugin.Dependency        = dependencyCompilationLibrary;
                    plugin.CurrentPluginPath = CurrentPath;
                }
            }

            if (plugin != null)
            {
                PluginActivtor.LoadedPlugins.Add(plugin);
            }
        }
Exemple #31
0
        /// <summary>
        /// Adds all assemblies referencing Orleans found in the provided assembly's <see cref="DependencyContext"/>.
        /// </summary>
        /// <param name="manager">The builder.</param>
        /// <returns>The builder with the additionally included assemblies.</returns>
        public static IApplicationPartManagerWithAssemblies AddFromDependencyContext(this IApplicationPartManager manager, Assembly entryAssembly)
        {
            entryAssembly = entryAssembly ?? Assembly.GetCallingAssembly();
            var dependencyContext = DependencyContext.Default;

            if (entryAssembly != null)
            {
                dependencyContext = DependencyContext.Load(entryAssembly) ?? DependencyContext.Default;
                manager           = manager.AddApplicationPart(entryAssembly);
            }

            if (dependencyContext == null)
            {
                return(new ApplicationPartManagerWithAssemblies(manager, Array.Empty <Assembly>()));
            }

            var assemblies = new List <Assembly>();

            foreach (var lib in dependencyContext.RuntimeLibraries)
            {
                if (!lib.Dependencies.Any(dep => dep.Name.Contains("Orleans")))
                {
                    continue;
                }

                try
                {
                    var asm = Assembly.Load(lib.Name);
                    manager.AddApplicationPart(new AssemblyPart(asm));
                    assemblies.Add(asm);
                }
                catch
                {
                    // Ignore any exceptions thrown during non-explicit assembly loading.
                }
            }

            return(new ApplicationPartManagerWithAssemblies(manager, assemblies));
        }
Exemple #32
0
 private static ConcurrentBag <AssemblyData> ResolveAssemblies(DependencyContext dependencyContext)
 {
     return(new ConcurrentBag <AssemblyData>(dependencyContext.CompileLibraries
                                             .SelectMany(l => {
         try
         {
             var paths = l.ResolveReferencePaths();
             return paths.Select(p => new AssemblyData {
                 Library = l,
                 AssemblyFullPath = p,
                 AssemblyFileName = Path.GetFileNameWithoutExtension(p)
             });
         }
         catch (Exception)
         {
             try
             {
                 Assembly a;
                 if (TryLoadAssemblyFromUserFolders(l.Name, out a))
                 {
                     return new List <AssemblyData>()
                     {
                         new AssemblyData {
                             Library = l,
                             AssemblyFullPath = a.Location,
                             AssemblyFileName = Path.GetFileNameWithoutExtension(a.Location)
                         }
                     };
                 }
                 return Enumerable.Empty <AssemblyData>();
             }
             catch (Exception e)
             {
                 return Enumerable.Empty <AssemblyData>();
             }
         }
     })
                                             .ToList()));
 }
Exemple #33
0
        /// <inheritdoc />
        public IEnumerable <string> GetReferencePaths()
        {
            if (Assembly.IsDynamic)
            {
                // Skip loading process for dynamic assemblies. This prevents DependencyContextLoader from reading the
                // .deps.json file from either manifest resources or the assembly location, which will fail.
                return(Enumerable.Empty <string>());
            }

            var dependencyContext = DependencyContext.Load(Assembly);

            if (dependencyContext != null)
            {
                return(dependencyContext.CompileLibraries.SelectMany(library => library.ResolveReferencePaths()));
            }

            // If an application has been compiled without preserveCompilationContext, return the path to the assembly
            // as a reference. For runtime compilation, this will allow the compilation to succeed as long as it least
            // one application part has been compiled with preserveCompilationContext and contains a super set of types
            // required for the compilation to succeed.
            return(new[] { Assembly.Location });
        }
            public ContextualLogger(DependencyContext context)
            {
                Assert.IsNotNull(context, "context should not be null.");

                this.Context = context;
            }
 public ContextualLogger(DependencyContext context)
 {
     this.Context = context;
 }
Exemple #36
0
 private DependencyContext CreateDependencyContext(Runtime.Project project, FrameworkName frameworkName)
 {
     var dependencyContext = new DependencyContext(project.ProjectDirectory, _options.Configuration, frameworkName);
     dependencyContext.Walk(project.Name, project.Version);
     return dependencyContext;
 }