Ejemplo n.º 1
0
 public ModerationModule(RecordService r, UnpunishService u, BlacklistService b, LogService l, CoreConfig config, ModerationService m)
 {
     _service   = m;
     _unpunish  = u;
     _records   = r;
     _blacklist = b;
     _log       = l;
     _config    = config;
 }
Ejemplo n.º 2
0
        public bool appendBlock(Block b, bool add_to_storage = true)
        {
            lock (blocks)
            {
                if (b.blockNum > lastBlockNum)
                {
                    lastBlock    = b;
                    lastBlockNum = b.blockNum;
                    if (b.version != lastBlockVersion)
                    {
                        lastBlockVersion = b.version;
                    }
                }

                if (b.lastSuperBlockChecksum != null || b.blockNum == 1)
                {
                    pendingSuperBlocks.Remove(b.blockNum);

                    lastSuperBlockNum      = b.blockNum;
                    lastSuperBlockChecksum = b.blockChecksum;
                }

                // special case when we are starting up and have an empty chain
                if (blocks.Count == 0)
                {
                    blocks.Add(b);
                    lock (blocksDictionary)
                    {
                        blocksDictionary.Add(b.blockNum, b);
                    }
                    Storage.insertBlock(b);
                    return(true);
                }
                // check for invalid block appending
                if (b.blockNum != blocks[blocks.Count - 1].blockNum + 1)
                {
                    Logging.warn(String.Format("Attempting to add non-sequential block #{0} after block #{1}.",
                                               b.blockNum,
                                               blocks[blocks.Count - 1].blockNum));
                    return(false);
                }
                if (!b.lastBlockChecksum.SequenceEqual(blocks[blocks.Count - 1].blockChecksum))
                {
                    Logging.error(String.Format("Attempting to add a block #{0} with invalid lastBlockChecksum!", b.blockNum));
                    return(false);
                }
                if (b.signatureFreezeChecksum != null && blocks.Count > 5 && !blocks[blocks.Count - 5].calculateSignatureChecksum().SequenceEqual(b.signatureFreezeChecksum))
                {
                    Logging.error(String.Format("Attempting to add a block #{0} with invalid sigFreezeChecksum!", b.blockNum));
                    return(false);
                }
                blocks.Add(b);
                lock (blocksDictionary)
                {
                    blocksDictionary.Add(b.blockNum, b);
                }
            }

            if (add_to_storage)
            {
                // Add block to storage
                Storage.insertBlock(b);
            }

            CoreConfig.redactedWindowSize    = CoreConfig.getRedactedWindowSize(b.version);
            CoreConfig.minRedactedWindowSize = CoreConfig.getRedactedWindowSize(b.version);

            redactChain();
            lock (blocks)
            {
                if (blocks.Count > 20)
                {
                    Block tmp_block = getBlock(b.blockNum - 20);
                    if (tmp_block != null)
                    {
                        TransactionPool.compactTransactionsForBlock(tmp_block);
                        tmp_block.compact();
                    }
                }
                compactBlockSigs();
            }

            lastBlockReceivedTime = Clock.getTimestamp();

            return(true);
        }
Ejemplo n.º 3
0
 public CoreConfig(CoreConfig coreConfig)
 {
     Lines = coreConfig.Lines.ToList();
 }
Ejemplo n.º 4
0
        public void CanParse()
        {
            var testConfig =
                @"foo=buz
foo = bar";

            testConfig += Environment.NewLine;
            testConfig += Environment.NewLine;
            testConfig += Environment.NewLine;
            testConfig +=
                @" foo = bar
foo bar = buz quxx

too =1
foo
bar
#qoo=boo";
            var coreConfig = new CoreConfig();

            coreConfig.TryAdd(testConfig);

            var expectedConfig =
                @"foo = buz

foo bar = buz quxx

too = 1
foo
bar
#qoo=boo
";

            Assert.Equal(expectedConfig, coreConfig.ToString());

            var configDic = coreConfig.ToDictionary();

            Assert.True(configDic.TryGetValue("foo", out string v1));
            Assert.True(configDic.TryGetValue("too", out string v2));
            Assert.False(configDic.TryGetValue("qoo", out _));
            Assert.False(configDic.TryGetValue("bar", out _));
            Assert.True(configDic.TryGetValue("foo bar", out string v3));

            Assert.Equal("buz", v1);
            Assert.Equal("1", v2);
            Assert.Equal("buz quxx", v3);

            var coreConfig2 = new CoreConfig();

            coreConfig2.AddOrUpdate(testConfig);

            var configDic2 = coreConfig2.ToDictionary();

            Assert.True(configDic2.TryGetValue("foo", out string v1_2));
            Assert.True(configDic2.TryGetValue("too", out string v2_2));
            Assert.False(configDic2.TryGetValue("qoo", out _));
            Assert.False(configDic2.TryGetValue("bar", out _));
            Assert.True(configDic2.TryGetValue("foo bar", out string v3_3));

            Assert.Equal("bar", v1_2);
            Assert.Equal("1", v2_2);
            Assert.Equal("buz quxx", v3_3);

            var add1 = "moo=1";
            var add2 = "foo=bar";
            var add3 = "too=0";

            coreConfig.TryAdd(add1);
            coreConfig2.AddOrUpdate(add1);
            coreConfig.TryAdd(add2);
            coreConfig2.AddOrUpdate(add2);
            coreConfig.TryAdd(add3);
            coreConfig2.AddOrUpdate(add3);

            configDic  = coreConfig.ToDictionary();
            configDic2 = coreConfig2.ToDictionary();

            Assert.True(configDic.TryGetValue("moo", out string mooValue));
            Assert.True(configDic.TryGetValue("foo", out string fooValue));
            Assert.True(configDic.TryGetValue("too", out string tooValue));
            Assert.Equal("1", mooValue);
            Assert.Equal("buz", fooValue);
            Assert.Equal("1", tooValue);

            Assert.True(configDic2.TryGetValue("moo", out mooValue));
            Assert.True(configDic2.TryGetValue("foo", out fooValue));
            Assert.True(configDic2.TryGetValue("too", out tooValue));
            Assert.Equal("1", mooValue);
            Assert.Equal("bar", fooValue);
            Assert.Equal("0", tooValue);

            expectedConfig =
                @"foo = buz

foo bar = buz quxx

too = 1
foo
bar
#qoo=boo
moo = 1
";

            Assert.Equal(expectedConfig, coreConfig.ToString());

            var expectedConfig2 =
                @"foo = bar

foo bar = buz quxx

foo
bar
#qoo=boo
moo = 1
too = 0
";

            Assert.Equal(expectedConfig2, coreConfig2.ToString());
        }
