コード例 #1
0
        public void MustCorrectlyForwardCalls()
        {
            var exception       = new Exception();
            var loggerMock      = new Mock <ILogger>();
            var logObserverMock = new Mock <ILogObserver>();
            var logText         = new LogText("Log text");
            var sut             = new ModuleLogger(loggerMock.Object, nameof(ModuleLoggerTests));

            loggerMock.SetupGet(l => l.LogLevel).Returns(LogLevel.Error);

            sut.LogLevel = LogLevel.Debug;
            sut.Debug("Debug");
            sut.Info("Info");
            sut.Warn("Warning");
            sut.Error("Error");
            sut.Error("Error", exception);
            sut.Log("Raw text");
            sut.Subscribe(logObserverMock.Object);
            sut.Unsubscribe(logObserverMock.Object);
            sut.GetLog();

            loggerMock.VerifySet(l => l.LogLevel = LogLevel.Debug, Times.Once);
            loggerMock.Verify(l => l.Debug($"[{nameof(ModuleLoggerTests)}] Debug"), Times.Once);
            loggerMock.Verify(l => l.Info($"[{nameof(ModuleLoggerTests)}] Info"), Times.Once);
            loggerMock.Verify(l => l.Warn($"[{nameof(ModuleLoggerTests)}] Warning"), Times.Once);
            loggerMock.Verify(l => l.Error($"[{nameof(ModuleLoggerTests)}] Error"), Times.Once);
            loggerMock.Verify(l => l.Error($"[{nameof(ModuleLoggerTests)}] Error", exception), Times.Once);
            loggerMock.Verify(l => l.Log("Raw text"), Times.Once);
            loggerMock.Verify(l => l.Subscribe(logObserverMock.Object), Times.Once);
            loggerMock.Verify(l => l.Unsubscribe(logObserverMock.Object), Times.Once);
            loggerMock.Verify(l => l.GetLog(), Times.Once);

            Assert.AreEqual(LogLevel.Error, sut.LogLevel);
        }
コード例 #2
0
ファイル: Client.cs プロジェクト: pashcovich/mptanks2d
        public NetClient(string connection, ushort port, ILogger logger = null,
                         string password = null, bool connectOnInit = true)
        {
            if (logger != null)
            {
                Logger = new ModuleLogger(logger, "CLIENT");
            }
            else
            {
                Logger = new NullLogger();
            }

            MessageProcessor = new ClientNetworkProcessor(this);
            GameInstance     = new NetworkedGame(null);
            Chat             = new Chat.ChatClient(this);

            Host     = connection;
            Port     = port;
            Password = password;

            NetworkClient = new Lidgren.Network.NetClient(
                new Lidgren.Network.NetPeerConfiguration("MPTANKS")
            {
                ConnectionTimeout  = 15,
                AutoFlushSendQueue = false
            });
            SetupNetwork();

            if (connectOnInit)
            {
                Connect();
            }
        }
コード例 #3
0
        public GameCoreRenderer(Game client, string[] assetPaths, int[] teamsToDisplayFor, ILogger logger)
        {
            Client = client;
            TeamsToDisplayLightsFor = teamsToDisplayFor;

            Finder = new AssetFinder(this, new AssetCache(client.GraphicsDevice,
                                                          new AssetLoader(this, client.GraphicsDevice, new AssetResolver(assetPaths, this)),
                                                          this));

            Logger = new ModuleLogger(logger, "Renderer");

            _fxaaRenderer = new FXAARenderer(
                this, client.GraphicsDevice, client.Content, Finder);
            FXAAEnabled   = true;
            _gameRenderer = new GameWorldRenderer(
                this, client.GraphicsDevice, client.Content, Finder);

            _renderers.Add(new MapBackgroundRenderer(
                               this, client.GraphicsDevice, client.Content, Finder));
            _renderers.Add(_gameRenderer);
            //For another time...
            //_renderers.Add(new LightRenderer(
            //    this, client.GraphicsDevice, client.Content, Finder));
            _renderers.Add(_fxaaRenderer);
        }
コード例 #4
0
        /// <summary>
        /// Creates a new GameCore instance.
        /// </summary>
        /// <param name="logger"></param>
        /// <param name="gamemode"></param>
        /// <param name="skipInit">Whether to skip the customary X second init and gamemode setup</param>
        public GameCore(ILogger logger, Gamemodes.Gamemode gamemode, ModAssetInfo map, EngineSettings settings = null)
        {
            if (Logger == null)
            {
                Logger = new NullLogger();
            }
            else
            {
                Logger = new ModuleLogger(logger, "Game");
            }
            if (settings == null)
            {
                Settings = new EngineSettings();
            }
            else
            {
                Settings = settings;
            }

            //Set up the game mode internally
            Gamemode = gamemode;
            Gamemode.SetGame(this);

            Map = Maps.Map.LoadMap(map, this);

            InitializeGame();
        }
