public async Task <ResponseBase> RegisterNotificationUrl() { if (SettingsManager.IsNotificationUrlRegistered) { // Already registered return(null); } FSLog.Info("Not registered yet"); // Register notification token, this is used to track the type of devices being used // at the moment. "W" is used as a workaround for missing token. var tokenResp = await this.Request.RegisterNotificationUrl("W"); if (!tokenResp.IsSuccessful) { // NOTE: Not failing if this fails. FSLog.Error("Failed to register token"); } else { FSLog.Info("Notification token sent"); SettingsManager.IsNotificationUrlRegistered = true; } return(tokenResp); }
void NotificationService_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e) { FSLog.Error("Push notification error {0} occured. {1} {2} {3}", e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData); Stop(); Start(); }
/// <summary> /// Signup to Lokki service with email /// </summary> public async Task <SignupResponse> Signup(string email) { var current = SettingsManager.CurrentUser; current.Email = email; SignupResponse resp = await Request.Signup(email, DeviceId); // Store user id and auth if successful if (resp.IsSuccessful) { FSLog.Info("Signup successful"); SettingsManager.AuthToken = resp.AuthorizationToken; this.Request.AuthToken = SettingsManager.AuthToken; this.Request.UserId = resp.Id; current.BackendId = resp.Id; SettingsManager.SavePeople(); await RegisterNotificationUrl(); } else { FSLog.Error("Signup failed:", resp.HttpStatus, resp.Error); } return(resp); }
/// <summary> /// Toggle user's visibility to others. /// </summary> public async void ToggleVisibility() { SystemTrayProgressIndicator.TaskCount++; try { var previous = SettingsManager.CurrentUser.IsVisible; // Toggle var visible = previous == false; // Change immediately to show something happened SettingsManager.CurrentUser.IsVisible = visible; Dispatcher.BeginInvoke(UpdateVisibilityIcon); // Send var resp = await ServerAPIManager.Instance.ChangeVisibility(visible); if (!resp.IsSuccessful) { FSLog.Error("Failed to update visibility"); SettingsManager.CurrentUser.IsVisible = previous; Dispatcher.BeginInvoke(UpdateVisibilityIcon); } } finally { SystemTrayProgressIndicator.TaskCount--; } }
private async Task SendLocation(Geoposition position) { var k = new Geolocation(position); var resp = await ServerAPIManager.Instance.ReportLocation(k); if (resp.IsSuccessful) { FSLog.Info("Location sent"); } else { FSLog.Error("Failed to send location"); } /* * // Launch a toast to show that the agent is running. * // The toast will not be shown if the foreground application is running. * ShellToast toast = new ShellToast(); * toast.Title = "Location sent"; * toast.Content = ""; * toast.Show(); */ // Call NotifyComplete to let the system know the agent is done working. if (position.Coordinate.Accuracy <= LocationService.Instance.TargetAccuracy) { FSLog.Debug("Stopping"); NotifyComplete(); } else { FSLog.Debug("Waiting for more accurate position"); } }
public async Task <ResponseBase> DisallowContactToSeeMe(Person person) { var resp = await Request.DisallowContactToSeeMe(person.BackendId); if (!resp.IsSuccessful) { FSLog.Error("Request failed"); } return(resp); }
private void ReadCallBack(RequestContext context, IAsyncResult asynchronousResult) { FSLog.Debug(context.Type); try { HttpWebResponse response = Request.EndGetResponse(asynchronousResult) as HttpWebResponse; FSLog.Info(response.StatusCode, response.StatusDescription); context.HttpStatus = response.StatusCode; context.ContentType = response.ContentType; using (StreamReader responseStream = new StreamReader(response.GetResponseStream())) { context.ResponseBody = responseStream.ReadToEnd(); } } catch (WebException e) { FSLog.Exception(e); HttpStatusCode responseCode; // Get the error JSON from SettingsService if (e.Response != null) { var response = ((HttpWebResponse)e.Response); responseCode = response.StatusCode; context.HttpStatus = response.StatusCode; FSLog.Error("StatusCode", (int)responseCode, responseCode, response.StatusDescription); FSLog.Error(((HttpWebResponse)e.Response).StatusDescription); using (StreamReader responseStream = new StreamReader(response.GetResponseStream())) { string err = responseStream.ReadToEnd(); FSLog.Error(err); context.ResponseBody = err; } } else { FSLog.Error("No response, canceled"); return; } } catch (Exception e) { FSLog.Error("Unexpected error"); FSLog.Exception(e); } finally { context.IsCompleted = true; } }
public Task <T> Execute(Uri uri, object data, string method = "POST", [CallerMemberName] string requestName = "") { return(Task <T> .Run(() => { RequestContext context = new RequestContext(requestName); if (method == "POST" || method == "PUT") { var jsonData = ""; if (data != null) { jsonData = JsonConvert.SerializeObject(data); } this.StartPostRequest(context, uri, jsonData, method: method); } else { this.StartRequest(context, uri, method: method); } context.AsyncWaitHandle.WaitOne(); if (context.HttpStatus != HttpStatusCode.OK || context.ResponseBody == null) { FSLog.Error("Request failed"); return new T { Error = "Request failed", HttpStatus = context.HttpStatus }; } T products; var aslist = new List <string>(context.ContentType.Split(';')); if (aslist.Contains("application/json")) { //products = JsonConvert.DeserializeObject<T>(context.ResponseBody); JObject json = JObject.Parse(context.ResponseBody); products = json.ToObject <T>(); products.PostProcess(json); } else { products = new T(); } products.HttpStatus = context.HttpStatus; return products; })); }
/// <summary> /// Update list of places /// </summary> /// <returns></returns> public async Task <PlacesResponse> GetPlaces() { var resp = await Request.GetPlaces(); if (!resp.IsSuccessful) { FSLog.Error("Request failed", resp.HttpStatus); return(resp); } var places = SettingsManager.Places; var removedPlace = new List <Place>(); foreach (var place in places) { if (resp.Places.ContainsKey(place.Id)) { PlaceData data = resp.Places[place.Id]; UpdatePlace(place, data); // Remove so not added as new resp.Places.Remove(place.Id); } else { removedPlace.Add(place); } } // Add new foreach (string id in resp.Places.Keys) { PlaceData data = resp.Places[id]; var place = new Place(); place.Id = id; UpdatePlace(place, data); places.Add(place); } foreach (Place place in removedPlace) { places.Remove(place); } // TODO: Check for accidental duplicates. Would use dictionary but there's no builtin ObservableDictionary SettingsManager.Save(); return(resp); }
public void SearchContact(string email) { if (string.IsNullOrWhiteSpace(email)) { FSLog.Error("Invalid email"); return; } Contacts cons = new Contacts(); cons.SearchCompleted += new EventHandler <ContactsSearchEventArgs>(Email_SearchCompleted); cons.SearchAsync(email, FilterKind.EmailAddress, this); }
public async Task <UpdatePlaceResponse> UpdatePlace(Place place) { var resp = await Request.UpdatePlace(place.Id, place.Name, place.Latitude, place.Longitude, place.Radius); if (!resp.IsSuccessful) { FSLog.Error("Request failed", resp.HttpStatus); return(resp); } SettingsManager.Save(); return(resp); }
public async Task <DeletePlaceResponse> DeletePlace(Place place) { var resp = await Request.DeletePlace(place.Id); if (!resp.IsSuccessful) { FSLog.Error("Request failed", resp.HttpStatus); return(resp); } SettingsManager.Places.Remove(place); SettingsManager.Save(); return(resp); }
async private Task <SignupResponse> Signup() { var email = EmailTextBox.Text; if (!IsEmail(email)) { return(null); } SignupButton.IsEnabled = false; EmailTextBox.IsEnabled = false; SystemTrayProgressIndicator.TaskCount++; var reply = await ServerAPIManager.Instance.Signup(EmailTextBox.Text); SystemTrayProgressIndicator.TaskCount--; if (reply.IsSuccessful) { FSLog.Info("Login succesful, show map page"); // To enable location updater task SettingsManager.IsLocationUploadEnabled = true; OpenMapPage(); } else { FSLog.Error("Failed to login"); SignupButton.IsEnabled = true; EmailTextBox.IsEnabled = true; // Handle 401 if (reply.HttpStatus == HttpStatusCode.Unauthorized) { MessageBox.Show(Localized.SignupError401.FormatLocalized(email)); } else { MessageBox.Show(Localized.SignupError); } } return(reply); }
async void button_Click(object sender, EventArgs e) { SystemTrayProgressIndicator.TaskCount++; var resp = await ServerAPIManager.Instance.AllowContactToSeeMe(SelectedEmails.ToList <string>()); if (resp.IsSuccessful) { NavigationService.GoBack(); } else { FSLog.Error("Failed to allow contacts"); MessageBox.Show(Localized.ApiError); } SystemTrayProgressIndicator.TaskCount--; }
public async Task <CreatePlaceResponse> CreatePlace(Place place) { var resp = await Request.CreatePlace(place.Name, place.Latitude, place.Longitude, 100); if (!resp.IsSuccessful) { FSLog.Error("Request failed", resp.HttpStatus); return(resp); } //var place = new Place(resp.Id, name, lat, lon, 100); var places = SettingsManager.Places; place.Id = resp.Id; places.Add(place); SettingsManager.Save(); return(resp); }
public async Task <ResponseBase> ReportLocation(Geolocation location) { // Update setting here to update with bg agent and app. var p = SettingsManager.CurrentUser; p.Position = location; SettingsManager.CurrentUser = p; if (string.IsNullOrEmpty(SettingsManager.AuthToken)) { FSLog.Error("Not authenticated"); return(new ResponseBase()); } return(await Request.ReportLocationToServer( location.Latitude, location.Longitude, location.Accuracy, location.Time.ToMillisecondsSince1970())); }
void LocationService_LocationChanged(object sender, LocationChangeEventArgs e) { FSLog.Debug(); var coords = e.Position.Coordinate; var location = new Geolocation( lat: coords.Latitude, lon: coords.Longitude, acc: coords.Accuracy, time: coords.Timestamp.UtcDateTime); Deployment.Current.Dispatcher.BeginInvoke(async() => { var resp = await ServerAPIManager.Instance.ReportLocation(location); if (!resp.IsSuccessful) { FSLog.Error("Failed to update location"); } }); }
/// <summary> /// Start inviting another user with confirmation dialog. /// </summary> /// <param name="email"></param> /// <returns></returns> public async Task InviteUserAsync(string email) { SystemTrayProgressIndicator.TaskCount++; //Email = e.Email; var reply = MessageBox.Show( Localized.InvitingConfirmMessage.FormatLocalized(email), Localized.Inviting, MessageBoxButton.OKCancel); if (reply != MessageBoxResult.OK) { FSLog.Info("User declined"); return; } var resp = await ServerAPIManager.Instance.AllowContactToSeeMe(new List <string> { email }); if (resp.IsSuccessful) { // Display tutorial popup in map page if (UserInvited != null) { UserInvited(this, new EventArgs()); } } else { FSLog.Error("Request failed"); MessageBox.Show(Localized.ApiError); } SystemTrayProgressIndicator.TaskCount--; }
public static Entity CreateItem(EntityManager entityManager, EntityType type, Vector3 position, Entity owner) { if (!prefabs.ContainsKey(type)) { FSLog.Error($"can't find prefabs by type:{type}"); return(Entity.Null); } var e = entityManager.Instantiate(prefabs[type]); var translation = entityManager.GetComponentData <Translation>(e); var rotation = entityManager.GetComponentData <Rotation>(e); // FSLog.Info($"CreateItemComponent,translation:{translation.Value}"); //if(!entityManager.HasComponent<OffsetSetting>(e)) // entityManager.AddComponentData(e, new OffsetSetting() // { // Pos = translation.Value, // Rot = rotation.Value // }); var newPosition = (float3)position + translation.Value; entityManager.SetComponentData(e, new Translation { Value = newPosition }); entityManager.SetComponentData(e, new Rotation { Value = rotation.Value }); entityManager.AddComponentData(e, new ReplicatedEntityData { Id = -1, PredictingPlayerId = -1 }); entityManager.AddComponentData(e, new GameEntity() { Type = type }); entityManager.AddComponentData(e, new Item()); entityManager.AddComponentData(e, new TransformPredictedState { Position = newPosition, Rotation = rotation.Value }); entityManager.AddComponentData(e, new VelocityPredictedState { MotionType = MotionType.Static, Linear = float3.zero, Angular = float3.zero }); entityManager.AddComponentData(e, new OwnerPredictedState { Owner = owner, PreOwner = Entity.Null }); entityManager.AddComponentData(e, new DespawnPredictedState { IsDespawn = false, Tick = 0 }); entityManager.AddComponentData(e, new TriggerSetting { Distance = 0.01f, IsMotionLess = false }); entityManager.AddComponentData(e, new TriggerPredictedState { TriggeredEntity = Entity.Null, PreTriggeredEntity = Entity.Null, IsAllowTrigger = false }); entityManager.RemoveComponent <PhysicsVelocity>(e); if (IsFood(type)) { entityManager.AddComponentData(e, new Food()); entityManager.AddComponentData(e, new FlyingPredictedState() { IsFlying = false }); } if (IsUnsliced(type)) { entityManager.AddComponentData(e, new Unsliced()); entityManager.AddComponentData(e, new ProgressSetting() { Type = ProgressType.Slice, TotalTick = 150, OffPos = new float3(0, 1.7f, 0) }); entityManager.AddComponentData(e, new ProgressPredictState() { CurTick = 0 }); } if (IsSliced(type)) { entityManager.AddComponentData(e, new Sliced()); } if (IsUncooked(type)) { entityManager.AddComponentData(e, new Uncooked()); } if (IsCooked(type)) { entityManager.AddComponentData(e, new Cooked()); } if (CanDishOut(type)) { entityManager.AddComponentData(e, new CanDishOut()); } if (IsProduct(type)) { entityManager.AddComponentData(e, new Product()); } if (IsPlate(type)) { entityManager.AddComponentData(e, new Plate()); entityManager.AddComponentData(e, new PlatePredictedState() { Product = Entity.Null, IsGenProduct = false }); } if (IsPlateDirty(type)) { entityManager.AddComponentData(e, new PlateDirty()); entityManager.AddComponentData(e, new ProgressSetting() { Type = ProgressType.Wash, TotalTick = 150, OffPos = new float3(0, 1.7f, 0) }); entityManager.AddComponentData(e, new ProgressPredictState() { CurTick = 0 }); } if (IsPot(type)) { entityManager.AddComponentData(e, new Pot()); entityManager.AddComponentData(e, new ProgressSetting() { Type = ProgressType.Cook, TotalTick = 250, OffPos = new float3(0, -1f, 0) }); entityManager.AddComponentData(e, new ProgressPredictState() { CurTick = 0 }); entityManager.AddComponentData(e, new FireAlertSetting() { TotalTick = 250 }); entityManager.AddComponentData(e, new FireAlertPredictedState() { CurTick = 0 }); entityManager.AddComponentData(e, new PotPredictedState() { State = PotState.Empty }); } if (IsExtinguisher(type)) { entityManager.AddComponentData(e, new Extinguisher()); entityManager.AddComponentData(e, new ExtinguisherPredictedState() { Distance = 0 }); } return(e); }
/** Retrieve dashboard data from backend and update app state */ public async Task <DashboardResponse> GetDashboard() { var resp = await Request.GetDashboard(); if (!resp.IsSuccessful) { FSLog.Error("Request failed", resp.HttpStatus); return(resp); } var people = SettingsManager.People; // TODO: Refactor the 2 loops to use common function var newPeople = new List <string>(resp.IdMapping.Keys); foreach (var person in people) { if (person.IsCurrent) { // Refresh to keep in sync person.IsVisible = resp.Visibility; newPeople.Remove(person.BackendId); continue; } ; if (resp.ICanSee.ContainsKey(person.BackendId)) { person.ICanSee = true; var dashboard = resp.ICanSee[person.BackendId]; RefreshPerson(person, dashboard); } else { person.ICanSee = false; } person.CanSeeMe = resp.CanSeeMe.Contains(person.BackendId); newPeople.Remove(person.BackendId); } // Add new people foreach (var key in newPeople) { var person = new Person(); person.BackendId = key; var email = resp.IdMapping[key]; person.Email = email; person.CanSeeMe = resp.CanSeeMe.Contains(key); if (resp.ICanSee.ContainsKey(key)) { person.ICanSee = true; var dashboard = resp.ICanSee[key]; RefreshPerson(person, dashboard); } else { person.ICanSee = false; } // This triggers CollectionChanged event to UI, see MapPage::People_CollectionChanged people.Add(person); } SettingsManager.SavePeople(); return(resp); }