Esempio n. 1
0
        public static void HandleException(Exception ex)
        {
            AppCenterHelper.Error("AsyncErrorHandler HandleException", ex);
#if DEBUG
            Debug.WriteLine(ex);
#endif
        }
Esempio n. 2
0
        async void handleApplicationTapped(object sender, ItemTappedEventArgs e)
        {
            try
            {
                if (!isBusy)
                {
                    isBusy = true;
                    if (e.Item == null)
                    {
                        return;
                    }

                    var selectedApplication = e.Item as Workbench.Client.Models.Application;

                    //Reset the IsInitiator property
                    App.ViewModel.IsUserInitiator = false;


                    await App.ViewModel.SetCurrentApplication(selectedApplication.Id.ToString());

                    await App.ViewModel.RefreshWorkflowsForSelectedApplication(selectedApplication.Id.ToString());
                }
            }
            catch (Exception ex)
            {
                AppCenterHelper.Report(ex);
            }
            finally
            {
                isBusy = false;
            }
        }
        public async Task <bool> LoginAsync()
        {
            if (IsBusy)
            {
                return(false);
            }

            IsBusy             = true;
            IsAnimationVisible = true;

            try
            {
                var response = await executeLoginAsync();

                IsAnimationVisible = false;

                return(response);
            }
            catch (Exception e)
            {
                AppCenterHelper.Report(e);
                await App.Current.MainPage.DisplayAlert("Error", $"executeLoginAsync: {e.Message}", "OK");
            }
            finally
            {
                IsBusy             = false;
                IsAnimationVisible = false;
            }

            return(false);
        }
        protected override async void ViewIsAppearing(object sender, EventArgs e)
        {
            AppCenterHelper.Track("DeviceTwinPageModel - ViewIsAppearing");
            await OutputDeviceTwin();

            base.ViewIsAppearing(sender, e);
        }
        private void MonitorProximityBeacons()
        {
            _monitoringV2ManagerImmediate.StartMonitoring(BeaconsImmediate.Select(x => x.Key).ToArray());
            _monitoringV2ManagerImmediate.EnterdDesiredRange += (object sender, MonitoringV2ManagerEnterdDesiredRangeEventArgs e) =>
            {
                switch (BeaconsImmediate[e.Identifier])
                {
                case "Bedroom":
                    _settings.AtBedroom = true;
                    break;
                }

                AppCenterHelper.Track($"LocationBeacon EnterdDesiredRange: {BeaconsImmediate[e.Identifier]}");
            };
            _monitoringV2ManagerImmediate.ExitedDesiredRange += (object sender, MonitoringV2ManagerExitedDesiredRangeEventArgs e) =>
            {
                switch (BeaconsImmediate[e.Identifier])
                {
                case "Bedroom":
                    _settings.AtBedroom = false;
                    break;
                }

                AppCenterHelper.Track($"LocationBeacon ExitedDesiredRange: {BeaconsImmediate[e.Identifier]}");
            };
        }
