Beispiel #1
0
        async void updateProgress(int percent, string status)
        {
            log.Info(status);

            Device.BeginInvokeOnMainThread(() =>
            {
                {
                    var newstatus = status;
                    if (percent >= 0)
                    {
                        newstatus += " " + percent + "%";
                    }

                    if (laststatus != newstatus)
                    {
                        laststatus = newstatus;
                        UserDialogs.Instance.Toast(newstatus, TimeSpan.FromSeconds(10));
                    }
                }

                if (Progress != null)
                {
                    Progress(percent, status);
                }
            });
        }
Beispiel #2
0
        bool ConfirmationHandler()
        {
            XamarinDevice.BeginInvokeOnMainThread(() =>
            {
                Current.MainPage.DisplayActionSheet("Crash detected. Send anonymous crash report?", null, null, "Send", "Always Send", "Don't Send").ContinueWith((arg) =>
                {
                    var answer = arg.Result;
                    UserConfirmation userConfirmationSelection;
                    if (answer == "Send")
                    {
                        userConfirmationSelection = UserConfirmation.Send;
                    }
                    else if (answer == "Always Send")
                    {
                        userConfirmationSelection = UserConfirmation.AlwaysSend;
                    }
                    else
                    {
                        userConfirmationSelection = UserConfirmation.DontSend;
                    }
                    AppCenterLog.Debug(LogTag, "User selected confirmation option: \"" + answer + "\"");
                    Crashes.NotifyUserConfirmation(userConfirmationSelection);
                });
            });

            return(true);
        }
 public void MessageReceived(string notificationBody, string title)
 {
     Device.BeginInvokeOnMainThread(() =>
     {
         App.Current.MainPage.DisplayAlert(title, notificationBody, "Ok");
     });
 }
Beispiel #4
0
        private async Task Handle_UnhandledException(Exception ex, string title, bool shutdown)
        {
            if (!(ex is null))
            {
                this.sdk.LogService.SaveExceptionDump(title, ex.ToString());
            }

            if (!(ex is null))
            {
                this.sdk.LogService?.LogException(ex, this.GetClassAndMethod(MethodBase.GetCurrentMethod(), title));
            }

            if (shutdown)
            {
                await this.Shutdown(true);
            }

#if DEBUG
            if (!shutdown)
            {
                if (Device.IsInvokeRequired && !(MainPage is null))
                {
                    Device.BeginInvokeOnMainThread(async() => await MainPage.DisplayAlert(title, ex?.ToString(), AppResources.Ok));
                }
                else if (!(MainPage is null))
                {
                    await MainPage.DisplayAlert(title, ex?.ToString(), AppResources.Ok);
                }
            }
#endif
        }
Beispiel #5
0
        private async Task <bool> TryHubConnectAsync()
        {
            bool success = true;

            try
            {
                await hubConnection.StartAsync();

                _ = hubConnection.On <string, string>("ReceiveMessage", (a, b) =>
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        //_ = RefreshMatchData(a, b);
                    });
                });
                _ = hubConnection.On <string, string>("ReceiveMatchDetails", (action, matchDetailsJson) =>
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        var matchDetails = JsonConvert.DeserializeObject <MatchDetails>(matchDetailsJson);
                        RefreshMatchData(action, matchDetails);
                    });
                });
            }
            catch (Exception ex)
            {
                success = false;
                Console.WriteLine($"Error: {ex.Message}");
                await Task.Delay(1000);
            }
            return(success);
        }
Beispiel #6
0
        /// <summary>
        /// Create new QR Code object
        /// </summary>
        private void AddNewRecord(string qrCodeId)
        {
            Device.BeginInvokeOnMainThread(async() =>
            {
                var r = await UserDialogs.Instance.PromptAsync(AppResources.qrcode_name, inputType: InputType.Name);
                await Task.Delay(500);

                if (!r.Ok)
                {
                    return;
                }
                var name = r.Text;
                if (string.IsNullOrEmpty(name))
                {
                    return;
                }
                App.ShowToast(AppResources.qrcode_saved + " " + name);
                var qrCode = new QRCodeModel()
                {
                    Id      = qrCodeId,
                    Name    = name,
                    Enabled = true,
                };
                _oListSource.Add(qrCode);
                SaveAndRefresh();
            });
        }
 private void ShowLoginModal()
 {
     Device.BeginInvokeOnMainThread(async() =>
     {
         var page = FreshPageModelResolver.ResolvePageModel <LoginViewModel>();
         await _masterDetailNav.PushPage(page, null, true);
     });
 }
 private void _inputView_Unfocused(object sender, FocusEventArgs e)
 {
     caretptr = IntPtr.Zero;
     Device.BeginInvokeOnMainThread(() =>
     {
         _inputView.IsVisible = false;
     });
 }
Beispiel #9
0
 // TODO: implement notification logic here
 private void OnMessageReceived(object sender, string msg)
 {
     Device.BeginInvokeOnMainThread(() =>
     {
         var alertService = DependencyService.Get <IAlertService>();
         alertService.ShowYesNoAlert("Notification received", "Ok", "Cancel");
     });
 }
            private void _inputView_Completed(object sender, EventArgs e)
            {
                var focusctl = Control.FromHandle(_focusWindow);

                focusctl.Text = (sender as Entry)?.Text;
                Device.BeginInvokeOnMainThread(() =>
                {
                    _inputView.IsVisible = false;
                });
            }
Beispiel #11
0
        public async Task <bool> RefreshPageData()
        {
            bool connected = await _viewModel.GetPageData();

            Device.BeginInvokeOnMainThread(() =>
            {
                PopulatePageView(true);
            });
            _viewModel.IsLoading = false;
            return(connected);
        }
Beispiel #12
0
 private void SetupGeolocator()
 {
     Device.BeginInvokeOnMainThread(async() =>
     {
         if (await CoordinateHelper.HasGeolocationAccess())
         {
             await CrossGeolocator.Current.StartListeningAsync(50, 100);
             CrossGeolocator.Current.PositionChanged += CurrentOnPositionChanged;
         }
     });
 }
Beispiel #13
0
        public async void PushOperationAsync(Operation operation, bool isAlarm = true)
        {
            await DependencyService.Get <IDataStore <Operation> >().AddItemAsync(operation);

            MessagingCenter.Send(this, Constants.MessageNewOperation);

            Device.BeginInvokeOnMainThread(async() =>
            {
                MainPage = new NavigationPage(new OperationsPage());
                await MainPage.Navigation.PushAsync(new OperationTabPage(operation, isAlarm));
            });
        }