Ejemplo n.º 5
0
 /// <summary>
 /// Constructs an instance.
 /// </summary>
 public XilinxMultiplierXILMapper()
 {
     Config = new CoreConfig();
 }
Ejemplo n.º 6
0
Archivo: Engine.cs Proyecto: idafi/heng
 /// <summary>
 /// Initializes the engine and its services, using the provided configuration structure.
 /// <para>Duplicate calls shouldn't have adverse effects, but try to avoid them anyway.</para>
 /// </summary>
 /// <param name="config">Configuration settings for engine services.</param>
 /// <returns>True if initialization was successful; false if not.</returns>
 public static bool Init(CoreConfig config) => Core.Init(config);
Ejemplo n.º 7
0
 public bool CheckDependencies()
 {
     return(CoreConfig.GetInstance().GetBoolValue("csharp", "enabled"));
 }
Ejemplo n.º 8
0
        public BaseService(IUserIdentity identity, string connName)
        {
            var connStr = CoreConfig.GetConnectionString(connName);

            sqlExecutor = SqlExecutor.CreateOracleExecutor(connStr, identity, false, ConfigurationManager.AppSettings.Get("AllowAnanimus") == "true");
        }
Ejemplo n.º 9
0
        static async Task <(EventExchange, IContainer)> SetupAssetSystem(string baseDir)
        {
            var generalConfigTask = Task.Run(() =>
            {
                var result = GeneralConfig.Load(Path.Combine(baseDir, "data", "config.json"), baseDir);
                PerfTracker.StartupEvent("Loaded general config");
                return(result);
            });
            var settingsTask = Task.Run(() =>
            {
                var result = GeneralSettings.Load(Path.Combine(baseDir, "data", "settings.json"));
                PerfTracker.StartupEvent("Loaded settings");
                return(result);
            });
            var coreConfigTask = Task.Run(() =>
            {
                var result = CoreConfig.Load(Path.Combine(baseDir, "data", "core.json"));
                PerfTracker.StartupEvent("Loaded core config");
                return(result);
            });
            var gameConfigTask = Task.Run(() =>
            {
                var result = GameConfig.Load(Path.Combine(baseDir, "data", "game.json"));
                PerfTracker.StartupEvent("Loaded game config");
                return(result);
            });

            var assets                  = new AssetManager();
            var factory                 = new VeldridCoreFactory();
            var loaderRegistry          = new AssetLoaderRegistry();
            var locatorRegistry         = new AssetLocatorRegistry();
            var containerLoaderRegistry = new ContainerLoaderRegistry().AddLoader(new RawContainerLoader())
                                          .AddLoader(new XldContainerLoader())
                                          .AddLoader(new BinaryOffsetContainerLoader())
                                          .AddLoader(new ItemListContainerLoader())
                                          .AddLoader(new SpellListContainerLoader())
                                          .AddLoader(new DirectoryContainerLoader())
            ;

            var modApplier = new ModApplier()
                             // Register post-processors for handling transformations of asset data that can't be done by UAlbion.Formats alone.
                             .AddAssetPostProcessor(new AlbionSpritePostProcessor())
                             .AddAssetPostProcessor(new ImageSharpPostProcessor())
                             .AddAssetPostProcessor(new InterlacedBitmapPostProcessor())
                             .AddAssetPostProcessor(new InventoryPostProcessor())
                             .AddAssetPostProcessor(new ItemNamePostProcessor());

            var settings = await settingsTask.ConfigureAwait(false);

            var services = new Container("Services", settings, // Need to register settings first, as the AssetLocator relies on it.
                                         loaderRegistry, locatorRegistry, containerLoaderRegistry, new MetafontBuilder(factory), new StdioConsoleLogger(),
                                                               // new ClipboardManager(),
                                         new ImGuiConsoleLogger(), new WordLookup(), new AssetLocator(), modApplier, assets);

            var generalConfig = await generalConfigTask.ConfigureAwait(false);

            using var exchange = new EventExchange(new LogExchange()).Register <IGeneralConfig>(generalConfig)
                                 .Register <ICoreFactory>(factory)
                                 .Attach(services);
            PerfTracker.StartupEvent("Registered asset services");

            Engine.GlobalExchange = exchange;
            generalConfig.SetPath("LANG", settings.Language.ToString()
                                  .ToUpperInvariant()); // Ensure that the LANG path is set before resolving any assets
            modApplier.LoadMods(generalConfig);
            PerfTracker.StartupEvent("Loaded mods");

            var coreConfig = await coreConfigTask.ConfigureAwait(false);

            var gameConfig = await gameConfigTask.ConfigureAwait(false);

            exchange // Need to load game config after mods so asset ids can be parsed.
            .Register(coreConfig)
            .Register(gameConfig);
            PerfTracker.StartupEvent("Loaded core and game config");
            return(exchange, services);
        }
Ejemplo n.º 10
0
        public async Task Start()
        {
            Console.Title = "Kratos";

            // Set up our Discord client
            _client = new DiscordSocketClient(new DiscordSocketConfig()
            {
                LogLevel         = LogSeverity.Verbose,
                MessageCacheSize = 100
            });

            _client.Log += Log;

            // Set up the config directory and core config
            if (!Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "config")))
            {
                Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), "config"));
            }

            if (File.Exists(Path.Combine(Directory.GetCurrentDirectory(), "config", "core.json")))
            {
                _config = await CoreConfig.UseCurrentAsync();
            }
            else
            {
                _config = await CoreConfig.CreateNewAsync();
            }

            // Set up services
            _mod = new ModerationService();
            await _mod.LoadConfigurationAsync();

            _usernotes = new UsernoteService();

            _records = new RecordService();

            _tags = new TagService();

            _log = new LogService(_client);
            await _log.LoadConfigurationAsync();

            _unpunish = new UnpunishService(_client, _blacklist, _log, _records, _config);
            await _unpunish.GetRecordsAsync();

            _slowmode = new SlowmodeService(_client, _log, _unpunish, _records, _config);

            _ratelimit = new RatelimitService(_client, _config, _records, _unpunish, _log);
            await _ratelimit.LoadConfigurationAsync();

            if (_ratelimit.IsEnabled)
            {
                _ratelimit.Enable(_ratelimit.Limit);
            }

            _blacklist = new BlacklistService(_client, _unpunish, _records, _log, _config);

            _aliases = new AliasTrackingService(_client);
            await _aliases.LoadConfigurationAsync();

            _permissions = new PermissionsService();
            _permissions.LoadPermissions(Assembly.GetEntryAssembly());
            await _permissions.LoadConfigurationAsync();

            // Instantiate the dependency map and add our services and client to it.
            var serviceProvider = ConfigureServices();

            // Set up command handler
            _commands = new CommandHandler(serviceProvider);
            await _commands.InstallAsync();

            // Set up an event handler to execute some state-reliant startup tasks
            _client.Ready += async() =>
            {
                await _blacklist.LoadConfigurationAsync();
            };
            // Connect to Discord
            await _client.LoginAsync(TokenType.Bot, _config.Token);

            await _client.StartAsync();

            // Start unpunisher loop
            await _unpunish.StartAsync();

            // Hang indefinitely
            await Task.Delay(-1);
        }
