protected override async Task ExecuteAsync(CancellationToken stoppingToken) { while (!stoppingToken.IsCancellationRequested) { try { string token = refreshToken(); var urlArral = ConfigExtensions.GetListAppSettings <string>("url"); HttpRequestClient http = new HttpRequestClient(); http.ContentType = "application/json"; Dictionary <string, string> dictionary = new Dictionary <string, string>(); dictionary.Add("Authorization", "Bearer " + token); http.dicion = dictionary; foreach (var url in from url in urlArral let html = http.HttpGet(url) where html.StatusCode == HttpStatusCode.OK select url) { _logger.LogInformation("执行------>>>>>" + url + "-------<<<<成功"); } //需要执行的任务 } catch (Exception ex) { _logger.LogError(ex.Message); } await Task.Delay(Convert.ToInt32(ConfigExtensions.Configuration["Interval"]), stoppingToken); } }
public void GetGlobalMarketView() { HttpRequestClient client = new HttpRequestClient(); var obj = client.GetGlobalMarketView(); tblGlobalMarketView gmv = new tblGlobalMarketView(); Guid guid = Guid.NewGuid(); gmv = new tblGlobalMarketView() { ID = guid, ActiveAssets = Utlity.ParseInt(obj.ActiveAssets), ActiveCurrencies = Utlity.ParseInt(obj.ActiveCurrencies), ActiveMarkets = Utlity.ParseInt(obj.ActiveMarkets), BTCPercentageofMarketCap = Utlity.ParseDouble(obj.BTCPercentageOfMarketCap), LastUpdated = obj.LastUpdated, TimeStamp = DateTime.Now, Total24HVolumeConvertCurrency = Utlity.ParseDecimal(obj.Total24hVolumeConvertCurrency), Total24HVolumeUSD = Utlity.ParseDecimal(obj.Total24hVolumeUSD), TotalMarketCapConvertCurrency = Utlity.ParseDecimal(obj.TotalMarketCapConvertCurrency), TotalMarketCapUSD = Utlity.ParseDecimal(obj.TotalMarketCapUSD), TransactionID = guid.ToString().GetHashCode() }; CurrencyDataContext.InsertGlobalMarketView(gmv); }
private static async Task Main(string[] args) { // Subscribe start var handler = new Handler(); await handler.SubscribeAndStartAsync(); // Subscribe end while (true) { Console.WriteLine("Press any key to start or ESC to exit."); var key = Console.ReadKey(); if (key.Key == ConsoleKey.Escape) { break; } var sw = Stopwatch.StartNew(); // Request start using IRequestClient client = new HttpRequestClient("http://localhost:5000"); var weatherForecasts = await client.GetAsync <List <WeatherForecast> >("/WeatherForecast"); foreach (var forecast in weatherForecasts) { Console.WriteLine(forecast.Date + ": " + forecast.TemperatureC); } // Request end Console.WriteLine("Request finished in " + sw.Elapsed); } await handler.StopAsync(); }
public string GetProfileContent(string profileServiceName, string application, string profile) { var invoker = new ProfileInvoker <string>((i, node, path) => { string url = i.JoinURL(node, path); string query = $"?application={application}&profile={profile}"; try { var result = HttpRequestClient.Request(url + query, "GET", false).Send().GetBodyContent(true); return(result); } catch (Exception e) { LogManager.Error("GetProfileContent error", e.Message); } return(string.Empty); }); var context = new InvokerContext( new DirectoryContext("Profile/Pull", profileServiceName), new ClusterContext(FailoverCluster.NAME), new LoadBalanceContext(RandomLoadBalance.NAME)); return(ClientInvoker.Invoke(invoker, context)); }
private async ValueTask <RemoteSchemaDefinition?> FetchSchemaDefinitionAsync( CancellationToken cancellationToken) { using var writer = new ArrayWriter(); IQueryRequest request = QueryRequestBuilder.New() .SetQuery( $@"query GetSchemaDefinition($c: String!) {{ {SchemaDefinitionFieldNames.SchemaDefinitionField}(configuration: $c) {{ name document extensionDocuments }} }}") .SetVariableValue("c", new StringValueNode(_configuration.Value)) .Create(); HttpRequestMessage requestMessage = await HttpRequestClient .CreateRequestMessageAsync(writer, request, cancellationToken) .ConfigureAwait(false); HttpResponseMessage responseMessage = await _httpClient .SendAsync(requestMessage, cancellationToken) .ConfigureAwait(false); IQueryResult result = await HttpRequestClient .ParseResponseMessageAsync(responseMessage, cancellationToken) .ConfigureAwait(false); if (result.Errors is { Count : > 1 })
private async Task <bool> ValidateToken(string token) { var encodedToken = System.Web.HttpUtility.UrlEncode(token); var authUri = $"{_configuration["AuthorizationServiceEndpoint"]}Login/ValidateToken?token={encodedToken}"; var IsValid = await HttpRequestClient.GetRequest <bool>(authUri); return(IsValid); }
public ActionResult Index() { var requestClient = new HttpRequestClient(); var model = requestClient.GetFixtureTable(); return View(model); }
/// <summary> /// OnSendEnd() /// </summary> public virtual void OnSendEnd(HttpRequestClient request) { SendEnd?.Invoke(this, new RequestEventArgs() { Request = request }); Request = request; }
public async Task <ActionResult <GifGiphy> > RandomAsync() { HttpRequestClient client = new HttpRequestClient(); //HttpResponse<List<Gif>> response = new HttpResponse<List<Gif>>(); HttpResponse <GifGiphy> response = await client.GetAsync <HttpResponse <GifGiphy> >(BaseUrl + "/random?api_key=uDl0yncHQqgk1r6zkkCh0tNkHGqpQmUn"); return(response.Data); }
public SrvBlockchainHelper(IWalletCredentialsRepository walletCredentialsRepository, HttpRequestClient requestClient, BaseSettings settings, ILog log, IWalletCredentialsHistoryRepository walletCredentialsHistoryRepository) { _walletCredentialsRepository = walletCredentialsRepository; _requestClient = requestClient; _settings = settings; _log = log; _walletCredentialsHistoryRepository = walletCredentialsHistoryRepository; }
public override async Task <bool> Run() { this.Info($"Host:{Arguments.Host} Start rollBack from version:" + Arguments.DeployFolderName); HttpRequestClient httpRequestClient = new HttpRequestClient(); httpRequestClient.SetFieldValue("publishType", "windowservice_rollback"); httpRequestClient.SetFieldValue("id", Arguments.LoggerId); httpRequestClient.SetFieldValue("serviceName", Arguments.ServiceName); httpRequestClient.SetFieldValue("deployFolderName", Arguments.DeployFolderName); httpRequestClient.SetFieldValue("Token", Arguments.Token); HttpLogger HttpLogger = new HttpLogger { Key = Arguments.LoggerId, Url = $"http://{Arguments.Host}/logger?key=" + Arguments.LoggerId }; var isSuccess = true; WebSocketClient webSocket = new WebSocketClient(this.Log, HttpLogger); try { var hostKey = await webSocket.Connect($"ws://{Arguments.Host}/socket"); httpRequestClient.SetFieldValue("wsKey", hostKey); var uploadResult = await httpRequestClient.Upload($"http://{Arguments.Host}/rollback", null, GetProxy()); webSocket.ReceiveHttpAction(true); if (webSocket.HasError) { isSuccess = false; this.Error($"Host:{Arguments.Host},Rollback Fail,Skip to Next"); } else { if (uploadResult.Item1) { this.Info($"【rollback success】Host:{Arguments.Host},Response:{uploadResult.Item2}"); } else { isSuccess = false; this.Error($"Host:{Arguments.Host},Response:{uploadResult.Item2},Skip to Next"); } } } catch (Exception ex) { isSuccess = false; this.Error($"Fail Rollback,Host:{Arguments.Host},Response:{ex.Message},Skip to Next"); } finally { await webSocket?.Dispose(); } return(await Task.FromResult(isSuccess)); }
public async Task <IActionResult> Delete(int driverId) { string DeleteDriverUri = $"{Configuration["DriverServiceEndpoint"]}/Drivers/Delete/{driverId}"; await HttpRequestClient.DeleteRequest <object>(DeleteDriverUri); string DeleteDriverForOrderMicroserviceUri = $"{Configuration["OrderServiceEndpoint"]}/Drivers/Delete/{driverId}"; await HttpRequestClient.DeleteRequest <object>(DeleteDriverForOrderMicroserviceUri); return(Ok()); }
public async Task <IActionResult> Edit(Driver driver) { string EditDriverUri = $"{Configuration["DriverServiceEndpoint"]}/Drivers/Edit"; await HttpRequestClient.PutRequest <object>(EditDriverUri, driver); string EditDriverForOrderMicroserviceUri = $"{Configuration["OrderServiceEndpoint"]}/Drivers/Edit"; await HttpRequestClient.PutRequest <object>(EditDriverForOrderMicroserviceUri, driver); return(Ok()); }
public ShellViewModel() { AppDomain appDomain = AppDomain.CurrentDomain; appDomain.UnhandledException += new UnhandledExceptionEventHandler(ShutDown); EventAggregationProvider.EventAggregator.Subscribe(this); ActivateItem(new FileTabViewModel()); CamWindowViewModel = new CamWindowViewModel(); httpRequestClient = HttpRequestClient.Instance(); }
public void InvalidUrlThrowsException() { var client = new HttpClient(); var url = "https://INVALIDurl.co"; var path = "api/starships/?format=json"; client.BaseAddress = new Uri(url); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var ex = Assert.ThrowsAsync <Exception>(() => HttpRequestClient.GetShipAsync(path, client)); }
public async Task <IActionResult> Edit(Restaurant restaurant) { string EditRestaurantUri = $"{Configuration["RestaurantServiceEndpoint"]}/Restaurant/Edit"; await HttpRequestClient.PutRequest <object>(EditRestaurantUri, restaurant); string EditRestaurantForCustomerMicroserviceUri = $"{Configuration["CusotmerServiceEndpoint"]}/Restaurant/Edit"; await HttpRequestClient.PutRequest <object>(EditRestaurantForCustomerMicroserviceUri, restaurant); string EditRestaurantForOrderMicroserviceUri = $"{Configuration["OrderServiceEndpoint"]}/Restaurant/Edit"; await HttpRequestClient.PutRequest <object>(EditRestaurantForOrderMicroserviceUri, restaurant); return(Ok()); }
public async Task <IActionResult> Delete(int restaurantId) { string DeleteRestaurantUri = $"{Configuration["RestaurantServiceEndpoint"]}/Restaurant/Delete/{restaurantId}"; await HttpRequestClient.DeleteRequest <object>(DeleteRestaurantUri); string DeleteRestaurantForCustomerMicroserviceUri = $"{Configuration["CusotmerServiceEndpoint"]}/Restaurant/Delete/{restaurantId}"; await HttpRequestClient.DeleteRequest <object>(DeleteRestaurantForCustomerMicroserviceUri); string DeleteRestaurantForOrderMicroserviceUri = $"{Configuration["OrderServiceEndpoint"]}/Restaurant/Delete/{restaurantId}"; await HttpRequestClient.DeleteRequest <object>(DeleteRestaurantForOrderMicroserviceUri); return(Ok()); }
public async Task <IActionResult> Edit(MenuItem menuItem) { string EditMenuItemUri = $"{Configuration["RestaurantServiceEndpoint"]}/MenuItem/Edit"; await HttpRequestClient.PutRequest <object>(EditMenuItemUri, menuItem); string EditMenuItemForCustomerMicroserviceUri = $"{Configuration["CusotmerServiceEndpoint"]}/MenuItem/Edit"; await HttpRequestClient.PutRequest <object>(EditMenuItemForCustomerMicroserviceUri, menuItem); string EditMenuItemForOrderMicroserviceUri = $"{Configuration["OrderServiceEndpoint"]}/MenuItem/Edit"; await HttpRequestClient.PutRequest <object>(EditMenuItemForOrderMicroserviceUri, menuItem); return(Ok()); }
//写诗 static string ComposePoem(string imageBase64) { string url = "https://poem.msxiaobing.com/api/upload";//小冰上传图片地址 HttpRequestClient httpRequestClient = new HttpRequestClient(); httpRequestClient.SetFieldValue("userid", new Guid().ToString("x")); //发送数据 httpRequestClient.SetFieldValue("text", ""); //发送数据 httpRequestClient.SetFieldValue("guid", new Guid().ToString("x")); //发送数据 httpRequestClient.SetFieldValue("image", imageBase64.Split(',')[1]); //发送数据 string responseText = string.Empty; bool uploaded = httpRequestClient.Upload(url, out responseText); return(responseText); }
public void Test_ExecuteBearerToken_ToUpdate_TheGlobalBearerToken() { try { HttpRequestClient httpRequestClient = TestHelper.InitializeHttpRequestClientWithCorrectCredential(); string bearerToken = httpRequestClient.ExecuteBearerTokenRequest().GetAwaiter().GetResult(); // Check that the Bearer Token generated is equal to the one in the global variable Assert.AreEqual(bearerToken, httpRequestClient.BearerToken); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public async Task <IActionResult> Add(MenuItem menuItem) { string AddMenuItemUri = $"{Configuration["RestaurantServiceEndpoint"]}/MenuItem/Add"; var response = await HttpRequestClient.PostRequest <AddResponseModel>(AddMenuItemUri, menuItem); menuItem.Id = response.Id; string AddMenuItemForCustomerMicroserviceUri = $"{Configuration["CusotmerServiceEndpoint"]}/MenuItem/Add"; await HttpRequestClient.PostRequest <object>(AddMenuItemForCustomerMicroserviceUri, menuItem); string AddMenuItemForOrderMicroserviceUri = $"{Configuration["OrderServiceEndpoint"]}/MenuItem/Add"; await HttpRequestClient.PostRequest <object>(AddMenuItemForOrderMicroserviceUri, menuItem); return(Ok()); }
public async Task <IActionResult> GetOrders(int customerId) { string GetCustomerUri = $"{Configuration["CusotmerServiceEndpoint"]}/Customers/Get/{customerId}"; CustomerDetails customerDetails = await HttpRequestClient.GetRequest <CustomerDetails>(GetCustomerUri); string GetOrderUri = $"{Configuration["OrderServiceEndpoint"]}/Orders/GetByCustomer/{customerId}"; List <OrderDetails> orderDetails = await HttpRequestClient.GetRequest <List <OrderDetails> >(GetOrderUri); if (orderDetails == null) { orderDetails = new List <OrderDetails>(); } customerDetails.OrderDetails = orderDetails; return(Ok(customerDetails)); }
public async Task <IActionResult> AddCustomer(Customer customer) { User user = new User() { Email = customer.Email, Password = customer.Password, Role = UserRole.Customer }; string AddUserUri = $"{Configuration["AuthorizationServiceEndpoint"]}/Users/Add"; await HttpRequestClient.PostRequest <object>(AddUserUri, user); string AddCustomerUri = $"{Configuration["CusotmerServiceEndpoint"]}/Customers/Add"; await HttpRequestClient.PostRequest <object>(AddCustomerUri, customer); return(Ok()); }
public void Test_ExecuteBearerToken_WithWrongCredential() { try { HttpRequestClient httpRequestClient = TestHelper.InitializeHttpRequestClientWithCorrectCredential(); string bearerToken = httpRequestClient.ExecuteBearerTokenRequest().GetAwaiter().GetResult(); } catch (XenteIncorrectRequestException ex) { Assert.AreEqual("Incorrect Authentication Credentials", ex.Message); } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public static HttpRequestClient InitializeHttpRequestClientWithWrongCredential() { //Authenication Credentias const string apikey = "WrongApikey"; const string password = "******"; const Mode mode = Mode.Sandbox; AuthCredential authCredential = new AuthCredential(apikey, password, mode); HttpRequestClient httpRequestClient = HttpRequestClient.GetInstance(authCredential); return(httpRequestClient); }
public static HttpRequestClient InitializeHttpRequestClientWithCorrectCredential() { //Authenication Credentias const string apikey = "6A19EA2A706041A599375CC95FF08809"; const string password = "******"; const Mode mode = Mode.Sandbox; AuthCredential authCredential = new AuthCredential(apikey, password, mode); HttpRequestClient httpRequestClient = HttpRequestClient.GetInstance(authCredential); return(httpRequestClient); }
public virtual ResultWithData <string> SayHello(string name, int age, InvokerContext context = null) { var actualContext = context as ServiceInvokerContext; var foodInvoker = new DemoInvoker <ResultWithData <string> >((invoker, node, path) => { LogManager.Info("==test==", JsonConvert.SerializeObject(node)); string url = invoker.JoinURL(node, path) + "?name=" + name + "&age=" + age; var request = HttpRequestClient.Request(url, "GET", false); request.Headers.Add("SystemId", actualContext.SystemId); request.Headers.Add("Version", actualContext.Version); return(request.Send() .GetBodyContent <ResultWithData <string> >(close: true)); }); return(ClientInvoker.Invoke(foodInvoker, context)); }
public static void GetMyIpPort(ref string ip, ref int port) { string url = "http://api.ip.data5u.com/dynamic/get.html?order=7000cbf17bb5c8349ee19886bf92906e&json=1&sep=3"; HttpRequestClient s = new HttpRequestClient(true); string result = s.httpGet(url, "", "", "", 0).Replace("\"", ""); if (!string.IsNullOrEmpty(result) && result.Contains("ip")) { // var cls = JsonConvert.DeserializeObject<EntityModel>(result); int indexIp = result.IndexOf("ip") + 3; int indexNum = result.IndexOf(","); ip = result.Substring(indexIp, indexNum - indexIp); int indexPort = result.IndexOf("port") + 5; indexNum = result.IndexOf("ttl") - 1; port = int.Parse(result.Substring(indexPort, indexNum - indexPort)); } }
private async Task SendNotification(string type, string message, string sender = null) { var webHookUrl = _slackIntegrationSettings.GetChannelWebHook(type); if (webHookUrl == null) { return; } var text = new StringBuilder(); if (!string.IsNullOrEmpty(_slackIntegrationSettings.Env)) { text.AppendLine($"Environment: {_slackIntegrationSettings.Env}"); } text.AppendLine(sender != null ? $"{sender} : {message}" : message); await HttpRequestClient.PostRequestAsync(webHookUrl, new { text = text.ToString() }.ToJson()); }
static async Task RunAsync() { var shipsUnableToCalc = new List <string>(); try { Ship[] ships = await HttpRequestClient.GetShipAsync("api/starships/?format=json", client); if (ships.Length > 0) { foreach (var ship in ships) { if (ship.MGLT > 0) { Console.WriteLine(ship.Name + ": " + Calculations.GetResupplyCount(megaLights, ship)); } else { shipsUnableToCalc.Add(ship.Name); } } if (verboseOperation) { Console.WriteLine("\nUnable to calculate resupply frequence for the following ships:"); foreach (var s in shipsUnableToCalc) { Console.WriteLine(s); } } } else { throw new Exception("No Ships were found\nMove along"); } } catch (Exception e) { Console.WriteLine(e.Message); } }
public async static void Login(string device, string PicPath) { try { string responseText = ""; FileStream fs = new FileStream(PicPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] fileBytes = new byte[fs.Length]; fs.Read(fileBytes, 0, fileBytes.Length); fs.Close(); fs.Dispose(); HttpRequestClient httpRequestClient = new HttpRequestClient(); httpRequestClient.SetFieldValue("device", device); httpRequestClient.SetFieldValue("pic", Path.GetFileName(PicPath), "application/octet-stream", fileBytes); string UploadApiUrl = ServerUrl + "/wgcs/custom/upload"; httpRequestClient.Upload(UploadApiUrl, out responseText); } catch (Exception ex) { MessageBox.Show("服务器连接异常!"); } }