コード例 #5
0
ファイル: Module.cs プロジェクト: mmisztal1980/Nx
        public override void Load()
        {
            ModuleLogger = this.Kernel.Get <ILogFactory>().CreateLogger(string.Format(CultureInfo.InvariantCulture, "NxModule:{0}", Name));

            ModuleLogger.Info("Loading...");
            OnLoading();
        }
コード例 #6
0
        private IOperation BuildBrowserOperation()
        {
            var moduleLogger = new ModuleLogger(logger, nameof(BrowserApplication));
            var browser      = new BrowserApplication(configuration.AppConfig, configuration.Settings.Browser, messageBox, moduleLogger, text, uiFactory);
            var browserInfo  = new BrowserApplicationInfo();
            var operation    = new BrowserOperation(actionCenter, browser, logger, taskbar, uiFactory);

            this.browser = browser;

            return(operation);
        }
コード例 #7
0
        public void MustCorrectlyClone()
        {
            var loggerMock = new Mock <ILogger>();
            var sut        = new ModuleLogger(loggerMock.Object, nameof(ModuleLoggerTests));
            var clone      = sut.CloneFor("blubb");

            sut.Debug("Debug");
            clone.Debug("Debug");

            loggerMock.Verify(l => l.Debug($"[{nameof(ModuleLoggerTests)}] Debug"), Times.Once);
            loggerMock.Verify(l => l.Debug($"[blubb] Debug"), Times.Once);
        }
コード例 #8
0
        internal void CreateNewInstanceInvoke(string startUrl = null)
        {
            var id             = ++instanceIdCounter;
            var isMainInstance = instances.Count == 0;
            var numWindows     = instances.Count;
            var instanceLogger = new ModuleLogger(logger, nameof(MainWindow));
            var instance       = new BrowserApplicationInstance(appSettings, messageBox, id, isMainInstance, numWindows, startUrl, instanceLogger, text);

            instance.PopupRequested       += Instance_PopupRequested;
            instance.TerminationRequested += Instance_TerminationRequested;
            instance.Terminated           += Instance_Terminated;

            instance.Activate();
            instances.Add(instance);
            logger.Info($"Created browser instance {instance.Id}.");
            WindowsChanged?.Invoke();
        }
コード例 #9
0
        public BrowserApplicationInstance(
            AppSettings appSettings,
            IMessageBox messageBox,
            int id,
            bool isMainInstance,
            int numWindows,
            string startUrl,
            IModuleLogger logger,
            IText text)
        {
            this.appSettings                         = appSettings;
            this.messageBox                          = messageBox;
            this.Id                                  = id;
            this.isMainInstance                      = isMainInstance;
            this.logger                              = logger;
            this.text                                = text;
            this.startUrl                            = startUrl;
            this.settings                            = new BrowserSettings();
            settings.QuitUrl                         = appSettings.QuitUrl;
            settings.DownloadDirectory               = appSettings.DownloadDirectory;
            settings.AllowDownloads                  = true;
            settings.MainWindow.AllowReloading       = appSettings.AllowReload;
            settings.AdditionalWindow.AllowReloading = appSettings.AllowReload;

            var instanceLogger = new ModuleLogger(logger, nameof(MainWindow));

            window = new MainWindow(appSettings, settings, messageBox, id, isMainInstance, numWindows, startUrl, instanceLogger, text);
            window.TerminationRequested += () => TerminationRequested?.Invoke();
            window.IconChanged          += (i) => IconChanged?.Invoke(i);

            Handle = window.Handle;
            Icon   = new BrowserIconResource();

            window.Closing        += Control_Closing;
            window.TitleChanged   += Control_TitleChanged;
            window.PopupRequested += Control_PopupRequested;
        }
