/// <summary>Initialises the assembly loader.</summary>
 internal static void Init()
 {
     if (instance == null)
     {
         instance = new AssemblyLoader();
     }
 }
Example #2
0
        public static void Main()
        {
            var loader = new AssemblyLoader();

            var plugin = loader.LoadPlugInAppDomain("Plug.dll");

            plugin.Delay(TimeSpan.FromSeconds(2)).Subscribe(x => Console.WriteLine("Delayed: " + x));
            var isTrue = true;

            while (isTrue)
            {
                var text = Console.ReadLine();

                plugin.Push(text);

                if (string.IsNullOrEmpty(text))
                    isTrue = false;
            }

            plugin.Dispose();

            Console.WriteLine("Plugin disposed.");

            Console.ReadLine();
        }
        public static void LoadPackages(Action<IPackageFacility> configuration, bool runActivators = true)
        {
            _packages.Clear();

            Diagnostics = new PackagingDiagnostics();
            var record = new PackageLoadingRecord();

            Diagnostics.LogExecution(record, () =>
            {
                var facility = new PackageFacility();
                var assemblyLoader = new AssemblyLoader(Diagnostics);
                var graph = new PackagingRuntimeGraph(Diagnostics, assemblyLoader, _packages);

                var codeLocation = findCallToLoadPackages();
                graph.PushProvenance(codeLocation);
                configuration(facility);
                facility.Configure(graph);


                graph.PopProvenance();
                graph.DiscoverAndLoadPackages(() =>
                {
                    _assemblies.Clear();
                    _assemblies.AddRange(assemblyLoader.Assemblies);
                }, runActivators);
            });

            record.Finished = DateTime.Now;

            //_packages.Clear();


        }
        public void Run()
        {
            var assemblyLoader = new AssemblyLoader(this.assemblyPath);
            var assembly = assemblyLoader.Assembly;

            var testMethodLoader = new TestMethodLoader(assembly);
            var testContainers = testMethodLoader.LoadTestMethods();
            foreach (var testContainer in testContainers)
            {
                var instance = Activator.CreateInstance(testContainer.Key);
                var testMethods = testContainer.Value;
                foreach (MethodInfo testMethod in testMethods)
                {
                    var testType = this.GetTestType(testMethod);

                    var testRunner = TestRunnerFactory.GetTestRunner(
                        testType,
                        testMethod,
                        instance);

                    testRunner.RunTest();
                    this.LogTestResult(testRunner, testMethod);
                }
            }
        }
Example #5
0
        public void Load_NullOrEmptyPath_ReturnsNull(string path)
        {
            var subject = new AssemblyLoader(path);
            var result = subject.Load();

            Assert.AreEqual(null, result);
        }
        public static void RunTests()
        {
            var loader = new AssemblyLoader();
            var testMethods = loader.GatherTests();

            Console.LogDateTime = true;

            foreach (var untypedTest in testMethods)
            {
                var methodInfo = (MethodInfo)untypedTest;

                try
                {
                    methodInfo.Invoke(null, null);
                    Console.WriteLine(methodInfo.DeclaringType + "." + methodInfo.Name + " - Passed.");
                }
                catch(ControlledAssertionException controlledAssertionException)
                {
                    Log(methodInfo, controlledAssertionException.Message);
                }
                catch (Exception ex)
                {
                    Log(methodInfo, "Failed", ex);
                }
            }

            Console.WriteLine("End of test run.");
        }
        //parameterParsers are classes that extends from IExternalConstructor
        public ClassHierarchyImpl(string[] assemblies, Type[] parameterParsers)  
        {
            this.assemblies = assemblies;
            rootNode = NodeFactory.CreateRootPackageNode();
            loader = new AssemblyLoader(assemblies);
           
            foreach (Type p in parameterParsers) //p must be extend from IExternalConstructor
            {
                try 
                {
                    Parameterparser.AddParser(p);
                } 
                catch (BindException e)
                {
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Caught(e, Level.Error, LOGGER);
                    Org.Apache.REEF.Utilities.Diagnostics.Exceptions.Throw(new ArgumentException("Could not register parameter parsers", e), LOGGER);
                }
            }

            foreach (var a in loader.Assemblies)
            {
                foreach (var t in a.GetTypes())
                {
                    RegisterType(t);
                }
            }
        }
 public TestRunner(Logger output, AssemblyLoader assemblyLoader)
 {
     AllPassed = true;
     this.output = output;
     this.assemblyLoader = assemblyLoader;
     processor = new StepProcessor(this);
 }
        public void Loader_returns_null_if_assembly_is_not_found_at_path()
        {
            var assemblyLoader = new AssemblyLoader();
            var assembly = assemblyLoader.LoadAssembly(@"c:\a\non\existent\path\assembly.dll");

            Assert.That(assembly, Is.Null);
        }
 public PluginContainerBuilder(AssemblyLoader assemblyLoader, IPluginJudge pluginJudge, IContainerFactory containerFactory, ILogger logger)
 {
     _assemblyLoader = assemblyLoader;
     _pluginJudge = pluginJudge;
     _containerFactory = containerFactory;
     _logger = logger;
 }
        public OperationExecutor(
            [NotNull] CommonOptions options,
            [CanBeNull] string environment)
        {
            var projectFile = Path.Combine(Directory.GetCurrentDirectory(), Project.FileName);
            var project = ProjectReader.GetProject(projectFile);

            var projectConfiguration = options.Configuration ?? Constants.DefaultConfiguration;
            var projectFramework = options.Framework;

            var projectContext = ProjectContext.Create(project.ProjectFilePath,
                projectFramework,
                RuntimeEnvironmentRidExtensions.GetAllCandidateRuntimeIdentifiers());

            var runtimeOutputPath = projectContext.GetOutputPaths(projectConfiguration)?.RuntimeOutputPath;
            if (!string.IsNullOrEmpty(runtimeOutputPath))
            {
                Reporter.Verbose.WriteLine(
                    ToolsCliStrings.LogDataDirectory(runtimeOutputPath));
                Environment.SetEnvironmentVariable(DataDirEnvName, runtimeOutputPath);
#if NET451
                AppDomain.CurrentDomain.SetData("DataDirectory", runtimeOutputPath);
#endif
            }

            var assemblyName = project.GetCompilerOptions(projectFramework, projectConfiguration).OutputName;
            var projectDir = project.ProjectDirectory;
            var rootNamespace = project.Name;

            var assemblyLoader = new AssemblyLoader(Assembly.Load);
            var projectAssembly = assemblyLoader.Load(assemblyName);

            _contextOperations = new LazyRef<DbContextOperations>(
                          () => new DbContextOperations(
                              new LoggerProvider(name => new ConsoleCommandLogger(name)),
                              projectAssembly,
                              projectAssembly,
                              environment,
                              projectDir));
            _databaseOperations = new LazyRef<DatabaseOperations>(
                () => new DatabaseOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    assemblyLoader,
                    projectAssembly,
                    environment,
                    projectDir,
                    projectDir,
                    rootNamespace));
            _migrationsOperations = new LazyRef<MigrationsOperations>(
                () => new MigrationsOperations(
                    new LoggerProvider(name => new ConsoleCommandLogger(name)),
                    projectAssembly,
                    assemblyLoader,
                    projectAssembly,
                    environment,
                    projectDir,
                    projectDir,
                    rootNamespace));
        }