Ejemplo n.º 11
0
        // Returns the most recent block without a PoW flag in the redacted blockchain
        private void searchForBlock()
        {
            lock (solvedBlocks)
            {
                List <ulong> tmpSolvedBlocks = new List <ulong>(solvedBlocks);
                foreach (ulong blockNum in tmpSolvedBlocks)
                {
                    Block b = Node.blockChain.getBlock(blockNum, false, false);
                    if (b == null || b.powField != null)
                    {
                        solvedBlocks.Remove(blockNum);
                    }
                }
            }

            Block candidate_block = null;

            List <Block> blockList = null;

            int block_offset = 1;

            if (Node.blockChain.Count > (long)CoreConfig.getRedactedWindowSize())
            {
                block_offset = 1000;
            }

            if (searchMode == BlockSearchMode.lowestDifficulty)
            {
                blockList = Node.blockChain.getBlocks(block_offset, (int)Node.blockChain.Count - block_offset).Where(x => x.powField == null).OrderBy(x => x.difficulty).ToList();
            }
            else if (searchMode == BlockSearchMode.randomLowestDifficulty)
            {
                Random rnd = new Random();
                blockList = Node.blockChain.getBlocks(block_offset, (int)Node.blockChain.Count - block_offset).Where(x => x.powField == null).OrderBy(x => x.difficulty).Skip(rnd.Next(500)).ToList();
            }
            else if (searchMode == BlockSearchMode.latestBlock)
            {
                blockList = Node.blockChain.getBlocks(block_offset, (int)Node.blockChain.Count - block_offset).Where(x => x.powField == null).OrderByDescending(x => x.blockNum).ToList();
            }
            else if (searchMode == BlockSearchMode.random)
            {
                Random rnd = new Random();
                blockList = Node.blockChain.getBlocks(block_offset, (int)Node.blockChain.Count - block_offset).Where(x => x.powField == null).OrderBy(x => rnd.Next()).ToList();
            }

            // Check if the block list exists
            if (blockList == null)
            {
                Logging.error("No block list found while searching. Likely an incorrect miner block search mode.");
                return;
            }

            // Go through each block in the list
            foreach (Block block in blockList)
            {
                if (block.powField == null)
                {
                    ulong solved = 0;
                    lock (solvedBlocks)
                    {
                        solved = solvedBlocks.Find(x => x == block.blockNum);
                    }

                    // Check if this block is in the solved list
                    if (solved > 0)
                    {
                        // Do nothing at this point
                    }
                    else
                    {
                        // Block is not solved, select it
                        candidate_block = block;
                        break;
                    }
                }
            }

            if (candidate_block == null)
            {
                // No blocks with empty PoW field found, wait a bit
                Thread.Sleep(1000);
                return;
            }

            currentBlockNum        = candidate_block.blockNum;
            currentBlockDifficulty = candidate_block.difficulty;
            currentBlockVersion    = candidate_block.version;
            currentHashCeil        = getHashCeilFromDifficulty(currentBlockDifficulty);

            activeBlock = candidate_block;
            byte[] block_checksum = activeBlock.blockChecksum;
            byte[] solver_address = Node.walletStorage.getPrimaryAddress();
            activeBlockChallenge = new byte[block_checksum.Length + solver_address.Length];
            System.Buffer.BlockCopy(block_checksum, 0, activeBlockChallenge, 0, block_checksum.Length);
            System.Buffer.BlockCopy(solver_address, 0, activeBlockChallenge, block_checksum.Length, solver_address.Length);

            blockFound = true;

            return;
        }
Ejemplo n.º 12
0
        // Static function used by the getMiningBlock API call
        public static Block getMiningBlock(BlockSearchMode searchMode)
        {
            Block candidate_block = null;

            List <Block> blockList = null;

            int block_offset = 1;

            if (Node.blockChain.Count > (long)CoreConfig.getRedactedWindowSize())
            {
                block_offset = 1000;
            }

            if (searchMode == BlockSearchMode.lowestDifficulty)
            {
                blockList = Node.blockChain.getBlocks(block_offset, (int)Node.blockChain.Count - block_offset).Where(x => x.powField == null).OrderBy(x => x.difficulty).ToList();
            }
            else if (searchMode == BlockSearchMode.randomLowestDifficulty)
            {
                Random rnd = new Random();
                blockList = Node.blockChain.getBlocks(block_offset, (int)Node.blockChain.Count - block_offset).Where(x => x.powField == null).OrderBy(x => x.difficulty).Skip(rnd.Next(500)).ToList();
            }
            else if (searchMode == BlockSearchMode.latestBlock)
            {
                blockList = Node.blockChain.getBlocks(block_offset, (int)Node.blockChain.Count - block_offset).Where(x => x.powField == null).OrderByDescending(x => x.blockNum).ToList();
            }
            else if (searchMode == BlockSearchMode.random)
            {
                Random rnd = new Random();
                blockList = Node.blockChain.getBlocks(block_offset, (int)Node.blockChain.Count - block_offset).Where(x => x.powField == null).OrderBy(x => rnd.Next()).ToList();
            }
            // Check if the block list exists
            if (blockList == null)
            {
                Logging.error("No block list found while searching.");
                return(null);
            }

            // Go through each block in the list
            foreach (Block block in blockList)
            {
                if (block.powField == null)
                {
                    ulong solved = 0;
                    lock (solvedBlocks)
                    {
                        solved = solvedBlocks.Find(x => x == block.blockNum);
                    }

                    // Check if this block is in the solved list
                    if (solved > 0)
                    {
                        // Do nothing at this point
                    }
                    else
                    {
                        // Block is not solved, select it
                        candidate_block = block;
                        break;
                    }
                }
            }

            return(candidate_block);
        }