コード例 #10
0
        private void SetupCommands(CommandDispatcher dispatcher)
        {
            ModuleLogger.Init(logger, gui);

            var minimumFee = this.mempool != null ? mempool.MinimumFee : 1;

            dispatcher.RegisterCommand("quit", "Stops the node and exits", (args) => Terminate());

            if (gui != null)
            {
                dispatcher.RegisterCommand("gui.log", "Switches the gui to log view", (args) => gui.ShowLog(args));
                dispatcher.RegisterCommand("gui.graph", "Switches the gui to graph view", (args) => gui.ShowGraph(args));
            }

            dispatcher.RegisterCommand("help", "Lists available commands", (args) => dispatcher.Commands.ToList().ForEach(x => logger.Message($"{x.Name}\t{x.Description}")));

            foreach (var method in nexusApi.Methods)
            {
                dispatcher.RegisterCommand("api." + method.Name, "API CALL", (args) => ExecuteAPI(method.Name, args));
            }

            dispatcher.RegisterCommand("script.assemble", "Assembles a .asm file into Phantasma VM script format",
                                       (args) => ScriptModule.AssembleFile(args));

            dispatcher.RegisterCommand("script.disassemble", $"Disassembles a {ScriptFormat.Extension} file into readable Phantasma assembly",
                                       (args) => ScriptModule.DisassembleFile(args));

            dispatcher.RegisterCommand("script.compile", "Compiles a .sol file into Phantasma VM script format",
                                       (args) => ScriptModule.CompileFile(args));

            dispatcher.RegisterCommand("wallet.open", "Opens a wallet from a WIF key",
                                       (args) => WalletModule.Open(args));

            dispatcher.RegisterCommand("wallet.create", "Creates new a wallet",
                                       (args) => WalletModule.Create(args));

            dispatcher.RegisterCommand("wallet.balance", "Shows the current wallet balance",
                                       (args) => WalletModule.Balance(nexusApi, restPort, neoScanAPI, args));

            dispatcher.RegisterCommand("wallet.transfer", "Generates a new transfer transaction",
                                       (args) => WalletModule.Transfer(nexusApi, minimumFee, neoAPI, args));

            dispatcher.RegisterCommand("wallet.stake", $"Stakes {DomainSettings.StakingTokenSymbol}",
                                       (args) => WalletModule.Stake(nexusApi, args));

            dispatcher.RegisterCommand("wallet.airdrop", "Does a batch transfer from a .csv",
                                       (args) => WalletModule.Airdrop(args, nexusApi, minimumFee));

            dispatcher.RegisterCommand("wallet.migrate", "Migrates a validator to another address ",
                                       (args) =>
            {
                WalletModule.Migrate(args, nexusApi, minimumFee);
                if (mempool != null)
                {
                    mempool.SetKeys(WalletModule.Keys);
                }
            });

            dispatcher.RegisterCommand("file.upload", "Uploads a file into Phantasma",
                                       (args) => FileModule.Upload(WalletModule.Keys, nexusApi, args));

            dispatcher.RegisterCommand("oracle.read", "Read transaction from oracle",
                                       (args) =>
            {
                var hash   = Hash.Parse(args[0]);
                var reader = nexus.CreateOracleReader();
                var tx     = reader.ReadTransaction("neo", "neo", hash);
                logger.Message(tx.Transfers[0].interopAddress.Text);
            });

            if (mempool != null)
            {
                dispatcher.RegisterCommand("mempool.list", "Shows mempool pending transaction list",
                                           (args) =>
                {
                    var txs = mempool.GetTransactions();
                    foreach (var tx in txs)
                    {
                        logger.Message(tx.ToString());
                    }
                });
            }

            dispatcher.RegisterCommand("neo.deploy", "Deploys a contract into NEO",
                                       (args) =>
            {
                if (args.Length != 2)
                {
                    throw new CommandException("Expected: WIF avm_path");
                }
                var avmPath = args[1];
                if (!File.Exists(avmPath))
                {
                    throw new CommandException("path for avm not found");
                }

                var keys       = Neo.Core.NeoKeys.FromWIF(args[0]);
                var script     = File.ReadAllBytes(avmPath);
                var scriptHash = Neo.Utils.CryptoUtils.ToScriptHash(script);
                logger.Message("Deploying contract " + scriptHash);

                try
                {
                    var tx = neoAPI.DeployContract(keys, script, Base16.Decode("0710"), 0x05, Neo.Core.ContractProperties.HasStorage | Neo.Core.ContractProperties.Payable, "Contract", "1.0", "Author", "*****@*****.**", "Description");
                    logger.Success("Deployed contract via transaction: " + tx.Hash);
                }
                catch (Exception e)
                {
                    logger.Error("Failed to deploy contract: " + e.Message);
                }
            });

            dispatcher.RegisterCommand("exit", "Terminates the node", (args) =>
            {
                this.Terminate();
            });

            if (useSimulator)
            {
                dispatcher.RegisterCommand("simulator.timeskip", $"Skips minutse in simulator",
                                           (args) =>
                {
                    if (args.Length != 1)
                    {
                        throw new CommandException("Expected: minutes");
                    }
                    var minutes            = int.Parse(args[0]);
                    simulator.CurrentTime += TimeSpan.FromMinutes(minutes);
                    logger.Success($"Simulator time advanced by {minutes}");
                });
            }
        }