Esempio n. 6
0
        protected override async void OnStart()
        {
            AppCenterHelper.Start();
            AppCenterHelper.TrackEvent("App Started");

#if DEBUG
            var res = await LocalDbHelper.Instance.GetAllSavedEnvironmentsAsync();

            if (res.Count == 0)
            {
                /* The following can be used when debugging to input a sample environment
                 *
                 * var environment = new BlockchainEnvironment
                 * {
                 *  ResourceId = "YOUR RESOURCE ID",
                 *  ClientId = "YOUR CLIENT ID",
                 *  ReturnUrl = "YOUR RETURN URI",
                 *  SiteUrl = "YOUR API ENDPOINT",
                 *  TenantId = "YOUR AD TENANT INFORMATION",
                 *  NickName = "A NICKNAME FOR THE ENV"
                 * };
                 *
                 * await LocalDbHelper.Instance.SaveEnvironmentAsync(environment);
                 */
            }
#endif
        }
        public async Task <LoginResponse> LoginAsync(string authority, string resource, string clientId, string returnUri, bool isRefresh = false)
        {
            var authContext = new AuthenticationContext(authority);

            if (authContext.TokenCache.ReadItems().Any())
            {
                authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
            }

            try
            {
                AuthenticationResult authResult;
                if (isRefresh)
                {
                    authResult = await authContext.AcquireTokenSilentAsync(resource, clientId);
                }
                else
                {
                    var controller     = ViewControllerHelpers.GetVisibleViewController();
                    var uri            = new Uri(returnUri);
                    var platformParams = new PlatformParameters(controller);

                    authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams);
                }

                var result = new LoginResponse
                {
                    AuthHeader            = authResult.CreateAuthorizationHeader(),
                    AccessToken           = authResult.AccessToken,
                    AccessTokenType       = authResult.AccessTokenType,
                    ExpiresOn             = authResult.ExpiresOn,
                    ExtendedLifetimeToken = authResult.ExtendedLifeTimeToken,
                    IdToken  = authResult.IdToken,
                    TenantId = authResult.TenantId
                };

                result.Profile.DisplayableId = authResult.UserInfo.DisplayableId;
                result.Profile.FamilyName    = authResult.UserInfo.FamilyName;
                result.Profile.GivenName     = authResult.UserInfo.GivenName;
                result.Profile.UniqueId      = authResult.UserInfo.UniqueId;

                return(result);
            }
            catch (Exception e)
            {
                var _controller = ViewControllerHelpers.GetVisibleViewController();
                var alert       = UIAlertController.Create("Error", e.Message, UIAlertControllerStyle.Alert);
                alert.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));

                _controller.BeginInvokeOnMainThread(() =>
                {
                    _controller.PresentViewController(alert, true, null);
                });

                AppCenterHelper.Report(e);
                clearTokenFromCache(authority);
                return(null);
            }
        }
 //--------------------------------------------------------Set-, Get- Methods:---------------------------------------------------------\\
 #region --Set-, Get- Methods--
 private void SetAnalytics(bool value)
 {
     if (SetProperty(ref _Analytics, value, nameof(Analytics)))
     {
         Settings.setSetting(SettingsConsts.DISABLE_ANALYTICS, !value);
         Task.Run(async() => await AppCenterHelper.SetAnalyticsEnabledAsync(value));
     }
 }
Esempio n. 9
0
        protected override async void ViewIsAppearing(object sender, EventArgs e)
        {
            await _azureIoTHub.GetDeviceTwin();

            AppCenterHelper.Track("SecurityPageModel - ViewIsAppearing");

            base.ViewIsAppearing(sender, e);
        }
 private void SetCrashreports(bool value)
 {
     if (SetProperty(ref _Crashreports, value, nameof(Crashreports)))
     {
         Settings.setSetting(SettingsConsts.DISABLE_CRASH_REPORTING, !value);
         Task.Run(async() => await AppCenterHelper.SetCrashesEnabledAsync(value));
     }
 }
        private async Task OccupantStateUpdated()
        {
            var occupantState = GetOccupantState();

            _settings.OccupantState = occupantState;
            await _azureIoTHub.UpdateOccupantState(occupantState);

            AppCenterHelper.Track(nameof(OccupantStateUpdated));
        }
Esempio n. 12
0
        public App()
        {
            InitializeComponent();

            if (appCenterHelper == null)
            {
                appCenterHelper = new AppCenterHelper();
            }

            MainPage = new MainPage();
        }
        private async Task ShowReportCrashIfNeeded()
        {
            if (await Crashes.IsEnabledAsync() && await Crashes.HasCrashedInLastSessionAsync())
            {
                ErrorReport crashReport = await Crashes.GetLastSessionCrashReportAsync();

                Logger.Error("Detected a crash in the last session: " + crashReport.StackTrace);
                ReportLastCrashDialog dialog = new ReportLastCrashDialog(AppCenterHelper.GenerateCrashReport(crashReport));
                await UiUtils.ShowDialogAsync(dialog);
            }
        }