Ejemplo n.º 13
0
            public static void SetOptions(OptionsInfo options, AmoebaInterfaceManager serviceManager, DialogService dialogService)
            {
                try
                {
                    bool uploadFlag = false;

                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        // AccountInfo
                        {
                            var info = SettingsManager.Instance.AccountSetting;

                            if (info.Agreement == null || info.DigitalSignature != options.Account.DigitalSignature)
                            {
                                info.Agreement = new Agreement(AgreementAlgorithm.EcDhP521_Sha256);

                                uploadFlag = true;
                            }
                            else if (info.Comment != options.Account.Comment ||
                                     !CollectionUtils.Equals(info.TrustSignatures, options.Account.TrustSignatures) ||
                                     !CollectionUtils.Equals(info.UntrustSignatures, options.Account.UntrustSignatures) ||
                                     !CollectionUtils.Equals(info.Tags, options.Account.Tags))
                            {
                                uploadFlag = true;
                            }

                            info.DigitalSignature = options.Account.DigitalSignature;
                            info.Comment          = options.Account.Comment;
                            info.TrustSignatures.Clear();
                            info.TrustSignatures.AddRange(options.Account.TrustSignatures);
                            info.UntrustSignatures.Clear();
                            info.UntrustSignatures.AddRange(options.Account.UntrustSignatures);
                            info.Tags.Clear();
                            info.Tags.AddRange(options.Account.Tags);
                        }

                        // UpdateInfo
                        {
                            var info       = SettingsManager.Instance.UpdateSetting;
                            info.IsEnabled = options.Update.IsEnabled;
                            info.Signature = options.Update.Signature;
                        }

                        // SubscribeSignatures
                        {
                            SettingsManager.Instance.SubscribeSignatures.Clear();
                            SettingsManager.Instance.SubscribeSignatures.UnionWith(options.View.SubscribeSignatures);
                        }
                    }));

                    if (uploadFlag)
                    {
                        var info = SettingsManager.Instance.AccountSetting;

                        ProgressCircleService.Instance.Increment();

                        var task = serviceManager.SetProfile(
                            new ProfileContent(info.Comment,
                                               null,
                                               info.TrustSignatures,
                                               info.UntrustSignatures,
                                               info.Tags,
                                               info.Agreement.GetAgreementPublicKey()),
                            info.DigitalSignature,
                            CancellationToken.None);

                        task.ContinueWith((_) =>
                        {
                            ProgressCircleService.Instance.Decrement();
                        });
                    }

                    // AmoebaInterfaceManager
                    {
                        ServiceConfig serviceConfig;
                        {
                            ConnectionConfig connectionConfig;
                            {
                                TcpConnectionConfig tcpConnectionConfig;
                                {
                                    var type = TcpConnectionType.None;
                                    if (options.Connection.Tcp.Ipv4IsEnabled)
                                    {
                                        type |= TcpConnectionType.Ipv4;
                                    }
                                    if (options.Connection.Tcp.Ipv6IsEnabled)
                                    {
                                        type |= TcpConnectionType.Ipv6;
                                    }

                                    tcpConnectionConfig = new TcpConnectionConfig(
                                        type,
                                        options.Connection.Tcp.Ipv4Port,
                                        options.Connection.Tcp.Ipv6Port,
                                        options.Connection.Tcp.ProxyUri);
                                }

                                I2pConnectionConfig i2PConnectionConfig;
                                {
                                    i2PConnectionConfig = new I2pConnectionConfig(
                                        options.Connection.I2p.IsEnabled,
                                        options.Connection.I2p.SamBridgeUri);
                                }

                                CustomConnectionConfig customConnectionConfig;
                                {
                                    customConnectionConfig = new CustomConnectionConfig(
                                        options.Connection.Custom.LocationUris,
                                        options.Connection.Custom.ConnectionFilters,
                                        options.Connection.Custom.ListenUris);
                                }

                                CatharsisConfig catharsisConfig;
                                {
                                    var catharsisIpv4Config = new CatharsisIpv4Config(Array.Empty <string>(), Array.Empty <string>());

                                    catharsisConfig = new CatharsisConfig(catharsisIpv4Config);
                                }

                                connectionConfig = new ConnectionConfig(
                                    tcpConnectionConfig,
                                    i2PConnectionConfig,
                                    customConnectionConfig,
                                    catharsisConfig);
                            }

                            CoreConfig coreConfig;
                            {
                                NetworkConfig networkConfig;
                                {
                                    networkConfig = new NetworkConfig(
                                        options.Connection.Bandwidth.ConnectionCountLimit,
                                        options.Connection.Bandwidth.BandwidthLimit);
                                }

                                DownloadConfig downloadConfig;
                                {
                                    downloadConfig = new DownloadConfig(
                                        options.Data.Download.DirectoryPath,
                                        options.Data.Download.ProtectedPercentage);
                                }

                                coreConfig = new CoreConfig(networkConfig, downloadConfig);
                            }

                            MessageConfig messageConfig;
                            {
                                messageConfig = new MessageConfig(options.View.SubscribeSignatures);
                            }

                            serviceConfig = new ServiceConfig(coreConfig, connectionConfig, messageConfig);
                        }

                        serviceManager.SetConfig(serviceConfig);
                    }

                    // AmoebaInterfaceManager (Resize)
                    {
                        long orginalCacheSize = serviceManager.Size;

                        if (options.Data.Cache.Size < orginalCacheSize)
                        {
                            App.Current.Dispatcher.Invoke(new Action(() =>
                            {
                                if (dialogService.ShowDialog(LanguagesManager.Instance.DataOptionsControl_CacheResize_Message,
                                                             MessageBoxButton.OKCancel, MessageBoxImage.Question, MessageBoxResult.Cancel) == MessageBoxResult.OK)
                                {
                                    Task.Run(() =>
                                    {
                                        ProgressCircleService.Instance.Increment();

                                        serviceManager.Resize(options.Data.Cache.Size);

                                        ProgressCircleService.Instance.Decrement();
                                    });
                                }
                            }));
                        }
                        else if (options.Data.Cache.Size > orginalCacheSize)
                        {
                            ProgressCircleService.Instance.Increment();

                            serviceManager.Resize(options.Data.Cache.Size);

                            ProgressCircleService.Instance.Decrement();
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Error(e);
                }
            }
 /// <summary>
 /// Constructs an instance.
 /// </summary>
 public XilinxAdderSubtracterXILMapper()
 {
     Config = new CoreConfig();
 }
Ejemplo n.º 15
0
 public UnpunishService(DiscordSocketClient c, BlacklistService b, LogService l, RecordService r, CoreConfig config)
 {
     _client    = c;
     _blacklist = b;
     _log       = l;
     _records   = r;
     _config    = config;
     Bans       = new List <TempBan>();
     Mutes      = new List <Mute>();
 }