Example #12
0
        public void AssemblyLoaderMustLoadTargetAssemblyFromDisk()
        {
            IAssemblyLoader loader = new AssemblyLoader();

            // The loader should return a valid assembly
            Assembly result = loader.Load(typeof(SampleClass).Assembly.Location);
            Assert.IsNotNull(result);
        }
Example #13
0
 public static FrameworkAdapter Try(AssemblyLoader assemblyLoader) {
    foreach (var assemblyName in assemblyLoader.GetReferencedAssemblies()) {
       if (assemblyName.FullName.Contains("Microsoft.VisualStudio.QualityTools.UnitTestFramework,")) {
          return new MsUnitTestAdapter();
       }
    }
    return null;
 }
Example #14
0
 internal PackageInstaller(IFileSystem fileSystem, AssemblyLoader assemblyLoader)
 {
     _fileSystem = fileSystem;
     _assemblyLoader = assemblyLoader;
     _currentFramework = GetCurrentFramework();
     _settings = Settings.LoadDefaultSettings(fileSystem.RootPath.FullPath, null, new MachineWideSettings());
     _sourceRepositories = new SourceRepositoryProvider(_settings);
 }
Example #15
0
 public static FrameworkAdapter Try(AssemblyLoader assemblyLoader) {
    foreach (var assemblyName in assemblyLoader.GetReferencedAssemblies()) {
       if (assemblyName.FullName.ToLower().Contains("nunit.framework,")) {
          return new NUnitAdapter();
       }
    }
    return null;
 }
Example #16
0
 public void ShouldBeAbleToGetTypes()
 {
     var assemblyLoader = new AssemblyLoader();
     var types = assemblyLoader.GetTypes(@"C:\Source\Mike.AmqpSpike\EasyNetQ.Tests.Messages\bin\Debug\EasyNetQ.Tests.Messages.dll");
     foreach (var type in types)
     {
         Console.WriteLine(type);
     }
 }
Example #17
0
        static void Main(string[] args)
        {
            var arguments = ParseCommandLine(args);

            var loader = new AssemblyLoader();
            var dbProvider = loader.CreateTypeFromAssembly<DbProvider>(arguments["dbp.provider"], arguments);
            var dbCodeFormatter = loader.CreateTypeFromAssembly<DbTraceCodeFormatter>(arguments["tcf.provider"], arguments);
            var codeHighlighter = loader.CreateTypeFromAssembly<HighlightCodeProvider>(arguments["hcp.provider"], arguments);
            var outputProvider = loader.CreateTypeFromAssembly<OutputProvider>(arguments["out.provider"], arguments);

            var command = arguments["app.command"].ToLower().Trim();

            // Get trace name from provided, last trace, or generate one.
            string traceName = null;
            if (arguments.ContainsKey("app.traceName"))
            {
                traceName = arguments["app.traceName"];
            }
            if (traceName == null && command != "start")
            {
                traceName = dbProvider.GetLastTraceName();
            }
            else if (traceName == null && command == "start")
            {
                traceName = DateTime.Now.ToString("yyyyMMddHHmmss");
            }

            // Get the specific database object name to run against, if specified (mainly used for testing).
            if (arguments.ContainsKey("test.objectname"))
            {
                var objectName = arguments["test.objectname"];
                dbProvider.SetSpecificObjectNameForTesting(objectName);
            }

            switch (command)
            {
                case "generate":
                    var generateCommand = new GenerateOutputCommand(dbProvider, dbCodeFormatter, codeHighlighter, outputProvider, traceName);
                    generateCommand.Execute();
                    break;

                case "start":
                    var startCommand = new StartCommand(outputProvider, dbProvider, traceName);
                    startCommand.Execute();
                    break;

                case "stop":
                    var stopCommand = new StopCommand(dbProvider, outputProvider, traceName);
                    stopCommand.Execute();
                    break;

                case "finish":
                    new GenerateOutputCommand(dbProvider, dbCodeFormatter, codeHighlighter, outputProvider, traceName).Execute();
                    new StopCommand(dbProvider, outputProvider, traceName).Execute();
                    break;
            }
        }