Beispiel #14
0
 static void PrintNotification(object sender, PushNotificationReceivedEventArgs e)
 {
     XamarinDevice.BeginInvokeOnMainThread(() =>
     {
         var message = e.Message;
         if (e.CustomData != null)
         {
             message += "\nCustom data = {" + string.Join(",", e.CustomData.Select(kv => kv.Key + "=" + kv.Value)) + "}";
         }
         Current.MainPage.DisplayAlert(e.Title, message, "OK");
     });
 }
Beispiel #15
0
        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        protected MainViewModel(INavigationService navigationService)
        {
            _navigationService = navigationService;

            //current location updates
            GeolocationManager.instance.LocationUpdatesEvent += OnLocationUpdates;

            //Event handlers when app starts, sleeps, or resumes
            ((App)Application.Current).AppStart  += OnForegroundWork;
            ((App)Application.Current).AppSleep  += OnBackgroundWork;
            ((App)Application.Current).AppResume += OnForegroundWork;

            Messenger.Default.Register <string>(this, PublishedData.MemberLocationNotification, async(memberId) =>
            {
                Location location = await ServerCommunicator.Instance.GetLocationAsync(memberId);
                Device.BeginInvokeOnMainThread(() =>
                {
                    if (Members == null)
                    {
                        Members = new Dictionary <string, Location>();
                    }

                    if (Members.Keys.Contains(memberId))
                    {
                        Members[memberId] = location;
                    }
                    else
                    {
                        Members.Add(memberId, location);
                    }

                    RaisePropertyChanged("Members");
                });
            });

            Messenger.Default.Register <string>(this, PublishedData.GroupIdNotification, async(leaderId) =>
            {
                if (leaderId != null)
                {
                    var location = await ServerCommunicator.Instance.GetLocationAsync(leaderId);
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        LeaderLocation = location;
                    });
                }
                if (!_hasSent)
                {
                    await ServerCommunicator.Instance.SendLocationAsync(MyLocation);
                    _hasSent = true;
                }
            });
        }
        public static async Task <Plugin.Permissions.Abstractions.PermissionStatus> CheckLocationServices()
        {
            try
            {
                Plugin.Permissions.Abstractions.PermissionStatus status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);

                Plugin.Permissions.Abstractions.PermissionStatus status2 = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.LocationWhenInUse);

                Plugin.Permissions.Abstractions.PermissionStatus status3 = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.LocationAlways);

                Console.WriteLine("Location Permissions: Location: " + status.ToString() + ", When In Use: " + status2.ToString() + ", Always: " + status3.ToString());
                if (status3 != Plugin.Permissions.Abstractions.PermissionStatus.Granted)
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        if (Device.RuntimePlatform == Device.iOS)
                        {
                            ILocationManager manager = DependencyService.Get <ILocationManager>();
                            manager.RequestBackgroundLocation();
                        }
                    });
                }
                else
                {
                    try
                    {
                        var request  = new GeolocationRequest(GeolocationAccuracy.Lowest, new TimeSpan(0, 0, 0, 0, 100));
                        var location = await Geolocation.GetLocationAsync(request);

                        if (location != null)
                        {
                            Console.WriteLine($"Latitude: {location.Latitude}, Longitude: {location.Longitude}, Altitude: {location.Altitude}");
                        }
                    }
                    catch (FeatureNotSupportedException)
                    {
                        return(Plugin.Permissions.Abstractions.PermissionStatus.Denied);
                    }
                    catch (FeatureNotEnabledException)
                    {
                        return(Plugin.Permissions.Abstractions.PermissionStatus.Denied);
                    }
                }
                return(status3);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
                return(Plugin.Permissions.Abstractions.PermissionStatus.Denied);
            }
        }
Beispiel #17
0
 private async void OnLocationUpdates(object sender, Location location)
 {
     //Hover on customized "CompareTo" to see how two locations compared.
     if ((MyLocation == null) || (MyLocation.CompareTo(location) != 0))
     {
         Device.BeginInvokeOnMainThread(() =>
         {
             MyLocation = location;
         });
         if (ServerCommunicator.Instance.GroupID != null)
         {
             //TODO: why SendLocationAsync(MyLocation) throwing exception
             await ServerCommunicator.Instance.SendLocationAsync(location);
         }
     }
 }