Ejemplo n.º 16
0
 /// <summary>
 /// Constructs an instance.
 /// </summary>
 public XilinxAdderSubtracterXILMapper()
 {
     Config = new CoreConfig();
 }
Ejemplo n.º 17
0
 public CoreModule(DiscordSocketClient c, CommandService s, BlacklistService b, CoreConfig config)
 {
     _client    = c;
     _commands  = s;
     _blacklist = b;
     _config    = config;
 }
Ejemplo n.º 18
0
        public SettingLightViewModel(LightControlService lightControlService, StateStore stateStore, CoreConfig coreConfig)
        {
            StateStore = stateStore;
            CoreConfig = coreConfig;

            _responseTimeout = CoreConfig.ReponseTimeout;

            OnCommand = new DelegateCommand(() =>
            {
                lightControlService.SetValue(coreConfig.LightValues);
                lightControlService.LightOn();
            });

            OffCommand = new DelegateCommand(() =>
            {
                lightControlService.LightOff();
            });

            var temp = new byte[coreConfig.LightNum];

            if (coreConfig.LightValues != null)
            {
                Array.Copy(coreConfig.LightValues, temp, coreConfig.LightNum);
            }

            LightNum = coreConfig.LightNum;
            if (coreConfig.LightValues != null)
            {
                for (int i = 0; i < LightNum; i++)
                {
                    _lightValues[i].Value = temp[i];
                }
            }

            RefreshPorts();

            BaudRates = new int[] { 1200, 2400, 4800, 9600, 19200, 38400, 57600, 115200 };
            Parities  = Enum.GetValues(typeof(Parity)).Cast <Parity>();
            DataBits  = new int[] { 5, 6, 7, 8 };
            StopBits  = Enum.GetValues(typeof(StopBits)).Cast <StopBits>();

            RefreshCommand = new DelegateCommand(() =>
            {
                RefreshPorts();
            });

            ConnectCommand = new DelegateCommand(() =>
            {
                if (CoreConfig.LightSerialInfo != null)
                {
                    lightControlService.Connect();
                }
            });

            DisconnectCommand = new DelegateCommand(() =>
            {
                lightControlService.Disconnect();
            });
        }
Ejemplo n.º 19
0
 public BlacklistService(DiscordSocketClient c, UnpunishService u, RecordService r, LogService l, CoreConfig config)
 {
     _client                  = c;
     _unpunish                = u;
     _records                 = r;
     _log                     = l;
     _config                  = config;
     ChannelBlacklists        = new List <ChannelBlacklist>();
     GlobalBlacklist          = new GlobalBlacklist();
     _client.MessageReceived += _client_MessageReceived_Blacklist;
 }
Ejemplo n.º 20
0
        // Start the node
        static public void start(bool verboseConsoleOutput)
        {
            // First create the data folder if it does not already exist
            checkDataFolder();

            renameStorageFiles(); // this function will be here temporarily for the next few version, then it will be removed to keep a cleaner code base

            // debug
            if (Config.networkDumpFile != "")
            {
                NetDump.Instance.start(Config.networkDumpFile);
            }

            NetworkUtils.configureNetwork();

            char node_type = 'M'; // TODO TODO TODO TODO change this to 'W' or 'C' after the upgrade

            if (Config.disableMiner)
            {
                node_type = 'M';
            }

            // Check if we're in worker-only mode
            if (Config.workerOnly)
            {
                // Enable miner
                Config.disableMiner = false;
                node_type           = 'W';
                CoreConfig.simultaneousConnectedNeighbors = 4;
            }

            // Generate presence list
            PresenceList.generatePresenceList(Config.publicServerIP, node_type);

            // Initialize storage
            Storage.prepareStorage();

            ActivityStorage.prepareStorage();

            // Initialize the block chain
            blockChain = new BlockChain();

            //runDiffTests();
            //return;

            // Create the block processor and sync
            blockProcessor = new BlockProcessor();
            blockSync      = new BlockSync();

            // Start the HTTP JSON API server
            apiServer = new APIServer();

            if (IXICore.Platform.onMono() == false && !Config.disableWebStart)
            {
                System.Diagnostics.Process.Start("http://localhost:" + Config.apiPort);
            }

            miner = new Miner();

            // Start the network queue
            NetworkQueue.start();

            // prepare stats screen
            Config.verboseConsoleOutput = verboseConsoleOutput;
            Logging.consoleOutput       = verboseConsoleOutput;
            Logging.flush();
            if (Config.verboseConsoleOutput == false)
            {
                statsConsoleScreen.clearScreen();
            }

            // Distribute genesis funds
            IxiNumber genesisFunds = new IxiNumber(Config.genesisFunds);

            // Check if this is a genesis node
            if (genesisFunds > (long)0)
            {
                Logging.info(String.Format("Genesis {0} specified. Starting operation.", genesisFunds));

                distributeGenesisFunds(genesisFunds);

                genesisNode = true;
                blockProcessor.resumeOperation();
                serverStarted = true;
                if (!isMasterNode())
                {
                    Logging.info("Network server is not enabled in modes other than master node.");
                }
                else
                {
                    NetworkServer.beginNetworkOperations();
                }
            }
            else
            {
                if (File.Exists(Config.genesisFile))
                {
                    Block genesis = new Block(Crypto.stringToHash(File.ReadAllText(Config.genesisFile)));
                    blockChain.setGenesisBlock(genesis);
                }
                ulong lastLocalBlockNum = Meta.Storage.getLastBlockNum();
                if (lastLocalBlockNum > 6)
                {
                    lastLocalBlockNum = lastLocalBlockNum - 6;
                }
                if (Config.lastGoodBlock > 0 && Config.lastGoodBlock < lastLocalBlockNum)
                {
                    lastLocalBlockNum = Config.lastGoodBlock;
                }
                if (lastLocalBlockNum > 0)
                {
                    Block b = blockChain.getBlock(lastLocalBlockNum, true);
                    if (b != null)
                    {
                        CoreConfig.minRedactedWindowSize = CoreConfig.getRedactedWindowSize(b.version);
                        CoreConfig.redactedWindowSize    = CoreConfig.getRedactedWindowSize(b.version);
                    }
                }

                if (Config.recoverFromFile)
                {
                    Block b = Meta.Storage.getBlock(lastLocalBlockNum);
                    blockSync.onHelloDataReceived(b.blockNum, b.blockChecksum, b.version, b.walletStateChecksum, b.getUniqueSignatureCount(), lastLocalBlockNum);
                }
                else
                {
                    ulong blockNum = WalletStateStorage.restoreWalletState(lastLocalBlockNum);
                    if (blockNum > 0)
                    {
                        Block b = blockChain.getBlock(blockNum, true);
                        if (b != null)
                        {
                            blockSync.onHelloDataReceived(blockNum, b.blockChecksum, b.version, b.walletStateChecksum, b.getUniqueSignatureCount(), lastLocalBlockNum);
                        }
                        else
                        {
                            walletState.clear();
                        }
                    }
                    else
                    {
                        blockSync.lastBlockToReadFromStorage = lastLocalBlockNum;
                    }

                    // Start the server for ping purposes
                    serverStarted = true;
                    if (!isMasterNode())
                    {
                        Logging.info("Network server is not enabled in modes other than master node.");
                    }
                    else
                    {
                        NetworkServer.beginNetworkOperations();
                    }

                    // Start the network client manager
                    NetworkClientManager.start();
                }
            }

            PresenceList.startKeepAlive();

            TLC = new ThreadLiveCheck();
            // Start the maintenance thread
            maintenanceThread      = new Thread(performMaintenance);
            maintenanceThread.Name = "Node_Maintenance_Thread";
            maintenanceThread.Start();
        }
