public ActionResult Tienepromociones(int Producto = 0, string FechaInicio = "", string FechaFin = "", int Promocion = 0) { String url = $"{urlBase}/TienePromociones?"; NameValueCollection queryString = HttpUtility.ParseQueryString(String.Empty); queryString.Add("Producto", Producto.ToString()); queryString.Add("FechaInicio", FechaInicio); queryString.Add("FechaFin", FechaFin); queryString.Add("Promocion", Promocion.ToString()); url += queryString.ToString(); GenericResponseModel <Boolean> responseModel = ApiRequests .Get <GenericResponseModel <Boolean>, GenericResponseModel <String> >(url, out errorResponse); if (errorResponse == null) { return(Json(responseModel, JsonRequestBehavior.AllowGet)); } else { return(Json(errorResponse, JsonRequestBehavior.AllowGet)); } }
private void refresh() { string respnoseJson = ApiRequests.PublicTestsGet(isSortDesc); if (Parser.ResultParse(respnoseJson)) { if (!lastResponse.Equals(respnoseJson)) { lastResponse = respnoseJson; testCards = Parser.FieldParse <List <TestCard> >(respnoseJson, "testCards"); flowLayoutPanel1.Controls.Clear(); foreach (TestCard testCard in testCards) { flowLayoutPanel1.Controls.Add(new TestCardItemUC(testCard, this)); } } flowLayoutPanel1.Focus(); } else { MessageBox.Show("Попытка получить публичные тесты обломилась", "Ошибка", MessageBoxButtons.OK); } }
private async void submitButton_Click(object sender, System.EventArgs e) { string validateResult = validate(); if (!validateResult.Equals("")) { ErrorForm errorForm = new ErrorForm(validateResult, "Ошибка валидации", false); errorForm.ShowDialog(Owner); } else { try { string resultString = await Task.Run(() => ApiRequests.RegistrationPost(loginTextBox.Text, emailTextBox.Text, MD5Handler.GetMd5Hash(passwordTextBox.Text))); bool result = Parser.ResultParse(resultString); if (result) { //добавить что-то дополнительное об успешности changeToLogin(); } else { Error("Регистрация не удалась", closeApp: false); } } catch (Exception exc) { Console.WriteLine(exc); Error("Не удалось выполнить запрос на регистрацию.", closeApp: false); } } }
public ActionResult EditarCuenta(UsuarioViewModel newUsuario) { String url = $"{baseUrl}/EditarCuenta"; UsuarioViewModel usuarioLogeado = (UsuarioViewModel)Session["usuario"]; newUsuario.Id = usuarioLogeado.Id; GenericResponseModel <String> responseModel = ApiRequests .Patch <GenericResponseModel <String>, UsuarioViewModel, GenericResponseModel <String> >(url, newUsuario, out errorResponse); if (errorResponse == null) { //Volver a poner en session el usuario actual url = $"{baseUrl}/{usuarioLogeado.Id}"; GenericResponseModel <UsuarioViewModel> nuevoUsuarioResponseModel = ApiRequests .Get <GenericResponseModel <UsuarioViewModel>, GenericResponseModel <String> >(url, out errorResponse); if (errorResponse == null) { nuevoUsuarioResponseModel.Data.Token = usuarioLogeado.Token; Session["usuario"] = nuevoUsuarioResponseModel.Data; return(Json(responseModel, JsonRequestBehavior.AllowGet)); } return(Json(errorResponse, JsonRequestBehavior.AllowGet)); } else { return(Json(errorResponse, JsonRequestBehavior.AllowGet)); } }
public static ApiResult GetApiRequest(ApiRequests type, string name) { name = GetName(name); string url = getApiUrl(type, name); try { ApiErrors error = ApiErrors.None_Online; WebClient wc = new WebClient(); wc.Encoding = Encoding.UTF8; string outs = wc.DownloadString(url).Replace("{", "").Replace("}", ""); wc.Dispose(); error = CheckError(outs); //if (error == ApiErrors.None) //{ // outs = outs.Replace("{\"stream\":", ""); //} return(new ApiResult(outs, error, type)); } catch (Exception x) { return(new ApiResult(x.Message, ApiErrors.Error, type)); } }
public ActionResult Listar(string Descripcion = "") { String url = "Producto?"; NameValueCollection queryString = HttpUtility.ParseQueryString(String.Empty); queryString.Add("registros", "0"); if (Descripcion != "") { queryString.Add("Descripcion", Descripcion); } url += queryString.ToString(); GenericResponseModel <IEnumerable <ProductoViewModel> > responseModel = ApiRequests .Get <GenericResponseModel <IEnumerable <ProductoViewModel> >, GenericResponseModel <String> >(url, out errorResponse); if (errorResponse == null) { return(Json(responseModel, JsonRequestBehavior.AllowGet)); } else { return(Json(errorResponse, JsonRequestBehavior.AllowGet)); } }
private async void RunGps() { this.SetSearchState(true); this.SearchDescription = "Bestimme aktuelle Position ..."; GlobalCoordinate position = await GeoLocator.GetCurrentPosition(); if (position == null) { this.SetSearchState(false); CrossToast.ShowToast("Positionsbestimmung fehlgeschlagen!"); return; } this.SearchDescription = "Suche Tankstellen ..."; List <PriceInfo> results = await ApiRequests.RequestGasStations(new GlobalCoordinate(position.Latitude, position.Longitude)); if (results == null) { this.SetSearchState(false); CrossToast.ShowToast("Suche fehlgeschlagen!"); return; } if (results.Count > 0) { // Add prices to the database DbDataProvider.Instance.AddPricesToHistory(results); this.ResultsFound?.Invoke(this, results); this.SearchDescription = String.Empty; // bug fix for small return delay } else { this.SetSearchState(false); CrossToast.ShowToast("Es wurden keine Tankstellen gefunden."); } }
public async Task <IActionResult> Create(Components model) { try { // todo: errors when at least one of the items is null var configuration = new { cpuWatercoolerId = model.SelectedCPUWatercoolerId, description = model.Configuration.Description, fanId = model.SelectedFanId, graphicsCardId = model.SelectedGraphicsCardId, graphicsCardQty = model.Configuration.GraphicsCardQty, pcBuildHardDrives = new List <HardDrive> { }, motherboardId = model.SelectedMotherboardId, pcBuildOthers = new List <Other> { }, pcCaseId = model.SelectedPCCaseId, powerSupplyId = model.SelectedPowerSupplyId, processorId = model.SelectedProcessorId, ramId = model.SelectedRAMId, }; // iterate over selected hard drives and add them to the configuration object. if (model.SelectedHardDriveIds != null) { foreach (string item in model.SelectedHardDriveIds) { configuration.pcBuildHardDrives.Add( new HardDrive { HardDriveId = Guid.Parse(item), } ); } } if (model.SelectedOtherIds != null) { foreach (string item in model.SelectedOtherIds) { configuration.pcBuildOthers.Add( new Other { OtherId = Guid.Parse(item), } ); } } string accessToken = await this.HttpContext.GetTokenAsync("access_token"); await ApiRequests.PostAsync(accessToken, string.Format("{0}/{1}", this.apiBaseUrl, this.apiController), configuration); return(this.RedirectToAction(nameof(Index))); } catch (Exception) { return(this.View()); } }
public ActionResult Listar(string Proveedor = "") { String url = $"{baseUrl}?"; NameValueCollection queryString = HttpUtility.ParseQueryString(String.Empty); queryString.Add("registros", "0"); if (Proveedor != "") { queryString.Add("Proveedor", Proveedor); } url += queryString.ToString(); GenericResponseModel <IEnumerable <PedidoViewModel> > responseModel = ApiRequests .Get <GenericResponseModel <IEnumerable <PedidoViewModel> >, GenericResponseModel <String> >(url, out errorResponse); if (errorResponse == null) { return(Json(responseModel, JsonRequestBehavior.AllowGet)); } else { return(Json(errorResponse, JsonRequestBehavior.AllowGet)); } }
private async void RunAddress() { this.SetSearchState(true); this.SearchDescription = "Ermittle Position der Adresse ..."; GlobalCoordinate position = await GeoCoder.GetPositionForAddress(this.AddressStreet + "\n" + this.AddressTown); if (position == null) { this.SetSearchState(false); CrossToast.ShowToast("Positionsermittlung fehlgeschlagen"); return; } this.SearchDescription = "Suche Tankstellen ..."; List <PriceInfo> results = await ApiRequests.RequestGasStations(position); if (results == null) { this.SetSearchState(false); CrossToast.ShowToast("Suche fehlgeschlagen!"); return; } if (results.Count > 0) { // Add prices to the database DbDataProvider.Instance.AddPricesToHistory(results); this.ResultsFound?.Invoke(this, results); this.SearchDescription = String.Empty; // bug fix for small return delay } else { this.SetSearchState(false); CrossToast.ShowToast("Es wurden keine Tankstellen gefunden."); } }
public ActionResult Listar(string Nombre = "") { String url = "Cliente?"; NameValueCollection queryString = HttpUtility.ParseQueryString(String.Empty); queryString.Add("registros", "0"); if (Nombre != "") { queryString.Add("Nombre", Nombre); } url += queryString.ToString(); GenericResponseModel <IEnumerable <ClienteViewModel> > responseModel = ApiRequests .Get <GenericResponseModel <IEnumerable <ClienteViewModel> >, GenericResponseModel <String> >(url, out errorResponse); if (errorResponse == null) { return(Json(responseModel, JsonRequestBehavior.AllowGet)); } else { return(Json(errorResponse, JsonRequestBehavior.AllowGet)); } }
private void button1_Click(object sender, EventArgs e) { string validateResult = validateEmailChange(); if (!validateResult.Equals("")) { Error(validateResult, closeApp: false); clearTextBox(); return; } bool requestResult = Parser.ResultParse(ApiRequests.ProfileEmailPut (MD5Handler.GetMd5Hash(textBox2.Text), textBox1.Text)); if (requestResult) { Owner.popUC(); Owner.refresh(); } else { Error("Данные введены неправильно или такой email уже занят", closeApp: false); clearTextBox(); } }
private async void submitButton_Click(object sender, EventArgs e) { string validateResult = validate(); if (!validateResult.Equals("")) { ErrorForm errorForm = new ErrorForm(validateResult, "Ошибка валидации", false); errorForm.ShowDialog(Owner); } else { string resultString = await Task.Run(() => ApiRequests.LoginPost(emailTextBox.Text, MD5Handler.GetMd5Hash(passwordTextBox.Text))); bool result = Parser.ResultParse(resultString); if (result) { //добавить что-то дополнительное об успешности Memory.isAuth = true; Settings.SaveSettingsCrypt(); changeToMain(); } else { Error("Авторизация не удалась", closeApp: false); } } }
public async Task <IActionResult> Edit(Guid id, RAM model) { try { if (model == null) { return(this.NotFound()); } if (model.ImageFile != null) { model.ImageTitle = model.ImageFile.FileName; model.ImageData = ImageManager.GetByteArrayFromImage(model.ImageFile); } model.RamId = id; string accessToken = await this.HttpContext.GetTokenAsync("access_token"); await ApiRequests.PutAsync(accessToken, string.Format("{0}/{1}", this.apiBaseUrl, this.apiController), model); return(this.RedirectToAction(nameof(Index))); } catch { return(this.View()); } }
private async void Login_Click(object sender, RoutedEventArgs e) { string nickname = nickNameLoginBox.Text; string password = passwordLoginBox.Password; bool remember = (bool)rememberBtn.IsChecked; LoginForm loginForm = new LoginForm(nickname, password); HttpResponseMessage httpResponse = await ApiRequests.Login(loginForm); if (httpResponse.StatusCode == HttpStatusCode.OK) { UserAuthenticated user = await httpResponse.Content.ReadAsAsync <UserAuthenticated>(); Finish_Login(user, remember); } else if (httpResponse.StatusCode == HttpStatusCode.BadRequest) { nickNameLoginBox.BorderBrush = Brushes.Red; passwordLoginBox.BorderBrush = Brushes.Red; string msgResponse = await httpResponse.Content.ReadAsStringAsync(); Process_Error(msgResponse); } else { string msgResponse = "There is problem with server connection. Try again later."; Process_Error(msgResponse); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); ApiRequests.Configurar(); }
public void Publish() { if (MessageBox.Show("Если вы опубликуете тест, он станет доступен для прохождения," + "\n но больше вы не сможете его редактировать. Опубликовать?", "Внимание", MessageBoxButtons.OKCancel).Equals(DialogResult.OK)) { ApiRequests.TestPublishPost(testID); Exit(); } }
/// <summary> /// Получение всех записей в таблице БД /// </summary> /// <param name="apiUrl">Ссылка на api ex: api/entity</param> /// <typeparam name="T">Тип экземпляра записи</typeparam> /// <returns>Список записей</returns> public static async Task <List <T> > GetAll <T>(string apiUrl) where T : IEntity { var response = await ApiRequests.SendApiRequest <T>(apiUrl, RequestTypes.Get, new HttpClient()); var responseStream = await response.Content.ReadAsStreamAsync(); var entities = await JsonSerializer.DeserializeAsync <List <T> >(responseStream); return(entities); }
// GET: CPUWatercooler/Details/5 public async Task <IActionResult> Details(Guid id) { string accessToken = await this.HttpContext.GetTokenAsync("access_token"); string response = await ApiRequests.GetAsync(accessToken, string.Format("{0}/{1}/{2}", this.apiBaseUrl, this.apiController, id)); CPUWatercooler cpuWatercooler = JsonConvert.DeserializeObject <CPUWatercooler>(response); return(this.View(cpuWatercooler)); }
private void initUC() { string response = ApiRequests.PassingTestGet(testID); if (JObject.Parse(response)["slide"].ToObject <object>() != null && JObject.Parse(response)["slide"]["author"] != null) { authorID = JObject.Parse(response)["slide"]["author"]["userID"].ToObject <string>(); } updateSlide(response); }
// GET: HardDrives public async Task <IActionResult> Index() { string accessToken = await this.HttpContext.GetTokenAsync("access_token"); string response = await ApiRequests.GetAsync(accessToken, string.Format("{0}/{1}", this.apiBaseUrl, this.apiController)); List <HardDrive> hardDrive = JsonConvert.DeserializeObject <List <HardDrive> >(response); return(this.View(hardDrive)); }
// GET: RAMs/Edit/5 public async Task <IActionResult> Edit(Guid id) { string accessToken = await this.HttpContext.GetTokenAsync("access_token"); string response = await ApiRequests.GetAsync(accessToken, string.Format("{0}/{1}/{2}", this.apiBaseUrl, this.apiController, id)); RAM ram = JsonConvert.DeserializeObject <RAM>(response); return(this.View(ram)); }
public async Task <ActionResult> Checkout() { string[] cartItems = await ApiRequests.GetCartItems(); ViewBag.cart_num = cartItems[1]; ViewBag.cart_price = cartItems[2]; ViewBag.cart_item = cartItems[3] + cartItems[4]; return(View()); }
public UserProfileUC(MainForm owner, string userID = "") : base(owner) { InitializeComponent(); bottomNavigation.setProfileActive(); if (userID.Equals("")) { pictureBox1.Visible = false; profilePictureBox.Location = new Point(7, profilePictureBox.Location.Y); } else { editPictureBox.Visible = false; logoutPictureBox.Visible = false; bottomNavigation.Visible = false; flowLayoutPanel1.Size = new Size(flowLayoutPanel1.Size.Width, flowLayoutPanel1.Size.Height + 20); } string requestResult = ApiRequests.ProfileGet(userID); if (Parser.ResultParse(requestResult)) { object emailObject = Parser.FieldParse <object>(requestResult, "email"); if (emailObject == null) { email.Text = "<ЗАКРЫТ>"; } else { email.Text = (string)emailObject; } loginLabel.Text = Parser.FieldParse <string>(requestResult, "login"); testCards = Parser.FieldParse <List <TestCard> >(requestResult, "createdTests"); foreach (TestCard testCard in testCards) { flowLayoutPanel1.Controls.Add(new TestCardItemUC(testCard, this)); } foreach (Control control in flowLayoutPanel1.Controls) { if (control is TestCardItemUC) { ((TestCardItemUC)control).resetActions(); } } } else { Error("Ошибка при получении профиля", closeApp: false); Owner.changeUC(new MainMenuUC(Owner)); } }
public async void Show_Rank(object sender, RoutedEventArgs e) { rankArray = await ApiRequests.Get_Ranking(); if (rankArray == null || rankArray.Length == 0) { Connection_Error(); return; } rankWin = new RankWindow(rankArray); rankWin.Owner = this; rankWin.ShowDialog(); }
private void button1_Click(object sender, EventArgs e) // rate { string response = ApiRequests.RateTestPost(testID, (int)numericUpDown1.Value); if (Parser.ResultParse(response)) { MessageBox.Show("Оценка выставлена", "Успешно", MessageBoxButtons.OK); } else { MessageBox.Show("Во время оценивания произошла ошибка", "Ошибка", MessageBoxButtons.OK); } }
public async Task <ActionResult> Index() { string items = await ApiRequests.GetAllEquipment(); ViewBag.equipment = items; string[] cartItems = await ApiRequests.GetCartItems(); ViewBag.cart_num = cartItems[1]; ViewBag.cart_price = cartItems[2]; return(View()); }
public void HeaderClickHandler(TestCardItemUC sender) { string response = ApiRequests.PassingTestGet(getTestCardByItem(sender).testID); if (Parser.ResultParse(response)) { Owner.addUC(new PassingTestUC(Owner, getTestCardByItem(sender).testID)); } else { MessageBox.Show("Тест не найден или неактивен", "Ошибка", MessageBoxButtons.OK); } }
/// <summary> /// Appended an API request to be logged /// </summary> /// <param name="values">Request infomation</param> /// <param name="requestTime">Time of request</param> private void AddApiRequest(LoggingApiContextValues values, DateTime requestTime) { ApiRequests.Add(new LogRequestAndResponseCommand { Connector = values.ConnectorName, Resource = values.ResourceName, ResourceId = values.ResourceId, ResourceType = values.ResourceType, RequestType = values.HttpMethod, RequestTime = requestTime, RequestGuid = Guid.NewGuid() }); }
private void button1_Click(object sender, EventArgs e) { string response = ApiRequests.PassingFinishPost(testID); if (Parser.ResultParse(response)) { isDecrementing = false; passingUC.updateSlide(response); } else { MessageBox.Show("Не удалось завершить опрос ", "Ошибка", MessageBoxButtons.OK); } }