Example #18
0
        static void Main(string[] args)
        {
            var arguments = new Dictionary<string, string>();

             // App.Config Settings
             var appSettingKeys = ConfigurationManager.AppSettings.Keys;
             for (var i = 0; i < appSettingKeys.Count; i++)
             {
            var key = appSettingKeys[i];
            arguments.AddOrUpdate(key, ConfigurationManager.AppSettings[key]);
             }

             // Manual override through CLI.
             var p = new OptionSet()
                    {
                       {
                          "<>", v =>
                                   {
                                      if (!v.StartsWith("--"))
                                         return;
                                      var split = v.Split(new[] { '=' }, 2);
                                      if (split.Length != 2)
                                         return;
                                      arguments.AddOrUpdate(split[0].TrimStart('-'), split[1]);
                                   }
                          }
                    };

             p.Parse(args);

             var loader = new AssemblyLoader();
             var dbProvider = loader.CreateTypeFromAssembly<DbProvider>(arguments["dbp.provider"], arguments);
             var dbCodeFormatter = loader.CreateTypeFromAssembly<DbTraceCodeFormatter>(arguments["tcf.provider"], arguments);
             var codeHighlighter = loader.CreateTypeFromAssembly<HighlightCodeProvider>(arguments["hcp.provider"], arguments);
             var outputProvider = loader.CreateTypeFromAssembly<OutputProvider>(arguments["out.provider"], arguments);

             switch (arguments["app.mode"].ToLower().Trim())
             {
            case "generate":
               var generateCommand = new GenerateOutputCommand(dbProvider, dbCodeFormatter, codeHighlighter, outputProvider, arguments["app.traceName"]);
               generateCommand.Execute();
               break;

            case "start":
               var startCommand = new StartCommand(outputProvider, dbProvider, arguments["app.traceName"]);
               startCommand.Execute();
               break;

            case "stop":
               {
                  var stopCommand = new StopCommand(dbProvider, outputProvider, arguments["app.traceName"]);
                  stopCommand.Execute();
               }
               break;
             }
        }
        public void Load_LoadsAssemblyFromExecutingDirectoryWhenOnlyTheAssemblyFileNameIsProvided()
        {
            var expected = GetType().Assembly;

            var sut = new AssemblyLoader(() => expected.GetName().Name + ".dll");

            var actual = sut.Load();

            Assert.Equal(expected, actual);
        }
        public void Load_LoadsAssemblyFromFile()
        {
            var expected = GetType().Assembly;

            var sut = new AssemblyLoader(() => expected.Location);

            var actual = sut.Load();

            Assert.Equal(expected, actual);
        }
        public void Loader_returns_assembly_if_assembly_is_found_at_path()
        {
            var assemblyLoader = new AssemblyLoader();

            string fullPath = Path.GetFullPath(@"assemblies\log4net.dll");
            var assembly = assemblyLoader.LoadAssembly(fullPath);

            Assert.That(assembly, Is.Not.Null);
            Assert.That(assembly.GetName().Name, Is.EqualTo("log4net"));
        }
        /// <summary>Downloads the specified XAP file.</summary>
        /// <param name="xapFileName">The name of the XAP file to download.</param>
        /// <param name="callback">Action to invoke when complete (passes back the entry-point assembly).</param>
        public static void DownloadXapFile(string xapFileName, Action<Assembly> callback)
        {
            // Setup initial conditions.
            if (DownloadCatalog == null) throw new InitializationException("The 'DownloadCatalog' has not been set. Create this an initialize it with the CompositionHost during startup.");

            // Download the XAP file.
            var loader = new AssemblyLoader(xapFileName);
            loader.Load(() =>
                            {
                                // Check for errors.
                                if (loader.Error != null)
                                {
                                    Output.Write("Failed to load XAP file: " + xapFileName);
                                    Output.Write(loader.Error);
                                    if (callback != null) callback(loader.RootAssembly);
                                    return;
                                }

                                // Register the assemblies with MEF.
                                var currentAssemblies = Deployment.Current.GetAssemblies();
                                foreach (var assembly in loader.Assemblies)
                                {
                                    try
                                    {
                                        if (currentAssemblies.Contains(assembly)) continue; // Ensure assemblies are not added more than once.
                                        DownloadCatalog.Catalogs.Add(new AssemblyCatalog(assembly));
                                    }
                                    catch (Exception error)
                                    {
                                        Output.WriteTitle(Colors.Red, "Load Failure");
                                        Output.Write(
                                            Colors.Red, 
                                            string.Format("Failed to load assembly while downloading the XAP file: '{0}'", 
                                                    xapFileName));
                                        Output.WriteException(error);
                                        break;
                                    }
                                }

                                // Finish up.
                                if (callback != null) callback(loader.RootAssembly);


                                //TEMP 
                                // Re-download with the MEF package-downloader to ensure it gets registered correctly with MEF.
                                // NB: This should get the XAP file from cache.
                                //var mefDownloader = new DeploymentCatalog(loader.XapFileName);
                                //mefDownloader.DownloadCompleted += delegate
                                //                                       {
                                //                                           // Finish up.
                                //                                           if (callback != null) callback(loader.RootAssembly);
                                //                                       };
                                //mefDownloader.DownloadAsync();
                            });
        }
Example #23
0
        public ScriptBuilder(AssemblyLoader assemblyLoader = null)
        {
            if (assemblyLoader == null)
            {
                assemblyLoader = new InteractiveAssemblyLoader();
            }

            _assemblyNamePrefix = s_globalAssemblyNamePrefix + "#" + Interlocked.Increment(ref s_engineIdDispenser).ToString();
            _collectibleCodeManager = new CollectibleCodeManager(assemblyLoader, _assemblyNamePrefix);
            _uncollectibleCodeManager = new UncollectibleCodeManager(assemblyLoader, _assemblyNamePrefix);
        }
        public void Load_LoadsAssemblyAlongWithAllDependentAssembliesCorrectly()
        {
            var sut = new AssemblyLoader(() => "FluentInstallation.TestAssembly.dll");

            var assembly = sut.Load();

            // Trigger dependent assembly by loading all types
            var types = assembly.GetTypes();

            Assert.NotEmpty(types);
        }
Example #25
0
        public void MissingDependenciesAreIgnored()
        {
            var testLoader = new TestAssemblyLoader()
                .Package("a", "1.0", that => that.Needs("x", "1.0"));

            var loader = new AssemblyLoader();
            loader.Add(testLoader);
            loader.Walk("a", new SemanticVersion("1.0"), VersionUtility.ParseFrameworkName("net45"));

            testLoader.Dependencies.ShouldBe(Dependencies(that => that
                .Needs("a", "1.0")));
        }
 public void ReflectiionLoad_AssemblyLoaded()
 {
     // Arrange.
     IAssemblyLoader assemblyLoader = new AssemblyLoader();
     var name = Assembly.GetExecutingAssembly().GetName().Name;
     // Act
     assemblyLoader.RefeflectionOnly(name);
     // Assert
     Assert.AreEqual(name, assemblyLoader.Name);
     Assert.AreEqual(true, assemblyLoader.AssemblyLoaded);
     Assert.IsNotNull(assemblyLoader.Assembly);
 }
Example #27
0
 public Check(string referencePath, string newPath, string htmlPath, string xmlPath, string ignorePath, bool verbose)
 {
     using (AssemblyLoader assemblyLoader = new AssemblyLoader())
       {
     _referenceAssembly = assemblyLoader.ReflectionOnlyLoad(referencePath);
     _newAssembly = assemblyLoader.ReflectionOnlyLoad(newPath);
       }
       _htmlStream = GetWriteStream(htmlPath);
       _xmlStream = GetWriteStream(xmlPath);
       _ignoreList = IgnoreListLoader.LoadIgnoreList(GetReadStream(ignorePath));
       _log = verbose ? (Action<string>)(System.Console.WriteLine) : s => { };
 }
 public void ReflectionLoad_EmptyString_ThrowsArgumentNullException()
 {
     // Arrange
     IAssemblyLoader assemblyLoader = new AssemblyLoader();
     // Act
     try
     {
         assemblyLoader.RefeflectionOnly("");
         Assert.Fail("No exception thrown");
     }
     catch (ArgumentNullException) { }
 }
        public void load_a_package_info_from_a_manifest_file_when_given_the_folder()
        {
            // the reader is rooted at the folder location of the main app
            var package = reader.LoadFromFolder("../../../TestPackage1".ToFullPath());

            var assemblyLoader = new AssemblyLoader(new PackagingDiagnostics());
            assemblyLoader.AssemblyFileLoader = file => Assembly.Load(File.ReadAllBytes(file));
            assemblyLoader.LoadAssembliesFromPackage(package);

            var loadedAssemblies = assemblyLoader.Assemblies.ToArray();
            loadedAssemblies.ShouldHaveCount(1);
            loadedAssemblies[0].GetName().Name.ShouldEqual("TestPackage1");
        }