Ejemplo n.º 21
0
 public void UpdateCoreConfig(CoreConfig entity)
 {
     this.Update(entity);
 }
Ejemplo n.º 22
0
 public WebAppTypeFinder(CoreConfig config)
 {
     this._ensureBinFolderAssembliesLoaded = config.DynamicDiscovery;
 }
Ejemplo n.º 23
0
 public CoreConfigTranslator(CoreConfig config, Network network)
 {
     Config  = Guard.NotNull(nameof(config), config);
     Network = Guard.NotNull(nameof(network), network);
 }
Ejemplo n.º 24
0
        //在联网前,读取Read本地缓存文件,如果没有文件,hashcode为"",第一行是hashcode
        //加载Load hashcode,数据,到内存
        //登录,比较新hashcode,相同则跳过;不同,则申请新的hashcode
        //申请的结果和运行时动态更新都是收到服务端的ResponseTextConfig,加载hashcode,数据,到内存,组装新文件替换缓存

        /// <summary>
        /// 从硬盘读取bytes加载到内存。每次刚运行时调用
        /// </summary>
        public static void ReadCacheAndLoadAllLargeConfigs()
        {
            for (int i = 0; i < Configs.Length; i++)
            {
                var configType = (ConfigType)i;

                var    path  = GetFilePath(configType);
                byte[] bytes = null;
                if (File.Exists(path))
                {
                    try
                    {
                        //bytes = File.ReadAllBytes(path);
                    }
                    catch (Exception e)
                    {
                        Debug.LogException(e);
                    }
                }
                if (bytes != null)
                {
                    IReceiveable configCmd = null;
                    switch (configType)
                    {
                    case ConfigType.CoreConfig:
                        configCmd = new CoreConfig();
                        break;

                    case ConfigType.RechargeConfig:
                        configCmd = new RechargeConfig();
                        break;

                    case ConfigType.SkillConfig:
                        configCmd = new SkillConfig();
                        break;

                    case ConfigType.SkillParameterConfig:
                        configCmd = new SkillParameterConfig();
                        break;

                    case ConfigType.ExchangeConfig:
                        configCmd = new ExchangeConfig();
                        break;

                    case ConfigType.VegetableConfig:
                        configCmd = new VegetableConfig();
                        break;

                    case ConfigType.ChallengeLevelConfig:
                        configCmd = new ChallengeLevelConfig();
                        break;

                    case ConfigType.SkillIntroTextConfig:
                        configCmd = new SkillIntroTextConfig();
                        break;

                    case ConfigType.SkillLevelDetailTextConfig:
                        configCmd = new SkillLevelDetailTextConfig();
                        break;

                    case ConfigType.VegetableIntroTextConfig:
                        configCmd = new VegetableIntroTextConfig();
                        break;

                    case ConfigType.WaitHintTextConfig:
                        configCmd = new WaitHintTextConfig();
                        break;

                    case ConfigType.CharacterConfig:
                        configCmd = new CharacterConfig();
                        break;

                    case ConfigType.EquipConfig:
                        configCmd = new EquipConfig();
                        break;

                    case ConfigType.MajorLevelIntroTextConfig:
                        configCmd = new MajorLevelIntroTextConfig();
                        break;

                    case ConfigType.EquipIntroTextConfig:
                        configCmd = new EquipIntroTextConfig();
                        break;

                    case ConfigType.CharacterIntroTextConfig:
                        configCmd = new CharacterIntroTextConfig();
                        break;

                    case ConfigType.OAuthParamConfig:
                        configCmd = new OAuthParamConfig();
                        break;

                    default:
                        Debug.LogError("遇到新的ConfigType,需添加代码。type:" + configType);
                        break;
                    }
                    if (configCmd != null)
                    {
                        configCmd.ParseFrom(bytes);
                        SetConfig(configType, configCmd);
                    }
                }
            }
        }
Ejemplo n.º 25
0
 private SaveFile()
 {
     CoreConfig = new CoreConfig();
 }
