static async Task Main(string[] args) { const int MAX_NUMBER_REQUEST = 800; const string BEARER_KEY = "Bearer {replace with you bearer token from your tweeter dev account}"; const int MAX_RESULTS_PER_REQUEST = 99; //parameters var NewestDate = DateTime.Parse("2021-05-14T07:00:33Z"); var OldestDate = DateTime.Parse("2020-12-28T07:00:33Z"); var searchKeys = "doge bitcoin"; var username = "******"; var httpClient = new CustomHttpClient(); var serializer = new CustomJsonSerializer(); var tweeterSearch = new TweetSearch(MAX_NUMBER_REQUEST, MAX_RESULTS_PER_REQUEST, BEARER_KEY, httpClient, serializer); Console.WriteLine("Process started. Please wait.."); var final_result = await tweeterSearch.GetAllRelevantTweets(username, NewestDate, OldestDate, searchKeys); Console.WriteLine("------------------------------------------------------------------------"); foreach (var tweet in final_result) { Console.WriteLine(string.Format("{0} ({1})\r\n", tweet.text, tweet.created_At)); } }
public GameController(Account account, TabPage tabPage) { tabPage.Text = account.AccountName + " - Speed: " + account.Speed.ToString(); PlayerAccount = account; WebBrowser = (WebBrowser)tabPage.Controls.Find("webBrowser", true)[0]; WebBrowser.ScriptErrorsSuppressed = true; StatusStrip ss = (StatusStrip)tabPage.Controls.Find("statusStrip1", true)[0]; ProgressBar = (ToolStripProgressBar)ss.Items.Find("tspbOpperationProgress", true)[0]; ProgressLabel = (ToolStripStatusLabel)ss.Items.Find("tsslOpperation", true)[0]; ProgressLabel.Text = "Starting up, starting login soon."; Client = new CustomHttpClient(account); HtmlReader = new HtmlReader(); WorkerPriorityQueue = new SimplePriorityQueue <IWorker, int>(); var loginWorker = new LoginWorker(PlayerAccount, Client, HtmlReader, WebBrowser, ProgressLabel, ProgressBar); loginWorker.Worker.RunWorkerCompleted += Worker_RunWorkerCompleted; WorkerPriorityQueue.Enqueue(loginWorker, 0); IWorker worker = WorkerPriorityQueue.Dequeue(); worker.StartWork(); }
private async void UnknownApiExceptionTest() { var httpClient = new CustomHttpClient(); await Assert.ThrowsAsync <UnknownApiException>( () => httpClient.Execute(new Uri("http://alex.com"), HttpVerb.Get, null)); }
public async Task DownloadSource(Component componente) { string url = String.Format($"{Config.SonarBaseUrl}{Config.SourcesUrl}", componente.key); //var client = new CustomHttpClient<List<KeyValuePair<int, string>>>(Config); var client = new CustomHttpClient <SourcesResponse>(Config); var sourceResponse = await client.GetAsync(url); componente.source = new Source(); componente.source.lines = new List <SourceLine>(); //{ // lines = sourceResponse.sources.Select( // s=> new SourceLine() { lineNum = (int)s[0], lineText = ((string)s[1])} ).ToList() //}; int lineNum = 1; foreach (var item in sourceResponse.sources) { var text = (string)item[1]; componente.source.lines.Add(new SourceLine() { lineNum = lineNum, lineText = text }); lineNum++; } }
static void Main(string[] args) { IGenericHttpClient <ProductDto> httpClientSample = new CustomHttpClient <ProductDto>(); IProductService productService = new ProductManager(httpClientSample); var products = productService.GetAll(); var product = productService.GetById(1); Console.WriteLine("Http Client Worked..."); IGenericHttpClient <ProductDto> restClientSample = new CustomRestClient <ProductDto>(); IProductService productService2 = new ProductManager(restClientSample); var products2 = productService2.GetAll(); var product2 = productService2.GetById(1); Console.WriteLine("Rest Client Worked..."); Console.Read(); }
private void ShowChososenPhoto(Intent data) { imageView.SetImageURI(data.Data); CustomHttpClient client = new CustomHttpClient(); string json = client.UploadImage(data.Data.Path); ChangeActivity(json); }
public AuthService(CustomHttpClient customHttpClient, AuthenticationStateProvider authenticationStateProvider, ILocalStorageService localStorage) { _customHttpClient = customHttpClient; _authenticationStateProvider = authenticationStateProvider; _localStorage = localStorage; }
public async Task DownloadMetrics(Project proyecto) { string url = String.Format($"{Config.SonarBaseUrl}{Config.MetricsUrl}", proyecto.Key); var client = new CustomHttpClient <Measures>(Config); proyecto.Measure = await client.GetAsync(url); }
public static async Task <FundraisingDetail> GetFundraisingDetail(int id) { var request = new GetFundraisingDetailRequest { ID = id }; return(await CustomHttpClient.Post <FundraisingDetail>(request, "/GetFundraisingDetail")); }
public void GetApplicationUsers() { using (var client = new CustomHttpClient("http://localhost:3314/api")) { client.LoginWindows(); var users = client.LoadAsync<ApplicationUser>(); Assert.IsTrue(users.Wait(5000)); } }
static void UpdateDepartment(short DepartmentId) { var httpManeger = new CustomHttpClient(); bool result = httpManeger.UpdateDepartment(DepartmentId).Result; string Message = result ? "L'opération s'est exécuté avec succès" : "L'opération a échoué"; Console.WriteLine(Message); }
static void DeleteDepartment(int departmentID) { var httpManeger = new CustomHttpClient(); bool result = httpManeger.DeleteElement(departmentID).Result; string Message = result ? "L'opération s'est exécuté avec succès" : "L'opération a échoué"; Console.WriteLine(Message); }
static void GetDepartmentById(int departmentId) { var httpManeger = new CustomHttpClient(); var department = httpManeger.GetDepartementById(departmentId); Console.WriteLine("Id: " + department.DepartmentId); Console.WriteLine("Name: " + department.Name); Console.WriteLine("GroupName: " + department.GroupName); }
static void AddDepartment() { var httpManeger = new CustomHttpClient(); bool result = httpManeger.PostData().Result; string Message = result ? "L'opération s'est exécuté avec succès" : "L'opération a échoué"; Console.WriteLine(result); }
static void GetAllDepartment() { var httpManeger = new CustomHttpClient(); var departments = httpManeger.GetDepartement(); foreach (var department in departments) { Console.WriteLine(department.Name); } }
public AzureDevOpsLogic(OptionsDto optionsDto) { _optionsDto = optionsDto; _httpClient = new CustomHttpClient(); _fileBuildOrderLogic = new FileBuildOrderLogic(optionsDto); //Define PAT token var authToken = Convert.ToBase64String(Encoding.ASCII.GetBytes($":{_optionsDto.ApiKey}")); //Define Authorization _httpClient.SetAuthorization(new AuthenticationHeaderValue("Basic", authToken)); }
public async Task <IList <Contact> > GetAllContactsDetails() { using (var httpClient = new CustomHttpClient()) { httpClient.BaseAddress = _baseAddress; var response = await httpClient.GetAsync(GetAllContactsDetailsUrl); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsAsync <IList <Contact> >(); return(result); } }
static void Main(string[] args) { var myHttpClient = new CustomHttpClient(); var x = myHttpClient.GetItem <Object>("http://localhost:49597/Setting").Result; myHttpClient.PostItem( new Object(), "http://localhost:49597/Setting").Wait(); Console.WriteLine(x); Console.Read(); }
private async void GetUpdatesAsync() { var parameters = $@"offset={_offset}&allowed_updates={_parameters}"; var updatesJToken = await CustomHttpClient.MakeRequest("getUpdates", parameters); var lastUpdateIdJToken = updatesJToken["result"].Last?["update_id"]; if (lastUpdateIdJToken != null) { var lastUpdateId = int.Parse(lastUpdateIdJToken.ToString()); _offset = lastUpdateId + 1; } OnUpdatesRecieved(updatesJToken); }
public async Task DownloadNewIssues(Project proyecto) { string url = String.Format($"{Config.SonarBaseUrl}{Config.IssuesUrl}", proyecto.Key); var client = new CustomHttpClient <IssuesResponse>(Config); var issuesResponse = await client.GetAsync(url); proyecto.Issues = issuesResponse.issues; proyecto.Components = issuesResponse.components; await Task.WhenAll( from comp in proyecto.Components where comp.qualifier == "FIL" select DownloadSource(comp)); }
public async Task <bool> CreateContactDetails(Contact contact) { using (var httpClient = new CustomHttpClient()) { httpClient.BaseAddress = _baseAddress; var response = await httpClient.PostAsJsonAsync(CreateContactDetailsUrl, contact); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsAsync <bool>(); return(result); } }
private void ConfigureAzureBlobStorage(IServiceCollection services) { AzureBlobStorageConfiguration azureBlobStorageConfiguration = Configuration.GetSection($"AzureConfiguration:{nameof(AzureBlobStorageConfiguration)}") .Get <AzureBlobStorageConfiguration>(); services.AddSingleton(azureBlobStorageConfiguration); services.AddTransient <AzureBlobStorageService>(sp => { CustomHttpClient customHttpClient = sp.GetRequiredService <CustomHttpClient>(); customHttpClient.Timeout = TimeSpan.FromMinutes(60); return(new AzureBlobStorageService(logger: sp.GetRequiredService <ILogger <AzureBlobStorageService> >(), azureBlobStorageConfiguration: azureBlobStorageConfiguration, customHttpClient: customHttpClient)); }); }
public async Task <Contact> GetDetails(decimal id) { using (var httpClient = new CustomHttpClient()) { httpClient.BaseAddress = _baseAddress; var requesUrl = string.Format(GetDetailsUrl, id); var response = await httpClient.GetAsync(requesUrl); response.EnsureSuccessStatusCode(); var result = await response.Content.ReadAsAsync <Contact>(); return(result); } }
public async Task<HttpResponseMessage> Get(string uri) { //var serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); //var i = serializer.MaxJsonLength ; //new System.Web.Script.Serialization.JavaScriptSerializer { MaxJsonLength = int.MaxValue }; try { using (var client = new CustomHttpClient()) { client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); client.DefaultRequestHeaders.ExpectContinue = false; //credentials client.DefaultRequestHeaders.Authorization = Credentials.GetAuthenticationHeader(); client.DefaultRequestHeaders.Add("Fuente", "Web"); client.DefaultRequestHeaders.Add("IdEmpresa", /*HttpContext.Current.Session["IdEmpresa" + HttpContext.Current.Session.SessionID]?.ToString() ??*/ Guid.Empty.ToString()); client.DefaultRequestHeaders.Add("IdUsuario", /*HttpContext.Current.Session["idUsuario" + HttpContext.Current.Session.SessionID]?.ToString() ??*/ "0"); client.DefaultRequestHeaders.Add("Nombre", (/*(UsuarioModelo)HttpContext.Current.Session["usuario" + HttpContext.Current.Session.SessionID])?.Nombre ??*/ "----"); client.DefaultRequestHeaders.Add("Correo", (/*(UsuarioModelo)HttpContext.Current.Session["usuario" + HttpContext.Current.Session.SessionID])?.Correo ??*/ "*****@*****.**"); //obtenemos el timeOut de la solicitud var timeOut = 60; //tiempo de espera del servicio client.Timeout = TimeSpan.FromMinutes(timeOut); var response = client.GetAsync(uri).Result; return response; } } catch (AggregateException ee) { //retorna una exception var exc = new HttpResponseMessage(HttpStatusCode.InternalServerError) { ReasonPhrase = ee.InnerException != null ? ee.InnerException.Message : ee.Message }; return exc; } catch (Exception ee) { //retorna una exception throw ee; } }
public LoginWorker(Account account, CustomHttpClient client, HtmlReader htmlReader, WebBrowser webBrowser, ToolStripStatusLabel progressLabel, ToolStripProgressBar progressBar) { PlayerAccount = account; Client = client; HtmlReader = htmlReader; WebBrowser = webBrowser; ProgressLabel = progressLabel; ProgressBar = progressBar; Worker = new BackgroundWorker(); Worker.WorkerReportsProgress = true; Worker.DoWork += ExecuteWork; Worker.ProgressChanged += ProgressChanged; Worker.RunWorkerCompleted += Completed; }
static void Main() { Task.Run(async() => { var baseAddress = IsDevelopment ? "http://*****:*****@gmail.com" }); if (!jsonResponse.IsSuccessStatusCode) { Console.WriteLine(jsonResponse.StatusCode); } else { var content = await jsonResponse.Content.ReadAsStringAsync(); var jsonObject = await client.ReadAsJsonAsync <ResultModel>(jsonResponse.Content); if (jsonObject.IsSuccess) { Console.WriteLine(content); } } Console.ReadKey(); }).Wait(); Console.ReadKey(); }
private async void MessageHandle(JToken message) { var dictionary = new Dictionary <int, int>(); var chatId = (int)message["chat"]["id"]; var messageText = (string)message["text"]; var messageWords = messageText.Split(); var maxPriority = 0; for (int i = 0; i < _messagesBase.MessagesList.Count; i++) { var currentMessage = _messagesBase.MessagesList[i]; var priority = 0; foreach (var word in messageWords) { if (currentMessage.Contains(word)) { priority++; } } if (maxPriority < priority) { dictionary.Clear(); dictionary.Add(dictionary.Count, i); maxPriority = priority; } if (maxPriority == priority) { dictionary.Add(dictionary.Count, i); } } var resultAnswer = ""; if (dictionary.Count > 0) { var resultIndex = new Random().Next(0, dictionary.Count); resultAnswer = _messagesBase.MessagesList[dictionary[resultIndex] + new Random().Next(0, dictionary.Count - resultIndex)]; } else { resultAnswer = "мне нечего сказать("; } await CustomHttpClient.MakeRequest("sendMessage", $"chat_id={chatId}&text={resultAnswer}"); }
public async Task <List <Project> > DownloadProjects() { string url = $"{Config.SonarBaseUrl}{Config.ProjectsUrl}"; var client = new CustomHttpClient <List <Project> >(Config); var projectsResponse = await client.GetAsync(url); string[] filters = Config.ProjectFilter.Split('@'); var proyectos = projectsResponse .Where(p => filters.Any(f => p.Key.StartsWith(f))) .ToList(); await Task.WhenAll( from prj in proyectos select DownloadMetrics(prj)); return(proyectos); }
public VideoService(AzureVideoIndexerService azureVideoIndexerService, AzureBlobStorageService azureBlobStorageService, DataStorageConfiguration dataStorageConfiguration, ICurrentUserProvider currentUserProvider, FairplaytubeDatabaseContext fairplaytubeDatabaseContext, AzureVideoIndexerConfiguration azureVideoIndexerConfiguration, CustomHttpClient customHttpClient, IHubContext <NotificationHub, INotificationHub> hubContext, EmailService emailService, IConfiguration configuration) { this.AzureVideoIndexerService = azureVideoIndexerService; this.AzureBlobStorageService = azureBlobStorageService; this.DataStorageConfiguration = dataStorageConfiguration; this.CurrentUserProvider = currentUserProvider; this.FairplaytubeDatabaseContext = fairplaytubeDatabaseContext; this.AzureVideoIndexerConfiguration = azureVideoIndexerConfiguration; this.CustomHttpClient = customHttpClient; this.HubContext = hubContext; this.EmailService = emailService; this.Configuration = configuration; }
public async Task <BaseResult <CalculateRouteResult> > CalculateRoute(LocationPoint point1, LocationPoint point2) { var result = new BaseResult <CalculateRouteResult>(); try { var action = MethodBase.GetCurrentMethod().GetRealMethodFromAsyncMethod().GetCustomAttribute <DescriptionAttribute>(true).Description; var routeLocations = HttpUtility.UrlEncode($"{point1}:{point2}"); var endPoint = CustomHttpClient.UrlCombine(RouteEndPoint, Version_1, action, routeLocations, ResultType); var dictionary = new Dictionary <string, object>() { { "key", ApiKey }, { "travelMode", TravelMode } }; var response = await _httpClient.HttpSendAsync <CalculateRouteResult>(Url, endPoint, method : HttpMethod.Get, queryParameters : dictionary); result.OriginalString = response.OriginalDataString; if (result.Success = response.Success) { result.Data = response.Data; result.Message = GeneralSuccessMessage; } else { result.Message = GeneralErrorMessage; } } catch (Exception ex) { result.Data = null; result.Message = GeneralErrorMessage; } return(result); }
/// <summary> /// Initializes a new instance of the <see cref="AmazonDrive"/> class. /// </summary> /// <param name="clientId">Your Application ClientID. From Amazon Developers Console.</param> /// <param name="clientSecret">Your Application Secret. From Amazon Developers Console.</param> public AmazonDrive(string clientId, string clientSecret) { this.clientSecret = clientSecret; this.clientId = clientId; http = new CustomHttpClient(SettingsSetter); http.RetryErrorProcessor.Add((int)HttpStatusCode.Unauthorized, async(code) => { await UpdateToken().ConfigureAwait(false); return(true); }); http.RetryErrorProcessor.Add(429, async(code) => { await Task.Delay(1000).ConfigureAwait(false); return(true); }); http.RetryErrorProcessor.Add(500, (code) => Task.FromResult(true)); http.RetryErrorProcessor.Add(504, (code) => Task.FromResult(true)); http.RetryErrorProcessor.Add((int)HttpStatusCode.NotFound, (code) => Task.FromResult(false)); http.FileSendRetryErrorProcessor.Add(429, code => Task.FromResult(false)); }