Beispiel #18
0
        private void RefreshMatchData(string action, MatchDetails matchDetails)
        {
            try
            {
                Match match = matchDetails?.Match;
                if (match != null)
                {
                    Match findMatch = _viewModel.AllMatches?.FirstOrDefault(x => x.MatchID == match.MatchID);
                    if (findMatch != null)
                    {
                        int findMatchIndex = _viewModel.AllMatches.IndexOf(findMatch);
                        _viewModel.AllMatches?.Insert(findMatchIndex, match);
                        _viewModel.AllMatches?.Remove(findMatch);
                    }
                    else
                    {
                        _viewModel.AllMatches?.Add(match);
                    }

                    //if (match.StatusID != findMatch?.StatusID)
                    //{
                    //    await _viewModel.GetStandingsAsync();
                    //}
                    bool isSelectedMatch = _viewModel.SelectedLiveMatch.MatchID == match.MatchID;
                    if (isSelectedMatch)
                    {
                        Match selectedMatch = matchDetails.Match;
                        selectedMatch.PlayersOfMatch          = new ObservableCollection <PlayerOfMatch>(matchDetails.PlayersOfMatch);
                        selectedMatch.EventsOfMatch           = new ObservableCollection <EventOfMatch>(matchDetails.EventsOfMatch);
                        _viewModel.SelectedLiveMatch          = selectedMatch;
                        _viewModel.SelectedLiveMatch.LiveTime = selectedMatch.LiveTime;
                        _viewModel.TimeCounter.MatchesTime(_viewModel, new ObservableCollection <Match>());
                        _viewModel.SetMatchAdditionalDetails();
                        _viewModel.SelectedLiveMatch.IsLoadingSelectedMatch = false;
                    }

                    Device.BeginInvokeOnMainThread(() =>
                    {
                        PopulatePageView(false);
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
        private void StartThreads()
        {
            size = Device.Info.ScaledScreenSize;
            size = Device.Info.PixelScreenSize;

            size  = new Forms.Size(900, 540); // 1.66 - remove back and home pane
            scale = new Forms.Size((Device.Info.PixelScreenSize.Width / size.Width),
                                   (Device.Info.PixelScreenSize.Height / size.Height));

            XplatUIMine.GetInstance()._virtualScreen = new Rectangle(0, 0, (int)size.Width, (int)size.Height);
            XplatUIMine.GetInstance()._workingArea   = new Rectangle(0, 0, (int)size.Width, (int)size.Height);

            winforms = new Thread(() =>
            {
                AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

                Application.Idle += (sender, args) => Thread.Sleep(0);

                MissionPlanner.Program.Main(new string[0]);
            });
            winforms.Start();

            Forms.Device.StartTimer(TimeSpan.FromMilliseconds(1000 / 30), () =>
            {
                Monitor.Enter(XplatUIMine.paintlock);
                if (XplatUIMine.PaintPending)
                {
                    if (SkCanvasView != null)
                    {
                        scale = new Forms.Size((Instance.SkCanvasView.CanvasSize.Width / size.Width),
                                               (Instance.SkCanvasView.CanvasSize.Height / size.Height));

                        XplatUIMine.GetInstance()._virtualScreen =
                            new Rectangle(0, 0, (int)size.Width, (int)size.Height);
                        XplatUIMine.GetInstance()._workingArea =
                            new Rectangle(0, 0, (int)size.Width, (int)size.Height);

                        Device.BeginInvokeOnMainThread(() => { Instance.SkCanvasView.InvalidateSurface(); });
                        XplatUIMine.PaintPending = false;
                    }
                }
                Monitor.Exit(XplatUIMine.paintlock);

                return(true);
            });
        }
Beispiel #20
0
        public Task <bool> ShowMessageBoxAsync(string message, string caption)
        {
            var tcs = new TaskCompletionSource <bool>();

            Device.BeginInvokeOnMainThread(async() =>
            {
                try
                {
                    var result = await MainPage.DisplayAlert(message, caption, "OK", "Cancel");
                    tcs.TrySetResult(result);
                }
                catch (Exception ex)
                {
                    tcs.TrySetException(ex);
                }
            });
            return(tcs.Task);
        }
Beispiel #21
0
        private async void OnForegroundWork()
        {
            await ServerCommunicator.Instance.SendMemberInfo();

            #region Location Permissions
            try
            {
                var status = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Location);

                if (status != PermissionStatus.Granted)
                {
                    //if (await CrossPermissions.Current.ShouldShowRequestPermissionRationaleAsync(Permission.Location))
                    //{
                    //    await DisplayAlert("Need location", "Gunna need that location", "OK");
                    //}

                    var results = await CrossPermissions.Current.RequestPermissionsAsync(Permission.Location);

                    //Best practice to always check that the key exists
                    if (results.ContainsKey(Permission.Location))
                    {
                        status = results[Permission.Location];
                    }
                }
                if (status == PermissionStatus.Granted)
                {
                    await GeolocationManager.instance.StartUpdatingLocationAsync();

                    Device.BeginInvokeOnMainThread(() =>
                    {
                        IsShowingLocation = true;
                    });
                }
                else if (status != PermissionStatus.Unknown)
                {
                    //await DisplayAlert("Location Denied", "Can not continue, try again.", "OK");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex);
            }
            #endregion
        }
Beispiel #22
0
        /// <summary>
        /// Resumes the last session, makes an initial sync and opens the login page if needed.
        /// </summary>
        /// <returns></returns>
        private async Task GenerelSetup()
        {
            Device.BeginInvokeOnMainThread(() => UserDialogs.Instance.ShowLoading());
            await Task.Delay(500);

            var storage = FreshIOC.Container.Resolve <IStorageService>();
            await storage.OpenStorage();

            //Make an inital token refresh

            if (!storage.IsLogIn)
            {
                Task.Run(async() => await FreshIOC.Container.Resolve <IDataService>().RequestPartyWithFilter());
                ShowLoginModal();
            }
            else
            {
                await FreshIOC.Container.Resolve <IDataService>().BatchRefresh();
            }

            Device.BeginInvokeOnMainThread(() => UserDialogs.Instance.HideLoading());
        }
Beispiel #23
0
        private async void OnImport()
        {
            try
            {
                var stream = await _pickAsync();

                StreamReader reader   = new StreamReader(stream);
                string       contents = reader.ReadToEnd();
                var          gas      = GetGa(contents).ToList();
                _settings.ImportGroupAddress = gas;
                OnPropertyChanged(nameof(GaCount));
                OnPropertyChanged(nameof(ImportGroupAddress));
            }
            catch (Exception ex)
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                {
                    _manager.SendNotification("Error:", "Could not import GA (" + ex.Message + ")");
                });
            }
        }
Beispiel #24
0
        private async Task RefreshMatchData(string action, string message)
        {
            try
            {
                string[] textArray = message.Split(';');
                string   matchID   = textArray[0];
                Match    match     = await _viewModel.GetMatchByIDAsync(matchID);

                if (match != null)
                {
                    Match findMatch = _viewModel.AllMatches?.FirstOrDefault(x => x.MatchID == match?.MatchID);
                    if (findMatch != null)
                    {
                        int findMatchIndex = _viewModel.AllMatches.IndexOf(findMatch);
                        _viewModel.AllMatches?.Insert(findMatchIndex, match);
                        _viewModel.AllMatches?.Remove(findMatch);
                    }
                    else
                    {
                        _viewModel.AllMatches?.Add(match);
                    }

                    if (match.StatusID != findMatch?.StatusID)
                    {
                        await _viewModel.GetStandingsAsync();
                    }
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        PopulatePageView(_viewModel.SelectedLiveMatch.MatchID == match?.MatchID);
                    });
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
            public void SetCaretPos(CaretStruct caret, IntPtr handle, int x, int y)
            {
                if (_focusWindow == handle && caret.Hwnd == _focusWindow)
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        if (caretptr == handle)
                        {
                            return;
                        }

                        var focusctl = Control.FromHandle(_focusWindow);
                        var p        = focusctl.PointToClient(Form.MousePosition);

                        if (focusctl.ClientRectangle.Contains(p))
                        {
                            // unbind
                            _inputView.Unfocused   -= _inputView_Unfocused;
                            _inputView.TextChanged -= View_TextChanged;
                            _inputView.Completed   -= _inputView_Completed;
                            // set

                            _inputView.Text = focusctl.Text;
                            // rebind
                            _inputView.Completed   += _inputView_Completed;
                            _inputView.TextChanged += View_TextChanged;
                            _inputView.Unfocused   += _inputView_Unfocused;
                            //show
                            _inputView.IsVisible = true;
                            _inputView.Focus();

                            caretptr = handle;
                        }
                    });
                }
            }
Beispiel #26
0
        protected override void OnStart()
        {
            // Handle when your app starts
            //AppCenter.Start("android=a97b2a41-0589-47b1-92dd-571d0400c65e;" +
            //      "uwp={Your UWP App secret here};" +
            //      "ios={Your iOS App secret here}",
            //      typeof(Analytics), typeof(Crashes),typeof(Distribute));

            if (Device.RuntimePlatform == Device.Android || Device.RuntimePlatform == Device.iOS)
            {
                CrossFirebasePushNotification.Current.RegisterForPushNotifications();

                CrossFirebasePushNotification.Current.Subscribe("general");
                CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
                {
                    System.Diagnostics.Debug.WriteLine($"TOKEN REC: {p.Token}");
                    Application.Current.Properties["AppFirebaseToken"] = p.Token;
                    Application.Current.SavePropertiesAsync();

                    if (userData != null)
                    {
                        //UpdateDeviceInfo();
                    }
                };
                System.Diagnostics.Debug.WriteLine($"TOKEN: {CrossFirebasePushNotification.Current.Token}");

                CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
                {
                    try
                    {
                        IsNotificationRecieved = true;
                        //MessagingCenter.Send("5", "NotificationRecieved");
                        System.Diagnostics.Debug.WriteLine("Received");
                        if (p.Data.ContainsKey("body"))
                        {
                            IsNotificationRecieved = true;
                            Device.BeginInvokeOnMainThread(() =>
                            {
                                var data = $"{p.Data["body"]}";
                                if (data.StartsWith("You have a new message"))
                                {
                                }
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                };

                CrossFirebasePushNotification.Current.OnNotificationOpened += async(s, p) =>
                {
                    //System.Diagnostics.Debug.WriteLine(p.Identifier);

                    try
                    {
                        if (Device.RuntimePlatform == Device.iOS)
                        {
                            if (p.Data.ContainsKey("aps.alert"))
                            {
                                Device.BeginInvokeOnMainThread(() =>
                                {
                                    var data = $"{p.Data["aps.alert"]}";
                                    if (data.StartsWith("You have a new message"))
                                    {
                                        App.Current.MainPage = new NavigationPage(new HomeTabPage());
                                        App.Current.MainPage.Navigation.PushAsync(new ChatListPage());
                                    }
                                    else
                                    {
                                        App.Current.MainPage = new NavigationPage(new HomeTabPage());
                                        MessagingCenter.Send("Notification_Tab", "HomeTabBar");
                                    }
                                });
                            }
                        }
                        else if (Device.RuntimePlatform == Device.Android)
                        {
                            if (p.Data.ContainsKey("body"))
                            {
                                Device.BeginInvokeOnMainThread(() =>
                                {
                                    var data = $"{p.Data["body"]}";

                                    if (data.StartsWith("You have a new message"))
                                    {
                                        App.Current.MainPage = new NavigationPage(new HomeTabPage());
                                        App.Current.MainPage.Navigation.PushAsync(new ChatListPage());
                                    }
                                    else
                                    {
                                        App.Current.MainPage = new NavigationPage(new HomeTabPage());
                                        MessagingCenter.Send("Notification_Tab", "HomeTabBar");
                                    }
                                });
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        // Some other exception occurred
                    }
                    //System.Diagnostics.Debug.WriteLine("Opened");
                    //foreach (var data in p.Data)
                    //{
                    //    System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                    //}

                    //if (!string.IsNullOrEmpty(p.Identifier))
                    //{
                    //    Device.BeginInvokeOnMainThread(() =>
                    //    {
                    //        var data = p.Identifier;
                    //    });
                    //}
                    //else if (p.Data.ContainsKey("color"))
                    //{
                    //    Device.BeginInvokeOnMainThread(() =>
                    //    {
                    //        //mPage.Navigation.PushAsync(new ContentPage()
                    //        //{
                    //        //    BackgroundColor = Color.FromHex($"{p.Data["color"]}")

                    //        //});
                    //    });

                    //}
                    //else if (p.Data.ContainsKey("aps.alert.title"))
                    //{
                    //    Device.BeginInvokeOnMainThread(() =>
                    //    {
                    //        var data = $"{p.Data["aps.alert.title"]}";
                    //    });

                    //}
                };

                CrossFirebasePushNotification.Current.OnNotificationAction += (s, p) =>
                {
                    System.Diagnostics.Debug.WriteLine("Action");

                    if (!string.IsNullOrEmpty(p.Identifier))
                    {
                        System.Diagnostics.Debug.WriteLine($"ActionId: {p.Identifier}");
                        foreach (var data in p.Data)
                        {
                            System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                        }
                    }
                };

                CrossFirebasePushNotification.Current.OnNotificationDeleted += (s, p) =>
                {
                    System.Diagnostics.Debug.WriteLine("Dismissed");
                };
            }
        }
Beispiel #27
0
        public async void InsertForeignData(int user_id, int box_id)
        {
            try
            {
                var apiSecurity = Application.Current.Resources["APISecurity"].ToString();
                AddViewToUser(user_id);
                var ForeingUser = await apiService.GetUserId(apiSecurity,
                                                             "/api",
                                                             "/Users",
                                                             user_id);

                using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                {
                    connSQLite.CreateTable <ForeingProfile>();
                }

                ForeingBox foreingBox;
                ForeingBox A          = new ForeingBox();
                ForeingBox oldForeing = new ForeingBox();

                //Validar que la box no exista
                using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                {
                    A = connSQLite.FindWithQuery <ForeingBox>("select * from ForeingBox where ForeingBox.BoxId = " + box_id + " and ForeingBox.UserRecivedId = " + MainViewModel.GetInstance().User.UserId);
                }

                if (A == null)
                {
                    //Inicializar la box foranea
                    foreingBox = new ForeingBox
                    {
                        BoxId         = box_id,
                        UserId        = user_id,
                        Time          = DateTime.Now,
                        ImagePath     = ForeingUser.ImagePath,
                        UserTypeId    = ForeingUser.UserTypeId,
                        FirstName     = ForeingUser.FirstName,
                        LastName      = ForeingUser.LastName,
                        Edad          = ForeingUser.Edad,
                        Ubicacion     = ForeingUser.Ubicacion,
                        Ocupacion     = ForeingUser.Ocupacion,
                        Conexiones    = ForeingUser.Conexiones,
                        UserRecivedId = MainViewModel.GetInstance().User.UserId
                    };

                    //Insertar la box foranea
                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                    {
                        connSQLite.CreateTable <ForeingBox>();
                        connSQLite.Insert(foreingBox);
                    }
                }
                else
                {
                    using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                    {
                        oldForeing = A;
                        connSQLite.ExecuteScalar <ForeingBox>("UPDATE ForeingBox SET Conexiones = ? WHERE ForeingBox.UserId = ?", ForeingUser.Conexiones, ForeingUser.UserId);
                        connSQLite.ExecuteScalar <ForeingBox>("UPDATE ForeingBox SET Time = ? WHERE ForeingBox.BoxId = ?", DateTime.Now, A.BoxId);
                        A = connSQLite.FindWithQuery <ForeingBox>("select * from ForeingBox where ForeingBox.BoxId = ?", box_id);
                    }
                    foreingBox = A;
                }

                if (box_id != 0)
                {
                    if (A != null)
                    {
                        using (var connSQLite = new SQLite.SQLiteConnection(App.root_db))
                        {
                            connSQLite.Execute("Delete from ForeingProfile Where ForeingProfile.BoxId = ?", A.BoxId);
                        }
                    }

                    #region Foreing Profiles New Code
                    await GetListEmail(user_id, box_id);
                    await GetListPhone(user_id, box_id);
                    await GetListSM(user_id, box_id);
                    await GetListWhatsapp(user_id, box_id);

                    #endregion

                    if (NotNull1 == true && NotNull2 == true && NotNull3 == true && NotNull4 == true)
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            MainViewModel.GetInstance().ForeingBox = new ForeingBoxViewModel(foreingBox);
                            if (PopupNavigation.PopupStack.Count != 0)
                            {
                                PopupNavigation.Instance.PopAllAsync();
                            }

                            if (A == null)
                            {
                                MainViewModel.GetInstance().ListForeignBox.AddList(foreingBox);
                            }
                            else
                            {
                                //Box anterior
                                //oldForeing
                                MainViewModel.GetInstance().ListForeignBox.UpdateList(foreingBox.UserId);
                            }
                            PopupNavigation.Instance.PushAsync(new ForeingBoxPage(foreingBox, true));
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
        }
Beispiel #28
0
        protected override void OnStart()
        {
            Registrations.Start("XamarinJKH");

            int theme = Preferences.Get("Theme", 0);

            //только темная тема в ios
            //if (Xamarin.Essentials.DeviceInfo.Platform == DevicePlatform.iOS)
            //    theme = Preferences.Get("Theme", 1);

            switch (theme)
            {
            case 0:
                switch (Settings.MobileSettings.appTheme)
                {
                case "": Current.UserAppTheme = OSAppTheme.Unspecified;  break;

                case "light": Current.UserAppTheme = OSAppTheme.Light; break;

                case "dark": Current.UserAppTheme = OSAppTheme.Dark; break;
                }
                break;

                break;

            case 1:
                Current.UserAppTheme = OSAppTheme.Dark;
                break;

            case 2:
                Current.UserAppTheme = OSAppTheme.Light;
                break;
            }



            AppCenter.Start("android=4384b8c4-8639-411c-b011-9d9e8408acde;ios=4a45a15f-a591-4860-b748-a856636cf982;", typeof(Analytics), typeof(Crashes));
            //AppCenter.Start("39dce15b-0d85-46a2-bf90-a28af9fb8795", typeof(Analytics), typeof(Crashes)); //тихая гавань иос
            AppCenter.LogLevel = LogLevel.Verbose;



            // Handle when your app starts
            CrossFirebasePushNotification.Current.Subscribe("general");
            CrossFirebasePushNotification.Current.OnTokenRefresh += (s, p) =>
            {
                System.Diagnostics.Debug.WriteLine($"TOKEN REC: {p.Token}");
            };
            System.Diagnostics.Debug.WriteLine($"TOKEN: {CrossFirebasePushNotification.Current.Token}");

            CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
            {
                try
                {
                    System.Diagnostics.Debug.WriteLine("Received");
                    if (p.Data.ContainsKey("body"))
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            System.Diagnostics.Debug.WriteLine($"{p.Data["body"]}");
                        });
                    }

                    if (p.Data.ContainsKey("aps.alert.body"))
                    {
                        Device.BeginInvokeOnMainThread(() =>
                        {
                            System.Diagnostics.Debug.WriteLine($"{p.Data["aps.alert.body"]}");
                        });
                    }
                }
                catch (Exception ex)
                {
                }
            };

            CrossFirebasePushNotification.Current.OnNotificationOpened += (s, rea) =>
            {
                //System.Diagnostics.Debug.WriteLine(p.Identifier);

                System.Diagnostics.Debug.WriteLine("Opened");
                foreach (var data in rea.Data)
                {
                    System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                }

                if (!string.IsNullOrEmpty(rea.Identifier))
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        // MainPage.Message = p.Identifier;
                        System.Diagnostics.Debug.WriteLine("123");
                    });
                }
                else if (rea.Data.ContainsKey("color"))
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        MainPage.Navigation.PushAsync(new ContentPage()
                        {
                            BackgroundColor = Color.FromHex($"{rea.Data["color"]}")
                        });
                    });
                }
                else if (rea.Data.ContainsKey("aps.alert.title"))
                {
                    Device.BeginInvokeOnMainThread(() =>
                    {
                        // MainPage.Message = $"{p.Data["aps.alert.title"]}";
                        System.Diagnostics.Debug.WriteLine($"Пушшшш2 ==== {rea.Data["aps.alert.title"]}");
                    });
                }
            };

            CrossFirebasePushNotification.Current.OnNotificationAction += (s, p) =>
            {
                System.Diagnostics.Debug.WriteLine("Action");

                if (!string.IsNullOrEmpty(p.Identifier))
                {
                    System.Diagnostics.Debug.WriteLine($"ActionId: {p.Identifier}");
                    foreach (var data in p.Data)
                    {
                        System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                    }
                }
            };

            CrossFirebasePushNotification.Current.OnNotificationDeleted += (s, p) =>
            {
                System.Diagnostics.Debug.WriteLine("Dismissed");
            };
        }