Esempio n. 14
0
        public override void WillPresentNotification(UNUserNotificationCenter center, UNNotification notification, Action <UNNotificationPresentationOptions> completionHandler)
        {
            // Do something with the notification

            AppCenterHelper.Track("DidReceiveRemoteNotification - Active Notification");

            // Will also call '// App Active' in AppDelegate

            // Tell system to display the notification anyway or use
            // `None` to say we have handled the display locally.
            completionHandler(UNNotificationPresentationOptions.Alert);
        }
        public async Task GetDeviceTwin()
        {
            var twin = await _registryManager.GetTwinAsync(DeviceId);

            AppCenterHelper.Track(nameof(GetDeviceTwin));

            // Update DeviceTwin
            _deviceTwin.ApplianceConnected = twin.ConnectionState == DeviceConnectionState.Connected;

            try
            {
                var        reportedPropertyForRelayState = twin.Properties.Reported["RelayState"];
                RelayState relayState = JsonConvert.DeserializeObject <RelayState>(reportedPropertyForRelayState.ToJson());
                _deviceTwin.LightsGarden = relayState.LightsGarden;
                _deviceTwin.AlarmStrobe  = relayState.AlarmStrobe;
                _deviceTwin.AlarmSiren   = relayState.AlarmSiren;
            }
            catch (Exception ex)
            {
                AppCenterHelper.Error("Error updating RelayState", ex);
            }

            try
            {
                var reportedPropertyOccupantState = twin.Properties.Reported[nameof(_deviceTwin.Occupant)];
                var occupant = JsonConvert.DeserializeObject <OccupantState>(reportedPropertyOccupantState.ToJson());
                _deviceTwin.Occupant = occupant;
            }
            catch (Exception ex)
            {
                AppCenterHelper.Error("Error updating Occupant", ex);
            }

            try
            {
                var reportedPropertyArmedState = twin.Properties.Reported[nameof(ArmedState)];
                var armedState = JsonConvert.DeserializeObject <ArmedState>(reportedPropertyArmedState.ToJson());
                _deviceTwin.ArmedState = armedState;
            }
            catch (Exception ex)
            {
                AppCenterHelper.Error("Error updating ArmedState", ex);
            }

            try
            {
                _deviceTwin.GarageDoorOpen = (bool)twin.Properties.Reported["GarageDoorOpen"];
            }
            catch (Exception ex)
            {
                AppCenterHelper.Error("Error updating GarageDoorOpen", ex);
            }
        }
        private void MonitorSecureBeacons()
        {
            _secureBeaconManager.AuthorizationStatusChanged += (object sender, SecureBeaconManagerAuthorizationStatusChangedEventArgs e) =>
            {
                StartMonitorinBeacons();
            };

            _secureBeaconManager.EnteredRegion += (object sender, SecureBeaconManagerEnteredRegionEventArgs e) =>
            {
                switch (e.Region.Identifier)
                {
                case nameof(MySecureBeacon):
                    // Do stuff
                    break;
                }

                AppCenterHelper.Track($"SecureBeacon EnteredRegion: {e.Region.Identifier}");
            };

            _secureBeaconManager.ExitedRegion += (object sender, SecureBeaconManagerExitedRegionEventArgs e) =>
            {
                switch (e.Region.Identifier)
                {
                case nameof(MySecureBeacon):
                    // Do stuff
                    break;
                }

                AppCenterHelper.Track($"SecureBeacon ExitedRegion: {e.Region.Identifier}");
            };

            _secureBeaconManager.DeterminedState += (object sender, SecureBeaconManagerDeterminedStateEventArgs e) =>
            {
                switch (e.Region.Identifier)
                {
                case nameof(MySecureBeacon):
                    // Do stuff
                    break;
                }

                AppCenterHelper.Track($"SecureBeacon DeterminedState: {e.Region.Identifier}");
            };

            try
            {
                StartMonitorinBeacons();
            }
            catch (Exception ex)
            {
                AppCenterHelper.Error(nameof(MonitorSecureBeacons), ex);
            }
        }
