public void Test1() { var ini = new InIConfigProvider { FileName = "Config/core0.ini" }; var xml = new XmlConfigProvider { FileName = "Config/core0.xml" }; var json = new JsonConfigProvider { FileName = "Config/core0.json" }; var http = new HttpConfigProvider { Server = "http://127.0.0.1:5000/config,http://10.0.0.4/config", AppKey = "Test", Secret = "12345678", LocalCache = true, }; var p = http["LogPath"]; http["LogPath"] = p; var cfg = http.Load <Setting>(); Assert.NotNull(cfg); Assert.True(cfg.Debug); Assert.NotEmpty(cfg.LogFileFormat); ini.Save(cfg); xml.Save(cfg); json.Save(cfg); }
public void Initialize() { var privateKey = new PrivateKey(TestPrivateKeyHex); _publicKey = privateKey.PublicKey; var logManager = NullLogManager.Instance; //var config = new NetworkConfigurationProvider(new NetworkHelper(logger)) { PongTimeout = 100 }; var config = new JsonConfigProvider(); var networkConfig = config.GetConfig <INetworkConfig>(); networkConfig.PongTimeout = 100; var statsConfig = config.GetConfig <IStatsConfig>(); _messageSender = Substitute.For <IMessageSender>(); _nodeFactory = new NodeFactory(); var calculator = new NodeDistanceCalculator(config); _nodeTable = new NodeTable(_nodeFactory, new FileKeyStore(config, new JsonSerializer(logManager), new AesEncrypter(config, logManager), new CryptoRandom(), logManager), calculator, config, logManager); _nodeTable.Initialize(); var evictionManager = new EvictionManager(_nodeTable, logManager); var lifecycleFactory = new NodeLifecycleManagerFactory(_nodeFactory, _nodeTable, new DiscoveryMessageFactory(config), evictionManager, new NodeStatsProvider(statsConfig, _nodeFactory, logManager), config, logManager); _nodes = new[] { _nodeFactory.CreateNode("192.168.1.18", 1), _nodeFactory.CreateNode("192.168.1.19", 2) }; _discoveryManager = new DiscoveryManager(lifecycleFactory, _nodeFactory, _nodeTable, new NetworkStorage("test", networkConfig, logManager, new PerfService(logManager)), config, logManager); _discoveryManager.MessageSender = _messageSender; }
public void Start() { const string configFileName = "config.json"; var applicationFilePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); if (applicationFilePath == null) { Log.Error("Unable to get applications path"); Environment.Exit(404); } var configfilePath = Path.Combine(applicationFilePath, configFileName); var config = JsonConfigProvider.GetConfigFromFile(configfilePath); _reporter = PerfMonAgentFactory.CreateAgentWithConfiguration(config); if (_reporter == null) { Log.Error("Unable to start service."); Environment.Exit(500); } Log.Info("Starting service."); try { _reporter.Start(); } catch (Exception ex) { Log.Error("Failed to start, unable to continue.", ex); } }
public void Initialize() { Assembly jConfig = typeof(JsonRpcConfig).Assembly; _configurationProvider = new JsonConfigProvider(); _logManager = NullLogManager.Instance; }
public void Initialize() { var keystoreConfig = new KeystoreConfig(); var networkConfig = new NetworkConfig(); var jsonRpcConfig = new JsonRpcConfig(); _configProvider = new JsonConfigProvider(); }
public void Initialize() { KeyStoreConfig keystoreConfig = new(); NetworkConfig networkConfig = new(); JsonRpcConfig jsonRpcConfig = new(); StatsParameters statsConfig = StatsParameters.Instance; _configProvider = new JsonConfigProvider("SampleJson/SampleJsonConfig.cfg"); }
public void Initialize() { var keystoreConfig = new KeyStoreConfig(); var networkConfig = new NetworkConfig(); var jsonRpcConfig = new JsonRpcConfig(); var statsConfig = new StatsConfig(); _configProvider = new JsonConfigProvider("SampleJsonConfig.cfg"); }
private void Init() { Local = new LocalStarClient(); // 读取本地appsetting if (Server.IsNullOrEmpty()) { var json = new JsonConfigProvider { FileName = "appsettings.json" }; json.LoadAll(); Server = json["StarServer"]; } if (Server.IsNullOrEmpty()) { try { var inf = Local.GetInfo(); var server = inf?.Server; if (!server.IsNullOrEmpty()) { Server = server; XTrace.WriteLine("星尘探测:{0}", server); } } catch (Exception ex) { XTrace.WriteException(ex); } } // 如果探测不到本地应用,则使用配置 var set = Setting.Current; if (Server.IsNullOrEmpty()) { Server = set.Server; } if (AppId.IsNullOrEmpty()) { AppId = set.AppKey; } if (Secret.IsNullOrEmpty()) { Secret = set.Secret; } if (AppId.IsNullOrEmpty()) { AppId = AssemblyX.Entry.Name; } XTrace.WriteLine("星尘分布式服务 Server={0} AppId={1}", Server, AppId); }
static DataLoader() { var configProvider = new JsonConfigProvider(); Config = configProvider.GetConfig(); var dataPath = Config.DataFilePath.Trim(); var dataPathWithTrailingSlash = dataPath.EndsWith("/", StringComparison.OrdinalIgnoreCase) || dataPath.EndsWith(@"\", StringComparison.OrdinalIgnoreCase) ? dataPath : $"{dataPath}/"; BasePath = dataPathWithTrailingSlash; }
public void SetUp() { NullLogManager logManager = NullLogManager.Instance; JsonConfigProvider configProvider = new JsonConfigProvider(); _tempDir = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString()); _networkConfig = configProvider.GetConfig <INetworkConfig>(); _networkConfig.DbBasePath = _tempDir; _statsConfig = configProvider.GetConfig <IStatsConfig>(); _nodeFactory = new NodeFactory(); _storage = new NetworkStorage("test", _networkConfig, logManager, new PerfService(logManager)); }
protected override (CommandLineApplication, Func <IConfigProvider>, Func <string>) BuildCommandLineApp() { var app = new CommandLineApplication { Name = "Nethermind.Runner" }; app.HelpOption("-?|-h|--help"); var configFile = app.Option("-c|--config <configFile>", "config file path", CommandOptionType.SingleValue); var dbBasePath = app.Option("-d|--baseDbPath <baseDbPath>", "base db path", CommandOptionType.SingleValue); IConfigProvider BuildConfigProvider() { // ReSharper disable once NotAccessedVariable var config = typeof(KeystoreConfig).Assembly; config = typeof(NetworkConfig).Assembly; config = typeof(JsonRpcConfig).Assembly; config = typeof(InitConfig).Assembly; config = typeof(DbConfig).Assembly; config = typeof(StatsConfig).Assembly; config = typeof(BlockchainConfig).Assembly; var configProvider = new JsonConfigProvider(); string configFilePath = configFile.HasValue() ? configFile.Value() : _defaultConfigFile; var configPathVariable = Environment.GetEnvironmentVariable("NETHERMIND_CONFIG"); if (!string.IsNullOrWhiteSpace(configPathVariable)) { configFilePath = configPathVariable; } if (!Path.HasExtension(configFilePath) && !configFilePath.Contains(Path.DirectorySeparatorChar)) { string redirectedConfigPath = Path.Combine("configs", string.Concat(configFilePath, ".cfg")); Console.WriteLine($"Redirecting config {configFilePath} to {redirectedConfigPath}"); configFilePath = redirectedConfigPath; } Console.WriteLine($"Reading config file from {configFilePath}"); configProvider.LoadJsonConfig(configFilePath); return(configProvider); } string GetBaseDbPath() { return(dbBasePath.HasValue() ? dbBasePath.Value() : null); } return(app, BuildConfigProvider, GetBaseDbPath); }
public static void Main() { var assembly = Assembly.GetExecutingAssembly(); IDialogService dialogService = new MessageBoxDialogService( assembly.GetCustomAttribute <AssemblyTitleAttribute>()?.Title ); var dir = Path.GetDirectoryName(assembly.Location); IConfigProvider configProvider = null; var yamlFile = Path.Combine(dir, "OpenWith.yaml"); if (File.Exists(yamlFile)) { configProvider = new YamlConfigProvider(yamlFile); } else { var jsonFile = Path.Combine(dir, "OpenWith.json"); if (File.Exists(jsonFile)) { configProvider = new JsonConfigProvider(jsonFile); } } if (configProvider == null) { dialogService.Error("Config not found"); return; } var app = new OpenWithApp( configProvider, dialogService, new FilterFactory() .WithFilter("name", NameFilter.Build) .WithFilter("ext", ExtensionFilter.Build) .WithFilter("size", SizeFilter.Build) .WithFilter("magic", MagicBytesFilter.Build), new DefaultProcessStarter(), new FileIconProvider() ); //Stopwatch stopwatch = Stopwatch.StartNew(); var args = Environment.GetCommandLineArgs(); app.Run(args); //File.AppendAllText(Path.Combine(dir, "Stat.txt"), $"{DateTime.Now} : {args[1]} : {stopwatch.ElapsedMilliseconds}ms\n"); }
public SerializationBuilder WithDiscovery(PrivateKey privateKey) { var config = new JsonConfigProvider(); Signer signer = new Signer(); var privateKeyProvider = new SameKeyGenerator(privateKey); PingMessageSerializer pingSerializer = new PingMessageSerializer(signer, privateKeyProvider, new DiscoveryMessageFactory(config, _timestamp), new NodeIdResolver(signer), new NodeFactory(LimboLogs.Instance)); PongMessageSerializer pongSerializer = new PongMessageSerializer(signer, privateKeyProvider, new DiscoveryMessageFactory(config, _timestamp), new NodeIdResolver(signer), new NodeFactory(LimboLogs.Instance)); FindNodeMessageSerializer findNodeSerializer = new FindNodeMessageSerializer(signer, privateKeyProvider, new DiscoveryMessageFactory(config, _timestamp), new NodeIdResolver(signer), new NodeFactory(LimboLogs.Instance)); NeighborsMessageSerializer neighborsSerializer = new NeighborsMessageSerializer(signer, privateKeyProvider, new DiscoveryMessageFactory(config, _timestamp), new NodeIdResolver(signer), new NodeFactory(LimboLogs.Instance)); return(With(pingSerializer) .With(pongSerializer) .With(findNodeSerializer) .With(neighborsSerializer)); }
protected override void OnStart(string[] args) { var baseDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), "CoreProxy"); logger = new FileLogger(Path.Combine(baseDir, "service.log")); try { var config = new JsonConfigProvider(Path.Combine(baseDir, "service.config.json")).Load(); service = new jnm2.CoreProxy.CoreProxyService(config, logger.Log); service.StartAll(); } catch (Exception ex) { logger.Log(ex.ToString()); logger.Dispose(); throw; } }
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); using (GlobalKeyboardHook ghk = new GlobalKeyboardHook()) { JsonConfigProvider optionsProvider = new JsonConfigProvider(GetConfigFileName()); configData = optionsProvider.Load(); //TODO: Load this from configData var kps = new KeyPressState() { IsCtrl = true, Key = Keys.Oemtilde }; Instance = new TrayBasedContext(Resources.AppIcon, kps, optionsProvider); ghk.KeyboardPressed += Instance.HandleKey; Application.Run(Instance); } }
protected override (CommandLineApplication, Func <IConfigProvider>, Func <string>) BuildCommandLineApp() { var app = new CommandLineApplication { Name = "Nethermind.Runner" }; app.HelpOption("-?|-h|--help"); var configFile = app.Option("-c|--config <configFile>", "config file path", CommandOptionType.SingleValue); var dbBasePath = app.Option("-d|--baseDbPath <baseDbPath>", "base db path", CommandOptionType.SingleValue); IConfigProvider BuildConfigProvider() { //TODO find better way to enforce assemblies with config impl are loaded // ReSharper disable once NotAccessedVariable var config = typeof(KeystoreConfig).Assembly; config = typeof(NetworkConfig).Assembly; config = typeof(JsonRpcConfig).Assembly; config = typeof(InitConfig).Assembly; config = typeof(DbConfig).Assembly; config = typeof(StatsConfig).Assembly; config = typeof(BlockchainConfig).Assembly; var configProvider = new JsonConfigProvider(); configProvider.LoadJsonConfig(configFile.HasValue() ? configFile.Value() : DefaultConfigFile); return(configProvider); }; string GetBaseDbPath() { return(dbBasePath.HasValue() ? dbBasePath.Value() : null); } return(app, BuildConfigProvider, GetBaseDbPath); }
public static void Main(string[] args) { string configPath; if (args.Length > 1 || !File.Exists(configPath = args.FirstOrDefault() ?? "CoreProxy.config.json")) { Console.WriteLine("Usage: CoreProxy.Console [path/to/config.json]"); Console.WriteLine("If no path is specified, CoreProxy.config.json will be used."); return; } var config = new JsonConfigProvider(configPath).Load(); using (var service = new CoreProxyService(config, message => Console.WriteLine($"{DateTime.UtcNow:yyyy/MM/dd HH:mm:ss}\t{message}"))) { service.StartAll(); Console.WriteLine("Press Q to quit."); while (Console.ReadKey(true).Key != ConsoleKey.Q) { ; } } }
private static Tuple <IEnumerable <PluginInfo>, IEnumerable <IPlugin> > LoadPluginsFromFile(string file, string exeName) { List <PluginInfo> bsPlugins = new List <PluginInfo>(); List <IPlugin> ipaPlugins = new List <IPlugin>(); if (!File.Exists(file) || !file.EndsWith(".dll", true, null)) { return(new Tuple <IEnumerable <PluginInfo>, IEnumerable <IPlugin> >(bsPlugins, ipaPlugins)); } T OptionalGetPlugin <T>(Type t) where T : class { // use typeof() to allow for easier renaming (in an ideal world this compiles to a string, but ¯\_(ツ)_/¯) if (t.GetInterface(typeof(T).Name) != null) { try { T pluginInstance = Activator.CreateInstance(t) as T; string[] filter = null; if (pluginInstance is IGenericEnhancedPlugin) { filter = ((IGenericEnhancedPlugin)pluginInstance).Filter; } if (filter == null || filter.Contains(exeName, StringComparer.OrdinalIgnoreCase)) { return(pluginInstance); } } catch (Exception e) { Logger.loader.Error($"Could not load plugin {t.FullName} in {Path.GetFileName(file)}! {e}"); } } return(null); } try { Assembly assembly = Assembly.LoadFrom(file); foreach (Type t in assembly.GetTypes()) { IBeatSaberPlugin bsPlugin = OptionalGetPlugin <IBeatSaberPlugin>(t); if (bsPlugin != null) { try { var init = t.GetMethod("Init", BindingFlags.Instance | BindingFlags.Public); if (init != null) { var initArgs = new List <object>(); var initParams = init.GetParameters(); Logger modLogger = null; IModPrefs modPrefs = null; IConfigProvider cfgProvider = null; foreach (var param in initParams) { var ptype = param.ParameterType; if (ptype.IsAssignableFrom(typeof(Logger))) { if (modLogger == null) { modLogger = new StandardLogger(bsPlugin.Name); } initArgs.Add(modLogger); } else if (ptype.IsAssignableFrom(typeof(IModPrefs))) { if (modPrefs == null) { modPrefs = new ModPrefs(bsPlugin); } initArgs.Add(modPrefs); } else if (ptype.IsAssignableFrom(typeof(IConfigProvider))) { if (cfgProvider == null) { cfgProvider = new JsonConfigProvider { Filename = Path.Combine("UserData", $"{bsPlugin.Name}") }; configProviders.Add(new KeyValuePair <IConfigProvider, Ref <DateTime> >(cfgProvider, new Ref <DateTime>(cfgProvider.LastModified))); cfgProvider.Load(); } initArgs.Add(cfgProvider); } else { initArgs.Add(ptype.GetDefault()); } } init.Invoke(bsPlugin, initArgs.ToArray()); } bsPlugins.Add(new PluginInfo { Plugin = bsPlugin, Filename = file.Replace("\\.cache", ""), // quick and dirty fix ModSaberInfo = bsPlugin.ModInfo }); } catch (AmbiguousMatchException) { Logger.loader.Error("Only one Init allowed per plugin"); } } else { IPlugin ipaPlugin = OptionalGetPlugin <IPlugin>(t); if (ipaPlugin != null) { ipaPlugins.Add(ipaPlugin); } } } } catch (Exception e) { Logger.loader.Error($"Could not load {Path.GetFileName(file)}! {e}"); } return(new Tuple <IEnumerable <PluginInfo>, IEnumerable <IPlugin> >(bsPlugins, ipaPlugins)); }
public void Provides_helpful_error_message_when_file_does_not_exist() { Assert.Throws <IOException>(() => _configProvider = new JsonConfigProvider("SampleJson.cfg")); }
private void Init() { Local = new LocalStarClient(); // 读取本地appsetting if (Server.IsNullOrEmpty() && File.Exists("appsettings.Development.json".GetFullPath())) { using var json = new JsonConfigProvider { FileName = "appsettings.Development.json" }; json.LoadAll(); Server = json["StarServer"]; } if (Server.IsNullOrEmpty() && File.Exists("appsettings.json".GetFullPath())) { using var json = new JsonConfigProvider { FileName = "appsettings.json" }; json.LoadAll(); Server = json["StarServer"]; } if (!Server.IsNullOrEmpty() && Local.Server.IsNullOrEmpty()) { Local.Server = Server; } try { var inf = Local.GetInfo(); var server = inf?.Server; if (!server.IsNullOrEmpty()) { if (Server.IsNullOrEmpty()) { Server = server; } XTrace.WriteLine("星尘探测:{0}", server); } } catch (Exception ex) { XTrace.Log.Error("星尘探测失败!{0}", ex.Message); } // 如果探测不到本地应用,则使用配置 var set = StarSetting.Current; if (Server.IsNullOrEmpty()) { Server = set.Server; } if (AppId.IsNullOrEmpty()) { AppId = set.AppKey; } if (Secret.IsNullOrEmpty()) { Secret = set.Secret; } try { var executing = AssemblyX.Create(Assembly.GetExecutingAssembly()); var asm = AssemblyX.Entry ?? executing; if (asm != null) { if (AppId.IsNullOrEmpty()) { AppId = asm.Name; } if (AppName.IsNullOrEmpty()) { AppName = asm.Title; } } ClientId = $"{NetHelper.MyIP()}@{Process.GetCurrentProcess().Id}"; } catch { } XTrace.WriteLine("星尘分布式服务 Server={0} AppId={1}", Server, AppId); var ioc = ObjectContainer.Current; ioc.AddSingleton(this); ioc.AddSingleton(p => Tracer); ioc.AddSingleton(p => Config); ioc.AddSingleton(p => Service); }
static Config() { JsonConfigProvider.RegisterConfig(); }
protected async Task StartRunners(InitParams initParams) { try { //TODO find better way to enforce assemblies with config impl are loaded IKeystoreConfig kConfig; INetworkConfig nConfig; IJsonRpcConfig jConfig; var configProvider = new JsonConfigProvider(); var logManager = new NLogManager(initParams.LogFileName); //configProvider.LoadJsonConfig(""); //discovering and setting local, remote ips for client machine var networkHelper = new NetworkHelper(Logger); var localHost = networkHelper.GetLocalIp()?.ToString() ?? "127.0.0.1"; var networkConfig = configProvider.GetConfig <NetworkConfig>(); networkConfig.MasterExternalIp = localHost; networkConfig.MasterHost = localHost; ChainSpecLoader chainSpecLoader = new ChainSpecLoader(new UnforgivingJsonSerializer()); string path = initParams.ChainSpecPath; if (!Path.IsPathRooted(path)) { path = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, path)); } byte[] chainSpecData = File.ReadAllBytes(path); ChainSpec chainSpec = chainSpecLoader.Load(chainSpecData); //Setting trusted nodes var nodes = chainSpec.NetworkNodes.Select(GetNode).ToArray(); networkConfig.TrustedPeers = nodes; networkConfig.BootNodes = nodes; networkConfig.DbBasePath = initParams.BaseDbPath; _ethereumRunner = new EthereumRunner(configProvider, networkHelper, logManager); await _ethereumRunner.Start(initParams); if (initParams.JsonRpcEnabled) { Bootstrap.Instance.ConfigProvider = configProvider; Bootstrap.Instance.LogManager = logManager; Bootstrap.Instance.BlockchainBridge = _ethereumRunner.BlockchainBridge; Bootstrap.Instance.EthereumSigner = _ethereumRunner.EthereumSigner; _jsonRpcRunner = new JsonRpcRunner(configProvider, Logger); await _jsonRpcRunner.Start(initParams); } else { if (Logger.IsInfoEnabled) { Logger.Info("Json RPC is disabled"); } } } catch (Exception e) { Logger.Error("Error while starting Nethermind.Runner", e); throw; } }
/// <summary> /// Register all of the dependencies to the container. /// </summary> private void Register() { IConfigProvider configProvider = new JsonConfigProvider(); configProvider.Load(StaticState.RemoteConfigUrl); this.AddSingleton(provider => configProvider); this.AddSingleton <LogFactory>(); this.AddTransient(provider => provider.GetService <LogFactory>().GetLogger()); this.AddSingleton <IDatabaseProvider, DatabaseProvider>(provider => new DatabaseProvider( configProvider.GetValueByKey("database.name"), configProvider.GetValueByKey("database.password"), uint.Parse(configProvider.GetValueByKey("database.port")), configProvider.GetValueByKey("database.host"), configProvider.GetValueByKey("database.username"))); var chromeOptions = new ChromeOptions(); chromeOptions.AddUserProfilePreference("profile.managed_default_content_settings.images", 2); chromeOptions.AddUserProfilePreference("profile.managed_default_content_settings.stylesheets", 2); chromeOptions.AddArgument("--disable-notifications"); chromeOptions.AddArgument("--user-agent=Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.97 Safari/537.36"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { chromeOptions.AddArgument("headless"); } if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { chromeOptions.AddArgument("--no-sandbox"); } this.AddSingleton <IWebDriver>(provider => new ChromeDriver(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), chromeOptions, TimeSpan.FromSeconds(120))); this.AddSingleton <ScraperQueueDao>(); this.AddSingleton <ScraperAccountDao>(); this.AddSingleton <InstagramProfileDao>(); var maleNames = Utilities.GetListFromLineOfStrings("https://cdn.cascade.io/lists/blacklisted-male-first-name-phrases.txt?v=10"); var maleUsernames = Utilities.GetListFromLineOfStrings("https://cdn.cascade.io/lists/blacklisted-male-username-phrases.txt?v=8"); var femaleNames = Utilities.GetListFromLineOfStrings("https://cdn.cascade.io/lists/female-first-name-phrases.txt?v=7"); this.AddSingleton <IScraperValidator>(provider => new InstagramValidator( maleNames, maleUsernames, femaleNames )); this.AddSingleton <ScraperSettingsDao>(); this.AddSingleton <ScraperSettings>(); this.AddSingleton(provider => new NotificationSender( "*********************", "***********************************************")); this.AddSingleton <InstagramEventHandler>(); this.AddSingleton(provider => new Dictionary <string, ISocialEventHandler> { { "instagram.com", provider.GetService <InstagramEventHandler>() }, }); this.AddSingleton(provider => { var bugSnagClient = new Client(new Configuration(StaticState.BugSnagApiKey)); bugSnagClient.BeforeNotify(report => { report.Event.User = new User { Id = "Worker " + StaticState.WorkerId, }; }); return(bugSnagClient); }); this.AddSingleton <ScraperWorker>(); this.AddSingleton <ScraperWorkerDao>(); }