public webui(JsonConfig setconfig, SecondBot setbot) { bot = setbot; siteconfig = setconfig; }
public bool reConnet(JsonConfig config) { return(connect.StartConnect(config)); }
public static void Save(CommonConfig config) { string configFileName = GetFileName(); JsonConfig.Save <CommonConfig>(config, configFileName); }
public async Task DatabricksTestEndToEndGeneration() { var flowName = "dbconfiggentest"; var testingConfig = await File.ReadAllTextAsync(@"Resource\databricksFlowSaved.json"); await DesignTimeStorage.SaveByName(flowName, testingConfig, FlowDataManager.DataCollectionName); await CommonData.Add("defaultJobTemplate", @"Resource\sparkJobTemplate.json"); await CommonData.Add(ConfigFlattenerManager.DefaultConfigName, @"Resource\flattenerConfig.json"); await CommonData.Add(FlowDataManager.CommonDataName_DefaultFlowConfig, @"Resource\flowDefault.json"); var result = await this.RuntimeConfigGeneration.GenerateRuntimeConfigs(flowName); var runtimeConfigFolder = result.Properties?.GetValueOrDefault(PrepareJobConfigVariables.ResultPropertyName_RuntimeConfigFolder, null); Assert.IsTrue(result.IsSuccess); Assert.AreEqual(expected: 4, actual: RuntimeStorage.Cache.Count); // verify output schema file is expected var expectedSchema = JsonConfig.From(await File.ReadAllTextAsync(@"Resource\schema.json")); var actualSchema = JsonConfig.From(RuntimeStorage.Cache[ResourcePathUtil.Combine(runtimeConfigFolder.ToString(), "inputschema.json")]); foreach (var match in JsonConfig.Match(expectedSchema, actualSchema)) { Assert.AreEqual(expected: match.Item2, actual: match.Item3, message: $"path:{match.Item1}"); } // verify output projection file is expected var expectedProjection = await File.ReadAllTextAsync(@"Resource\projection.txt"); var actualProjection = RuntimeStorage.Cache[ResourcePathUtil.Combine(runtimeConfigFolder.ToString(), "projection.txt")]; Assert.AreEqual(expected: expectedProjection, actual: actualProjection); // verify transform file is exepcted var expectedTransform = await File.ReadAllTextAsync(@"Resource\configgentest-combined.txt"); var actualTransform = RuntimeStorage.Cache[ResourcePathUtil.Combine(runtimeConfigFolder.ToString(), "dbconfiggentest-combined.txt")]; Assert.AreEqual(expected: expectedTransform, actual: actualTransform); // Verify output configuration is expected var actualConf = PropertiesDictionary.From(this.RuntimeStorage.Cache[ResourcePathUtil.Combine(runtimeConfigFolder.ToString(), $"{flowName}.conf")]); var expectedConf = PropertiesDictionary.From(await File.ReadAllTextAsync(@"Resource\databricksJobConfig.conf")); var matches = PropertiesDictionary.Match(expectedConf, actualConf).ToList(); foreach (var match in matches) { Console.WriteLine($"prop:{match.Item1 ?? "null"}, expected:<{match.Item2 ?? "null"}>, actual:<{match.Item3 ?? "null"}>"); } foreach (var match in matches) { Assert.AreEqual(expected: match.Item2, actual: match.Item3, message: $"property:{match.Item1}"); } // Verify metrics var expectedConfig = JsonConfig.From(await File.ReadAllTextAsync(@"Resource\databricksFlowStarted.json")); var actualConfig = JsonConfig.From(await this.DesignTimeStorage.GetByName(flowName, FlowDataManager.DataCollectionName)); foreach (var match in JsonConfig.Match(expectedConfig, actualConfig)) { Assert.AreEqual(expected: match.Item2, actual: match.Item3, message: $"path:{match.Item1}"); } Cleanup(); }
private async Task <OrderResponse> PlaceOrderAsync(Order order) { return(await SendServiceCall <OrderResponse>(HttpMethod.Post, "/orders", JsonConfig.SerializeObject(order)).ConfigureAwait(false)); }
void Test () { const string json = @"[{""$type"":""file"",""Code"":""code"",""Id"":""1029"",""Input"":"""",""NeedRun"":true}]"; var list = JsonConvert.DeserializeObject <List <RunnerSubmission> >(json, JsonConfig.GetSettings()); Assert.That(list.Count, Is.EqualTo(1)); Assert.That(list[0], Is.InstanceOf <FileRunnerSubmission>()); }
static void Main(string[] args) { InstallUtil(); Console.Clear(); Console.WriteLine("======================================"); Console.WriteLine("= TECZFTP - Download de arquivos ftp ="); Console.WriteLine("======================================\r\n"); Console.WriteLine("\r\n<<FIAP Challenge - SANOFI - Grupo +Vida>>\r\n"); Console.WriteLine("\tAntonio Ferrer (83398)"); Console.WriteLine("\tHenrique Lima (83324)"); Console.WriteLine("\tSidnei (82128)"); Console.WriteLine("\tVictor Ribeiro (81969)"); Console.WriteLine("\tWallace Sousa (82307)"); Util.Wait(); Console.Clear(); Console.WriteLine("Atenção!"); Console.WriteLine("Programa para uso estritamente acadêmico"); Console.WriteLine("Não deve ser usado para outros fins comerciais sem o consentimento de seu(s) criador(es)"); Util.Wait(); Console.WriteLine("Pressione [C] para informações de contato ou aguarde..."); var tsk = Task.Run(() => { if (Console.ReadLine().ToUpper() == "C") { Console.WriteLine("Antonio R. Ferrer - [email protected]"); Process.Start("mailto:[email protected]"); } }); tsk.Wait(TimeSpan.FromSeconds(3)); Console.Clear(); string configJs = args.FirstOrDefault() ?? "todo.js"; if (!System.IO.File.Exists(configJs)) { Console.WriteLine("arquivo de configuração não encontrado!"); Console.WriteLine("a aplicação será encerrada"); Util.Wait(); return; } Console.WriteLine("Carregando informações de " + configJs); string config = System.IO.File.ReadAllText(configJs); JsonConfig jsonConfig = JsonConvert.DeserializeObject <JsonConfig>(config); if (jsonConfig != null && jsonConfig?.Downloads?.Count > 0) { try { Console.Clear(); Console.WriteLine("Iniciando downloads..."); Util.Wait(); Console.Clear(); Console.WriteLine("@Start " + DateTime.Now + "\r\n\r\n"); DownloadManager dm = new DownloadManager(jsonConfig); dm.Download(Progress); Console.WriteLine("\r\n\r\n@End " + DateTime.Now); } catch (Exception ex) { Console.WriteLine("Ocorreu o erro:\r\n" + ex); } } Console.WriteLine("\r\n\r\nO programa será encerrado em 3 segundos..."); Util.Wait(); }
private async Task <LDAPEntity> ValidateRemoteCredentialsAsync(string username, string password, string domain) { ConfigHelper.TryGet("GlobalConfig:ActiveDirectoryEndpoint", out string endpoint); var uri = new Uri(endpoint); try { using (var httpClient = new HttpClient()) { var content = new { usuario = username, senha = password.Base64Encode(), dominio = domain }; var response = await httpClient.PostAsync(uri.AbsoluteUri, content, JsonConfig.Configure().MediaTypeFormatter); if (response.StatusCode == HttpStatusCode.OK) { var result = await response.Content.ReadAsAsync <LDAPEntity>(); return(result); } else if (response.StatusCode == HttpStatusCode.NotFound) { return(null); } else { response.EnsureSuccessStatusCode(); } } } catch (HttpRequestException ex) { _logger.LogError(ex, "Ocorreu um erro de comunicação com LDAP API."); } catch (Exception ex) { _logger.LogError(ex, "Ocorreu um erro na validação de credênciais de acesso."); } return(null); }
private void GenerateJobConfigContent(JobDeploymentSession job, string destFolder, JsonConfig defaultJobConfig) { Ensure.NotNull(destFolder, "destFolder"); Ensure.NotNull(defaultJobConfig, "defaultJobConfig"); // replace config with tokens from job and the flow var newJobConfig = job.Tokens.Resolve(defaultJobConfig); Ensure.NotNull(newJobConfig, "newJobConfig"); job.SetJsonToken(TokenName_JobConfigContent, newJobConfig); var jc = new JobConfig { Content = newJobConfig.ToString(), FilePath = ResourcePathUtil.Combine(destFolder, job.Name + ".conf"), SparkJobName = job.SparkJobName, }; job.JobConfigs.Add(jc); }
/// <summary> /// Obtiene los datos de la API con base en una URL concreta /// </summary> /// <typeparam name="T">API concreta a consumir</typeparam> /// <param name="apiUrl">URL concreta de la API</param> /// <returns>Toda la información relacionada con la API especificada en la URL</returns> public async Task <T> GetAsync <T>(string apiUrl) where T : class { T covidContentInfo = null; using (var httpClient = new HttpClient() { Timeout = TimeSpan.FromSeconds(_loginTimeOut) }) { httpClient.DefaultRequestHeaders.Accept.Clear(); httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); HttpResponseMessage response = await httpClient.GetAsync(_baseApiUrl + apiUrl); if (response.IsSuccessStatusCode) { string httpContent = await response.Content.ReadAsStringAsync(); covidContentInfo = JsonConvert.DeserializeObject <T>(httpContent, JsonConfig.GetJsonSerializerSettings()); } return(covidContentInfo); } }
public static async Task <T> ReadAsAsync <T>(this HttpContent content) { var s = await content.ReadAsStringAsync(); return(JsonConvert.DeserializeObject <T>(s, JsonConfig.GetSettings())); }
public CliHardware(string[] args) { SimpleIO io = new SimpleIO(); JsonConfig Config = new JsonConfig(); string loadFolder = "debug"; string json_file = "bot.json"; #if DEBUG LogFormater.Debug("!! RUNNING IN DEBUG !!"); #else LogFormater.Status("Hardware config"); if (args.Length == 1) { loadFolder = args[0]; } else { loadFolder = "default"; io.ChangeRoot("default"); LogFormater.Warn("Using: using default folder"); } #endif io.ChangeRoot(loadFolder); if (SimpleIO.DirExists("wiki") == false) { LogFormater.Info("Basic Wiki [Creating]"); new DebugModeCreateWiki(AssemblyInfo.GetGitHash(), io); LogFormater.Info("Basic Wiki [Ready]"); io = new SimpleIO(); } bool ok_to_try_start = false; if (SimpleIO.FileType(json_file, "json") == true) { if (io.Exists(json_file)) { string json = io.ReadFile(json_file); if (json.Length > 0) { try { Config = JsonConvert.DeserializeObject <JsonConfig>(json); ok_to_try_start = true; } catch (Exception e) { LogFormater.Warn("Unable to read config file\n moving config to " + json_file + ".old and creating a empty config\nError was: " + e.Message + ""); io.MarkOld(json_file); Config = new JsonConfig(); io.WriteJsonConfig(MakeJsonConfig.GetDefault(), json_file); } } else { LogFormater.Warn("Json config is empty creating an empty one for you"); io.WriteJsonConfig(MakeJsonConfig.GetDefault(), json_file); } } else { LogFormater.Warn("Json config does not Exist creating it for you"); io.WriteJsonConfig(MakeJsonConfig.GetDefault(), json_file); } } else { LogFormater.Crit("you must select a .json file for config! example \"BetterSecondBot.exe mybot\" will use the mybot.json file!"); } if (ok_to_try_start == true) { Config = MakeJsonConfig.Http_config_check(Config); new Discord_super(Config, false, loadFolder); } }
// If mock is enabled we skip the console readline. public static void Load(bool mocked = false) { m_Mocked = mocked; var updated = false; if (File.Exists(m_FilePath)) { logger.Information("Reading server configuration from {Path}...", _relPath); m_Settings = JsonConfig.Deserialize <ServerSettings>(m_FilePath); if (m_Settings == null) { logger.Error("Reading server configuration failed"); throw new FileNotFoundException($"Failed to deserialize {m_FilePath}."); } logger.Information("Reading server configuration done"); } else { updated = true; m_Settings = new ServerSettings(); } if (mocked) { return; } if (m_Settings.DataDirectories.Count == 0) { updated = true; foreach (var directory in ServerConfigurationPrompts.GetDataDirectories()) { m_Settings.DataDirectories.Add(directory); } } UOClient.Load(); var cuoClientFiles = UOClient.CuoSettings?.UltimaOnlineDirectory; if (cuoClientFiles != null) { DataDirectories.Add(cuoClientFiles); } if (m_Settings.Listeners.Count == 0) { updated = true; m_Settings.Listeners.AddRange(ServerConfigurationPrompts.GetListeners()); } bool?isPre60000 = null; if (m_Settings.Expansion == null) { var expansion = GetSetting <Expansion>("currentExpansion"); var hasExpansion = expansion != null; expansion ??= ServerConfigurationPrompts.GetExpansion(); if (expansion <= Expansion.ML && !hasExpansion) { isPre60000 = ServerConfigurationPrompts.GetIsClientPre6000(); if (isPre60000 == true) { SetSetting("maps.enablePre6000Trammel", true.ToString()); } } updated = true; m_Settings.Expansion = expansion; } if (isPre60000 != true) { if (ServerConfigurationPrompts.GetIsClient7090()) { updated = true; SetSetting("maps.enablePostHSMultiComponentFormat", true); } } Core.Expansion = m_Settings.Expansion.Value; if (updated) { Save(); Console.Write("Server configuration saved to "); Utility.PushColor(ConsoleColor.Green); Console.WriteLine($"{_relPath}."); Utility.PopColor(); } }
public async Task <CoinbaseResponse> DepositCoinbaseFundsAsync( string coinbaseAccountId, decimal amount, Currency currency) { var newCoinbaseDeposit = new Coinbase { Amount = amount, Currency = currency, CoinbaseAccountId = coinbaseAccountId }; return(await SendServiceCall <CoinbaseResponse>(HttpMethod.Post, "/deposits/coinbase-account", JsonConfig.SerializeObject(newCoinbaseDeposit)).ConfigureAwait(false)); }
public void ShouldFactoryAClass() { var file = JsonConfig.Factory("http://update.arcnet.com.br/autoupdatereasytest/config.json"); Assert.IsNotNull(file); }
public static T GetValue <T>(string path) { return(JsonConfig.GetValue <T>("..\\..\\..\\settings.json", path)); }
public void JsonNotFound() { JsonConfig.Factory("http://update.arcnet.com.br/autoupdatereasytest/config1.json"); }
public async Task <IActionResult> Config() { var config = await JsonConfig <SubmitSpiderConfig> .GetSiteConfigAsync(); return(View(config)); }
public void DnsNotResolve() { JsonConfig.Factory("http://update1.arcnet.com.br/autoupdatereasytest/myjsonupdater1.json"); }
public void Test_Serialization_and_Deserialization() { var inputList = new List <RunnerSubmission> { new ProjRunnerSubmission { Id = "E26C2109-F074-4117-B53F-0799E4140DEF", Input = "", NeedRun = true, ProjectFileName = "proj", ZipFileData = new byte[] { 1, 2, 3, 4, 5, 61, 23, 4, 3 } }, new FileRunnerSubmission { Code = "code", Id = "E9D8C168-A3D9-48CC-AF60-CE3B8A1D8314", Input = "", NeedRun = true } }; var json = JsonConvert.SerializeObject(inputList, JsonConfig.GetSettings()); var deserializedList = JsonConvert.DeserializeObject <List <RunnerSubmission> >(json, JsonConfig.GetSettings()); deserializedList.ShouldAllBeEquivalentTo(inputList); }
public override void LoadDefault() { data = new JsonConfig(); bossInfo = JsonConvert.DeserializeObject <List <Boss> >(File.ReadAllText("bossinfo.json")); Update(); }
public void WebSocket_MessageReceived(object sender, MessageReceivedEventArgs e) { if (stopWebSocket) { return; } var json = e.Message; var response = JsonConfig.DeserializeObject <BaseMessage>(json); switch (response.Type) { case ResponseType.Subscriptions: var subscription = JsonConfig.DeserializeObject <Subscription>(json); webSocketFeed.Invoke(OnSubscriptionReceived, sender, new WebfeedEventArgs <Subscription>(subscription)); break; case ResponseType.Ticker: var ticker = JsonConfig.DeserializeObject <Ticker>(json); webSocketFeed.Invoke(OnTickerReceived, sender, new WebfeedEventArgs <Ticker>(ticker)); break; case ResponseType.Snapshot: var snapshot = JsonConfig.DeserializeObject <Snapshot>(json); webSocketFeed.Invoke(OnSnapShotReceived, sender, new WebfeedEventArgs <Snapshot>(snapshot)); break; case ResponseType.L2Update: var level2 = JsonConfig.DeserializeObject <Level2>(json); webSocketFeed.Invoke(OnLevel2UpdateReceived, sender, new WebfeedEventArgs <Level2>(level2)); break; case ResponseType.Heartbeat: var heartbeat = JsonConfig.DeserializeObject <Heartbeat>(json); webSocketFeed.Invoke(OnHeartbeatReceived, sender, new WebfeedEventArgs <Heartbeat>(heartbeat)); break; case ResponseType.Received: var received = JsonConfig.DeserializeObject <Received>(json); webSocketFeed.Invoke(OnReceivedReceived, sender, new WebfeedEventArgs <Received>(received)); break; case ResponseType.Open: var open = JsonConfig.DeserializeObject <Open>(json); webSocketFeed.Invoke(OnOpenReceived, sender, new WebfeedEventArgs <Open>(open)); break; case ResponseType.Done: var done = JsonConfig.DeserializeObject <Done>(json); webSocketFeed.Invoke(OnDoneReceived, sender, new WebfeedEventArgs <Done>(done)); break; case ResponseType.Match: var match = JsonConfig.DeserializeObject <Match>(json); webSocketFeed.Invoke(OnMatchReceived, sender, new WebfeedEventArgs <Match>(match)); break; case ResponseType.LastMatch: var lastMatch = JsonConfig.DeserializeObject <LastMatch>(json); webSocketFeed.Invoke(OnLastMatchReceived, sender, new WebfeedEventArgs <LastMatch>(lastMatch)); break; case ResponseType.Error: var error = JsonConfig.DeserializeObject <Error>(json); webSocketFeed.Invoke(OnErrorReceived, sender, new WebfeedEventArgs <Error>(error)); break; default: throw new ArgumentOutOfRangeException(); } }
public override void LoadFrom(BinaryReader br) { data = JsonConvert.DeserializeObject <JsonConfig>(new StreamReader(br.BaseStream).ReadToEnd()); bossInfo = JsonConvert.DeserializeObject <List <Boss> >(File.ReadAllText("bossinfo.json")); Update(); }
public static void Configure() { // Set to true to support < 6.0.0 clients where map0.mul is both Felucca & Trammel var pre6000Trammel = ServerConfiguration.GetOrUpdateSetting("maps.enablePre6000Trammel", false); var failures = new List <string>(); var count = 0; var path = Path.Combine(Core.BaseDirectory, "Data/map-definitions.json"); logger.Information("Loading Map Definitions"); var stopwatch = Stopwatch.StartNew(); var maps = JsonConfig.Deserialize <List <MapDefinition> >(path); if (maps == null) { throw new JsonException($"Failed to deserialize {path}."); } foreach (var def in maps) { if (def.Id == 1 && pre6000Trammel) { // Use Old Haven by changing file index to Felucca def.FileIndex = 0; } try { RegisterMap(def); count++; } catch (Exception ex) { #if DEBUG Console.WriteLine(ex); #endif failures.Add($"\tInvalid map definition {def.Name} ({def.Id})"); } } stopwatch.Stop(); if (failures.Count > 0) { logger.Warning( "Map Definitions loaded with failures ({0} maps, {1} failures) ({2:F2} seconds)", count, failures.Count, stopwatch.Elapsed.TotalSeconds ); logger.Warning(string.Join(Environment.NewLine, failures)); } else { logger.Information( "Map Definitions loaded successfully ({0} maps, {1} failures) ({2:F2} seconds)", count, failures.Count, stopwatch.Elapsed.TotalSeconds ); } }
public async Task <DepositResponse> DepositFundsAsync( string paymentMethodId, decimal amount, Currency currency) { var newDeposit = new Deposit { Amount = amount, Currency = currency, PaymentMethodId = new Guid(paymentMethodId) }; return(await SendServiceCall <DepositResponse>(HttpMethod.Post, "/deposits/payment-method", JsonConfig.SerializeObject(newDeposit)).ConfigureAwait(false)); }
public Adapter(JsonConfig config) { connect = new Connect(config); }
public void Initialize() { _container.Register<INetworkStack>(() => { return new NetworkStack(); }); _container.Register<NetworkConfig>(() => { JsonConfig config = new JsonConfig("network.json", "config"); return config.LoadSection<NetworkConfig>(); }); _container.Register<IEventAggregator>(() => { return new EventAggregator(); }); _container.Register<IDefaultLogger>(() => { DefaultLogger logger = new DefaultLogger(); logger.Create("NetworkLogger"); return logger; }); }
void Run() { #region init ILoggerFactory fac = new NLoggerFactory(); logger = fac.GetLogger(this.GetType()); ExitCatcher catcher = new ExitCatcher(); catcher.Subscribe(() => { logger.Info("Daemon back to limbo\n"); }); logger.Info("Daemon wakes up"); IConfig config = new JsonConfig(fac); config.Load(Properties.Settings.Default.LOCALES); #endregion #region registeration logger.Info("Daemon assembles"); Container container = new Container(); container.Register<ILoggerFactory, NLoggerFactory>(); container.Register<IEar>(() => {return new ConsoleEar(fac, config.Get<float>("minaccuracy"));}); container.Register<IMouth, SimpleMouth>(); container.Register<INerve>(() => { return new DebugNerve(fac, config.Get<string>("server")); }); container.Register<ICortex, SimpleCortex>(); container.Register<ISimulacre, Simulacre>(); #endregion #region startup logger.Info("Daemon summons Charlie\n"); Personae charlie = new Personae { Name = "Charlie", Grammar = "charlieGrammar.xml", Voice = "Microsoft Hortense Desktop" }; container.GetInstance<ISimulacre>().Summon(charlie); #endregion }
public void TestInitialize() { ILoggerFactory logFac = new LoggerFactoryMock(); config = new JsonConfig(logFac); }