Example #30
0
 static void Main(string[] args)
 {
     var assemblyName = args[0];
     var assemblyLoader = new AssemblyLoader();
     var assemblyDependencies = new AssemblyDependencies();
     IGraph<string> graph = new Graph<string>();
     AddAllDependencies(assemblyLoader, assemblyDependencies, graph, assemblyName);
     Console.WriteLine("digraph g {");
     foreach (var v in graph.Edges)
         Console.WriteLine("\"" + v.Parent + "\" -> \"" + v.Child + "\" ;");
     Console.WriteLine("}");
     Console.ReadLine();
 }
Example #31
0
 public override void PhysicsProcess(float delta)
 {
     // Can't be too certain.
     gameTiming.InSimulation = true;
     gameTiming._tickRemainderTimer.Restart();
     try
     {
         if (!gameTiming.Paused)
         {
             gameTiming.CurTick++;
             _networkManager.ProcessPackets();
             var eventArgs = new ProcessFrameEventArgs(delta);
             AssemblyLoader.BroadcastUpdate(AssemblyLoader.UpdateLevel.PreEngine, eventArgs.Elapsed);
             _timerManager.UpdateTimers(delta);
             _userInterfaceManager.Update(eventArgs);
             _stateManager.Update(eventArgs);
             AssemblyLoader.BroadcastUpdate(AssemblyLoader.UpdateLevel.PostEngine, eventArgs.Elapsed);
         }
     }
     finally
     {
         gameTiming.InSimulation = false;
     }
 }
 protected override void EnsureAssembliesLoaded()
 {
     AssemblyLoader.EnsureLoaded <Marker_EdFi_Ods_Composites_Enrollment>();
     AssemblyLoader.EnsureLoaded <Marker_EdFi_Ods_Extensions_Sample>();
     AssemblyLoader.EnsureLoaded <Marker_EdFi_Ods_Extensions_Homograph>();
 }
Example #33
0
 protected override void OnStartup(object sender, StartupEventArgs e)
 {
     AssemblyLoader.PreJitControls();
     base.DisplayRootViewFor <IShell>(null);
 }
Example #34
0
 public void FilenameFilterRegex()
 {
     Assert.True(AssemblyLoader.LoadDirectory(".", @"Test.*Module1\.dll$", false).Count == 1);
 }
 protected override IGatewayListProvider CreateGatewayListProvider(TraceLogger logger)
 {
     return(AssemblyLoader.LoadAndCreateInstance <IGatewayListProvider>(Constants.ORLEANS_ZOOKEEPER_UTILS_DLL, logger));
 }
Example #36
0
        /// <inheritdoc />
        public bool Start()
        {
            //Sets up the configMgr
            _config.LoadFromFile(_commandLine.ConfigFile);

            //Sets up Logging
            _config.RegisterCVar("log.path", "logs", CVar.ARCHIVE);
            _config.RegisterCVar("log.format", "log_%(date)s-%(time)s.txt", CVar.ARCHIVE);
            _config.RegisterCVar("log.level", LogLevel.Info, CVar.ARCHIVE);

            var logPath     = _config.GetCVar <string>("log.path");
            var logFormat   = _config.GetCVar <string>("log.format");
            var logFilename = logFormat.Replace("%(date)s", DateTime.Now.ToString("yyyyMMdd")).Replace("%(time)s", DateTime.Now.ToString("hhmmss"));
            var fullPath    = Path.Combine(logPath, logFilename);

            if (!Path.IsPathRooted(fullPath))
            {
                logPath = PathHelpers.ExecutableRelativeFile(fullPath);
            }

            fileLogHandler         = new FileLogHandler(logPath);
            _log.RootSawmill.Level = _config.GetCVar <LogLevel>("log.level");
            _log.RootSawmill.AddHandler(fileLogHandler);

            // Has to be done early because this guy's in charge of the main thread Synchronization Context.
            _taskManager.Initialize();

            LoadSettings();

            var netMan = IoCManager.Resolve <IServerNetManager>();

            try
            {
                netMan.Initialize(true);
                netMan.StartServer();
            }
            catch (Exception e)
            {
                var port = netMan.Port;
                Logger.Fatal("Unable to setup networking manager. Check port {0} is not already in use and that all binding addresses are correct!\n{1}", port, e);
                return(true);
            }

            // Set up the VFS
            _resources.Initialize();

#if RELEASE
            _resources.MountContentDirectory(@"./Resources/");
#else
            // Load from the resources dir in the repo root instead.
            // It's a debug build so this is fine.
            _resources.MountContentDirectory(@"../../Resources/");
            _resources.MountContentDirectory(@"../../../bin/Content.Server/", new ResourcePath("/Assemblies/"));
#endif

            //mount the engine content pack
            // _resources.MountContentPack(@"EngineContentPack.zip");

            //mount the default game ContentPack defined in config
            // _resources.MountDefaultContentPack();

            //identical code in game controller for client
            if (!AssemblyLoader.TryLoadAssembly <GameShared>(_resources, $"Content.Shared"))
            {
                Logger.Warning($"[ENG] Could not load any Shared DLL.");
            }

            if (!AssemblyLoader.TryLoadAssembly <GameServer>(_resources, $"Content.Server"))
            {
                Logger.Warning($"[ENG] Could not load any Server DLL.");
            }

            // HAS to happen after content gets loaded.
            // Else the content types won't be included.
            // TODO: solve this properly.
            _serializer.Initialize();

            // Initialize Tier 2 services
            _stateManager.Initialize();
            _entities.Initialize();
            IoCManager.Resolve <IChatManager>().Initialize();
            IoCManager.Resolve <IPlayerManager>().Initialize(MaxPlayers);
            _mapManager.Initialize();
            IoCManager.Resolve <IPlacementManager>().Initialize();
            IoCManager.Resolve <IViewVariablesHost>().Initialize();

            // Call Init in game assemblies.
            AssemblyLoader.BroadcastRunLevel(AssemblyLoader.RunLevel.Init);

            // because of 'reasons' this has to be called after the last assembly is loaded
            // otherwise the prototypes will be cleared
            var prototypeManager = IoCManager.Resolve <IPrototypeManager>();
            prototypeManager.LoadDirectory(new ResourcePath(@"/Prototypes"));
            prototypeManager.Resync();

            IoCManager.Resolve <ITileDefinitionManager>().Initialize();
            IoCManager.Resolve <IConsoleShell>().Initialize();
            IoCManager.Resolve <IConGroupController>().Initialize();

            AssemblyLoader.BroadcastRunLevel(AssemblyLoader.RunLevel.PostInit);

            _entities.Startup();
            IoCManager.Resolve <IStatusHost>().Start();

            return(false);
        }