Beispiel #29
0
        public App()
        {
            InitializeComponent();
            Syncfusion.Licensing.SyncfusionLicenseProvider.RegisterLicense("MzU2OTY1QDMxMzgyZTMzMmUzMEtpcFNHRnBKOUppMFJ1RUxjWTlsbUt6QzFOY3JyMUlGVi9McDJSSmQxVW89");
            PdfViewerResourceManager.Manager = new ResourceManager("xamarinJKH.Resources.Syncfusion.SfPdfViewer.XForms", GetType().GetTypeInfo().Assembly);
            CrossBadge.Current.ClearBadge();
            Crashes.SendingErrorReport      += SendingErrorReportHandler;
            Crashes.SentErrorReport         += SentErrorReportHandler;
            Crashes.FailedToSendErrorReport += FailedToSendErrorReportHandler;
            Crashes.GetErrorAttachments     += GetErrorAttachmentHandler;
            //только темная тема в ios
            //if (Device.RuntimePlatform == Device.iOS && Application.Current.UserAppTheme == OSAppTheme.Unspecified)
            //    Application.Current.UserAppTheme = OSAppTheme.Light;

            var task = Task.Run(async() => await getSettingsAsync());

            task.Wait();

            // var f = getSettingsAsync();

            if (/*Device.RuntimePlatform == Device.iOS &&*/ Application.Current.UserAppTheme == OSAppTheme.Unspecified)
            {
                switch (Settings.MobileSettings.appTheme)
                {
                case "": Application.Current.UserAppTheme = OSAppTheme.Light; break;

                case "light": Application.Current.UserAppTheme = OSAppTheme.Light; break;

                case "dark": Application.Current.UserAppTheme = OSAppTheme.Dark; break;
                }
            }


            DependencyService.Register <RestClientMP>();
            switch (Device.RuntimePlatform)
            {
            case Device.iOS:

                Color color = Color.White;

                int theme = Preferences.Get("Theme", 0);

                switch (theme)
                {
                case 1: color = Color.White; break;

                case 2: color = Color.Black; break;

                case 0:
                    switch (Settings.MobileSettings.appTheme)
                    {
                    case "": color = Color.Black; break;

                    case "light": color = Color.Black; break;

                    case "dark": color = Color.White; break;
                    }
                    break;
                }

                //if (theme!=1)
                //    color = Color.Black;
                //else
                //    color = Color.White;

                //var color = Application.Current.UserAppTheme == OSAppTheme.Light /*|| Application.Current.UserAppTheme == OSAppTheme.Unspecified*/ ? Color.Black : Color.White;

                var c2 = Settings.MobileSettings.appTheme == "light" ? Color.Black : Color.White;

                var nav = new Xamarin.Forms.NavigationPage(new MainPage())
                {
                    BarBackgroundColor = c2,
                    BarTextColor       = color
                };

                nav.On <iOS>().SetIsNavigationBarTranslucent(true);
                nav.On <iOS>().SetStatusBarTextColorMode(StatusBarTextColorMode.MatchNavigationBarTextLuminosity);

                MainPage = nav;
                break;

            case Device.Android:
                MainPage = new MainPage();
                break;

            default:
                break;
            }

            CrossFirebasePushNotification.Current.Subscribe("general");
            CrossFirebasePushNotification.Current.OnTokenRefresh += async(s, p) =>
            {
                System.Diagnostics.Debug.WriteLine($"TOKEN : {p.Token}");
                token = p.Token;
                await server.RegisterDevice(isCons);
            };


            CrossFirebasePushNotification.Current.OnNotificationReceived += (s, p) =>
            {
                System.Diagnostics.Debug.WriteLine("Received");
                //CrossBadge.Current.ClearBadge();
                if (Device.RuntimePlatform == Device.iOS)
                {
                    if (DependencyService.Get <IAppState>().IsAppBackbround())
                    {
                        badgeCount++;
                        CrossBadge.Current.SetBadge(badgeCount);
                    }
                }
                else
                {
                    CrossBadge.Current.ClearBadge();
                }

                Device.BeginInvokeOnMainThread(async() =>
                {
                    if (isCons)
                    {
                        MessagingCenter.Send <Object>(this, "UpdateAppCons");
                    }
                    else
                    {
                        MessagingCenter.Send <Object>(this, "AutoUpdate");
                    }

                    try
                    {
                        bool displayAlert = false;
                        string o          = string.Empty;

                        // if (p.Data.ContainsKey("title") && p.Data.ContainsKey("body"))
                        // {
                        //     var current_page =
                        //         (App.Current.MainPage.Navigation.ModalStack.ToList()[0] as Xamarin.Forms.TabbedPage)
                        //         .CurrentPage;
                        //     if (!(current_page is AppPage))
                        //     {
                        //         displayAlert = await MainPage.DisplayAlert(p.Data["title"].ToString(),
                        //             p.Data["body"].ToString(), "OK", "Отмена");
                        //         if (p.Data.ContainsKey("type_push"))
                        //             o = p.Data["type_push"].ToString();
                        //     }
                        // }

                        //ios
                        // if (p.Data.ContainsKey("aps.alert.title") && p.Data.ContainsKey("aps.alert.body"))
                        // {
                        //     var current_page =
                        //         (App.Current.MainPage.Navigation.ModalStack.ToList()[0] as Xamarin.Forms.TabbedPage)
                        //         .CurrentPage;
                        //     if (!(current_page is AppPage))
                        //     {
                        //         displayAlert = await MainPage.DisplayAlert(p.Data["aps.alert.title"].ToString(),
                        //             p.Data["aps.alert.body"].ToString(), "OK", "Отмена");
                        //         if (p.Data.ContainsKey("gcm.notification.type_push"))
                        //             o = p.Data["gcm.notification.type_push"].ToString();
                        //     }
                        // }

                        if (o.ToLower().Equals("осс"))
                        {
                            await MainPage.Navigation.PushModalAsync(new OSSMain());
                        }

                        if (o.ToLower().Equals("comment"))
                        {
                            if (isCons)
                            {
                                await Task.Delay(500);
                                MessagingCenter.Send <Object>(this, "RefreshApp");
                            }
                            else
                            {
                                MessagingCenter.Send <Object>(this, "AutoUpdateComments");
                            }
                        }

                        if (o.ToLower().Equals("comment"))
                        {
                            var tabbedpage = App.Current.MainPage.Navigation.ModalStack.ToList()[0];
                            if (tabbedpage is xamarinJKH.Main.BottomNavigationPage)
                            {
                                var stack = (tabbedpage as Xamarin.Forms.TabbedPage).Children[3].Navigation
                                            .NavigationStack;
                                if (stack.Count == 2)
                                {
                                    var app_page = stack.ToList()[0];
                                }
                                else
                                {
                                    if (!isCons)
                                    {
                                        MessagingCenter.Send <Object, int>(this, "SwitchToApps",
                                                                           int.Parse(p.Data["id_request"].ToString()));
                                    }
                                    else
                                    {
                                        MessagingCenter.Send <Object, int>(this, "SwitchToAppsConst",
                                                                           int.Parse(p.Data["id_request"].ToString()));
                                    }
                                }
                            }

                            if (tabbedpage is xamarinJKH.MainConst.BottomNavigationConstPage)
                            {
                                var stack = (tabbedpage as Xamarin.Forms.TabbedPage).Children[0].Navigation
                                            .NavigationStack;
                                if (stack.Count == 2)
                                {
                                    var app_page = stack.ToList()[0];
                                }
                                else
                                {
                                    if (!isCons)
                                    {
                                        MessagingCenter.Send <Object, int>(this, "SwitchToApps",
                                                                           int.Parse(p.Data["id_request"].ToString()));
                                    }
                                    else
                                    {
                                        MessagingCenter.Send <Object, int>(this, "SwitchToAppsConst",
                                                                           int.Parse(p.Data["id_request"].ToString()));
                                    }
                                }
                            }
                        }

                        if (o.ToLower() == "announcement")
                        {
                            var tabbedpage = App.Current.MainPage.Navigation.ModalStack.ToList()[0];
                            if (tabbedpage is xamarinJKH.Main.BottomNavigationPage)
                            {
                                var stack = (tabbedpage as Xamarin.Forms.TabbedPage).Children[0].Navigation
                                            .NavigationStack;
                                if (stack.Count == 2 && !isCons)
                                {
                                    await(tabbedpage as Xamarin.Forms.TabbedPage).Children[0].Navigation.PopToRootAsync();
                                }
                                if (!isCons)
                                {
                                    MessagingCenter.Send <Object, (string, string)>(this, "OpenNotification", (p.Data["body"].ToString(), p.Data["title"].ToString()));
                                }
                            }

                            //if (tabbedpage is xamarinJKH.MainConst.BottomNavigationConstPage)
                            //{
                            //    var stack = (tabbedpage as Xamarin.Forms.TabbedPage).Children[0].Navigation
                            //        .NavigationStack;
                            //    if (stack.Count == 2)
                            //    {
                            //        var app_page = stack.ToList()[0];
                            //    }
                            //    else
                            //    {
                            //        if (!isCons)
                            //            MessagingCenter.Send<Object, int>(this, "SwitchToApps",
                            //                int.Parse(p.Data["id_request"].ToString()));
                            //        else
                            //            MessagingCenter.Send<Object, int>(this, "SwitchToAppsConst",
                            //                int.Parse(p.Data["id_request"].ToString()));
                            //    }
                            //}
                        }
                    }
                    catch
                    {
                    }
                });
            };
            CrossFirebasePushNotification.Current.OnNotificationOpened += async(s, rea) =>
            {
                Analytics.TrackEvent("открыт пуш");
                System.Diagnostics.Debug.WriteLine("Opened");
                if (rea.Data.ContainsKey("type_push") || rea.Data.ContainsKey("gcm.notification.type_push"))
                {
                    string o = "";
                    if (Device.RuntimePlatform == Device.Android)
                    {
                        o = rea.Data["type_push"].ToString();
                    }
                    else
                    {
                        o = rea.Data["gcm.notification.type_push"].ToString();
                    }

                    Analytics.TrackEvent($"тип пуша {o}");

                    if (o.ToLower().Equals("announcement"))
                    {
                        Device.BeginInvokeOnMainThread(async() =>
                        {
                            string login = Preferences.Get("login", "");
                            string pass  = Preferences.Get("pass", "");
                            if (!pass.Equals("") && !login.Equals(""))
                            {
                                LoginResult loginResult = await server.Login(login, pass);
                                if (loginResult.Error == null)
                                {
                                    Settings.EventBlockData = await server.GetEventBlockData();
                                    foreach (var each in Settings.EventBlockData.Announcements)
                                    {
                                        if (rea.Data.ContainsKey("aps.alert.title") && rea.Data.ContainsKey("aps.alert.body"))
                                        {
                                            if (rea.Data["aps.alert.title"].Equals(each.Header) & rea.Data["aps.alert.body"].Equals(each.Text))
                                            {
                                                await MainPage.Navigation.PushModalAsync(new NotificationOnePage(each));
                                            }
                                        }
                                        if (rea.Data.ContainsKey("title") && rea.Data.ContainsKey("body"))
                                        {
                                            if (rea.Data["title"].Equals(each.Header) & rea.Data["body"].Equals(each.Text))
                                            {
                                                await MainPage.Navigation.PushModalAsync(new NotificationOnePage(each));
                                            }
                                        }
                                    }
                                }
                                else
                                {
                                    Analytics.TrackEvent($"сервер вернул ошибку: {loginResult.Error}");
                                }
                            }
                        });
                    }

                    if (o.ToLower().Equals("осс"))
                    {
                        Device.BeginInvokeOnMainThread(async() =>
                        {
                            string login = Preferences.Get("login", "");
                            string pass  = Preferences.Get("pass", "");
                            if (!pass.Equals("") && !login.Equals(""))
                            {
                                LoginResult loginResult = await server.Login(login, pass);
                                if (loginResult.Error == null)
                                {
                                    Settings.Person = loginResult;
                                    await MainPage.Navigation.PushModalAsync(new OSSMain());
                                }
                            }
                        });
                    }

                    if (o.ToLower().Equals("comment"))
                    {
                        if (rea.Data.ContainsKey("id_request"))
                        {
                            var id = int.Parse(rea.Data["id_request"].ToString());
                            Analytics.TrackEvent("ключ id_request=" + id);
                            Analytics.TrackEvent("isCons=" + isCons);

                            // if (!isStart)
                            // {
                            //
                            //     if (!isCons)
                            //         MessagingCenter.Send<Object, int>(this, "SwitchToApps", id);
                            //     else
                            //         MessagingCenter.Send<Object, int>(this, "SwitchToAppsConst", id);
                            // }
                            // else
                            // {
                            string login      = Preferences.Get("login", "");
                            string pass       = Preferences.Get("pass", "");
                            string loginConst = Preferences.Get("loginConst", "");
                            string passConst  = Preferences.Get("passConst", "");

                            LoginResult loginResult = isCons ? await server.LoginDispatcher(loginConst, passConst) : await server.Login(login, pass);

                            if (loginResult.Error == null)
                            {
                                if (isCons)
                                {
                                    RequestList requestList = await server.GetRequestsListConst();

                                    var request = requestList.Requests.Find(x => x.ID == id);
                                    await MainPage.Navigation.PushModalAsync(new AppConstPage(request));
                                }
                                else
                                {
                                    RequestList requestsList = await server.GetRequestsList();

                                    var request = requestsList.Requests.Find(x => x.ID == id);
                                    await MainPage.Navigation.PushModalAsync(new AppPage(request, false,
                                                                                         request.IsPaid));
                                }
                            }
                        }
                        else
                        {
                            Analytics.TrackEvent("ключ id_request не найден");
                        }
                        // Analytics.TrackEvent($"App.Current.MainPage.Navigation.ModalStack.Count={App.Current.MainPage.Navigation.ModalStack.Count}");
                        // if (App.Current.MainPage.Navigation.ModalStack.Count>0)
                        // {
                        //     var tabbedpage = App.Current.MainPage.Navigation.ModalStack.ToList()[0];
                        //     if (tabbedpage is xamarinJKH.Main.BottomNavigationPage)
                        //     {
                        //         var tp = (tabbedpage as Xamarin.Forms.TabbedPage);
                        //         Analytics.TrackEvent($"BottomNavigationPage Children count = {tp.Children.Count}");
                        //
                        //         if (tp.Children.Count >= 4)
                        //         {
                        //             var stack = tp.Children[3].Navigation.NavigationStack;
                        //             if (stack.Count == 2)
                        //             {
                        //                 var app_page = stack.ToList()[0];
                        //             }
                        //             else
                        //             {
                        //                 pExec(rea);
                        //             }
                        //         }
                        //         else
                        //         {
                        //             pExec(rea);
                        //         }
                        //     }
                        //
                        //     if (tabbedpage is xamarinJKH.MainConst.BottomNavigationConstPage)
                        //     {
                        //         var tp = (tabbedpage as Xamarin.Forms.TabbedPage);
                        //         Analytics.TrackEvent($"BottomNavigationConstPage Children count = {tp.Children.Count}");
                        //         if (tp.Children.Count >= 1)
                        //         {
                        //             var stack = tp.Children[0].Navigation.NavigationStack;
                        //             if (stack.Count == 2)
                        //             {
                        //                     var app_page = stack.ToList()[0];
                        //             }
                        //             else
                        //             {
                        //                 pExec(rea);
                        //             }
                        //         }
                        //         else
                        //         {
                        //             pExec(rea);
                        //         }
                        //
                        //     }
                        // }
                    }
                }
            };
            CrossFirebasePushNotification.Current.OnNotificationAction += (s, p) =>
            {
                System.Diagnostics.Debug.WriteLine("Action");

                if (!string.IsNullOrEmpty(p.Identifier))
                {
                    System.Diagnostics.Debug.WriteLine($"ActionId: {p.Identifier}");
                    foreach (var data in p.Data)
                    {
                        System.Diagnostics.Debug.WriteLine($"{data.Key} : {data.Value}");
                    }
                }
            };
        }