Ejemplo n.º 26
0
 public SlowmodeService(DiscordSocketClient c, LogService l, UnpunishService u, RecordService r, CoreConfig config)
 {
     _client = c;
     _client.MessageReceived += _client_MessageReceived_Slowmode;
     _log         = l;
     _unpunish    = u;
     _records     = r;
     _config      = config;
     _lastMessage = new Dictionary <ulong, Dictionary <SocketTextChannel, DateTime> >();
     Intervals    = new Dictionary <SocketTextChannel, int>();
 }
        public SettingCameraViewModel(GrabService grabService, StateStore stateStore, CoreConfig coreConfig)
        {
            CoreConfig = coreConfig;
            StateStore = stateStore;

            AutoValues = Enum.GetValues(typeof(ECameraAutoValue)).Cast <ECameraAutoValue>();

            CameraInfos = grabService.GetDeviceInfos();

            if (grabService.IsConnected())
            {
                ParameterInfo = grabService.GetParameterInfo();
            }

            grabService.ParameterChanged += (parameterInfo =>
            {
                ParameterInfo = parameterInfo;
            });

            RefreshCommand = new DelegateCommand(() =>
            {
                CameraInfos = grabService.GetDeviceInfos();
            });

            ConnectCommand = new DelegateCommand(() =>
            {
                if (CoreConfig.CameraInfo != null)
                {
                    if (grabService.Connect(CoreConfig.CameraInfo))
                    {
                        ParameterInfo = grabService.GetParameterInfo();
                    }
                }
            });

            DisconnectCommand = new DelegateCommand(() =>
            {
                grabService.Disconnect();
                ParameterInfo = null;
            });

            SetAutoCommand = new DelegateCommand <ECameraAutoType?>(type =>
            {
                if (type == null)
                {
                    return;
                }

                grabService.SetAuto(type.Value, ParameterInfo.AutoValues[type.Value]);
            });

            SetTriggerModeCommand = new DelegateCommand(() =>
            {
                grabService.SetTriggerMode(ParameterInfo.OnTriggerMode);
            });
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Initialize components and plugins in the nop environment.
        /// </summary>
        /// <param name="config">Config</param>
        public void Initialize(CoreConfig config)
        {
            //dependencies
            var builder = new ContainerBuilder();

            builder.RegisterInstance(config).As <CoreConfig>().SingleInstance();
            builder.RegisterInstance(this).As <IEngine>().SingleInstance();

            ITypeFinder typeFinder = new WebAppTypeFinder(config);

            builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();

            //builder = new ContainerBuilder();
            string fullNameCurrentFinder = typeFinder.GetType().FullName;
            var    listTypeFinder        = typeFinder.FindClassesOfType <ITypeFinder>().ToList();
            var    tfInstances           = new List <ITypeFinder>();

            foreach (var tfType in listTypeFinder)
            {
                var ctor = tfType.GetConstructors().FirstOrDefault(c => c.GetParameters().Length == 1);
                if (ctor != null && ctor.GetParameters()[0].ParameterType == typeof(CoreConfig))
                {
                    tfInstances.Add((ITypeFinder)Activator.CreateInstance(tfType, config));
                }
                else
                {
                    tfInstances.Add((ITypeFinder)Activator.CreateInstance(tfType));
                }
            }

            var listConfig = typeFinder.FindClassesOfType <ConfigBase>();

            foreach (var configType in listConfig)
            {
                var configBase     = (ConfigBase)Activator.CreateInstance(configType);
                var instanceConfig = ConfigContext.GetConfig(configBase.SectionName);
                builder.RegisterInstance(instanceConfig).As(configType).SingleInstance();
            }

            //register dependencies provided by other assemblies
            var drTypes     = typeFinder.FindClassesOfType <IDependencyRegistrar>();
            var drInstances = new List <IDependencyRegistrar>();

            foreach (var drType in drTypes)
            {
                IDependencyRegistrar dependencyRegistrar = (IDependencyRegistrar)Activator.CreateInstance(drType);
                drInstances.Add(dependencyRegistrar);
            }
            //sort
            drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
            foreach (var dependencyRegistrar in drInstances)
            {
                dependencyRegistrar.Register(builder, typeFinder, config);
            }

            //controllers
            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());

            var container = builder.Build();

            _containerManager = new WebContainerManager(container);

            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Ejemplo n.º 29
0
        static void RegisterComponents(EventExchange global, IContainer services, string baseDir, CommandLineOptions commandLine)
        {
            PerfTracker.StartupEvent("Creating main components");
            var factory = global.Resolve <ICoreFactory>();

            global
            .Register <ICommonColors>(new CommonColors(factory))
            .Register(CoreConfig.Load(baseDir))
            .Register(GameConfig.Load(baseDir))
            ;

            if (commandLine.AudioMode == AudioMode.InProcess)
            {
                services.Add(new AudioManager(false));
            }

            services
            .Add(new GameState())
            .Add(new GameClock())
            .Add(new IdleClock())
            .Add(new SlowClock())
            .Add(new DeviceObjectManager())
            .Add(new SpriteManager())
            .Add(new TextureManager())
            .Add(new EventChainManager())
            .Add(new Querier())
            .Add(new MapManager())
            .Add(new CollisionManager())
            .Add(new SceneStack())
            .Add(new SceneManager()
                 .AddScene((GameScene) new EmptyScene()
                           .Add(new PaletteManager()))

                 .AddScene((GameScene) new AutomapScene()
                           .Add(new PaletteManager()))

                 .AddScene((GameScene) new FlatScene()
                           .Add(new ConversationManager())
                           .Add(new PaletteManager()))

                 .AddScene((GameScene) new DungeonScene()
                           .Add(new ConversationManager())
                           .Add(new PaletteManager()))

                 .AddScene((GameScene) new MenuScene()
                           .Add(new PaletteManager())
                           .Add(new MainMenu())
                           .Add(Sprite <PictureId> .ScreenSpaceSprite(
                                    PictureId.MenuBackground8,
                                    new Vector2(-1.0f, 1.0f),
                                    new Vector2(2.0f, -2.0f))))

                 .AddScene((GameScene) new InventoryScene()
                           .Add(new ConversationManager())
                           .Add(new PaletteManager())
                           .Add(new InventoryInspector())))

            .Add(new TextFormatter())
            .Add(new TextManager())
            .Add(new LayoutManager())
            .Add(new DialogManager())
            .Add(new InventoryScreenManager())
            .Add(new DebugMapInspector(services)
                 .AddBehaviour(new SpriteInstanceDataDebugBehaviour())
                 .AddBehaviour(new FormatTextEventBehaviour())
                 .AddBehaviour(new QueryEventDebugBehaviour()))
            .Add(new StatusBar())
            .Add(new ContextMenu())
            .Add(new CursorManager())
            .Add(new InputManager()
                 .RegisterInputMode(InputMode.ContextMenu, new ContextMenuInputMode())
                 .RegisterInputMode(InputMode.World2D, new World2DInputMode())
                 .RegisterMouseMode(MouseMode.DebugPick, new DebugPickMouseMode())
                 .RegisterMouseMode(MouseMode.MouseLook, new MouseLookMouseMode())
                 .RegisterMouseMode(MouseMode.Normal, new NormalMouseMode())
                 .RegisterMouseMode(MouseMode.RightButtonHeld, new RightButtonHeldMouseMode())
                 .RegisterMouseMode(MouseMode.ContextMenu, new ContextMenuMouseMode()))
            .Add(new SelectionManager())
            .Add(new InputBinder(InputConfig.Load(baseDir)))
            .Add(new ItemTransitionManager())
            ;
        }
    public void TryGetWhiteBindTests()
    {
        var config     = new CoreConfig();
        var translator = new CoreConfigTranslator(config, Network.Main);

        Assert.Null(translator.TryGetWhiteBind());

        config.AddOrUpdate("whitebind");
        Assert.Null(translator.TryGetWhiteBind());

        config.AddOrUpdate("main.whitebind=127.0.0.1:18444");
        WhiteBind?whiteBind = translator.TryGetWhiteBind();

        Assert.NotNull(whiteBind);
        var ipEndPoint = whiteBind !.EndPoint as IPEndPoint;

        Assert.NotNull(ipEndPoint);
        Assert.Equal(IPAddress.Loopback, ipEndPoint !.Address);
        Assert.Equal(18444, ipEndPoint.Port);
        Assert.Equal("", whiteBind.Permissions);

        config.AddOrUpdate("whitebind=127.0.0.1:0");
        whiteBind = translator.TryGetWhiteBind();
        Assert.NotNull(whiteBind);
        ipEndPoint = whiteBind !.EndPoint as IPEndPoint;
        Assert.NotNull(ipEndPoint);
        Assert.Equal(IPAddress.Loopback, ipEndPoint !.Address);
        Assert.Equal(0, ipEndPoint.Port);
        Assert.Equal("", whiteBind.Permissions);

        config.AddOrUpdate("whitebind=127.0.0.1");
        whiteBind = translator.TryGetWhiteBind();
        Assert.NotNull(whiteBind);
        ipEndPoint = whiteBind !.EndPoint as IPEndPoint;
        Assert.NotNull(ipEndPoint);
        Assert.Equal(IPAddress.Loopback, ipEndPoint !.Address);

        // Default port.
        Assert.Equal(8333, ipEndPoint.Port);
        Assert.Equal("", whiteBind.Permissions);

        config.AddOrUpdate("[email protected]");
        whiteBind = translator.TryGetWhiteBind();
        Assert.NotNull(whiteBind);
        ipEndPoint = whiteBind !.EndPoint as IPEndPoint;
        Assert.NotNull(ipEndPoint);
        Assert.Equal(IPAddress.Loopback, ipEndPoint !.Address);
        Assert.Equal(8333, ipEndPoint.Port);
        Assert.Equal("foo", whiteBind.Permissions);

        config.AddOrUpdate("whitebind=foo,[email protected]");
        whiteBind = translator.TryGetWhiteBind();
        Assert.NotNull(whiteBind);
        ipEndPoint = whiteBind !.EndPoint as IPEndPoint;
        Assert.NotNull(ipEndPoint);
        Assert.Equal(IPAddress.Loopback, ipEndPoint !.Address);
        Assert.Equal(8333, ipEndPoint.Port);
        Assert.Equal("foo,boo", whiteBind.Permissions);

        config.AddOrUpdate("main.whitebind=@@@");
        Assert.Null(translator.TryGetWhiteBind());
    }
Ejemplo n.º 31
0
    private ILogger InitLogger(CoreConfig config)
    {
        var consoleTemplate = "[{Timestamp:HH:mm:ss.fff}] {Level:u3} {Message:lj}{NewLine}{Exception}";
        var outputTemplate  = "[{Timestamp:yyyy-MM-dd HH:mm:ss.ffffff}] {Level:u3} {Message:lj}{NewLine}{Exception}";

        var logCfg = _cfg
                     .Enrich.FromLogContext()
                     .Enrich.WithProperty("GitCommitHash", BuildInfoService.FullVersion)
                     .ConfigureForNodaTime(DateTimeZoneProviders.Tzdb)
                     .Enrich.WithProperty("Component", _component)
                     .MinimumLevel.Is(config.ConsoleLogLevel)

                     // Don't want App.Metrics/D#+ spam
                     .MinimumLevel.Override("App.Metrics", LogEventLevel.Information)

                     // nor ASP.NET spam
                     .MinimumLevel.Override("Microsoft", LogEventLevel.Information)

                     // Actual formatting for these is handled in ScalarFormatting
                     .Destructure.AsScalar <SystemId>()
                     .Destructure.AsScalar <MemberId>()
                     .Destructure.AsScalar <GroupId>()
                     .Destructure.AsScalar <SwitchId>()
                     .Destructure.ByTransforming <ProxyTag>(t => new { t.Prefix, t.Suffix })
                     .Destructure.With <PatchObjectDestructuring>()
                     .WriteTo.Async(a =>
        {
            // Both the same output, except one is raw compact JSON and one is plain text.
            // Output simultaneously. May remove the JSON formatter later, keeping it just in cast.
            // Flush interval is 50ms (down from 10s) to make "tail -f" easier. May be too low?
            a.File(
                (config.LogDir ?? "logs") + $"/pluralkit.{_component}.log",
                outputTemplate: outputTemplate,
                retainedFileCountLimit: 10,
                rollingInterval: RollingInterval.Day,
                fileSizeLimitBytes: null,
                flushToDiskInterval: TimeSpan.FromMilliseconds(50),
                restrictedToMinimumLevel: config.FileLogLevel,
                formatProvider: new UTCTimestampFormatProvider(),
                buffered: true);

            a.File(
                new RenderedCompactJsonFormatter(new ScalarFormatting.JsonValue()),
                (config.LogDir ?? "logs") + $"/pluralkit.{_component}.json",
                rollingInterval: RollingInterval.Day,
                flushToDiskInterval: TimeSpan.FromMilliseconds(50),
                restrictedToMinimumLevel: config.FileLogLevel,
                buffered: true);
        })
                     .WriteTo.Async(a =>
                                    a.Console(
                                        theme: AnsiConsoleTheme.Code,
                                        outputTemplate: consoleTemplate,
                                        restrictedToMinimumLevel: config.ConsoleLogLevel));

        if (config.ElasticUrl != null)
        {
            var elasticConfig = new ElasticsearchSinkOptions(new Uri(config.ElasticUrl))
            {
                AutoRegisterTemplate        = true,
                AutoRegisterTemplateVersion = AutoRegisterTemplateVersion.ESv7,
                MinimumLogEventLevel        = config.ElasticLogLevel,
                IndexFormat     = "pluralkit-logs-{0:yyyy.MM.dd}",
                CustomFormatter = new ScalarFormatting.Elasticsearch()
            };

            logCfg.WriteTo.Elasticsearch(elasticConfig);
        }

        _fn.Invoke(logCfg);
        return(Log.Logger = logCfg.CreateLogger());
    }
Ejemplo n.º 32
0
 /// <summary>
 /// Constructs an instance.
 /// </summary>
 public XilinxDividerXILMapper()
 {
     Config = new CoreConfig();
 }
Ejemplo n.º 33
0
 /// <summary>
 /// Constructs an instance.
 /// </summary>
 public XilinxMultiplierXILMapper()
 {
     Config = new CoreConfig();
 }