Example #37
0
        private static ICollection <Assembly> GetReferencedAssemblies(this Assembly root, AssemblyLoader assemblyLoader)
        {
            List <Assembly> references = null;

            // references is created on demand, does not include root
            if (references == null)
            {
                Dictionary <string, Assembly> dicAssemblies = new Dictionary <string, Assembly>();
                foreach (AssemblyName a in root.GetReferencedAssemblies())
                {
                    try
                    {
                        if (dicAssemblies.ContainsKey(a.FullName))
                        {
                            continue;
                        }

                        Assembly assem = Assembly.Load(a);

                        if (assem != null)
                        {
                            dicAssemblies.Add(a.FullName, assem);
                        }
                    }
                    catch (AssemblyLoaderException)
                    {
                    }
                }

                //needed at design time for non-.NetFramework assemblies
                if (assemblyLoader != null)
                {
                    foreach (AssemblyName a in root.GetReferencedAssemblies())
                    {
                        if (dicAssemblies.ContainsKey(a.FullName))
                        {
                            continue;
                        }

                        try
                        {
                            Assembly assem = assemblyLoader.LoadAssembly(a);
                            if (assem != null)
                            {
                                dicAssemblies.Add(a.FullName, assem);
                            }
                        }
                        catch (AssemblyLoaderException)
                        {
                        }
                    }

                    //Add mscorlib types if the assembly is not a .NetFramework assembly
                    if (!root.IsNetFrameworkAssembly() && !dicAssemblies.ContainsKey(typeof(string).Assembly.FullName))
                    {
                        dicAssemblies.Add(typeof(string).Assembly.FullName, typeof(string).Assembly);
                    }
                }

                references = dicAssemblies.Values.ToList();
            }
            return(references);
        }
Example #38
0
        internal async Task <Strategy> RunStrategyAsync(Strategy strategy, string localPath)
        {
            ITradeStrategy tradeStrategy = null;

            try
            {
                Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Loading {strategy.Name}");

                var dependencies = GetAssemblies(localPath);

                var     assemblyLoader = new AssemblyLoader(localPath, dependencies);
                var     assembly       = assemblyLoader.LoadFromMemoryStream(Path.Combine(localPath, strategy.TargetAssembly));
                var     type           = assembly.GetType(strategy.TargetType);
                dynamic obj            = Activator.CreateInstance(type);

                tradeStrategy = (ITradeStrategy)obj;

                tradeStrategy.StrategyNotificationEvent       += StrategyNotificationEvent;
                tradeStrategy.StrategyAccountInfoEvent        += StrategyAccountInfoEvent;
                tradeStrategy.StrategyOrderBookEvent          += StrategyOrderBookEvent;
                tradeStrategy.StrategyTradeEvent              += StrategyTradeEvent;
                tradeStrategy.StrategyStatisticsEvent         += StrategyStatisticsEvent;
                tradeStrategy.StrategyCandlesticksEvent       += StrategyCandlesticksEvent;
                tradeStrategy.StrategyParameterUpdateEvent    += StrategyParameterUpdateEvent;
                tradeStrategy.StrategyCustomNotificationEvent += StrategyCustomNotificationEvent;

                tradeStrategy.SetStrategy(strategy);

                strategy.Status = StrategyStatus.Running;

                if (tradeStrategyCacheManager.TryAddTradeStrategy(strategy.Name, tradeStrategy))
                {
                    Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Subscribing {strategy.Name}");

                    await subscriptionsCacheManager.Subscribe(strategy, tradeStrategy).ConfigureAwait(false);

                    Notify(NotificationLevel.Information, NotificationEventId.RunStrategyAsync, strategy, $"Running {strategy.Name}");

                    var result = await tradeStrategy.RunAsync(cancellationToken).ConfigureAwait(false);

                    if (!tradeStrategyCacheManager.TryRemoveTradeStrategy(strategy.Name, out ITradeStrategy ts))
                    {
                        Notify(NotificationLevel.Error, NotificationEventId.RunStrategyAsync, strategy, $"Failed to remove {strategy.Name} from the cache manager.");
                    }
                }
                else
                {
                    Notify(NotificationLevel.Error, NotificationEventId.RunStrategyAsync, strategy, $"Failed to add {strategy.Name} to the cache manager.");
                }
            }
            finally
            {
                if (tradeStrategy != null)
                {
                    subscriptionsCacheManager.Unsubscribe(strategy, tradeStrategy);

                    tradeStrategy.StrategyNotificationEvent       -= StrategyNotificationEvent;
                    tradeStrategy.StrategyAccountInfoEvent        -= StrategyAccountInfoEvent;
                    tradeStrategy.StrategyOrderBookEvent          -= StrategyOrderBookEvent;
                    tradeStrategy.StrategyTradeEvent              -= StrategyTradeEvent;
                    tradeStrategy.StrategyParameterUpdateEvent    -= StrategyParameterUpdateEvent;
                    tradeStrategy.StrategyCustomNotificationEvent -= StrategyCustomNotificationEvent;
                }

                // TODO: Unload target assembly and it's dependencies from memory and delete them.
            }

            return(strategy);
        }
        private IEnumerable <java.net.URL> GetResourcesImpl(string unmangledName, bool getFromDelegates)
        {
            if (ReflectUtil.IsDynamicAssembly(assemblyLoader.Assembly))
            {
                yield break;
            }
#if !FIRST_PASS
            java.util.Enumeration urls = assemblyLoader.FindResources(unmangledName);
            while (urls.hasMoreElements())
            {
                yield return((java.net.URL)urls.nextElement());
            }
#endif
            string name = JVM.MangleResourceName(unmangledName);
            if (assemblyLoader.Assembly.GetManifestResourceInfo(name) != null)
            {
                yield return(MakeResourceURL(assemblyLoader.Assembly, name));
            }
            LazyInitExports();
            if (exports != null)
            {
                List <int> assemblies;
                if (exports.TryGetValue(JVM.PersistableHash(unmangledName), out assemblies))
                {
                    foreach (int index in assemblies)
                    {
                        AssemblyLoader loader = exportedAssemblies[index];
                        if (loader == null)
                        {
                            Assembly asm = LoadAssemblyOrClearName(ref exportedAssemblyNames[index], true);
                            if (asm == null)
                            {
                                continue;
                            }
                            loader = exportedAssemblies[index] = GetLoaderForExportedAssembly(asm);
                        }
#if !FIRST_PASS
                        urls = loader.FindResources(unmangledName);
                        while (urls.hasMoreElements())
                        {
                            yield return((java.net.URL)urls.nextElement());
                        }
#endif
                        if (loader.Assembly.GetManifestResourceInfo(name) != null)
                        {
                            yield return(MakeResourceURL(loader.Assembly, name));
                        }
                    }
                }
            }
            if (!getFromDelegates)
            {
                yield break;
            }
            for (int i = 0; i < delegates.Length; i++)
            {
                if (delegates[i] == null)
                {
                    Assembly asm = LoadAssemblyOrClearName(ref references[i], false);
                    if (asm != null)
                    {
                        delegates[i] = AssemblyClassLoader.FromAssembly(asm);
                    }
                }
                if (delegates[i] != null)
                {
                    foreach (java.net.URL url in delegates[i].FindResources(unmangledName))
                    {
                        yield return(url);
                    }
                }
            }
            if (!assemblyLoader.HasJavaModule)
            {
                foreach (java.net.URL url in GetBootstrapClassLoader().FindResources(unmangledName))
                {
                    yield return(url);
                }
            }
        }