Beispiel #30
0
        /// <summary>
        /// Add new qr code to system
        /// </summary>
        private async void ToolbarItem_Activated(object sender, EventArgs e)
        {
            if (!App.AppSettings.QRCodeEnabled)
            {
                return;
            }

            if (Device.RuntimePlatform == Device.iOS)
            {
                var scanner = new ZXing.Mobile.MobileBarcodeScanner();
                var result  = await scanner.Scan();

                if (result == null)
                {
                    return;
                }
                try
                {
                    var qrCodeId = result.Text.GetHashCode() + "";
                    if (_oListSource.Any(o => string.Compare(o.Id, qrCodeId, StringComparison.OrdinalIgnoreCase) == 0))
                    {
                        App.ShowToast(AppResources.qrcode_exists);
                    }
                    else
                    {
                        AddNewRecord(qrCodeId);
                    }
                }
                catch (Exception ex)
                {
                    App.AddLog(ex.Message);
                }
            }
            else
            {
                const BarcodeFormat expectedFormat = BarcodeFormat.QR_CODE;
                var opts = new ZXing.Mobile.MobileBarcodeScanningOptions
                {
                    PossibleFormats = new List <BarcodeFormat> {
                        expectedFormat
                    }
                };
                System.Diagnostics.Debug.WriteLine("Scanning " + expectedFormat);

                var scanPage = new ZXingScannerPage(opts);
                scanPage.OnScanResult += (result) =>
                {
                    scanPage.IsScanning = false;

                    Device.BeginInvokeOnMainThread(async() =>
                    {
                        await Navigation.PopAsync();
                        try
                        {
                            var qrCodeId = result.Text.GetHashCode() + "";
                            if (_oListSource.Any(
                                    o => string.Compare(o.Id, qrCodeId, StringComparison.OrdinalIgnoreCase) == 0))
                            {
                                App.ShowToast(AppResources.qrcode_exists);
                            }
                            else
                            {
                                AddNewRecord(qrCodeId);
                            }
                        }
                        catch (Exception ex)
                        {
                            App.AddLog(ex.Message);
                        }
                    });
                };

                await Navigation.PushAsync(scanPage);
            }
        }