Esempio n. 17
0
 public override void DidReceiveNotificationResponse(UNUserNotificationCenter center, UNNotificationResponse response, Action completionHandler)
 {
     // User Tapped
     if (response.IsDefaultAction)
     {
         var userInfo = response.Notification.Request.Content?.UserInfo;
         if (userInfo != null)
         {
             AppCenterHelper.Track("DidReceiveNotificationResponse - User Tapped");
         }
     }
     completionHandler();
 }
        public void MonitorHomeGeolocation()
        {
            LocationService.Instance.AuthorizationChanged += (s, e) =>
            {
                if (e.Status == CLAuthorizationStatus.AuthorizedAlways)
                {
                    LocationService.Instance.StartMonitoring(HomeRegion);
                }
            };

            // https://medium.com/@mizutori/tracking-highly-accurate-location-in-ios-vol-3-7cd827a84e4d
            LocationService.Instance.RequestAlwaysAuthorization();
            LocationService.Instance.AllowsBackgroundLocationUpdates    = true;
            LocationService.Instance.PausesLocationUpdatesAutomatically = false;
            LocationService.Instance.DesiredAccuracy = CLLocation.AccurracyBestForNavigation;
            LocationService.Instance.DistanceFilter  = CLLocationDistance.FilterNone;

            LocationService.Instance.RegionEntered += async(object sender, CLRegionEventArgs e) => {
                if (e.Region is CLCircularRegion && e.Region.Identifier == "Microsoft Melbourne")
                {
                    _settings.AtHome = true;

                    AppCenterHelper.Track("Microsoft Melbourne Entered");
                }
            };
            LocationService.Instance.RegionLeft += async(object sender, CLRegionEventArgs e) => {
                if (e.Region is CLCircularRegion && e.Region.Identifier == "Microsoft Melbourne")
                {
                    _settings.AtHome = false;

                    AppCenterHelper.Track("Microsoft Melbourne Left");
                }
            };
            LocationService.Instance.DidDetermineState += (object sender, CLRegionStateDeterminedEventArgs e) => {
                if (e.Region is CLCircularRegion && e.Region.Identifier == "Microsoft Melbourne")
                {
                    _settings.AtHome = e.State == CLRegionState.Inside;

                    AppCenterHelper.Track("Microsoft Melbourne Determine State");
                }
            };

            try
            {
                LocationService.Instance.StartMonitoring(HomeRegion);
            }
            catch (Exception ex)
            {
                AppCenterHelper.Error(nameof(MonitorHomeGeolocation), ex);
            }
        }