Example #40
0
 public WyamFolderNuGetProject(IFileSystem fileSystem, AssemblyLoader assemblyLoader, NuGetFramework currentFramework, string root) : base(root)
 {
     _fileSystem       = fileSystem;
     _assemblyLoader   = assemblyLoader;
     _currentFramework = currentFramework;
 }
Example #41
0
 public SchemaGenerator(List <string> dlls)
 {
     _assemblies = AssemblyLoader.Load(dlls);
 }
Example #42
0
 public void FilenameFilter()
 {
     Assert.True(AssemblyLoader.LoadDirectory(".", "*.Module1.dll").Count == 1);
 }
Example #43
0
 public void FilenameFilterRegexIgnoreCaseNoMatch()
 {
     Assert.True(AssemblyLoader.LoadDirectory(".", "test.*module1XXX", true).Count == 0);
 }
Example #44
0
 public void FilenameFilterRegexIgnoreCase()
 {
     Assert.True(AssemblyLoader.LoadDirectory(".", @"test.*module1.*\.dll$", true).Count == 1);
 }
Example #45
0
 public void Assembly(string assemblyName)
 {
     Assembly(AssemblyLoader.ByName(assemblyName));
 }
Example #46
0
 /// <summary>
 /// Loads assemblies that are not explicitly referenced by the metadata, yet were referenced by the compiler
 /// when the assembly was being built.
 /// </summary>
 internal virtual void LoadCompileTimeReferencedAssemblies(AssemblyLoader /*!*/ loader)
 {
 }
Example #47
0
 public void Generate(AssemblyLoader assemblyLoader, CodeGenerator codeGenerator)
 {
     throw new NotImplementedException();
 }
Example #48
0
 static MyPlugin()
 {
     AssemblyLoader.RegisterAssemblyLoader();
 }
Example #49
0
 protected MemberBase(AssemblyLoader loader, TableId table, int index)
 {
     Loader        = loader;
     MetadataToken = SimpleIndex.MakeToken(table, index + 1);
 }
Example #50
0
 public MemberRefTable(AssemblyLoader loader)
 {
     _loader = loader;
 }