コード例 #11
0
        private void LoadModules()
        {
            Logger.Info("Loading modules...");

            _Modules.Clear();

            var libs = Directory.GetFiles(Pathes.DIR_MODULES, "*.dll", SearchOption.TopDirectoryOnly);

            foreach (var lib in libs)
            {
                var fileName = Path.GetFileName(lib);
                Logger.Info($"Module ['{fileName}',?,?,?]: Loading...");
                try
                {
                    var asm      = Assembly.LoadFile(lib);
                    var asmTypes = (from type in asm.GetExportedTypes()
                                    where type.IsClass &&
                                    typeof(SACModuleBase.ISACBase).IsAssignableFrom(type) &&
                                    type.IsDefined(typeof(SACModuleBase.Attributes.SACModuleInfoAttribute))
                                    select type);

                    Logger.Info($"Module ['{fileName}',?,?,?]: {asmTypes.Count()} type(s) available.");

                    foreach (var asmType in asmTypes)
                    {
                        try
                        {
                            var asmInfo = asmType.GetCustomAttribute <SACModuleBase.Attributes.SACModuleInfoAttribute>();
                            if (asmInfo == null)
                            {
                                Logger.Warn($"Module ['{fileName}',?,?,?]: WTF? Cannot get info-attribute...");
                                continue;
                            }

                            var guid       = asmInfo.Guid;
                            var mName      = asmInfo.Name;
                            var mVer       = asmInfo.Version;
                            var isDisabled = ConfigDisabled.Any(g => g == guid);

                            if (isDisabled)
                            {
                                Logger.Warn($"Module ['{fileName}','{mName}',{mVer},{guid}]: Will be initialized anyway. To completely disabling module you need to remove '{fileName}' from '{Pathes.DIR_MODULES}'");
                            }

                            Logger.Info($"Module ['{fileName}','{mName}',{mVer},{guid}]: Check for GUID free...");
                            if (!Modules.GuidIsFree(guid))
                            {
                                Logger.Warn($"Module ['{fileName}','{mName}',{mVer},{guid}]: Was not be loaded GUID is NOT free.");
                                continue;
                            }
                            Logger.Info($"Module ['{fileName}','{mName}',{mVer},{guid}]: GUID is free.");

                            try
                            {
                                Logger.Info($"Module ['{fileName}','{mName}',{mVer},{guid}]: Creating instance...");
                                var module = (SACModuleBase.ISACBase)Activator.CreateInstance(asmType);
                                Logger.Info($"Module ['{fileName}','{mName}',{mVer},{guid}]: Seems to be created...");

                                Logger.Info($"Module ['{fileName}','{mName}',{mVer},{guid}]: Initializing...");
                                module.ModuleEnabled = !isDisabled; // anyway need full init to enable/disable using gui and during runtime...
                                try
                                {
                                    Logger.Info($"Module ['{fileName}','{mName}',{mVer},{guid}]: Initializing logger...");
                                    var logger = new ModuleLogger(module);

                                    var configDirectory = Path.Combine(Pathes.DIR_MODULES_CONFIGS, fileName);
                                    Utility.MkDirs(configDirectory);
                                    module.ModuleInitialize(new SACModuleBase.Models.SACInitialize(logger)
                                    {
                                        ConfigurationPath = configDirectory
                                    });
                                    Logger.Info($"Module ['{fileName}','{mName}',{mVer},{guid}]: Initialized.");

                                    try
                                    {
                                        _Modules.Add(new ModuleBinding(module));
                                    }
                                    catch (Exception ex)
                                    {
                                        Logger.Error($"Module ['{fileName}','{mName}',{mVer},{guid}]: Initialized but cannot add to module list...", ex);
                                        continue;
                                    }
                                }
                                catch (Exception ex)
                                {
                                    Logger.Error($"Module ['{fileName}','{mName}',{mVer},{guid}]: Initialize module error.", ex);
                                    continue;
                                }
                            }
                            catch (Exception ex)
                            {
                                Logger.Error($"Module ['{fileName}','{mName}',{mVer},{guid}]: Initialize assembly error.", ex);
                                continue;
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Error($"Module ['{fileName}',?,?]: Loading assembly error.", ex);
                            continue;
                        }
                        Logger.Info($"Module ['{fileName}',?,?]: Loading done.");
                    }
                }
                catch (Exception ex)
                {
                    Logger.Error($"Module ['{fileName}',?,?]: Loading error.", ex);
                }
            }

            Logger.Info("Loading modules done.");
        }
コード例 #12
0
 public ModuleBase(InstaFarmUser user)
 {
     this.User   = user;
     this.Logger = new ModuleLogger();
 }