Esempio n. 19
0
        public async Task <LoginResponse> LoginAsync(string authority, string resource, string clientId, string returnUri, bool isRefresh = false)
        {
            var authContext = new AuthenticationContext(authority);

            if (authContext.TokenCache.ReadItems().Any())
            {
                authContext = new AuthenticationContext(authContext.TokenCache.ReadItems().First().Authority);
            }

            var uri            = new Uri(returnUri);
            var platformParams = new PlatformParameters((Android.App.Activity)Xamarin.Forms.Forms.Context);

            try
            {
                AuthenticationResult authResult;

                if (isRefresh)
                {
                    authResult = await authContext.AcquireTokenSilentAsync(resource, clientId);
                }
                else
                {
                    authResult = await authContext.AcquireTokenAsync(resource, clientId, uri, platformParams).ConfigureAwait(false);
                }

                var result = new LoginResponse
                {
                    AuthHeader            = authResult.CreateAuthorizationHeader(),
                    AccessToken           = authResult.AccessToken,
                    AccessTokenType       = authResult.AccessTokenType,
                    ExpiresOn             = authResult.ExpiresOn,
                    ExtendedLifetimeToken = authResult.ExtendedLifeTimeToken,
                    IdToken  = authResult.IdToken,
                    TenantId = authResult.TenantId
                };

                result.Profile.DisplayableId = authResult.UserInfo.DisplayableId;
                result.Profile.FamilyName    = authResult.UserInfo.FamilyName;
                result.Profile.GivenName     = authResult.UserInfo.GivenName;
                result.Profile.UniqueId      = authResult.UserInfo.UniqueId;

                return(result);
            }
            catch (Exception e)
            {
                AppCenterHelper.Report(e);
                clearTokenFromCache(authority);
                return(null);
            }
        }
        public async Task LoadContractInstanceAsync()
        {
            IsBusy = true;

            try
            {
                Blocks         = new List <BlockModel>();
                DisplayActions = false;

                var res = await GatewayApi.Instance.GetContractByIdAsync(ContractInstance.Id.ToString());

                if (res != default(Contract) || res != null)
                {
                    ContractInstance = res;
                    assembleBlocks();
                }

                assembleUsers();

                var actions = await GatewayApi.Instance.GetWorkflowActionsAsync(ContractInstance.Id.ToString());

                if (actions != null)
                {
                    Actions = new List <WorkflowFunction>(actions);

                    if (Actions?.Count > 0)
                    {
                        DisplayActions = true;
                    }
                    else
                    {
                        DisplayActions = false;
                    }
                }
                else
                {
                    DisplayActions = false;
                }
            }
            catch (Exception e)
            {
                AppCenterHelper.Report(e);
            }
            finally
            {
                IsBusy = false;
            }
        }
        public async Task UpdateOccupantState(OccupantState occupantState)
        {
            using (await Lock.LockAsync())
            {
                switch (Config.Person)
                {
                case "Occupant":
                    if (_deviceTwin.Occupant.GetHashCode() == occupantState.GetHashCode())
                    {
                        AppCenterHelper.Track("UpdateOccupantState passed");
                        return;
                    }

                    break;
                }

                dynamic desiredState;
                switch (Config.Person)
                {
                case "Occupant":
                default:
                    desiredState = new
                    {
                        Occupant = occupantState
                    };
                    break;
                }

                var patch = new
                {
                    properties = new
                    {
                        desired = desiredState
                    }
                };


                // TODO: This can fail, add in resiliency
                var updatedTwin =
                    await _registryManager.UpdateTwinAsync(DeviceId, JsonConvert.SerializeObject(patch), "*");

                await GetDeviceTwin();

                AppCenterHelper.Track("Updated Occupant State");
            }
        }
        async Task configureFirstEnvironment()
        {
            try
            {
                addingNewEnvironment = true;

                var prompt = new PromptConfig
                {
                    IsCancellable = true,
                    Message       = $"Please enter the URL that contains your environment configuration JSON",
                    OkText        = "Ok",
                    Title         = "Add Environment"
                };

                var URLResults = await UserDialogs.Instance.PromptAsync(prompt);

                if (!string.IsNullOrEmpty(URLResults?.Value))
                {
                    using (var httpclient = new HttpClient())
                    {
                        var results = await httpclient.GetStringAsync(URLResults?.Value);

                        if (!string.IsNullOrEmpty(results))
                        {
                            var environment = JsonConvert.DeserializeObject <BlockchainEnvironment>(results);

                            await LocalDbHelper.Instance.SaveEnvironmentAsync(environment);

                            Device.BeginInvokeOnMainThread(async() =>
                            {
                                await LoginAsync();
                            });
                        }
                        else
                        {
                            await UserDialogs.Instance.AlertAsync("Unable to get environment data, please ensure you entered a valid URL", "Error", "OK");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                AppCenterHelper.Report(e);
                await UserDialogs.Instance.AlertAsync("Unable to get environment data, please ensure you entered a valid URL", "Error", "OK");
            }
        }
Esempio n. 23
0
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);

            if (e.OldElement != null || Element == null)
            {
                return;
            }

            try
            {
                SetAppTheme();
            }
            catch (Exception ex)
            {
                AppCenterHelper.TrackError(ex);
            }
        }
Esempio n. 24
0
        public void clearTokenFromCache(string authority)
        {
            try
            {
                Android.Webkit.CookieManager.Instance.RemoveAllCookies(null);

                var authContext = new AuthenticationContext(authority);
                authContext.TokenCache.Clear();

                var editor = SharedPreferences.Edit();
                editor.Remove(SharedPreferencesKey);
            }
            catch (Exception ex)
            {
                // log the error
                AppCenterHelper.Report(ex);
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
Esempio n. 25
0
        private async Task <bool> InvokeMethodWithResponseState(string method, bool currentState)
        {
            AppCenterHelper.Track($"SecurityPageModel - {method}");

            var response = await ResilientCall.ExecuteWithRetry(
                () => _azureIoTHub.InvokeMethod(method));

            if (response.Outcome == OutcomeType.Successful && response.Result.Status == 200)
            {
                var stateResponse = JsonConvert.DeserializeObject <StateResponse>(response.Result.ResponsePayload);
                return(stateResponse.State);
            }

            // Error
            ShowError();
            AppCenterHelper.Error(method, response.FinalException);

            return(currentState);
        }
        private async Task LoadAppAsync()
        {
            // Setup listening for theme changes:
            ThemeUtils.SetupThemeListener();

            // Setup listener for window activated changes:
            UiUtils.SetupWindowActivatedListener();

            // Setup window:
            UiUtils.SetupWindow(Application.Current);

            // Perform app update tasks if necessary:
            await AppUpdateHelper.OnAppStartAsync();

            // Setup App Center crashes, push:
            AppCenterHelper.SetupAppCenter();
            await ShowReportCrashIfNeeded();

            // Register background tasks:
            Logger.Info("Registering background tasks...");
            // TODO: Add background tasks here
            Logger.Info("Finished registering background tasks.");

            // Show initial start dialog:

            /*if (!Settings.getSettingBoolean(SettingsConsts.HIDE_INITIAL_START_DIALOG_ALPHA))
             * {
             *  InitialStartDialog initialStartDialog = new InitialStartDialog();
             *  await UiUtils.ShowDialogAsync(initialStartDialog);
             * }
             *
             * // Show what's new dialog:
             * if (!Settings.getSettingBoolean(SettingsConsts.HIDE_WHATS_NEW_DIALOG))
             * {
             *  WhatsNewDialog whatsNewDialog = new WhatsNewDialog();
             *  await UiUtils.ShowDialogAsync(whatsNewDialog);
             * }*/

            EvaluateActivationArgs();
        }
        public void RequestBeaconStates()
        {
            var monitoredBeacons = new Dictionary <string, MonitoringState>();

            foreach (var id in BeaconsImmediate.Keys)
            {
                var state = _monitoringV2ManagerImmediate.StateForBeacon(id);
                monitoredBeacons.Add(BeaconsImmediate[id], state);
            }

            foreach (var monitoredBeacon in monitoredBeacons)
            {
                switch (monitoredBeacon.Key)
                {
                case "Bedroom":
                    _settings.AtBedroom = monitoredBeacon.Value == MonitoringState.InsideZone;
                    break;
                }
            }

            _secureBeaconManager.RequestState(MySecureBeacon);

            AppCenterHelper.Track(nameof(RequestBeaconStates));
        }
Esempio n. 28
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            var eventUploadIntent = new Intent(this, typeof(EventUploadReceiver));

            _eventUploadPendingIntent = PendingIntent.GetBroadcast(this, 0, eventUploadIntent,
                                                                   PendingIntentFlags.UpdateCurrent);
            var alarmIntent = new Intent(this, typeof(LockAlarmReceiver));

            _vaultTimeoutAlarmPendingIntent = PendingIntent.GetBroadcast(this, 0, alarmIntent,
                                                                         PendingIntentFlags.UpdateCurrent);
            var clearClipboardIntent = new Intent(this, typeof(ClearClipboardAlarmReceiver));

            _clearClipboardPendingIntent = PendingIntent.GetBroadcast(this, 0, clearClipboardIntent,
                                                                      PendingIntentFlags.UpdateCurrent);

            var policy = new StrictMode.ThreadPolicy.Builder().PermitAll().Build();

            StrictMode.SetThreadPolicy(policy);

            _deviceActionService = ServiceContainer.Resolve <IDeviceActionService>("deviceActionService");
            _messagingService    = ServiceContainer.Resolve <IMessagingService>("messagingService");
            _broadcasterService  = ServiceContainer.Resolve <IBroadcasterService>("broadcasterService");
            _userService         = ServiceContainer.Resolve <IUserService>("userService");
            _appIdService        = ServiceContainer.Resolve <IAppIdService>("appIdService");
            _storageService      = ServiceContainer.Resolve <IStorageService>("storageService");
            _eventService        = ServiceContainer.Resolve <IEventService>("eventService");

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            UpdateTheme(ThemeManager.GetTheme(true));
            base.OnCreate(savedInstanceState);
            if (!CoreHelpers.InDebugMode())
            {
                Window.AddFlags(Android.Views.WindowManagerFlags.Secure);
            }

#if !FDROID
            var appCenterHelper = new AppCenterHelper(_appIdService, _userService);
            var appCenterTask   = appCenterHelper.InitAsync();
#endif

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            Xamarin.Forms.Forms.Init(this, savedInstanceState);
            _appOptions = GetOptions();
            LoadApplication(new App.App(_appOptions));

            _broadcasterService.Subscribe(_activityKey, (message) =>
            {
                if (message.Command == "scheduleVaultTimeoutTimer")
                {
                    var alarmManager        = GetSystemService(AlarmService) as AlarmManager;
                    var vaultTimeoutMinutes = (int)message.Data;
                    var vaultTimeoutMs      = vaultTimeoutMinutes * 60000;
                    var triggerMs           = Java.Lang.JavaSystem.CurrentTimeMillis() + vaultTimeoutMs + 10;
                    alarmManager.Set(AlarmType.RtcWakeup, triggerMs, _vaultTimeoutAlarmPendingIntent);
                }
                else if (message.Command == "cancelVaultTimeoutTimer")
                {
                    var alarmManager = GetSystemService(AlarmService) as AlarmManager;
                    alarmManager.Cancel(_vaultTimeoutAlarmPendingIntent);
                }
                else if (message.Command == "startEventTimer")
                {
                    StartEventAlarm();
                }
                else if (message.Command == "stopEventTimer")
                {
                    var task = StopEventAlarmAsync();
                }
                else if (message.Command == "finishMainActivity")
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() => Finish());
                }
                else if (message.Command == "listenYubiKeyOTP")
                {
                    ListenYubiKey((bool)message.Data);
                }
                else if (message.Command == "updatedTheme")
                {
                    RestartApp();
                }
                else if (message.Command == "exit")
                {
                    ExitApp();
                }
                else if (message.Command == "copiedToClipboard")
                {
                    var task = ClearClipboardAlarmAsync(message.Data as Tuple <string, int?, bool>);
                }
            });
        }
        async Task <bool> executeLoginAsync()
        {
            var localEnvironments = await LocalDbHelper.Instance.GetAllSavedEnvironmentsAsync();

            if (localEnvironments.Count <= 0)
            {
                System.Diagnostics.Debug.WriteLine("################### NO LOCAL ENVIRONMENTS FOUND");

                await configureFirstEnvironment();

                return(false);
            }

            BlockchainEnvironment environment = localEnvironments[0];

            var authService   = ServiceContainer.Resolve <IAuthentication>();
            var loginResponse = await authService.LoginAsync(
                $"https://login.windows.net/{environment.TenantId}",
                environment.ResourceId,
                environment.ClientId,
                environment.ReturnUrl);

            if (loginResponse != null)
            {
                AppCenterHelper.TrackEvent("Logged in", new Dictionary <string, string>()
                {
                    { "username", loginResponse.Profile.DisplayableId }
                });

                Settings.AccessToken = loginResponse.AccessToken;
#if DEBUG
                Settings.AccessTokenExpiration            = new DateTimeOffset(DateTime.UtcNow.AddMinutes(2));
                GatewayApi.Instance.AccessTokenExpiration = new DateTimeOffset(DateTime.UtcNow.AddMinutes(2));
#else
                Settings.AccessTokenExpiration            = loginResponse.ExpiresOn;
                GatewayApi.Instance.AccessTokenExpiration = loginResponse.ExpiresOn;
#endif

                GatewayApi.Instance.SetAuthToken(loginResponse.AccessToken);

                App.LOGGED_OUT = false;

                Device.BeginInvokeOnMainThread(async() =>
                {
                    if (App.Current.MainPage.Navigation.ModalStack.Count == 0)
                    {
                        await App.Current.MainPage.Navigation.PushModalAsync(App.Master);
                    }

                    App.ViewModel.WorkbenchEnvironments = localEnvironments;
                    App.ViewModel.SelectedEnvironment   = environment;
                });

                return(true);
            }
            else
            {
                await App.Logout();

                return(false);
            }
        }
