public void Init <T>() where T : class { new Task(new Action(async() => { var result = await DataProvider.Client.For <T>().FindEntriesAsync(); await MainThread.InvokeOnMainThreadAsync(() => { this.Items.Clear(); foreach (T entry in result) { this.Items.Add(entry); } }); })).Start(); }
public async Task GetAll() { await MainThread.InvokeOnMainThreadAsync(async() => { await Permissions.RequestAsync <Permissions.ContactsRead>(); }); var list = new List <Microsoft.Maui.Essentials.Contact>(); var contacts = await Microsoft.Maui.Essentials.Contacts.GetAllAsync(); foreach (var contact in contacts.Take(10)) { list?.Add(contact); } }
/// <inheritdoc /> public async Task <PermissionStatus> RequestPermissionsAsync <T>() where T : BasePermission, new() { return(await MainThread.InvokeOnMainThreadAsync(async() => { if (typeof(T) == typeof(NotificationsPermission)) { return await RequestNotificationPermissionAsync().ConfigureAwait(false); } var result = await EssentialsPermissions.RequestAsync <T>().ConfigureAwait(false); return result.ToPermissionStatus(); })); }
protected async Task DisplayAlert(List <string> notices) { if (displayAlert == null) { return; } if (notices?.Any() ?? false) { await MainThread.InvokeOnMainThreadAsync(async() => { await displayAlert(notices); }); } }
static async Task UpdateActivityIndicatorStatus(bool isActivityIndicatorDisplayed) { if (isActivityIndicatorDisplayed) { await MainThread.InvokeOnMainThreadAsync(() => GetBaseViewModel().IsInternetConnectionActive = Application.Current.MainPage.IsBusy = true); _networkIndicatorCount++; } else if (--_networkIndicatorCount <= 0) { await MainThread.InvokeOnMainThreadAsync(() => GetBaseViewModel().IsInternetConnectionActive = Application.Current.MainPage.IsBusy = false); _networkIndicatorCount = 0; } }
Task PulseImage() { return(MainThread.InvokeOnMainThreadAsync(async() => { //Image crouches down await _gitTrendsImage.ScaleTo(0.95, 100, Easing.CubicInOut); await Task.Delay(50); //Image jumps await _gitTrendsImage.ScaleTo(1.25, 250, Easing.CubicOut); //Image crashes back to the screen await _gitTrendsImage.ScaleTo(1, 500, Easing.BounceOut); })); }
public void OnAppearPage(object sender, EventArgs e) { if (OnRemoteNotifcation != null) { //if (mainpage != null) MessagingCenter.Subscribe <NetCoreNotification.Notification.Message, string>(this, "OnNewNotification", (msg, body) => { MainThread.InvokeOnMainThreadAsync(() => { OnRemoteNotifcation(body); //Label1.Text = body; }); Console.WriteLine(body); }); } }
private async void HandleTimerTick(object sender, ElapsedEventArgs e) { if (MainThread.IsMainThread == false) { await MainThread.InvokeOnMainThreadAsync(async() => { GeolocationRequest request = new GeolocationRequest(GeolocationAccuracy.Best, TimeSpan.FromSeconds(2)); Location currentLocation = await Geolocation.GetLocationAsync(request); Console.WriteLine($"Location: {currentLocation.Latitude}, {currentLocation.Longitude}"); }); } //We don't want requests to get the location backing up so we manually reset the time here instead of relying on the AutoReset property _timer.Start(); }
public Task OpenApp(string appScheme, string deepLinkingUrl, string browserUrl) { return(MainThread.InvokeOnMainThreadAsync(async() => { var supportsUri = await Launcher.CanOpenAsync(appScheme); if (supportsUri) { await Launcher.OpenAsync(deepLinkingUrl); } else { await OpenBrowser(browserUrl); } })); }
public async Task <AuthenticationResult> Authenticate(string authority, string resource, string clientId, string returnUri) { var authContext = new AuthenticationContext(authority); if (authContext.TokenCache?.ReadItems()?.Any() is true) { authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority); } var uri = new Uri(returnUri); var controller = await MainThread.InvokeOnMainThreadAsync(Platform.GetCurrentUIViewController); var platformParams = new PlatformParameters(controller); return(await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams).ConfigureAwait(false)); }
protected override void ViewIsAppearing(object sender, EventArgs e) { base.ViewIsAppearing(sender, e); Task.Run(async() => { await MainThread.InvokeOnMainThreadAsync(() => { IsActivityIndicatorRunning = true; }); //If you want to create a custom term list uncomment this code and add terms to look out for. //var termListId = await ContentModeratorService // .CreateTermList("InstaFaceFamTermList", "This is the term list for InstaFaceFam"); //await MainThread.InvokeOnMainThreadAsync(() => { // TermListId = termListId; //}); //await ContentModeratorService.AddTermToTermList(TermListId, "Fiddlesticks"); await LoadNewsFeedPosts(); await MainThread.InvokeOnMainThreadAsync(() => { IsActivityIndicatorRunning = false; }); }); }
public static async Task <UserActivitySession> AddToTimeLine(string area, ModelBase theModel, string bodyText) { UserActivitySession returnedFromUIThread = await MainThread.InvokeOnMainThreadAsync(async() => { UserActivitySession activitySession = null; try { // Record in the TimeLine UserActivityChannel channel = UserActivityChannel.GetDefault(); UserActivity _ModelUserActivity = await channel.GetOrCreateUserActivityAsync(theModel.HLinkKey.Value); if (theModel.Valid) { _ModelUserActivity.VisualElements.DisplayText = area.ToUpper(); _ModelUserActivity.VisualElements.Description = bodyText; _ModelUserActivity.VisualElements.BackgroundColor = ColorExtensions.ToPlatformColor(theModel.ModelItemGlyph.SymbolColour); // _ModelUserActivity.VisualElements.Content = // AdaptiveCardBuilder.CreateAdaptiveCardFromJson(CreateAdaptiveCardForTimeline(area, // theModel, bodyText).ToJson()); _ModelUserActivity.ActivationUri = new Uri("gramps://" + area + @"/handle/" + theModel.HLinkKey); //Save await _ModelUserActivity.SaveAsync(); if (_ModelUserActivity != null) { activitySession = _ModelUserActivity.CreateSession(); } } } catch (Exception ex) { DataStore.Instance.CN.NotifyException("Timeline Add", ex); throw; } return(activitySession); }).ConfigureAwait(false); return(returnedFromUIThread); }
private async Task <bool> DataLoadLogAdd(string entry) { await MainThread.InvokeOnMainThreadAsync(() => { DataLogEntry t = default(DataLogEntry); if (!string.IsNullOrEmpty(entry)) { t.Label = string.Format(System.Globalization.CultureInfo.CurrentCulture, "{0:HH: mm:ss}", System.DateTime.Now); t.Text = entry; DataLoadLog.Insert(0, t); } }); return(true); }
public async Task <bool> ShowPopup(string title, string message, string yesButtonText, string noButtonText) { var config = new ConfirmConfig() { CancelText = noButtonText, Message = message, OkText = yesButtonText, Title = title, }; bool result = false; await MainThread.InvokeOnMainThreadAsync(async() => { result = await UserDialogs.Instance.ConfirmAsync(config, null); }); return(result); }
public unsafe LogProgressDialog(FamiStudioForm parentForm) { this.parentForm = parentForm; MainThread.InvokeOnMainThreadAsync(() => { // HACK : We only use this for video export on mobile. dialog = new PropertyDialog("Exporting Video", 100, false); dialog.Properties.AddProgressBar("Export progress", 0.0f, "Exporting videos may take a very long time, especially at high resolutions. " + "Make sure FamiStudio remains open, clicking BACK or closing this window will abort the operation. " + "FamiStudio is currently preventing the screen from going to sleep.\n\n" + "Also please note that for reasons outside of our control, the video encoding quality on mobile " + "is inferior to the desktop version of FamiStudio."); // 0 dialog.Properties.AddLabel("Current Step", ""); // 1 dialog.Properties.Build(); }); }
private async Task SendAction() { await MainThread.InvokeOnMainThreadAsync(() => Messages.Add(new Message { Content = MessageBoxContent, IsMain = true })).ConfigureAwait(false); try { await _chatService.SendMessageAsync(MessageBoxContent).ConfigureAwait(false); MessageBoxContent = ""; } catch (Exception) { await _navigationService.PopAsync().ConfigureAwait(false); } }
/// <summary> /// Adds an item to the playlist. /// If it's the first item in the list, autoplay. /// </summary> /// <param name="item">Media Item.</param> /// <returns>Task.</returns> public async Task AddItemToPlaylistAsync(MediaProperties item) { if (item == null) { throw new ArgumentNullException(nameof(item)); } await MainThread.InvokeOnMainThreadAsync(async() => { this.MediaPlaylist.Add(item); // If first item in the list, autoplay it. if (this.MediaPlaylist.Count == 1) { this.CurrentMedia = item; } this.OnPropertyChanged(nameof(this.CanGoBack)); this.OnPropertyChanged(nameof(this.CanGoForward)); }).ConfigureAwait(false); }
async Task v_set_location_async_() { var status = await Permissions.CheckStatusAsync <Permissions.LocationWhenInUse>(); if (status != PermissionStatus.Granted) { await MainThread.InvokeOnMainThreadAsync(async() => { status = await Permissions.RequestAsync <Permissions.LocationAlways>(); }); } var l_req_ = new GeolocationRequest { DesiredAccuracy = GeolocationAccuracy.Best, Timeout = new TimeSpan(0, 0, 3) }; s_loc_ = await Geolocation.GetLocationAsync(l_req_); }
public static async Task <UserActivitySession> AddToTimeLine(string area, ModelBase theModel, string bodyText) { UserActivitySession returnedFromUIThread = await MainThread.InvokeOnMainThreadAsync(async() => { // Record in the TimeLine UserActivityChannel channel = UserActivityChannel.GetDefault(); UserActivity _ModelUserActivity = await channel.GetOrCreateUserActivityAsync(theModel.HLinkKey); Uri _Uri; UserActivitySession activitySession = null; if (theModel.Valid) { // Set deep-link and properties. _Uri = new Uri("gramps://" + area + @"/handle/" + theModel.HLinkKey); //// TODO Add Adapative card visuals once the API has settled down StorageFile // cardFile // = await StorageFile.GetFileFromApplicationUriAsync(new // // Uri("ms-appx:///Assets/Misc/UserActivityCard.json")); string cardText = await // // FileIO.ReadTextAsync(cardFile); // theModel.ModelUserActivity.VisualElements.Content // = AdaptiveCardBuilder.CreateAdaptiveCardFromJson(cardText); // theModel.ModelUserActivity.VisualElements.DisplayText = headerText; _ModelUserActivity.VisualElements.DisplayText = area; _ModelUserActivity.VisualElements.Description = bodyText; _ModelUserActivity.ActivationUri = new Uri("gramps://" + area + @"/handle/" + theModel.HLinkKey); //Save await _ModelUserActivity.SaveAsync(); //save the new metadata if (_ModelUserActivity != null) { activitySession = _ModelUserActivity.CreateSession(); } } return(activitySession); }).ConfigureAwait(false); return(returnedFromUIThread); }
public Task SendEmail(string subject, string body, IEnumerable <string> recipients) { return(MainThread.InvokeOnMainThreadAsync(async() => { var message = new EmailMessage { Subject = subject, Body = body, To = recipients.ToList() }; try { await Email.ComposeAsync(message).ConfigureAwait(false); } catch (FeatureNotSupportedException) { await DisplayAlert("No Email Client Found", "We'd love to hear your fedback!\[email protected]", "OK").ConfigureAwait(false); } })); }
public async Task Get_Location_Is_Something() { await MainThread.InvokeOnMainThreadAsync(async() => { await Permissions.RequestAsync <Permissions.LocationWhenInUse>(); }); var location = await Geolocation.GetLocationAsync(); Assert.NotNull(location); Assert.True(location.Accuracy > 0); Assert.NotEqual(0.0, location.Latitude); Assert.NotEqual(0.0, location.Longitude); Assert.NotEqual(DateTimeOffset.MaxValue, location.Timestamp); Assert.NotEqual(DateTimeOffset.MinValue, location.Timestamp); // before right now, but after yesterday Assert.True(location.Timestamp < DateTimeOffset.UtcNow); Assert.True(location.Timestamp > DateTimeOffset.UtcNow.Subtract(TimeSpan.FromDays(1))); }
/// <summary> /// 异步调用主线程。 /// </summary> /// <param name="action"></param> /// <param name="priority"></param> /// <returns></returns> public static Task InvokeOnMainThreadAsync(Action action, DispatcherPriority priority = DispatcherPriority.Normal) { if (Essentials.IsSupported) { return(MainThread.InvokeOnMainThreadAsync(action)); } else { if (IsMainThread) { action(); #if NETSTANDARD1_0 return(Task.FromResult(true)); #else return(Task.CompletedTask); #endif } var tcs = new TaskCompletionSource <bool>(); BeginInvokeOnMainThread(() => { try { action(); tcs.TrySetResult(true); } catch (Exception ex) { tcs.TrySetException(ex); } }, priority); return(tcs.Task); } }
Task StartGame() { var isPlayer1EntryTextEmpty = string.IsNullOrWhiteSpace(_player1Entry.Text); var isPlayer2EntryTextEmpty = string.IsNullOrWhiteSpace(_player2Entry.Text); if (isPlayer1EntryTextEmpty) { AnalyticsService.Track(AnalyticsConstants.StartGameButtonTapped, AnalyticsConstants.StartGameButtonTappedStatus, AnalyticsConstants.Player1NameEmpty); return(DisplayEmptyPlayerNameAlert(1)); } else if (isPlayer2EntryTextEmpty) { AnalyticsService.Track(AnalyticsConstants.StartGameButtonTapped, AnalyticsConstants.StartGameButtonTappedStatus, AnalyticsConstants.Player2NameEmpty); return(DisplayEmptyPlayerNameAlert(2)); } else { AnalyticsService.Track(AnalyticsConstants.StartGameButtonTapped, AnalyticsConstants.StartGameButtonTappedStatus, AnalyticsConstants.GameStarted); return(MainThread.InvokeOnMainThreadAsync(() => Navigation.PushAsync(new FaceOffPage()))); } Task DisplayEmptyPlayerNameAlert(int playerNumber) => MainThread.InvokeOnMainThreadAsync(() => DisplayAlert("Error", $"Player {playerNumber} Name is Blank", "OK")); }
Task PopPage() => MainThread.InvokeOnMainThreadAsync(Navigation.PopModalAsync);
public AddPhotoPage() { ViewModel.NoCameraFound += HandleNoCameraFound; ViewModel.SavePhotoFailed += HandleSavePhotoFailed; ViewModel.SavePhotoCompleted += HandleSavePhotoCompleted; this.Bind(TitleProperty, nameof(AddPhotoViewModel.PhotoTitle)); Title = PageTitles.AddPhotoPage; Padding = new Thickness(20); Content = new ScrollView { Content = new StackLayout { Spacing = 20, Children = { new CachedImage() .Bind(CachedImage.SourceProperty, nameof(AddPhotoViewModel.PhotoImageSource)), new Entry { ClearButtonVisibility = ClearButtonVisibility.WhileEditing,Placeholder = "Title", BackgroundColor = Color.White, TextColor = ColorConstants.TextColor }.FillExpand() .Bind(Entry.TextProperty, nameof(AddPhotoViewModel.PhotoTitle)), new AddPhotoPageButton("Take Photo") .Bind(Button.CommandProperty, nameof(AddPhotoViewModel.TakePhotoCommand)) .Bind <Button, bool, bool>(IsEnabledProperty, nameof(AddPhotoViewModel.IsPhotoSaving), convert: isPhotoSaving => !isPhotoSaving), new ActivityIndicator() .Bind(IsVisibleProperty, nameof(AddPhotoViewModel.IsPhotoSaving)) .Bind(ActivityIndicator.IsRunningProperty, nameof(AddPhotoViewModel.IsPhotoSaving)) } }.Top().FillExpandHorizontal().Assign(out StackLayout stackLayout) }; if (Device.RuntimePlatform is Device.iOS) { //Add title to UIModalPresentationStyle.FormSheet on iOS stackLayout.Children.Insert(0, new Label { Text = PageTitles.AddPhotoPage }.Font(24, true).Margins(0, 24, 5, 0)); stackLayout.Children.Add(new AddPhotoPageButton("Save") .Bind <Button, bool, bool>(IsVisibleProperty, nameof(AddPhotoViewModel.IsPhotoSaving), convert: isSaving => !isSaving) .Bind(Button.CommandProperty, nameof(AddPhotoViewModel.SavePhotoCommand))); } else { //Save Button can be added to the Navigation Bar ToolbarItems.Add(new ToolbarItem { Text = "Save", Priority = 0, AutomationId = AutomationIdConstants.AddPhotoPage_SaveButton, }.Bind(MenuItem.CommandProperty, nameof(AddPhotoViewModel.SavePhotoCommand))); //Cancel Button only needed for Android becuase iOS can swipe down to return to previous page ToolbarItems.Add(new ToolbarItem { Text = "Cancel", Priority = 1, AutomationId = AutomationIdConstants.CancelButton, Command = new AsyncCommand(ClosePage, _ => !ViewModel.IsPhotoSaving) }); } } void HandleSavePhotoCompleted(object sender, EventArgs e) { MainThread.BeginInvokeOnMainThread(async() => { await DisplayAlert("Photo Saved", string.Empty, "OK"); await ClosePage(); }); } async void HandleSavePhotoFailed(object sender, string errorMessage) => await DisplayErrorMessage(errorMessage); async void HandleNoCameraFound(object sender, EventArgs e) => await DisplayErrorMessage("No Camera Found"); Task ClosePage() => MainThread.InvokeOnMainThreadAsync(Navigation.PopModalAsync); Task DisplayErrorMessage(string message) => MainThread.InvokeOnMainThreadAsync(() => DisplayAlert("Error", message, "Ok"));
public Task <T> InvokeOnMainThreadAsync <T>(Func <Task <T> > func) => MainThread.InvokeOnMainThreadAsync(func);
public Task InvokeOnMainThreadAsync(Func <Task> func) => MainThread.InvokeOnMainThreadAsync(func);
public Task InvokeOnMainThreadAsync(Action action) => MainThread.InvokeOnMainThreadAsync(action);
public MainPage() { var visibleImage = new Image { Source = "song_entry_premium_symbol.png", HorizontalOptions = LayoutOptions.Start, HeightRequest = 50 }; var invisibleImage = new Image { Source = "song_entry_premium_symbol.png", HorizontalOptions = LayoutOptions.Start, IsVisible = false, HeightRequest = 50 }; var transparentImage = new Image { Source = "song_entry_premium_symbol.png", HorizontalOptions = LayoutOptions.Start, Opacity = 0, HeightRequest = 50 }; var offScreenImage = new Image { Source = "song_entry_premium_symbol.png", HorizontalOptions = LayoutOptions.Start, TranslationX = 1000, TranslationY = 1000, HeightRequest = 50 }; var visibleContainer = new StackLayout { Children = { new Image { Source = "song_entry_premium_symbol.png", HorizontalOptions = LayoutOptions.Start, HeightRequest = 50 } } }; var invisibleContainer = new StackLayout { Children = { new Image { Source = "song_entry_premium_symbol.png", HorizontalOptions = LayoutOptions.Start, HeightRequest = 50 } }, IsVisible = false }; var transparentContainer = new StackLayout { Children = { new Image { Source = "song_entry_premium_symbol.png", HorizontalOptions = LayoutOptions.Start, HeightRequest = 50 } }, Opacity = 0 }; var offScreenContainer = new StackLayout { Children = { new Image { Source = "song_entry_premium_symbol.png", HorizontalOptions = LayoutOptions.Start, HeightRequest = 50 } }, TranslationX = 1000, TranslationY = 1000 }; var contentWrapper = new StackLayout(); contentWrapper.Children.Add(visibleImage); contentWrapper.Children.Add(invisibleImage); contentWrapper.Children.Add(transparentImage); contentWrapper.Children.Add(offScreenImage); contentWrapper.Children.Add(visibleContainer); contentWrapper.Children.Add(invisibleContainer); contentWrapper.Children.Add(transparentContainer); contentWrapper.Children.Add(offScreenContainer); Task.Run(async() => { await Task.Delay(2000); await MainThread.InvokeOnMainThreadAsync(async() => { invisibleImage.IsVisible = true; await Task.WhenAll(transparentImage.FadeTo(1), offScreenImage.TranslateTo(0, 0)); invisibleContainer.IsVisible = true; await Task.WhenAll(transparentContainer.FadeTo(1), offScreenContainer.TranslateTo(0, 0)); //when forcing layout on parent layout, it works. But that is not an acceptable solution transparentContainer.ForceLayout(); }); }); Content = contentWrapper; }
protected override async Task <HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { if (request == null) { throw new ArgumentNullException(nameof(request)); } if (request.RequestUri.Segments?.Last() == "$ref") { return(new HttpResponseMessage(HttpStatusCode.OK)); } // ToDo: // Desired-Time-Zone Dictionary <string, string?> properties = new Dictionary <string, string?> { }; Guid xCorrelationID; if (!request.Headers.Any(h => h.Key == "Client-Type")) { #if DotNet request.Headers.Add("Client-Type", System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture == System.Runtime.InteropServices.Architecture.Wasm ? "Wasm" : "Xamarin"); #else request.Headers.Add("Client-Type", "Xamarin"); #endif request.Headers.Add("Client-Date-Time", DateTimeProvider.GetCurrentUtcDateTime().UtcDateTime.ToString("o", CultureInfo.InvariantCulture)); xCorrelationID = Guid.NewGuid(); request.Headers.Add("X-Correlation-ID", xCorrelationID.ToString()); request.Headers.Add("Bit-Client-Type", "CS-Client"); request.Headers.Add("Client-App-Version", AppInfo.VersionString); request.Headers.Add("Client-Culture", CultureInfo.CurrentUICulture.Name); request.Headers.Add("System-Language", CultureInfo.CurrentUICulture.ThreeLetterISOLanguageName); request.Headers.Add("Client-Sys-Language", CultureInfo.CurrentUICulture.ThreeLetterISOLanguageName); try { request.Headers.Add("Client-Route", DependencyDelegates.Current.GetNavigationUriPath?.Invoke()); } catch { } request.Headers.Add("Client-Platform", DeviceInfo.Platform.ToString()); request.Headers.Add("Current-Time-Zone", TimeZoneInfo.Local.Id); #if Android || iOS || UWP await MainThread.InvokeOnMainThreadAsync(() => { request.Headers.Add("Client-Theme", AppInfo.RequestedTheme.ToString()); if (DeviceInfo.Idiom != Xamarin.Essentials.DeviceIdiom.Unknown) { request.Headers.Add("Client-Screen-Size", DeviceInfo.Idiom == Xamarin.Essentials.DeviceIdiom.Phone ? "MobileAndPhablet" : "DesktopAndTablet"); } }).ConfigureAwait(false); #endif request.Headers.Add("Client-Debug-Mode", (ClientAppProfile.Environment == "Development").ToString(CultureInfo.InvariantCulture)); } else { xCorrelationID = Guid.Parse(request.Headers.ExtendedSingle("Finding X-Correlation-ID", h => h.Key == "X-Correlation-ID").Value.ExtendedSingle("Getting X-Correlation-ID value")); } DateTimeOffset startDate = DateTimeProvider.GetCurrentUtcDateTime(); HttpResponseMessage?response = null; try { response = await base.SendAsync(request, cancellationToken).ConfigureAwait(false); return(response); } #if Android catch (Java.Lang.Throwable exp) // https://github.com/xamarin/xamarin-android/issues/3216 { throw exp switch { Java.IO.IOException _ => new IOException(exp.Message, exp), _ => new Exception(exp.Message, exp), }; } #endif catch (HttpRequestException exp) { properties.Add("RequestException", exp.ToString()); throw; } finally { if (response != null) { if (response.Headers.TryGetValues("Reason-Phrase", out IEnumerable <string> reasonPhrases) && reasonPhrases.Any()) { response.ReasonPhrase = reasonPhrases.Single(); } } properties.Add("ReasonPhrase", response?.ReasonPhrase ?? "UnknownError"); properties.Add("X-Correlation-ID", xCorrelationID.ToString()); TimeSpan duration = DateTimeOffset.Now - startDate; TelemetryServices.All().TrackRequest(request.RequestUri.LocalPath, startDate, duration, response?.StatusCode.ToString() ?? "UnknownStatusCode", response?.IsSuccessStatusCode ?? false, request.RequestUri, request.Method.ToString(), properties); } }