/// <summary> /// Returns saved login credentials in a TruckDto object. /// Note: async await calls to secure storage were hanging -- so work-around is encapsulating synchronous calls in Task.Run. /// Note: Task.Run hangs on first SecureStorageGetAsync call inside the Task.Run. Tried with and without .ConfigureAwait(false) /// </summary> /// <returns>TruckDto with non-zero TruckId if there are saved credentials. TruckId = 0 otherwise.</returns> public static async Task <TruckDto> GetLoginCredentialsAsync() { TruckDto truckCreds = new TruckDto(); try { truckCreds = await Task.Run <TruckDto>(() => { string truckid = SecureStorage.GetAsync("TruckId").Result; int intTruckId = 0; if (int.TryParse(truckid, out intTruckId)) { truckCreds.TruckId = intTruckId; } else { truckCreds.TruckId = 0; } truckCreds.TruckNumber = SecureStorage.GetAsync("TruckNumber").Result; truckCreds.ApiKey = SecureStorage.GetAsync("TruckApiKey").Result; return(truckCreds); }); } catch (Exception ex) { truckCreds.Message = "Saved Credentials Not Available: " + ex.Message; } return(truckCreds); }
public async Task <TruckDto> RegisterTruckAsync(TruckDto truckRegistration) { try { using (var client = new HttpClient()) { client.BaseAddress = new Uri(TripApiUrlBase); var request = GetRequestHeaders(HttpMethod.Post, "PostRegisterTruck"); SetRequestContent <TruckDto>(request, truckRegistration); var result = await client.SendAsync(request).ConfigureAwait(false); if (result.IsSuccessStatusCode) { string serializedJson = await result.Content.ReadAsStringAsync().ConfigureAwait(false); TruckDto registeredTruck = JsonConvert.DeserializeObject <TruckDto>(serializedJson); return(registeredTruck); } else { truckRegistration.Message = $"Truck Registration Failed with status {result.StatusCode} and reason {result.ReasonPhrase}"; } } } catch (Exception ex) { //Logger.Log(ex); log to a file on HD - put in a helper truckRegistration.Message = "Truck Registration Failed: " + ex.Message; truckRegistration.TruckId = 0; } return(truckRegistration); }
public static async Task <TruckDto> VerifyCredentials(TruckDto newTruck) { var result = await Task.Run <TruckDto>(async() => { return(await CredentialsManager.VerifyCredentials(newTruck)); }); return(result); }
public HttpResponseMessage PostRegisterTruck([FromBody] TruckDto truckDto) { Truck truck = null; User user = null; HttpResponseMessage message = new HttpResponseMessage(); try { if (truckDto != null) { if (!String.IsNullOrEmpty(truckDto.TruckNumber) && !String.IsNullOrEmpty(truckDto.ApiKey)) { var username = $"TRUCK_{truckDto.TruckNumber}"; truck = db.Trucks.FirstOrDefault(t => t.TruckNumber == truckDto.TruckNumber); if (truck != null && VerifyAuthentication(username, truckDto.ApiKey, truck.TruckId)) { user = db.Users.FirstOrDefault(u => u.UserId == truck.TripApiUserId.Value); if (user != null) { user.LastLoginDate = DateTime.Now; user.FailedPasswordAttemptCount = 0; db.SaveChanges(); truckDto.TruckId = truck.TruckId; truckDto.Message = "Successful Registration"; message = Request.CreateResponse <TruckDto>(HttpStatusCode.Created, truckDto); } } else { Log.Info(HttpStatusCode.Unauthorized + " " + "Registration for this truck failed."); message.StatusCode = HttpStatusCode.Unauthorized; message.ReasonPhrase = "Registration for this truck failed. Verify your Truck Number and API Key."; } } else { Log.Info(HttpStatusCode.BadRequest + " " + "Bad Truck Number (" + truckDto.TruckNumber + ") or API Key."); message.StatusCode = HttpStatusCode.BadRequest; message.ReasonPhrase = "Please provide a Truck Number and Api Key"; } } } catch (Exception ex) { Log.Error("Error: " + ex.InnerException + "Message: " + ex.Message + "StackTrace: " + ex.StackTrace); message.StatusCode = HttpStatusCode.InternalServerError; message.ReasonPhrase = "The registration request is either invalid or the system encountered an error when processing it"; } return(message); }
public async Task <ActionResult <TruckDto> > UpdateTruck([FromBody] TruckDto truckDto) { if (truckDto == null) { return(BadRequest()); } var truck = _mapper.Map <Entities.Truck>(truckDto); if (await _service.UpdateTruck(truck)) { return(Ok()); } else { return(BadRequest()); } }
/// <summary> /// Calls the PostRegisterTruck API in order to verify that the credentials are valid. /// </summary> /// <param name="truckCredentials"></param> /// <returns>the TruckDto -- TruckId > 0 for a successful login.</returns> public static async Task <TruckDto> VerifyCredentials(TruckDto truckCredentials) { ApiClient.ApiClient client = new ApiClient.ApiClient(); var result = await client.RegisterTruckAsync(truckCredentials).ConfigureAwait(false); if (result != null) { return(result); } else { result = new TruckDto(); result.Message = "System or Network Error: Could not Verify the registration credentials. Please try again or report the problem if it continues."; result.TruckId = 0; return(result); } }
/// <summary> /// Save the Truck credentials for later use in subsequent API calls. /// </summary> /// <param name="truckId">unique identifier returned by PostRegisterTruck API call</param> /// <param name="truckNumber">The truck number entered by the user during truck registration</param> /// <param name="apiKey">The API key (password) entered by the user during truck registration</param> /// <returns>a message as to weather the credentials were saved</returns> //public static async Task<string> SaveLoginCredentials(TruckDto truckCredentials) public static string SaveLoginCredentials(TruckDto truckCredentials) { string message = $"Truck {truckCredentials.TruckNumber} was successfully registered and saved to your device."; try { //await Task.Run(() => { SecureStorage.SetAsync("TruckId", truckCredentials.TruckId.ToString()); SecureStorage.SetAsync("TruckNumber", truckCredentials.TruckNumber); SecureStorage.SetAsync("TruckApiKey", truckCredentials.ApiKey); //}); } catch (Exception ex) { message = "Error: Registration credentials could not be saved: " + ex.Message; } return(message); }
public static async Task <bool> EstablishVerifiedCredentials() { bool result = false; Credentials = null; var truckCredentials = CredentialsManager.GetLoginCredentials(); // try running the damn thing synchronously if (truckCredentials.TruckId > 0) { // run api tasks on thread pool var validCredentials = await Task.Run <TruckDto>(async() => { return(await CredentialsManager.VerifyCredentials(truckCredentials)); }); if (validCredentials.TruckId > 0) { Credentials = validCredentials; result = true; } } return(result); }
private async void ButtonRegisterTruck(object sender, EventArgs e) { string message = "Attempting to register the truck"; messageLabel.Text = message; TruckDto newTruck = new TruckDto(); newTruck.TruckNumber = usernameEntry.Text; newTruck.ApiKey = passwordEntry.Text; var result = await TripContext.VerifyCredentials(newTruck); if (result != null) { message = result.Message; if (result.TruckId > 0) { //message = await CredentialsManager.SaveLoginCredentials(result); message = CredentialsManager.SaveLoginCredentials(result); if (!message.StartsWith("Error:")) { messageLabel.Text = message; TripContext.Credentials = result; var jobChanged = await TripContext.GetNextJob(); TripContext.CurrentPage = "DirectionsPage"; await Navigation.PushAsync(new DirectionsPage()); } } } else { message += " failed"; } messageLabel.Text = message; }