/// <summary> /// Ticks the update asynchronous. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> private async void TickUpdateAsync(object sender, object e) { if (totalTime > 1) { try { timer.Stop(); await UpdateObject(); } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } finally { timerUpdate.Stop(); } } else { totalTime++; } }
/// <summary> /// Handles the Loaded event of the Map control. And set the pinpoint in the center of the map. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="Windows.UI.Xaml.RoutedEventArgs"/> instance containing the event data.</param> public async void Map_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e) { try { var locator = new Geolocator(); var position = await locator.GetGeopositionAsync(); var PositionOnMap = new BasicGeoposition() { Latitude = position.Coordinate.Point.Position.Latitude, Longitude = position.Coordinate.Point.Position.Longitude }; MapCenter = new Geopoint(PositionOnMap); MapZoomLevel = 14; Posistion = new Geopoint(PositionOnMap); } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); var PositionOnMap = new BasicGeoposition() { Latitude = 59.9, Longitude = 10.75 }; MapCenter = new Geopoint(PositionOnMap); MapZoomLevel = 14; Posistion = new Geopoint(PositionOnMap); } }
/// <summary> /// Starts the machine learning asynchronous. /// </summary> public async void StartMachineLearningAsync() { try { FileOpenPicker picker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary }; picker.FileTypeFilter.Add(".jpg"); file = await picker.PickSingleFileAsync(); MessageDialog dlg; string filePath = file.Path; using (var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read)) { BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(stream); ImageSource = bitmap; } await Task.Run(() => MakePredictionRequest(file)); } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } }
public async Task <IHttpActionResult> PostAsync() { try { var file = HttpContext.Current.Request.Files.Count > 0 ? HttpContext.Current.Request.Files[0] : null; if (file != null && file.ContentLength > 0) { var filename = Path.GetFileName(file.FileName); var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads"), filename); //var path = Path.Combine(@"C:\\Users\\bjornma\\Pictures\\bilder", filename); file.SaveAs(path); } return(Ok()); } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } return(Conflict()); }
/// <summary> /// Searches the asynchronous. /// </summary> public async void SearchAsync() { cts = new CancellationTokenSource(); Visible = false; RevertVisible = true; try { if (Text == "" || Text == null) { Animals = await ApiCall.Get <ObservableCollection <Animal> >($"Animals"); } else { Animals = await ApiCall.Get <ObservableCollection <Animal> >($"Animals/Search/{Text}"); } } catch (OperationCanceledException ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } finally { Visible = true; RevertVisible = false; } }
//[Route("api/Image/{Name}")] /// <summary> /// Gets the asynchronous. /// </summary> /// <param name="filename">The filename.</param> /// <returns></returns> public async Task <HttpResponseMessage> GetAsync(string filename) { try { string file = Path.Combine(HttpContext.Current.Server.MapPath("~/Uploads"), filename); var ext = new FileInfo(file).Extension; ext = ext.Substring(1); var img = File.ReadAllBytes(file); var ms = new MemoryStream(img); var respons = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StreamContent(ms) }; respons.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue($"image/{ext}"); return(respons); } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } return(default(HttpResponseMessage)); }
/// <summary> /// Gets the image. /// </summary> public async void GetImage() { FileOpenPicker picker = new FileOpenPicker { ViewMode = PickerViewMode.Thumbnail, SuggestedStartLocation = PickerLocationId.PicturesLibrary }; picker.FileTypeFilter.Add(".jpg"); try { File = await picker.PickSingleFileAsync(); if (File.Path != null) { //ImageSource = new BitmapImage(new Uri(file.Path, UriKind.Relative)); using (var stream = await File.OpenAsync(Windows.Storage.FileAccessMode.Read)) { BitmapImage bitmap = new BitmapImage(); bitmap.SetSource(stream); ImageSource = bitmap; HuntedAnimal.ImageUrl = File.Path; } } } catch (Exception ex) { Text = "Det skjedde noe feil"; await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } }
/// <summary> /// Selecteds the animal asynchronous. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="SelectionChangedEventArgs"/> instance containing the event data.</param> public async void SelectedAnimalAsync(object sender, SelectionChangedEventArgs e) { //Den her begynte bare å slutte å fungere og fikk en rar feilmelding som sa det var feil med assembly. Derfor try catch her. try { Animal = (Animal)e.AddedItems[0]; } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } //convert the Huntedanimal to child or parent if (Animal.IsPointsAnimal) { var serializedParent = JsonConvert.SerializeObject(HuntedAnimal); HuntedAnimalPoints c = JsonConvert.DeserializeObject <HuntedAnimalPoints>(serializedParent); HuntedAnimal = c; Visible = true; } else { var serializedParent = JsonConvert.SerializeObject(HuntedAnimal); HuntedAnimal c = JsonConvert.DeserializeObject <HuntedAnimal>(serializedParent); HuntedAnimal = c; Visible = false; } }
/// <summary> /// Makes the prediction request. /// </summary> /// <param name="file">The file.</param> /// <returns></returns> private async Task MakePredictionRequest(StorageFile file) { try { var client = new HttpClient(); // Request headers - replace this example key with your valid subscription key. client.DefaultRequestHeaders.Add("Prediction-Key", "4b013eec09d5460cb3cbd3178a91dbe0"); // Prediction URL - replace this example URL with your valid prediction URL. string url = "https://southcentralus.api.cognitive.microsoft.com/customvision/v1.0/Prediction/08cbc22c-7aa3-43f3-8363-d4895ee306aa/image?iterationId=f635df50-9c4a-4ed2-ad62-1875f2402139"; HttpResponseMessage response; // Request body. Try this sample with a locally stored image. byte[] byteData = await ConvertToImage(file); JToken[] memberName; using (var content = new ByteArrayContent(byteData)) { content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); response = await client.PostAsync(url, content); var stuff = (await response.Content.ReadAsStringAsync()); var test3 = JObject.Parse(stuff); memberName = test3["Predictions"].ToArray(); } Text = "Bilde inneholder følgende dyr: "; foreach (JToken jt in memberName) { if (Double.Parse(jt["Probability"].ToString()) >= 0.95) { Text += jt["Tag"] + " "; } } } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); Error = true; } }
public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args) { var animalList = await ApiCall.Get <ObservableCollection <Animal> >("HuntedAnimal/Hunter/1"); if (animalList == null) { animalList = await ApiCall.Get <ObservableCollection <Animal> >("HuntedAnimal/Hunter/1"); if (animalList == null) { await Task.Run(() => ReportError.ErrorAsync("User cannot connect")); } } else { await NavigationService.NavigateAsync(typeof(Views.HunterPage)); } // TODO: add your long-running task here }
/// <summary> /// Starts the asynchronous. /// </summary> public async void StartAsync() { Error = true; HttpClient client = new HttpClient(); //Convert to parent or child from a json string try { HuntedAnimals.Clear(); var jArray = JArray.Parse(await client.GetStringAsync(new Uri("http://localhost:61604/api/HuntedAnimal/Hunter/1"))); for (var i = 0; i < jArray.Count; i++) { if ((bool)jArray[i]["Animal"]["IsPointsAnimal"]) { HuntedAnimals.Add((jArray[i] as JObject).ToObject <HuntedAnimalPoints>()); } else { HuntedAnimals.Add((jArray[i] as JObject).ToObject <HuntedAnimal>()); } } } //Send the Excepetion to a file catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } //Get animal Animals = await ApiCall.Get <ObservableCollection <Animal> >("Animals"); if (HuntedAnimals != null && Animals != null) { Error = false; TotalLength = HuntedAnimals.Count(); } }
/// <summary> /// Posts the image asynchronous. /// </summary> public async void PostImageAsync() { try { var client = new HttpClient(); byte[] byteData = await ConvertToByteData(); var requestContent = new MultipartFormDataContent(); // here you can specify boundary if you need---^ var imageContent = new ByteArrayContent(byteData); imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg"); requestContent.Add(imageContent, "image", HuntedAnimal.HuntedAnimalId.ToString() + ".jpg"); var test2 = await client.PostAsync("http://localhost:61604/api/Image", requestContent); } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } }
/// <summary> /// Ticks the asynchronous. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The e.</param> private async void TickAsync(object sender, object e) { Resultat.Clear(); if (totalTime > 1) { timer.Stop(); if (SearchWord != "") { var list = Animals.Where(it => it.AnimalName.Contains(SearchWord.Substring(0, 1).ToUpper() + SearchWord.Substring(1))); foreach (var item in list) { Resultat.Add(item); } timer.Stop(); } else if (TotalLength != HuntedAnimals.Count()) { try { HuntedAnimals = await ApiCall.Get <ObservableCollection <HuntedAnimal> >("HuntedAnimal/Hunter/1"); timer.Stop(); } catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } } } totalTime++; }
/// <summary> /// Creates the object asynchronous. /// </summary> public async void CreateObjectAsync() { //set text to nothing Text = ""; Hit = false; RingVisible = true; try { //Wait for GPS location var position = await Task.WhenAll(GetPositionAsync()); var lat = position[0].Coordinate.Point.Position.Latitude; var lon = position[0].Coordinate.Point.Position.Longitude; //Set the latitude and longitude on HuntedAnimal object HuntedAnimal.Latitude = lat; HuntedAnimal.Longitude = lon; } catch (Exception ex) { //if users device dosent support location it will be sat to Oslo //Default Oslo HuntedAnimal.Latitude = 59.9; HuntedAnimal.Longitude = 10.75; await Task.Run(() => ReportError.ErrorAsync(ex.Message)); } finally { HuntedAnimal.DateTime = Date.ToString("MM/dd/yyyy"); try { // check if Huntedanimal have points or not. if (HuntedAnimal.GetType().Name == "HuntedAnimalPoints") { HuntedAnimal = await ApiCall.Post <HuntedAnimalPoints>("HuntedAnimalsPoints/", HuntedAnimal); } else { HuntedAnimal = await ApiCall.Post <HuntedAnimal>("HuntedAnimals/", HuntedAnimal); } // If user use own picture, post new picture. if (HuntedAnimal.ImageUrl != "http://localhost:61604/api/Image?filename=DummyPicture.png") { HuntedAnimal.ImageUrl = path + HuntedAnimal.HuntedAnimalId.ToString() + ".jpg"; await ApiCall.Update(uri, HuntedAnimal); await Task.Run(() => PostImageAsync()); } Hit = true; RingVisible = false; //navigate back to Home NavigationService.Navigate(typeof(Views.HunterPage), HuntedAnimal); } //report error catch (Exception ex) { await Task.Run(() => ReportError.ErrorAsync(ex.Message)); Text = "Det skjedde noe feil"; } } }