Esempio n. 30
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            var eventUploadIntent = new Intent(this, typeof(EventUploadReceiver));

            _eventUploadPendingIntent = PendingIntent.GetBroadcast(this, 0, eventUploadIntent,
                                                                   PendingIntentFlags.UpdateCurrent);

            var policy = new StrictMode.ThreadPolicy.Builder().PermitAll().Build();

            StrictMode.SetThreadPolicy(policy);

            _deviceActionService = ServiceContainer.Resolve <IDeviceActionService>("deviceActionService");
            _messagingService    = ServiceContainer.Resolve <IMessagingService>("messagingService");
            _broadcasterService  = ServiceContainer.Resolve <IBroadcasterService>("broadcasterService");
            _stateService        = ServiceContainer.Resolve <IStateService>("stateService");
            _appIdService        = ServiceContainer.Resolve <IAppIdService>("appIdService");
            _eventService        = ServiceContainer.Resolve <IEventService>("eventService");

            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            // this needs to be called here before base.OnCreate(...)
            Intent?.Validate();

            base.OnCreate(savedInstanceState);
            if (!CoreHelpers.InDebugMode())
            {
                Window.AddFlags(Android.Views.WindowManagerFlags.Secure);
            }

#if !DEBUG && !FDROID
            var appCenterHelper = new AppCenterHelper(_appIdService, _stateService);
            var appCenterTask   = appCenterHelper.InitAsync();
#endif

            var toplayout = Window?.DecorView?.RootView;
            if (toplayout != null)
            {
                toplayout.FilterTouchesWhenObscured = true;
            }

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            Xamarin.Forms.Forms.Init(this, savedInstanceState);
            _appOptions = GetOptions();
            LoadApplication(new App.App(_appOptions));

            _broadcasterService.Subscribe(_activityKey, (message) =>
            {
                if (message.Command == "startEventTimer")
                {
                    StartEventAlarm();
                }
                else if (message.Command == "stopEventTimer")
                {
                    var task = StopEventAlarmAsync();
                }
                else if (message.Command == "finishMainActivity")
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() => Finish());
                }
                else if (message.Command == "listenYubiKeyOTP")
                {
                    ListenYubiKey((bool)message.Data);
                }
                else if (message.Command == "updatedTheme")
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(() => AppearanceAdjustments());
                }
                else if (message.Command == "exit")
                {
                    ExitApp();
                }
            });
        }