static void Main(string[] args) { RequestAPI request = new RequestAPI(); ResultApi resultado = new ResultApi(); decimal valor, resultadoconversao; string op; Console.WriteLine("Digite o tipo de moeda que deseja converter"); Console.WriteLine("\nUSD Dolar"); op = Console.ReadLine(); Console.WriteLine("Digite o valor em Reais"); valor = decimal.Parse(Console.ReadLine()); switch (op) { case "USD": resultado = request.Request($"all/{op}", Method.GET); resultadoconversao = decimal.Parse(resultado.USD.Cotacao) * valor; Console.WriteLine($"O Resultado é :R$ {resultadoconversao:N2} na data de : {resultado.USD.DataCotacao.ToString("dd/MM/yyyy HH:mm")}"); break; default: break; } }
public async Task ThingsCache() { try { Dictionary <string, string> things = await RequestAPI.getAsyncThings(thingsURL); foreach (var thing in things) { lock (MemoryCaches.memThings) { if (!MemoryCaches.memThings.ContainsKey((thing.Key))) { MemoryCaches.memThings.Add(thing.Key, thing.Value); } else { MemoryCaches.memThings[thing.Key] = thing.Value; } } } Logger.Info("------------------Things Cache Updated------------------"); } catch (Exception ex) { Logger.Error(ex.ToString()); } }
public override async Task <User> GetUserSocialNetworkByTokenAsync(string token) { RequestInfo requestInfo = new RequestInfo { UrlBase = $"{QueryString}{token}" }; var responseData = await RequestAPI.ConnectRestAPI(requestInfo, MethodType.GET); var user = new User(); if (responseData.Code == ApiStatusCode.Ok && !string.IsNullOrEmpty(responseData.Data)) { var userGooogle = ConvertJson.Deserialize <UserGoogleInfo>(responseData.Data); user.FullName = ($"{userGooogle.GivenName} {userGooogle.FamilyName}").Trim(); user.UserName = userGooogle.Name; user.SocialNetworkId = userGooogle.Sub; user.Email = userGooogle.Email; //user.Gender user.Avatar = userGooogle.Picture; } return(user); }
public async Task DisplayCache() { try { Dictionary <string, string> displays = await RequestAPI.getAsyncDisplayIPs(displayURL); foreach (var display in displays) { lock (MemoryCaches.memMessages) { if (!MemoryCaches.memMessages.ContainsKey((display.Key))) { MemoryCaches.memMessages.Add(display.Key, display.Value); } else { MemoryCaches.memMessages[display.Key] = display.Value; } } } Logger.Info("------------------Display Cache Updated------------------"); } catch (Exception ex) { Logger.Error(ex.ToString()); } }
void LoadDialog() { #region Progress ON prog.IsVisible = true; prog.IsIndeterminate = true; SystemTray.SetProgressIndicator(this, prog); #endregion //Формируем запрос string uid = "uid=" + myApp.Uid; //string count = "count=10"; // string rev = "rev=1"; string access_token = "access_token=" + MyUserData.access_token; ///смещение, необходимое для выборки определенного подмножества сообщений. //string offset = "offset="; ///идентификатор сообщения, начиная с которго необходимо получить последующие сообщения. //string start_mid="start_mid="; string adr = RequestAPI.Request("messages.getHistory", uid, access_token); //Отправляем запрос, получаем ответ. Запускаем событие обработки. WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadDialogCompleted); client.DownloadStringAsync(new Uri(adr)); }
void SendMessage() { #region Progress ON prog.IsVisible = true; prog.IsIndeterminate = true; SystemTray.SetProgressIndicator(this, prog); #endregion //Формируем запрос string uid = "uid=" + myApp.Uid; messageSent = new Message() { Body = textSend.Text }; string message = "message=" + textSend.Text;//настроить форматирование!!! Проверка на длинну! string access_token = "access_token=" + MyUserData.access_token; ///смещение, необходимое для выборки определенного подмножества сообщений. //string offset = "offset="; ///идентификатор сообщения, начиная с которго необходимо получить последующие сообщения. //string start_mid="start_mid="; string adr = RequestAPI.Request("messages.send", uid, message, access_token); //Отправляем запрос, получаем ответ. Запускаем событие обработки. WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_SendMessageCompleted); client.DownloadStringAsync(new Uri(adr)); }
void LoadContact(string allPhones, int count) { #region Progress ON prog.IsVisible = true; prog.IsIndeterminate = true; SystemTray.SetProgressIndicator(this, prog); #endregion if (count < 1000) { //Формируем запрос allPhones = "phones=" + allPhones; string fields = "fields=photo_rec,photo_medium_rec"; string access_token = "access_token=" + MyUserData.access_token;//данные в MyUserData заносятся из словаря string adr = RequestAPI.Request("friends.getByPhones", allPhones, fields, access_token); WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadContactsCompleted); client.DownloadStringAsync(new Uri(adr)); } else { //реализовать разбиение на запросы MessageBox.Show("To big size of contact list. Sorry."); } }
public override async Task <User> GetUserSocialNetworkByTokenAsync(string token) { RequestInfo requestInfo = new RequestInfo { UrlBase = $"{QueryString}{token}" }; var responseData = await RequestAPI.ConnectRestAPI(requestInfo, MethodType.GET); var user = new User(); if (responseData.Code == ApiStatusCode.Ok && !string.IsNullOrEmpty(responseData.Data)) { var userFacebook = ConvertJson.Deserialize <UserFacebookInfo>(responseData.Data); user.FullName = userFacebook.Name; user.UserName = userFacebook.Email; user.SocialNetworkId = userFacebook.Id; user.Email = userFacebook.Email; //user.Gender = userFacebook.Gender; user.Avatar = userFacebook.Picture?.data?.url ?? string.Empty; } return(user); }
public BaseResult <T> Request <T>(RequestAPI requestAPI) where T : class { try { string url = $"{_customerAPIOptions.EndPointUrl}/{requestAPI.Route}"; HttpResponseMessage response; var httpClient = RequestHeader(); if (requestAPI.MethodType == RequestMethodTypeEnum.Get) { if (requestAPI.Body != null) { var queryParams = _fieldService.GetQueryString(requestAPI.Body); if (!String.IsNullOrEmpty(queryParams)) { url = $"{url}?{queryParams}"; } } response = httpClient.GetAsync(url).Result; } else { response = httpClient.PostAsync( url, new StringContent( JsonConvert.SerializeObject(requestAPI.Body), Encoding.UTF8, requestAPI.ContentType)).Result; } string content = response.Content.ReadAsStringAsync().Result; if (response.StatusCode == HttpStatusCode.OK) { ResponseAPI <T> responseAPI = JsonConvert.DeserializeObject <ResponseAPI <T> >(content); if (responseAPI.Success && responseAPI.Data != null) { return(BaseResult <T> .OK(responseAPI.Data)); } } else if (response.StatusCode == HttpStatusCode.Unauthorized) { return(BaseResult <T> .NotOK("Unauthorized. Please logg in.", (int)response.StatusCode)); } return(BaseResult <T> .NotOK("An error occurred while communicating with the server. Please try again.")); } catch (Exception e) { return(BaseResult <T> .NotOK(e.Message)); } }
public static List <CompanyModel> getAll() { var response = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(new RestRequest("membership", Method.GET, DataFormat.Json)) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .buildRequest(); return(RequestAPI.deserilizeProject <List <CompanyModel> >(response)); }
public static string sincronizeOdooContacts() { var response = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(new RestRequest("contact/sync", Method.POST, DataFormat.Json)) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .buildRequest(); return(RequestAPI.deserilizeProject <string>(response)); }
private UserResponse responseFromLoginAPI(UserModel user) { var responseLogin = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(new RestRequest("user/access/", Method.POST, DataFormat.Json)) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .addBodyData(user) .buildRequest(); return(JsonConvert.DeserializeObject <UserResponse>(responseLogin)); }
private List <ProjectModel> responseFromOperationAPI(int id) { var responseProjects = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(new RestRequest("operation/{idClient}", Method.GET)) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .addUrlSegmentParam(new KeyValuePair <string, object>("idClient", id)) // credenciales estaticas .buildRequest(); return(JsonConvert.DeserializeObject <List <ProjectModel> >(responseProjects)); }
public static List <TruckModel> update(TruckModel truck) { var response = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(new RestRequest("truck/update/", Method.GET, DataFormat.Json)) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .addBodyData(truck) .buildRequest(); return(RequestAPI.deserilizeProject <List <TruckModel> >(response)); }
private FileResponse responseFromDeleteFileAPI(string fileName) { RestRequest request = new RestRequest("operation/deleteFile/", Method.POST, DataFormat.Json); var responseFile = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(request) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .addBodyData(fileName) .buildRequest(); return(JsonConvert.DeserializeObject <FileResponse>(responseFile)); }
public static List <TaskConfigurationModel> refreshTasks(TaskConfigurationModel taskToUpdate) { var response = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(new RestRequest("taskConfiguration/updateAllowDocsAndDisplayClient", Method.PUT, DataFormat.Json)) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .addBodyData(taskToUpdate) .buildRequest(); TaskConfigurationModel userRefreshed = RequestAPI.deserilizeProject <TaskConfigurationModel>(response); return(getAll()); }
public static List <UsuarioModel> refreshUsers(UsuarioModel userToUpdate) { var response = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(new RestRequest("user/updatePrivileges", Method.PUT, DataFormat.Json)) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .addBodyData(userToUpdate) .buildRequest(); UsuarioModel userRefreshed = RequestAPI.deserilizeProject <UsuarioModel>(response); return(getAll()); }
public static List <UsuarioModel> sendPassword(int userId) { var response = new RequestAPI() .addClient(new RestClient(urlRequest)) .addRequest(new RestRequest("user/firstPassword/{userId}", Method.PUT, DataFormat.Json)) .addHeader(new KeyValuePair <string, object>("Accept", "application/json")) .addUrlSegmentParam(new KeyValuePair <string, object> ("userId", userId)) .buildRequest(); UsuarioModel userRefreshed = RequestAPI.deserilizeProject <UsuarioModel>(response); return(getAll()); }
public async Task dashBoardCache() { try { var dashboarList = await RequestAPI.getAsyncAllDashboards(dashBoards); foreach (var dashboardLazy in dashboarList) { if (dashboardLazy.disableShow != null) { dashboardLazy.disableShow = dashboardLazy.disableShow.ToLower(); } if (dashboardLazy.disableShow == "false" || dashboardLazy.disableShow == null) { var Dashboard = await RequestAPI.getAsyncDashboard(dashBoards + "/" + dashboardLazy.dashboardConfigId); lock (MemoryCaches.memDash) { if (MemoryCaches.memDash.Where(x => x.dashboardId == Dashboard.dashboardConfigId.ToString()).Count() == 0) { MemoryCaches.memDash.Add(new dashMemory { active = true, dashboardId = Dashboard.dashboardConfigId.ToString(), dashboard = Dashboard }); } else { var cacheItem = MemoryCaches.memDash.Where(x => x.dashboardId == Dashboard.dashboardConfigId.ToString()).FirstOrDefault(); var index = MemoryCaches.memDash.IndexOf(cacheItem); MemoryCaches.memDash[index] = new dashMemory { active = cacheItem.active, dashboardId = Dashboard.dashboardConfigId.ToString(), dashboard = Dashboard }; } } } else { RequestAPI.DelAsyncCache(cacheURlMain + "/" + dashboardLazy.dashboardConfigId); } } Logger.Info("------------------Dashboard Cache Updated------------------"); } catch (Exception ex) { Logger.Error(ex.ToString()); } }
private void phonenumBox_LostFocus(object sender, RoutedEventArgs e) { //Проверка номера телефона методами API Вконтакте //Формируем запрос string phone = "phone=" + phonenumBox.Text; string adr = RequestAPI.Request("auth.checkPhone.xml", phone, ApplicationSettings.client_id, ApplicationSettings.client_secret); //Создаем клиент для передачи данных WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); client.DownloadStringAsync(new Uri(adr)); }
private void buttonConfirm_Click(object sender, RoutedEventArgs e) { //Формируем запрос string phone = "phone=" + phoneConfirmBox.Text; string code = "code=" + CodeBox.Text; string test_mode = "test_mode=0"; string password = "******" + passwordBox.Password; string adr = RequestAPI.Request("auth.confirm", phone, code, password, ApplicationSettings.client_id, ApplicationSettings.client_secret, test_mode); //Создаем клиент для передачи данных WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_authConfirm); client.DownloadStringAsync(new Uri(adr)); }
public async Task <string> getTileValue(Tile tile, string dashboardid, bool PararellProcessTiles) { try { string url = null; string result = null; if (tile.dataSource != null) { var startTime = DateTime.Now; url = server + tile.dataSource.url; if (tile.dataSource.queryParameters != null) { url += "?"; tile.dataSource.queryParameters = tile.dataSource.queryParameters.OrderByDescending(o => o.param).ToList(); for (int i = 0; i < tile.dataSource.queryParameters.Count; i++) { url += tile.dataSource.queryParameters[i].param.ToLower() + "=" + tile.dataSource.queryParameters[i].value.ToLower() + "&"; } } if (PararellProcessTiles) { result = await RequestAPI.processGetTile(url, tile.dataSource.path, true); APIResponseTime.calculateResponseTime(tile.dataSource.url, DateTime.Now - startTime); } else { result = RequestAPISync.processGetTile(url, tile.dataSource.path, true); APIResponseTime.calculateResponseTime(tile.dataSource.url, DateTime.Now - startTime); } } if (result == null) { return("Error"); } else { return(result); }; } catch (Exception ex) { Logger.Warn(ex.ToString()); return("Error"); } }
public BaseResult <IEnumerable <CityModel> > Get() { try { var requestAPI = new RequestAPI { ContentType = _contentType, Route = _route, MethodType = RequestMethodTypeEnum.Get }; return(_restAPIService.Request <IEnumerable <CityModel> >(requestAPI)); } catch (Exception e) { return(BaseResult <IEnumerable <CityModel> > .NotOK(e.Message)); } }
public ActionResult SubmitResult(FormCollection form) { var request = new RequestAPI { Uri = "https://goodmorning-axa-dev.azure-api.net/register", Method = "POST", ContentType = "application/json", Body = new { Name = Convert.ToString(form["name"]), Email = Convert.ToString(form["email"]), Mobile = Convert.ToString(form["mobile"]), PositionApplied = Convert.ToString(form["position"]) } }; var result = JObject.FromObject(RequestAPIHelper.Send(request)); return(View(result)); }
void DeleteFromFriends(int uid) { #region Progress ON prog.IsVisible = true; prog.IsIndeterminate = true; SystemTray.SetProgressIndicator(this, prog); #endregion //Формируем запрос string s_uid = "uid=" + uid; string access_token = "access_token=" + MyUserData.access_token; string adr = RequestAPI.Request("friends.delete", s_uid, access_token); //Отправляем запрос, получаем ответ. Запускаем событие обработки. WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DeleteFriendsCompleted); client.DownloadStringAsync(new Uri(adr)); }
private void UpdateMessage() { #region Progress ON prog.IsVisible = true; prog.IsIndeterminate = true; SystemTray.SetProgressIndicator(this, prog); #endregion short size = 20; //Формируем запрос string count = "count=" + size; string access_token = "access_token=" + MyUserData.access_token;//данные в MyUserData заносятся из словаря string adr = RequestAPI.Request("messages.get", count, access_token); WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_UpdateMessagesCompleted); client.DownloadStringAsync(new Uri(adr)); }
public BaseResult <CityModel> GetById(int?id) { try { var requestAPI = new RequestAPI { ContentType = _contentType, Route = $"{_route}/{id}", MethodType = RequestMethodTypeEnum.Get }; return(_restAPIService.Request <CityModel>(requestAPI)); } catch (Exception e) { return(BaseResult <CityModel> .NotOK(e.Message)); } }
private void buttonRegistration_Click(object sender, RoutedEventArgs e) { //Формируем запрос string phone = "phone=" + phonenumBox.Text; string firstname = "first_name=" + firstnameBox.Text; string lastname = "last_name=" + lastnameBox.Text; string test_mode = "test_mode=0"; string adr = RequestAPI.Request("auth.signup", phone, firstname, lastname, ApplicationSettings.client_id, ApplicationSettings.client_secret, test_mode); //Создаем клиент для передачи данных WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_signupCompleted); client.DownloadStringAsync(new Uri(adr)); MessageBox.Show("Данны для регистрации отправлены! Дождитесь прихода SMS с кодом и введите его в окне подтверждения, для завершения регистрации"); }
public async Task DisableUnusedDash() { List <Task> tasks = new List <Task>(); List <dashMemory> localDict; lock (MemoryCaches.memDash) localDict = new List <dashMemory>(MemoryCaches.memDash); foreach (var item in localDict) { var DashboardId = item.dashboardId; var lastRequest = await RequestAPI.getAsyncLastAccessCache(LastAccessURL + "/" + DashboardId); TimeSpan dif; if (lastRequest != null) { dif = DateTime.Now - (DateTime)lastRequest; Logger.Info("->" + item.dashboardId + " : " + item.dashboard.name); Logger.Info("->Tempo desde Ultimo Acesso:" + dif); if (dif.TotalMinutes > MaxTimeCache) { if (item.active == true) { lock (MemoryCaches.memDash) { MemoryCaches.memDash.Where(x => x.dashboardId == item.dashboardId).FirstOrDefault().active = false; } RequestAPI.DelAsyncCache(cacheURlMain + "/" + item.dashboardId); } } else { if (item.active == false) { lock (MemoryCaches.memDash) { MemoryCaches.memDash.Where(x => x.dashboardId == item.dashboardId).FirstOrDefault().active = true; } } } } } }
public static object Send(RequestAPI request) { var jObject = new JObject(); try { var req = (HttpWebRequest)WebRequest.Create(new Uri(request.Uri)); ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12; req.Method = request.Method; req.ContentType = request.ContentType; foreach (var item in request.Headers) { req.Headers.Add(item.Property, item.Value); } var bodyString = JsonConvert.SerializeObject(request.Body); var encoding = new ASCIIEncoding(); var byteArray = encoding.GetBytes(bodyString); req.ContentLength = byteArray.Length; using (var dataStream = req.GetRequestStream()) { dataStream.Write(byteArray, 0, byteArray.Length); } using (var res = (HttpWebResponse)req.GetResponse()) { using (var sw = res.GetResponseStream()) { if (sw != null) { using (var reader = new StreamReader(sw)) { jObject = JObject.Parse(reader.ReadToEnd()); } } sw.Dispose(); } } } catch (Exception e) { var bodyObj = new { errorMessage = e.Message }; var bodyString = JsonConvert.SerializeObject(bodyObj); jObject = JObject.Parse(bodyString); } return(jObject); }