public async Task <Recipe> UpdateRecipe(Recipe recipe) { DataRecipe returned = BusinessToData(recipe); string recipeAsJson = JsonSerializer.Serialize(returned, serializeOptions); Console.WriteLine(recipeAsJson); HttpContent content = new StringContent( recipeAsJson, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PutAsync(uri + "/UpdateRecipe", content); if (!response.IsSuccessStatusCode) { APIError apiError = JsonSerializer.Deserialize <APIError>(await response.Content.ReadAsStringAsync()); throw new Exception($@"Error: {apiError.message}"); } string result = await response.Content.ReadAsStringAsync(); DataRecipe updatedRecipe = JsonSerializer.Deserialize <DataRecipe>(result, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); Recipe secondReturned = DataToBusiness(updatedRecipe); Console.WriteLine("result" + result); return(secondReturned); }
public async Task <IList <Recipe> > GetAllRecipes() { HttpResponseMessage responseMessage = await client.GetAsync(uri + "/GetAllRecipes"); if (!responseMessage.IsSuccessStatusCode) { APIError apiError = JsonSerializer.Deserialize <APIError>(await responseMessage.Content.ReadAsStringAsync()); throw new Exception($@"Error: {apiError.message}"); } string result = await responseMessage.Content.ReadAsStringAsync(); List <DataRecipe> gotRecipe = JsonSerializer.Deserialize <List <DataRecipe> >(result, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); List <Recipe> listRecipe = new List <Recipe>(); foreach (var item in gotRecipe) { var temp = DataToBusiness(item); listRecipe.Add(temp); } Console.WriteLine("result" + result); return(listRecipe); }
public async Task <IActionResult> GamingCheckInRequest([FromRoute] string venueId, [FromRoute] string areaId, [FromBody] GamingCheckInRequest checkIn) { try { // Check-in the patron to specified gaming area. await _patronService.SubmitGamingCheckIn(venueId, areaId, checkIn); // Log the check-in. _logger.LogInformation("Gaming check-in. [vId: {venueId}, aId: {areaId}]", venueId, areaId); // Return an empty OK status. return(Ok()); } catch (VenueNotFoundException e) { // Error: Venue could not be found. _logger.LogInformation(e, "Venue could not be found to complete gaming check-in. [vId: {venueId}]", venueId); return(BadRequest(APIError.VenueNotFound())); } catch (AreaNotFoundException e) { _logger.LogInformation(e, "Could not find a gaming area in specified venue. [vId: {venueId}, aId: {areaId}]", venueId, areaId); return(BadRequest(APIError.AreaNotFound())); } catch (Exception e) { // Error: Unknown error. _logger.LogError(e, "Gaming check-in failed. [vId: {venueId}, aId: {areaId}]", venueId, areaId); return(BadRequest(APIError.UnknownError())); } }
public async Task <IActionResult> RegisterForNewsletter(NewsLetterRegistration registration) { // Attempt to validate the captcha code as an anti-spam mechanism. bool captchaPassedValidation; try { captchaPassedValidation = await _captcha.Validate(registration.Captcha); } catch (Exception ex) { // Error: Unknown error. _logger.LogError(ex, "An unknown exception occurred"); return(BadRequest(APIError.UnknownError())); } // If the captcha failed validation, return bad request. if (!captchaPassedValidation) { return(BadRequest(APIError.RecaptchaFailure())); } MarketingUser marketingUser; try { // Register the user's email address in the database. marketingUser = await _newsletter.RegisterUser(registration.Name, registration.Email); } catch (MarketingUserAlreadySubscribedException ex) { // Error: User is already subscribed in the database. _logger.LogWarning(ex, "Failed to register marketing user. Email is already registered: {}", registration.Email); return(BadRequest(APIError.MarketingUserAlreadySubscribed())); } catch (Exception ex) { // Error: Unknown error. _logger.LogError(ex, "Exception occurred when attempting to register a marketing user."); return(BadRequest(APIError.UnknownError())); } try { // Send confirmation email to the user with unsubscribe link await _email.SendMarketWelcome(marketingUser); } catch (Exception ex) { // Error: Unknown error. _logger.LogError(ex, "An unknown error occurred when attempting to send marketing-welcome email."); return(BadRequest(APIError.UnknownError())); } return(Ok()); }
IEnumerator CheckAuth(RegisterComplete data, bool alreadySet = false) { WWW request = new WWW(CheckAuthURL + data.token); yield return(request); if (!string.IsNullOrEmpty(request.error)) { if (!string.IsNullOrEmpty(request.text)) { APIError errData = JsonUtility.FromJson <APIError>(request.text); SendErrorNotification(errData.error.message); } } else { // Set Player Prefs // user_id -> id (Int, Id of the account) // user_username -> savedUsername (String, username of the account) // user_token -> token (String, login token) // user_token_expireDate -> expire_date (String, token expire date) AuthComplete tokenDetails = JsonUtility.FromJson <AuthComplete>(request.text); if (!alreadySet) { SetUserData(data.id, savedUsername, tokenDetails.token, tokenDetails.expireDate); } LoadPostLoginLevel(); } }
public async Task <IActionResult> CheckOutGamingPatron([FromRoute] string serviceId, [FromRoute] string patronId) { // Pull manager ID from the HTTP context. string managerId = HttpContext.User.Identity.Name; try { // Checkout the gaming patron. await _managerService.CheckOutGamingPatron(managerId, serviceId, patronId); // Return an empty OK status. return(Ok()); } catch (PatronNotFoundException e) { // Error: Patron specified not found. _logger.LogInformation(e, "Could not find specified gaming patron for update. [mId: {managerId}, sId: {serviceId}, pId: {patronId}]", managerId, serviceId, patronId); return(BadRequest(APIError.PatronNotFound())); } catch (NoAccessException e) { // Error: Manager does not have sufficient permissions to checkout the gaming patron. _logger.LogInformation(e, "Manager was denied access to checkout gaming patron. [mId: {managerId}, sId: {serviceId}]", managerId, serviceId); return(BadRequest(APIError.NoAccess())); } catch (Exception e) { // Error: Unknown error. _logger.LogError(e, "Failed to checkout gaming patron"); return(BadRequest(APIError.UnknownError())); } }
IEnumerator LoginPostRequest(string username, string password) { WWWForm form = new WWWForm(); form.AddField("username", username); form.AddField("password", password); WWW request = new WWW(AuthURL, form); yield return(request); if (!string.IsNullOrEmpty(request.error)) { if (!string.IsNullOrEmpty(request.text)) { APIError data = JsonUtility.FromJson <APIError>(request.text); SendErrorNotification(data.error.message); } } else { LoginComplete loginDetails = JsonUtility.FromJson <LoginComplete>(request.text); SetUserData(loginDetails.id, username, loginDetails.token, loginDetails.expireDate); LoadPostLoginLevel(); } }
public static T GetAsync <T>(string scheme, string baseAddress, string path, Dictionary <string, string> keyValuePairs = null) { using (HttpClient client = new HttpClient()) { UriBuilder builder = new UriBuilder(scheme, baseAddress) { Port = -1, Path = path }; if (keyValuePairs != null) { System.Collections.Specialized.NameValueCollection query = HttpUtility.ParseQueryString(builder.Query); foreach (string param in keyValuePairs.Keys) { query[param] = keyValuePairs[param]; } builder.Query = query.ToString(); } HttpResponseMessage theResponse = client.GetAsync(builder.Uri).Result; if (!theResponse.IsSuccessStatusCode) { APIError aPIError = JsonConvert.DeserializeObject <APIError>(theResponse.Content.ReadAsStringAsync().Result); aPIError.MessageDetail += $"HTTP response: {theResponse.StatusCode.ToString()} "; throw new Exception($"Message: {aPIError.Message} MessageDetail:{aPIError.MessageDetail}"); } T Q = JsonConvert.DeserializeObject <T>(theResponse.Content.ReadAsStringAsync().Result); return(Q); } }
IEnumerator RegisterPostRequest(string username, string password) { WWWForm form = new WWWForm(); form.AddField("username", username); form.AddField("password", password); WWW request = new WWW(SaveURL, form); yield return(request); if (!string.IsNullOrEmpty(request.error)) { if (!string.IsNullOrEmpty(request.text)) { APIError data = JsonUtility.FromJson <APIError>(request.text); SendErrorNotification(data.error.message); } } else { RegisterComplete data = JsonUtility.FromJson <RegisterComplete>(request.text); savedUsername = username; StartCoroutine(CheckAuth(data)); } }
public async Task <User> UpdateUser(User user, string password) { User valid = await ValidateUser(user.Email, password); if (valid == null) { throw new Exception($@"Error: Password or email incorrect"); } string UserAsJson = JsonSerializer.Serialize(user); Console.WriteLine(UserAsJson); HttpContent content = new StringContent( UserAsJson, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PutAsync(uri + $"/UpdateUser", content); if (!response.IsSuccessStatusCode) { APIError apiError = JsonSerializer.Deserialize <APIError>(await response.Content.ReadAsStringAsync()); throw new Exception($@"Error: {apiError.message}"); } string result = await response.Content.ReadAsStringAsync(); User updateUser = JsonSerializer.Deserialize <User>(result, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); return(updateUser); }
static void Main(string[] args) { string endpoint = "ENTER YOUR ENDPOINT HERE"; string key = "ENTER YOUR KEY HERE"; // Anomaly detection samples. try { EntireDetectSample.RunAsync(endpoint, key).Wait(); LastDetectSample.RunAsync(endpoint, key).Wait(); } catch (Exception e) { Console.WriteLine(e.Message); if (e.InnerException != null && e.InnerException is APIErrorException) { APIError error = ((APIErrorException)e.InnerException).Body; Console.WriteLine("Error code: " + error.Code); Console.WriteLine("Error message: " + error.Message); } else if (e.InnerException != null) { Console.WriteLine(e.InnerException.Message); } } Console.WriteLine("\nPress ENTER to exit."); Console.ReadLine(); }
public async Task <User> RegisterUser(User user) { user.SecurityLevel = 1; string UserAsJson = JsonSerializer.Serialize(user); Console.WriteLine(UserAsJson); HttpContent content = new StringContent( UserAsJson, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PostAsync(uri + "/RegisterUser", content); if (!response.IsSuccessStatusCode) { APIError apiError = JsonSerializer.Deserialize <APIError>(await response.Content.ReadAsStringAsync()); throw new Exception($@"Error: {apiError.message}"); } string result = await response.Content.ReadAsStringAsync(); User userReceived = JsonSerializer.Deserialize <User>(result, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); return(userReceived); }
public async Task <User> RemoveUser(User user) { User valid = await ValidateUser(user.Email, user.Password); if (valid == null) { throw new Exception($@"Error: Password or email incorrect"); } HttpResponseMessage response = await client.DeleteAsync(uri + $"/RemoveUser?email={user.Email}"); if (!response.IsSuccessStatusCode) { APIError apiError = JsonSerializer.Deserialize <APIError>(await response.Content.ReadAsStringAsync()); throw new Exception($@"Error: {apiError.message}"); } string result = await response.Content.ReadAsStringAsync(); User removedUser = JsonSerializer.Deserialize <User>(result, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); return(removedUser); }
public async Task <IActionResult> GetSelf() { // Pull manager ID from the HTTP context string managerId = HttpContext.User.Identity.Name; try { // Use the manager ID to pull manager information. return(Ok(await _managerService.GetSelf(managerId))); } catch (ManagerNotFoundException e) { // Error: The manager specified in the request context does not exist. // This shouldn't really occur, since the authentication handler should fail before the request gets to the endpoint. _logger.LogError(e, "Session managerId resolved to unknown manager. [mId: {managerId}]", managerId); return(BadRequest(APIError.ManagerNotFound())); } catch (Exception e) { // Error: Unknown error. _logger.LogError(e, "Failed to pull authenticated manager information. [mId: {managerId}]", managerId); return(BadRequest(APIError.UnknownError())); } }
public async Task <IActionResult> CloseDiningTable([FromRoute] string serviceId, [FromRoute] string tableId) { // Pull manager ID from the HTTP context string managerId = HttpContext.User.Identity.Name; try { // Close the dining table. await _managerService.CloseDiningTable(managerId, serviceId, tableId); // Return an empty OK status. return(Ok()); } catch (TableNotFoundException e) { // Error: Table specified could not be found. _logger.LogInformation(e, "Could not find specified dining sitting. [service: {serviceId}, sitting: {tableId}]", serviceId, tableId); return(BadRequest(APIError.TableNotFound())); } catch (NoAccessException e) { // Error: Manager does not have sufficient permission to close the requested dining table. _logger.LogInformation(e, "Manager was denied access to close dining table. [mId: {managerId}, sId: {serviceId}]", managerId, serviceId); return(BadRequest(APIError.NoAccess())); } catch (Exception e) { // Error: Unknown error. _logger.LogError(e, "Failed to close dining table"); return(BadRequest(APIError.UnknownError())); } }
public async Task <Order> UpdateOrder(Order order) { DataOrder transformed = BusinessToData(order); string orderAsJson = JsonSerializer.Serialize(transformed, serializeOptions); Console.WriteLine("request" + orderAsJson); HttpContent content = new StringContent( orderAsJson, Encoding.UTF8, "application/json"); HttpResponseMessage response = await client.PutAsync(uri + "/UpdateOrder", content); if (!response.IsSuccessStatusCode) { APIError apiError = JsonSerializer.Deserialize <APIError>(await response.Content.ReadAsStringAsync()); throw new Exception($@"Error: {apiError.message}"); } string result = await response.Content.ReadAsStringAsync(); DataOrder gotOrders = JsonSerializer.Deserialize <DataOrder>(result, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); Order returned = DataToBusiness(gotOrders); Console.WriteLine("result" + result); return(returned); }
public async Task <IList <Order> > GetOrdersAdmin(int id, string email, string password) { User check = await userService.ValidateUser(email, password); if (check == null) { throw new Exception("Wrong email or password"); } HttpResponseMessage response = await client.GetAsync(uri + $"/GetUserOrders?userId={id}"); if (!response.IsSuccessStatusCode) { APIError apiError = JsonSerializer.Deserialize <APIError>(await response.Content.ReadAsStringAsync()); throw new Exception($@"Error: {apiError.message}"); } string result = await response.Content.ReadAsStringAsync(); List <DataOrder> gotOrders = JsonSerializer.Deserialize <List <DataOrder> >(result, new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }); List <Order> userOrders = new List <Order>(); foreach (var item in gotOrders) { userOrders.Add(DataToBusiness(item)); } Console.WriteLine("result" + result); return(userOrders); }
static void Main(string[] args) { // Add your Computer Vision subscription key and endpoint to your environment variables string endpoint = Environment.GetEnvironmentVariable("ANOMALY_DETECTOR_ENDPOINT"); string key = Environment.GetEnvironmentVariable("ANOMALY_DETECTOR_SUBSCRIPTION_KEY"); // Anomaly detection samples. try { EntireDetectSample.RunAsync(endpoint, key).Wait(); LastDetectSample.RunAsync(endpoint, key).Wait(); } catch (Exception e) { Console.WriteLine(e.Message); if (e.InnerException != null && e.InnerException is APIErrorException) { APIError error = ((APIErrorException)e.InnerException).Body; Console.WriteLine("Error code: " + error.Code); Console.WriteLine("Error message: " + error.Message); } else if (e.InnerException != null) { Console.WriteLine(e.InnerException.Message); } } Console.WriteLine("\nPress ENTER to exit."); Console.ReadLine(); }
public ExecuteWrapper(WebResponse response) { if (!response.Success) { Error = new APIError(response); } }
// </createClient> // <runSamples> static void runSamples(IAnomalyDetectorClient client, string dataPath) { try { List <Point> series = GetSeriesFromFile(dataPath); Request request = new Request(series, Granularity.Daily); EntireDetectSampleAsync(client, request).Wait(); LastDetectSampleAsync(client, request).Wait(); } catch (Exception e) { Console.WriteLine(e.Message); if (e.InnerException != null && e.InnerException is APIErrorException) { APIError error = ((APIErrorException)e.InnerException).Body; Console.WriteLine("Error code: " + error.Code); Console.WriteLine("Error message: " + error.Message); } else if (e.InnerException != null) { Console.WriteLine(e.InnerException.Message); } } }
public ActionResult Create([Bind(Include = "ID,CountryCode,Description")] Flag Flag) { if (ModelState.IsValid) { string JSONtheFlag = JsonConvert.SerializeObject(Flag); HttpContent content = new StringContent(JSONtheFlag, Encoding.UTF8, "application/json"); using (HttpClient client = new HttpClient()) { client.BaseAddress = new Uri(ConfigurationManager.AppSettings[ConfigurationParams.WCAPIHost]); HttpResponseMessage response = client.PostAsync(ConfigurationParams.FlagsURN, content).Result; if (!response.IsSuccessStatusCode) { APIError aPIError = JsonConvert.DeserializeObject <APIError>(response.Content.ReadAsStringAsync().Result); aPIError.MessageDetail += $"HTTP response: {response.StatusCode.ToString()} "; throw new Exception($"Message: {aPIError.Message} MessageDetail:{aPIError.MessageDetail}"); } } return(RedirectToAction("Index")); } else { throw new Exception(ConfigurationManager.AppSettings[ConfigurationParams.WCFlagCreateFormInvalid]); } }
static void Main(string[] args) { string endpoint = "[YOUR_ENDPOINT_URL]"; string key = "[YOUR_SUBSCRIPTION_KEY]"; string path = "[PATH_TO_TIME_SERIES_DATA]"; // Anomaly detection samples. try { List <Point> series = GetSeriesFromFile(path); Request request = new Request(series, Granularity.Daily); EntireDetectSampleAsync(endpoint, key, request).Wait(); LastDetectSampleAsync(endpoint, key, request).Wait(); } catch (Exception e) { Console.WriteLine(e.Message); if (e.InnerException != null && e.InnerException is APIErrorException) { APIError error = ((APIErrorException)e.InnerException).Body; Console.WriteLine("Error code: " + error.Code); Console.WriteLine("Error message: " + error.Message); } else if (e.InnerException != null) { Console.WriteLine(e.InnerException.Message); } } Console.WriteLine("\nPress ENTER to exit."); Console.ReadLine(); }
public void DisplayErrors(APIError error) { foreach (var err in error.Errors) { _messageStore.Add(CurrentEditContext.Field(err.FieldName), err.ErrorMSG); } CurrentEditContext.NotifyValidationStateChanged(); }
public ErrorResponse(ValidationResult validationResult) { var errors = validationResult.Errors .Select(validationResultError => new ValidationError(validationResultError)).ToList(); Error = new APIError { IsValid = validationResult.IsValid, ValidationErrors = errors }; }
public EntryItem AddEntry(byte[] dataEntry, byte [][] ExtIDs = null) { if (EcAddress == null) { throw new Exception("No EcAddress provided - read only"); } Action <EntryItem> action = (process) => { try { process.Commit = new CommitEntry(FactomD); var commitStatus = process.Commit.Run(ChainID, dataEntry, EcAddress, ExtIDs); if (commitStatus) //commit success? { process.Status = EntryItem.State.CommitOK; process.TxId = process.Commit?.Result?.result?.Txid ?? null; process.Reveal = new RevealEntry(FactomD); if (process.Reveal.Run(process.Commit.Entry)) { process.Status = EntryItem.State.RevealOK; process.EntryHash = process.Reveal?.Result?.result?.Entryhash; } else //Reveal failed { var error = JsonConvert.DeserializeObject <APIError>(process.Reveal.JsonReply); process.ApiError = error; process.Status = EntryItem.State.RevealFail; } } else //Commit failed { var error = JsonConvert.DeserializeObject <APIError>(process.Commit.JsonReply); process.ApiError = error; process.Status = EntryItem.State.CommitFail; } } catch (Exception ex) { var error = new APIError(ex); process.ApiError = error; process.Status = EntryItem.State.Exception; } }; var queueItem = new EntryItem(this, action, Blocking); lock (queueLock) { EntryQueue.Add(queueItem); } RunQueue(); return(queueItem); }
public async Task <IActionResult> UpdateDiningPatron( [FromRoute] string serviceId, [FromRoute] string tableId, [FromRoute] string checkInId, [FromRoute] string patronId, [FromBody] DiningPatronUpdateRequest update ) { // Pull manager ID from the HTTP context. string managerId = HttpContext.User.Identity.Name; try { // Update the dining patron with new information. await _managerService.UpdateDiningPatron(managerId, serviceId, tableId, checkInId, patronId, update); // Return an empty OK status. return(Ok()); } catch (TableNotFoundException e) { // Error: Table specified could not be found. _logger.LogInformation(e, "Could not find specified dining sitting to update patron. [service: {serviceId}, sitting: {tableId}]", serviceId, tableId); return(BadRequest(APIError.TableNotFound())); } catch (CheckInNotFoundExcption e) { // Error: Check-in specified could not be found. _logger.LogInformation(e, "Could not find specified dining check-in to update patron. [service: {serviceId}, sitting: {tableId}, checkIn: {checkInId}]", serviceId, tableId, checkInId); return(BadRequest(APIError.CheckInNotFound())); } catch (PatronNotFoundException e) { // Error: Patron specified for update does not exist. _logger.LogInformation(e, "Could not find specified dining patron for update. [mId: {managerId}, sId: {serviceId}, pId: {patronId}]", managerId, serviceId, patronId); return(BadRequest(APIError.PatronNotFound())); } catch (NoAccessException e) { // Error: Manager does not have sufficient access to update the dining patron. _logger.LogInformation(e, "Manager was denied access to update dining patron. [mId: {managerId}, sId: {serviceId}]", managerId, serviceId); return(BadRequest(APIError.NoAccess())); } catch (Exception e) { // Error: Unknown error. _logger.LogError(e, "Failed to update dining patron"); return(BadRequest(APIError.UnknownError())); } }
public async Task <IHttpActionResult> GetListByMultipleBahan(string ids) { try { return(Json(await panduanHandler.GetListByMultipleBahan(ids))); } catch (InternalServerErrorException e) { return(Json(APIError.From(e))); } }
public async Task <IHttpActionResult> Insert(JObject body) { try { return(Json(await panduanHandler.Insert(body))); } catch (InternalServerErrorException e) { return(Json(APIError.From(e))); } }
public async Task <IHttpActionResult> GetAllKategoriBahan() { try { return(Json(await kategoriBahanHandler.GetAllKategoriBahan())); } catch (InternalServerErrorException e) { return(Json(APIError.From(e))); } }
public async Task <IHttpActionResult> GetById(int id) { try { return(Json(await userHandler.GetById(id))); } catch (InternalServerErrorException e) { return(Json(APIError.From(e))); } }