Example #51
0
        private void ScanForComponents(MountPointScanSource source, bool allowDevInstall)
        {
            bool isCopiedIntoContentDirectory;

            if (!source.MountPoint.Root.EnumerateFiles("*.dll", SearchOption.AllDirectories).Any())
            {
                return;
            }

            string actualScanPath;

            if (!source.ShouldStayInOriginalLocation)
            {
                if (!TryCopyForNonFileSystemBasedMountPoints(source.MountPoint, source.Location, _paths.User.Content, true, out actualScanPath))
                {
                    return;
                }

                isCopiedIntoContentDirectory = true;
            }
            else
            {
                if (!allowDevInstall)
                {
                    // TODO: localize this message
                    _environmentSettings.Host.LogDiagnosticMessage("Installing local .dll files is not a standard supported scenario. Either package it in a .zip or .nupkg, or install it using '--dev:install'.", "Install");
                    // dont allow .dlls to be installed from a file unless the debugging flag is set.
                    return;
                }

                actualScanPath = source.Location;
                isCopiedIntoContentDirectory = false;
            }

            foreach (KeyValuePair <string, Assembly> asm in AssemblyLoader.LoadAllFromPath(_paths, out IEnumerable <string> failures, actualScanPath))
            {
                try
                {
                    IReadOnlyList <Type> typeList = asm.Value.GetTypes();

                    if (typeList.Count > 0)
                    {
                        // TODO: figure out what to do with probing path registration when components are not found.
                        // They need to be registered for dependent assemblies, not just when an assembly can be loaded.
                        // We'll need to figure out how to know when that is.
                        _environmentSettings.SettingsLoader.Components.RegisterMany(typeList);
                        _environmentSettings.SettingsLoader.AddProbingPath(Path.GetDirectoryName(asm.Key));
                        source.FoundComponents = true;
                    }
                }
                catch
                {
                    // exceptions here are ok, due to dependency errors, etc.
                }
            }

            if (!source.FoundComponents && isCopiedIntoContentDirectory)
            {
                try
                {
                    // The source was copied to content and then scanned for components.
                    // Nothing was found, and this is a copy that now has no use, so delete it.
                    // Note: no mount point was created for this copy, so no need to release it.
                    _environmentSettings.Host.FileSystem.DirectoryDelete(actualScanPath, true);
                }
                catch (Exception ex)
                {
                    _environmentSettings.Host.LogDiagnosticMessage($"During ScanForComponents() cleanup, couldn't delete source copied into the content dir: {actualScanPath}", "Install");
                    _environmentSettings.Host.LogDiagnosticMessage($"\tError: {ex.Message}", "Install");
                }
            }
        }
 protected override IMembershipTable CreateMembershipTable(TraceLogger logger)
 {
     return(AssemblyLoader.LoadAndCreateInstance <IMembershipTable>(Constants.ORLEANS_ZOOKEEPER_UTILS_DLL, logger));
 }
        void RunApiCheck(string packageName)
        {
            Console.WriteLine(">>>> Checking Api breaking change for: " + packageName + Environment.NewLine);

            var refAssemblyPath = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\Resource\refAssemblies\" + packageName + ".dll");
            var devAssemblyPath = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\Resource\devAssemblies\" + packageName + ".dll");
            var reportPath      = Path.Combine(Directory.GetCurrentDirectory(), @"..\..\..\Resource\reports\" + packageName + ".report.xml");
            var sb      = new StringBuilder();
            var succeed = true;

            try
            {
                using (AssemblyLoader assemblyLoader = new AssemblyLoader())
                {
                    // load assemblies
                    Assembly refAssembly = assemblyLoader.ReflectionOnlyLoad(refAssemblyPath);
                    Assembly devAssembly = assemblyLoader.ReflectionOnlyLoad(devAssemblyPath);

                    // configuration
                    ComparerConfiguration configuration = new ComparerConfiguration();
                    configuration.Severities.ParameterNameChanged = Severity.Warning;
                    configuration.Severities.AssemblyNameChanged  = Severity.Hint;
                    foreach (var allowedBreakingChange in _allowedApiBreakingChanges)
                    {
                        configuration.Ignore.Add(allowedBreakingChange);
                    }

                    // compare assemblies and write xml report
                    using (var stream = new FileStream(reportPath, FileMode.Create))
                    {
                        ApiComparer.CreateInstance(refAssembly, devAssembly)
                        .WithComparerConfiguration(configuration)
                        .WithDetailLogging(s => Console.WriteLine(s))
                        .WithInfoLogging(s => Console.WriteLine(s))
                        .WithXmlReport(stream)
                        .Build()
                        .CheckApi();
                    }
                }

                var scenarioList = new List <string>()
                {
                    "ChangedAttribute", "ChangedElement", "RemovedElement"
                };

                // check the scenarios that we might have a breaking change
                foreach (var scenario in scenarioList)
                {
                    XElement doc = XElement.Load(reportPath);

                    foreach (XElement change in doc.Descendants(scenario))
                    {
                        if (change.Attribute("Severity") != null && "Error".Equals(change.Attribute("Severity").Value))
                        {
                            succeed = false;

                            // append the parent, for instance,
                            if (change.Parent != null)
                            {
                                sb.AppendLine($"In {change.Parent.Attribute("Context").Value} : {change.Parent.Attribute("Name").Value}");
                            }

                            sb.AppendLine(change.ToString());
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new ApiChangeException("Assembly comparison failed.", ex);
            }

            if (!succeed)
            {
                throw new ApiChangeException($"The following breaking changes are found: {Environment.NewLine} {sb.ToString()}");
            }
        }
Example #54
0
 public void FilenameFilterNoMatch()
 {
     Assert.True(AssemblyLoader.LoadDirectory(".", "XXX").Count == 0);
 }
Example #55
0
 public void Setup()
 {
     var loader = new AssemblyLoader();
 }
Example #56
0
 public EmbeddedResourceStreamLoader(AssemblyLoader assemblyLoader)
 {
     this.assemblyLoader = assemblyLoader;
 }
Example #57
0
        /// <summary>Load and hook up the given mods.</summary>
        /// <param name="mods">The mods to load.</param>
        /// <param name="jsonHelper">The JSON helper with which to read mods' JSON files.</param>
        /// <param name="contentManager">The content manager to use for mod content.</param>
        private void LoadMods(IModMetadata[] mods, JsonHelper jsonHelper, SContentManager contentManager)
        {
            this.Monitor.Log("Loading mods...", LogLevel.Trace);

            // load mod assemblies
            IDictionary <IModMetadata, string> skippedMods = new Dictionary <IModMetadata, string>();

            {
                void TrackSkip(IModMetadata mod, string reasonPhrase) => skippedMods[mod] = reasonPhrase;

                AssemblyLoader modAssemblyLoader = new AssemblyLoader(Constants.TargetPlatform, this.Monitor, this.Settings.DeveloperMode);
                AppDomain.CurrentDomain.AssemblyResolve += (sender, e) => modAssemblyLoader.ResolveAssembly(e.Name);
                foreach (IModMetadata metadata in mods)
                {
                    // get basic info
                    IManifest manifest     = metadata.Manifest;
                    string    assemblyPath = metadata.Manifest?.EntryDll != null
                        ? Path.Combine(metadata.DirectoryPath, metadata.Manifest.EntryDll)
                        : null;

                    this.Monitor.Log(assemblyPath != null
                        ? $"Loading {metadata.DisplayName} from {assemblyPath.Replace(Constants.ModPath, "").TrimStart(Path.DirectorySeparatorChar)}..."
                        : $"Loading {metadata.DisplayName}...", LogLevel.Trace);

                    // validate status
                    if (metadata.Status == ModMetadataStatus.Failed)
                    {
                        this.Monitor.Log($"   Failed: {metadata.Error}", LogLevel.Trace);
                        TrackSkip(metadata, metadata.Error);
                        continue;
                    }

                    // preprocess & load mod assembly
                    Assembly modAssembly;
                    try
                    {
                        modAssembly = modAssemblyLoader.Load(metadata, assemblyPath, assumeCompatible: metadata.DataRecord?.GetCompatibility(metadata.Manifest.Version)?.Status == ModStatus.AssumeCompatible);
                    }
                    catch (IncompatibleInstructionException ex)
                    {
                        TrackSkip(metadata, $"it's no longer compatible (detected {ex.NounPhrase}). Please check for a newer version of the mod.");
                        continue;
                    }
                    catch (SAssemblyLoadFailedException ex)
                    {
                        TrackSkip(metadata, $"its DLL '{manifest.EntryDll}' couldn't be loaded: {ex.Message}");
                        continue;
                    }
                    catch (Exception ex)
                    {
                        TrackSkip(metadata, $"its DLL '{manifest.EntryDll}' couldn't be loaded:\n{ex.GetLogSummary()}");
                        continue;
                    }

                    // validate assembly
                    try
                    {
                        int modEntries = modAssembly.DefinedTypes.Count(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract);
                        if (modEntries == 0)
                        {
                            TrackSkip(metadata, $"its DLL has no '{nameof(Mod)}' subclass.");
                            continue;
                        }
                        if (modEntries > 1)
                        {
                            TrackSkip(metadata, $"its DLL contains multiple '{nameof(Mod)}' subclasses.");
                            continue;
                        }
                    }
                    catch (Exception ex)
                    {
                        TrackSkip(metadata, $"its DLL couldn't be loaded:\n{ex.GetLogSummary()}");
                        continue;
                    }

                    // initialise mod
                    try
                    {
                        // get implementation
                        TypeInfo modEntryType = modAssembly.DefinedTypes.First(type => typeof(Mod).IsAssignableFrom(type) && !type.IsAbstract);
                        Mod      mod          = (Mod)modAssembly.CreateInstance(modEntryType.ToString());
                        if (mod == null)
                        {
                            TrackSkip(metadata, "its entry class couldn't be instantiated.");
                            continue;
                        }

                        // inject data
                        {
                            IMonitor           monitor           = this.GetSecondaryMonitor(metadata.DisplayName);
                            ICommandHelper     commandHelper     = new CommandHelper(manifest.UniqueID, metadata.DisplayName, this.CommandManager);
                            IContentHelper     contentHelper     = new ContentHelper(contentManager, metadata.DirectoryPath, manifest.UniqueID, metadata.DisplayName, monitor);
                            IReflectionHelper  reflectionHelper  = new ReflectionHelper(manifest.UniqueID, metadata.DisplayName, this.Reflection);
                            IModRegistry       modRegistryHelper = new ModRegistryHelper(manifest.UniqueID, this.ModRegistry);
                            ITranslationHelper translationHelper = new TranslationHelper(manifest.UniqueID, manifest.Name, contentManager.GetLocale(), contentManager.GetCurrentLanguage());

                            mod.ModManifest = manifest;
                            mod.Helper      = new ModHelper(manifest.UniqueID, metadata.DirectoryPath, jsonHelper, contentHelper, commandHelper, modRegistryHelper, reflectionHelper, translationHelper);
                            mod.Monitor     = monitor;
                        }

                        // track mod
                        metadata.SetMod(mod);
                        this.ModRegistry.Add(metadata);
                    }
                    catch (Exception ex)
                    {
                        TrackSkip(metadata, $"initialisation failed:\n{ex.GetLogSummary()}");
                    }
                }
            }
            IModMetadata[] loadedMods = this.ModRegistry.GetMods().ToArray();

            // log skipped mods
            this.Monitor.Newline();
            if (skippedMods.Any())
            {
                this.Monitor.Log($"Skipped {skippedMods.Count} mods:", LogLevel.Error);
                foreach (var pair in skippedMods.OrderBy(p => p.Key.DisplayName))
                {
                    IModMetadata mod    = pair.Key;
                    string       reason = pair.Value;

                    if (mod.Manifest?.Version != null)
                    {
                        this.Monitor.Log($"   {mod.DisplayName} {mod.Manifest.Version} because {reason}", LogLevel.Error);
                    }
                    else
                    {
                        this.Monitor.Log($"   {mod.DisplayName} because {reason}", LogLevel.Error);
                    }
                }
                this.Monitor.Newline();
            }

            // log loaded mods
            this.Monitor.Log($"Loaded {loadedMods.Length} mods" + (loadedMods.Length > 0 ? ":" : "."), LogLevel.Info);
            foreach (IModMetadata metadata in loadedMods.OrderBy(p => p.DisplayName))
            {
                IManifest manifest = metadata.Manifest;
                this.Monitor.Log(
                    $"   {metadata.DisplayName} {manifest.Version}"
                    + (!string.IsNullOrWhiteSpace(manifest.Author) ? $" by {manifest.Author}" : "")
                    + (!string.IsNullOrWhiteSpace(manifest.Description) ? $" | {manifest.Description}" : ""),
                    LogLevel.Info
                    );
            }
            this.Monitor.Newline();

            // initialise translations
            this.ReloadTranslations();

            // initialise loaded mods
            foreach (IModMetadata metadata in loadedMods)
            {
                // add interceptors
                if (metadata.Mod.Helper.Content is ContentHelper helper)
                {
                    this.ContentManager.Editors[metadata] = helper.ObservableAssetEditors;
                    this.ContentManager.Loaders[metadata] = helper.ObservableAssetLoaders;
                }

                // call entry method
                try
                {
                    IMod mod = metadata.Mod;
                    mod.Entry(mod.Helper);
                }
                catch (Exception ex)
                {
                    this.Monitor.Log($"{metadata.DisplayName} failed on entry and might not work correctly. Technical details:\n{ex.GetLogSummary()}", LogLevel.Error);
                }
            }

            // invalidate cache entries when needed
            // (These listeners are registered after Entry to avoid repeatedly reloading assets as mods initialise.)
            foreach (IModMetadata metadata in loadedMods)
            {
                if (metadata.Mod.Helper.Content is ContentHelper helper)
                {
                    helper.ObservableAssetEditors.CollectionChanged += (sender, e) =>
                    {
                        if (e.NewItems.Count > 0)
                        {
                            this.Monitor.Log("Invalidating cache entries for new asset editors...", LogLevel.Trace);
                            this.ContentManager.InvalidateCacheFor(e.NewItems.Cast <IAssetEditor>().ToArray(), new IAssetLoader[0]);
                        }
                    };
                    helper.ObservableAssetLoaders.CollectionChanged += (sender, e) =>
                    {
                        if (e.NewItems.Count > 0)
                        {
                            this.Monitor.Log("Invalidating cache entries for new asset loaders...", LogLevel.Trace);
                            this.ContentManager.InvalidateCacheFor(new IAssetEditor[0], e.NewItems.Cast <IAssetLoader>().ToArray());
                        }
                    };
                }
            }

            // reset cache now if any editors or loaders were added during entry
            IAssetEditor[] editors = loadedMods.SelectMany(p => p.Mod.Helper.Content.AssetEditors).ToArray();
            IAssetLoader[] loaders = loadedMods.SelectMany(p => p.Mod.Helper.Content.AssetLoaders).ToArray();
            if (editors.Any() || loaders.Any())
            {
                this.Monitor.Log("Invalidating cached assets for new editors & loaders...", LogLevel.Trace);
                this.ContentManager.InvalidateCacheFor(editors, loaders);
            }
        }
Example #58
0
 private List <Type> GetAllDefinedApi()
 {
     return(AssemblyLoader.LoadTypeByInterface(typeof(IApi)));
 }
 protected WorkaroundBootstrapper(string[] args, IAbsoluteDirectoryPath rootPath) : base(args, rootPath)
 {
     _rootPath = rootPath;
     asl       = new AssemblyLoader(_rootPath.ToString());
 }
Example #60
0
 protected MetadataTable(AssemblyLoader loader)
 {
     Loader = loader;
 }