public SingleReportPurchaseViewModel(ValidationModel validation,
                                             Action <Uri> openUri,
                                             string runtimePlatform,
                                             AlertUtility alertUtility,
                                             MainThreadNavigator nav,
                                             IToastService toastService,
                                             IPurchasedReportService prService,
                                             IPurchasingService purchaseService,
                                             ICurrentUserService userCache,
                                             ICache <PurchasedReportModel> prCache,
                                             ILogger <SingleReportPurchaseViewModel> emailLogger)
        {
            _validation      = validation;
            _openUri         = openUri;
            _nav             = nav;
            _toastService    = toastService;
            _runtimePlatform = runtimePlatform;
            _userCache       = userCache;
            _purchaseService = purchaseService;
            _prService       = prService;
            _prCache         = prCache;
            _emailLogger     = emailLogger;
            _alertUtility    = alertUtility;

            SetViewState(validation);
        }
        private void HandleUpdatesForStopStartProgram(ProgressResponse response, ProgramViewModel program, bool start)
        {
            MainThreadUtility.InvokeOnMain(() =>
            {
                if (response != null)
                {
                    DataCache.AddCommandProgress(new CommandProgress(CommandType.StartPrograms, response.Body, new string[] { program.Id }));

                    if (response.IsFinal)
                    {
                        Action resetProgram = () =>
                        {
                            program.Starting = false;
                            //ServiceContainer.DeviceService.RequestDevice(this.Device.Device);
                        };

                        if (response.IsSuccessful)
                        {
                            //AlertUtility.ShowProgressResponse("Stop/Start Program " + program.Id, response);
                            this.RegisterForAsyncUpdate(resetProgram, 5000);
                        }
                        else
                        {
                            this.RegisterForAsyncUpdate(resetProgram);

                            if ((bool)!response?.IsReconnectResponse && (bool)!response?.IsServerDownResponse)
                            {
                                AlertUtility.ShowAppError(response?.ErrorBody);
                            }
                        }
                    }
                }
            });
        }
Beispiel #3
0
        //edited
        private void SetDismissAllButton()
        {
            ExceptionUtility.Try(() =>
            {
                if (this.HasAccessLevelToDelete())
                {
                    if (this.NavigationItem != null)
                    {
                        this.NavigationItem.RightBarButtonItem = new UIBarButtonItem(StringLiterals.DismissAll, UIBarButtonItemStyle.Plain, (o, e) =>
                        {
                            if (this.NavigationController != null)
                            {
                                //  this.NavigationController.PopViewController(false);

                                ExceptionUtility.Try(() =>
                                {
                                    string title = StringLiterals.Alert;
                                    AlertUtility.ShowConfirmationAlert(title, StringLiterals.DismissAllAlertsConfirmationMessage(), (b) =>
                                    {
                                        if (b)
                                        {
                                            DismissAlertsConfirmed();
                                        }
                                    }, StringLiterals.YesButtonText);
                                });
                            }
                        });
                    }
                }
            });
        }
Beispiel #4
0
 public PurchaseViewModel(IToastService toastService,
                          IPurchasingService purchaseService,
                          ICache <SubscriptionModel> subCache,
                          ISubscriptionService subService,
                          ICurrentUserService userCache,
                          MainThreadNavigator nav,
                          ValidationModel validationModel,
                          string runtimePlatform,
                          Action <BaseNavPageType> navigateFromMenu,
                          AlertUtility alertUtility,
                          Action <Uri> openUri)
 {
     _toastService         = toastService;
     _purchaseService      = purchaseService;
     _subCache             = subCache;
     _subService           = subService;
     _userCache            = userCache;
     _validationModel      = validationModel;
     _runtimePlatform      = runtimePlatform;
     _openUri              = openUri;
     _alertUtility         = alertUtility;
     _nav                  = nav;
     _navigateFromMenu     = navigateFromMenu;
     LegalLinkCommand      = new Command(() => _openUri(new Uri(Configuration.PrivacyPolicyUrl)));
     PurchaseButtonCommand = new Command(() => PurchaseButtonClicked());
     SetVisualState(validationModel);
 }
Beispiel #5
0
        private void HandleUpdatesForPrev(ProgressResponse response)
        {
            MainThreadUtility.InvokeOnMain(() =>
            {
                if (response != null)
                {
                    DataCache.AddCommandProgress(new CommandProgress(CommandType.DevicePrev, response.Body));

                    if (response.IsFinal)
                    {
                        this.Device.Preving = false;
                        this.SetButtonMode(this._prevButton, this._prevButtonSpinner, false);

                        if (response.IsSuccessful)
                        {
                        }
                        else
                        {
                            if ((bool)!response?.IsReconnectResponse && (bool)!response?.IsServerDownResponse)
                            {
                                AlertUtility.ShowAppError(response?.ErrorBody);
                            }
                        }
                    }
                }

                AlertUtility.ShowProgressResponse(this._prevFeature.ProgressText, response);
            });
        }
        private void NavigateToDeviceDetails(DeviceViewModel device)
        {
            try
            {
                ProgressUtility.SafeShow("Getting Device Details", async() =>
                {
                    var response = await ServiceContainer.DeviceService.RequestDevice(device.Device, () => { NavigateToDeviceDetails(device); });

                    MainThreadUtility.InvokeOnMain(() =>
                    {
                        if (response != null && response.IsSuccessful)
                        {
                            var d = response.Body.Devices.Items.FirstOrDefault().Value;
                            if (d == null)
                            {
                                ProgressUtility.Dismiss();
                                AlertUtility.ShowErrorAlert(StringLiterals.Error, StringLiterals.DeviceNotFoundErrorTitle);
                            }
                            else
                            {
                                this.Predecessor = null;
                                ProgressUtility.Dismiss();
                                this.NavigateTo(DeviceDetailsViewController.CreateInstance(d.Id));
                            }
                        }
                    });
                });
            }
            catch (Exception e)
            {
                LogUtility.LogException(e);
            }
        }
        protected override void HandleViewDidAppear(bool animated)
        {
            base.HandleViewDidAppear(animated);

            if (this.ShowConnectionError)
            {
                this.ShowConnectionError = false;
                AlertUtility.ShowErrorAlert(StringLiterals.ConnectionError, StringLiterals.AuthFailureMessage);

                Aquamonix.Mobile.IOS.Utilities.WebSockets.ConnectionManager.ReconnectProcess.Begin(showBannerStraightAway: true);
            }
        }
Beispiel #8
0
        public OrderViewModel(IOrderValidationService validator,
                              ICurrentUserService userCache,
                              IOrderService orderService,
                              IToastService toast,
                              IPageFactory pageFactory,
                              MainThreadNavigator nav,
                              IMessagingSubscriber topicSubscriber,
                              ILogger <OrderViewModel> logger,
                              string deviceType,
                              AlertUtility alertUtility,
                              Action <BaseNavPageType> baseNavigationAction,
                              ICache <Models.Order> orderCache)
        {
            _orderValidator       = validator;
            _userService          = userCache;
            _toast                = toast;
            _nav                  = nav;
            _orderService         = orderService;
            _pageFactory          = pageFactory;
            _orderCache           = orderCache;
            _alertUtility         = alertUtility;
            _topicSubscriber      = topicSubscriber;
            _baseNavigationAction = baseNavigationAction;
            _deviceType           = deviceType;
            _logger               = logger;

            PurchaseOptionsCommand = new Command(async() =>
            {
                var val = await _orderValidator.ValidateOrderRequest(_userService.GetLoggedInAccount());
                if (SubscriptionUtility.SubscriptionActive(val.Subscription))
                {
                    _nav.Push(_pageFactory.GetPage(PageType.SingleReportPurchase, val));
                }
                else
                {
                    _nav.Push(_pageFactory.GetPage(PageType.PurchaseOptions, val));
                }
            });
            OptionsInfoCommand = new Command(async() => await alertUtility.Display("Roof Option Selection",
                                                                                   $"Selecting a roof option allows Fair Squares to determine what roofs you would like measured at the submitted address.{Environment.NewLine}" +
                                                                                   $"{Environment.NewLine}Primary Only- Fair Squares will measure the primary structure, including attached garage.{Environment.NewLine}" +
                                                                                   $"Detached Garage- Fair Squares will also measure the detached garage on the property.{Environment.NewLine}" +
                                                                                   $"Shed/Barn- Fair Squares will also measure a shed or barn on the property.{Environment.NewLine}" +
                                                                                   $"{Environment.NewLine}NOTE: Fair Squares only supports measuring one primary structure per report (with a detached garage or shed/barn if needed).",
                                                                                   "Ok"));
            ErrorMessageRowHeight = 0;
            SelectedOptionIndex   = -1;
            SelectedStateIndex    = -1;
#pragma warning disable CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
            SetVisualStateForValidation();
#pragma warning restore CS4014 // Because this call is not awaited, execution of the current method continues before the call is completed
        }
        private void HandleUpdatesForTestStations(ProgressResponse response, string[] stationIds)
        {
            MainThreadUtility.InvokeOnMain(() =>
            {
                if (response != null)
                {
                    DataCache.AddCommandProgress(new CommandProgress(CommandType.TestStations, response.Body, stationIds));

                    if (response.IsFinal)
                    {
                        Action resetStations = () =>
                        {
                            foreach (string id in stationIds)
                            {
                                var station = this.Device?.Device?.Stations.Values.Where((d) => d.Id == id).FirstOrDefault();
                                if (station != null)
                                {
                                    station.Selected = false;
                                    station.Starting = false;
                                }
                            }
                        };

                        if (response.IsSuccessful)
                        {
                            //AlertUtility.ShowAlert("Testing Stations", "Testing Stations");
                            this.RegisterForAsyncUpdate(resetStations, 5000);
                        }
                        else
                        {
                            this.RegisterForAsyncUpdate(resetStations);

                            if ((bool)!response?.IsReconnectResponse && (bool)!response?.IsServerDownResponse)
                            {
                                AlertUtility.ShowAppError(response?.ErrorBody);
                            }
                        }

                        DataCache.TriggerDeviceUpdate(this.DeviceId);

                        int countSelected = Device.Stations.Where((s) => s.Selected).Count();
                        this._buttonFooterView.PermaDisabled = false;
                        this.ShowHideButtonFooter(countSelected);
                        this._selectionHeaderView.Enabled = true;

                        /*
                         *                      this.LoadData();
                         */
                    }
                }
            });
        }
        private void HandleUpdatesForStartCircuits(ProgressResponse response, string[] circuitIds, int durationMinutes)
        {
            MainThreadUtility.InvokeOnMain(() =>
            {
                if (response != null)
                {
                    DataCache.AddCommandProgress(new CommandProgress(CommandType.StartCircuits, response.Body, circuitIds));

                    if (response.IsFinal)
                    {
                        Action resetCircuits = () =>
                        {
                            foreach (string id in circuitIds)
                            {
                                var circuit = this.Device?.Device?.Circuits.Values.Where((d) => d.Id == id).FirstOrDefault();
                                if (circuit != null)
                                {
                                    circuit.Selected = false;
                                    circuit.Starting = false;
                                }
                            }
                        };

                        if (response.IsSuccessful)
                        {
                            //AlertUtility.ShowAlert("Start Circuits", "Start Circuits");
                            this.RegisterForAsyncUpdate(resetCircuits, 5000);
                        }
                        else
                        {
                            this.RegisterForAsyncUpdate(resetCircuits);

                            if ((bool)!response?.IsReconnectResponse && (bool)!response?.IsServerDownResponse)
                            {
                                AlertUtility.ShowAppError(response?.ErrorBody);
                            }
                        }

                        DataCache.TriggerDeviceUpdate(this.DeviceId);

                        int countSelected = Device.Circuits.Where((s) => s.Selected).Count();
                        this._buttonFooterView.PermaDisabled = false;
                        this.ShowHideButtonFooter(countSelected > 0);
                        this._selectionHeaderView.Enabled = true;
                    }
                }

                AlertUtility.ShowProgressResponse("Start Circuits", response);
            });
        }
        public FeedbackViewModel(INotificationService notifier,
                                 ICurrentUserService userCache,
                                 AlertUtility alertUtility,
                                 IPageFactory pageFactory,
                                 ILogger <FeedbackViewModel> logger,
                                 MainThreadNavigator nav)
        {
            _notifier     = notifier;
            _pageFactory  = pageFactory;
            _userCache    = userCache;
            _nav          = nav;
            _logger       = logger;
            _alertUtility = alertUtility;

            SubmitCommand = new Command(async() => await SubmitFeedback(_feedbackEntry));
        }
        private void WaterSelectedStations(IEnumerable <PumpViewModel> pumps, int durationMinutes)
        {
            ExceptionUtility.Try(() =>
            {
                IEnumerable <string> stationNames, stationNumbers;
                this.GetSelectedStationsList(out stationNames, out stationNumbers);

                AlertUtility.ShowConfirmationAlert(StringLiterals.StartStationConfirmationTitle, StringLiterals.FormatStartStationConfirmationMessage(stationNames, stationNumbers), (b) =>
                {
                    if (b)
                    {
                        this.WaterSelectedStationsConfirmed(pumps, durationMinutes);
                    }
                }, okButtonText: StringLiterals.StartButtonText);
            });
        }
        private void ShowEmail()
        {
            ExceptionUtility.Try(() =>
            {
                #if DEBUG
                string recipients = "*****@*****.**";
                #else
                string recipients = AppSettings.GetAppSettingValue <string>(AppSettings.LogEmailRecipientsAppSettingName, "*****@*****.**");
                #endif

                if (MFMailComposeViewController.CanSendMail)
                {
                    LogUtility.LogMessage("Preparing to send diagnostic email to " + recipients, LogSeverity.Info);
                    MFMailComposeViewController mailVc = new MFMailComposeViewController();
                    mailVc.SetToRecipients(new string[] { recipients });

                    string subject = StringLiterals.SupportRequestSubject;
                    //if (User.Current != null)
                    //    subject += " " + User.Current.Username;

                    mailVc.SetSubject(subject);

                    string message = StringLiterals.EmailText + this.GetDeviceInfoAsString();

                    mailVc.SetMessageBody(message, false);

                    mailVc.Finished += (object s, MFComposeResultEventArgs args) =>
                    {
                        LogUtility.LogMessage("Diagnostic email sent to " + recipients, LogSeverity.Info);
                        System.Diagnostics.Debug.WriteLine(args.Result.ToString());
                        args.Controller.DismissViewController(true, null);
                    };

                    string logData = LogUtility.GetLogData();
                    mailVc.AddAttachmentData(NSData.FromString(logData), "text/plain", "logfile.txt");

                    this.NavigationController.PresentViewController(mailVc, true, () => { });
                }
                else
                {
                    AlertUtility.ShowAlert(
                        StringLiterals.NoMailSupportAlertTitle,
                        String.Format(StringLiterals.NoMailSupportAlertMessage, recipients)
                        );
                }
            });
        }
        private void TestSelectedStations()
        {
            ExceptionUtility.Try(() =>
            {
                IEnumerable <string> stationNames, stationNumbers;
                this.GetSelectedStationsList(out stationNames, out stationNumbers);
                //var selectedStationIds = this.Device.Stations.Where((s) => s.Selected).Select((s) => s.Id);

                AlertUtility.ShowConfirmationAlert(StringLiterals.TestStationConfirmationTitle, StringLiterals.FormatTestStationConfirmationMessage(stationNames, stationNumbers), (b) =>
                {
                    if (b)
                    {
                        this.TestSelectedStationsConfirmed();
                    }
                }, okButtonText: StringLiterals.TestButtonText);
            });
        }
Beispiel #15
0
 private void PrevButtonClicked()
 {
     ExceptionUtility.Try(() =>
     {
         LogUtility.LogMessage("User clicked PREV button (footer).");
         string deviceId = this.Device?.Id;
         if (!String.IsNullOrEmpty(deviceId))
         {
             AlertUtility.ShowConfirmationAlert(this._prevFeature.ProgressText, _prevFeature.PromptText, (b) =>
             {
                 if (b)
                 {
                     this.PrevConfirmed();
                 }
             }, okButtonText: _prevFeature.PromptConfirm, cancelButtonText: _prevFeature.PromptCancel);
         }
     });
 }
        private void HandleUpdatesForStartStations(ProgressResponse response, IEnumerable <PumpViewModel> pumps, int durationMinutes, string[] stationIds)
        {
            MainThreadUtility.InvokeOnMain(() =>
            {
                if (response != null)
                {
                    DataCache.AddCommandProgress(new CommandProgress(CommandType.StartStations, response.Body, stationIds));

                    if (response.IsFinal)
                    {
                        Action resetStations = () =>
                        {
                            foreach (string id in stationIds)
                            {
                                var station = this.Device?.Device?.Stations.Values.Where((d) => d.Id == id).FirstOrDefault();
                                if (station != null)
                                {
                                    station.Selected = false;
                                    station.Starting = false;
                                }
                            }
                        };

                        if (response.IsSuccessful)
                        {
                            //AlertUtility.ShowAlert("Starting Stations", "Starting Stations");
                            this.RegisterForAsyncUpdate(resetStations, 5000);
                        }
                        else
                        {
                            this.RegisterForAsyncUpdate(resetStations);

                            if ((bool)!response?.IsReconnectResponse && (bool)!response?.IsServerDownResponse)
                            {
                                AlertUtility.ShowAppError(response?.ErrorBody);
                            }
                        }

                        DataCache.TriggerDeviceUpdate(this.DeviceId);
                    }
                }
            });
        }
 public void SetUp()
 {
     _notifier    = new Mock <INotificationService>();
     _userCache   = new Mock <ICurrentUserService>();
     _nav         = new Mock <INavigation>();
     _alert       = new AlertUtility((s1, s2, s3, s4) => Task.FromResult(false), (s1, s2, s3) => Task.Delay(0));
     _logger      = new Mock <MobileClient.Utilities.ILogger <FeedbackViewModel> >();
     _pageFactory = new Mock <IPageFactory>();
     _notifier.Setup(x => x.Notify(It.Is <NotificationRequest>(y => y.From == "*****@*****.**" &&
                                                               y.To == "*****@*****.**" &&
                                                               y.MessageType == MessageType.Email)));
     _userCache.Setup(x => x.GetLoggedInAccount()).Returns(new AccountModel()
     {
         Email  = "*****@*****.**",
         UserId = "1234"
     });
     _nav.Setup(x => x.PopAsync()).ReturnsAsync(null as Page);
     _mnNav = new MainThreadNavigator(x => x(), _nav.Object);
 }
 public void SetUp()
 {
     _alertService    = new Mock <IToastService>();
     _purchaseService = new Mock <IPurchasingService>();
     _subCache        = new Mock <ICache <SubscriptionModel> >();
     _subService      = new Mock <ISubscriptionService>();
     _userCache       = new Mock <ICurrentUserService>();
     _nav             = new Mock <INavigation>();
     _mnNav           = new MainThreadNavigator(x => x(), _nav.Object);
     _validationModel = new ValidationModel()
     {
         RemainingOrders = 0,
         State           = ValidationState.FreeReportValid
     };
     _runtimePlatform  = Device.Android;
     _navigateFromMenu = new Action <BaseNavPageType>(x => CurrentTab = x);
     _alertUtil        = new AlertUtility((s1, s2, s3, s4) => Task.FromResult(false), (s1, s2, s3) => Task.Delay(0));
     _openUri          = new Action <Uri>(x => OpenedUri = x);
 }
Beispiel #19
0
        protected virtual void OnAuthFailure()
        {
            ExceptionUtility.Try(() =>
            {
                if (this.IsShowing)
                {
                    //cancel reconnecting
                    ConnectionManager.CancelReconnecting();

                    //clear cache
                    Caches.ClearCachesForAuthFailure();

                    MainThreadUtility.InvokeOnMain(() => {
                        //show alert
                        ProgressUtility.Dismiss();
                        AlertUtility.ShowAlert(StringLiterals.AuthFailure, StringLiterals.AuthFailureMessage);

                        //nav to login screen
                        this.NavigateUserConfig();
                    });
                }
            });
        }
 private void StartButton_TouchUpInside(object sender, EventArgs e)
 {
     ExceptionUtility.Try(() =>
     {
         string title = _startPivot ? StringLiterals.StartStationConfirmationTitle : StringLiterals.StopProgramConfirmationTitle;
         AlertUtility.ShowConfirmationAlert(title, StringLiterals.FormatStartStopProgramConfirmationMessage(_startPivot, _programStart.Name, _programStart.Id), (b) =>
         {
             if (b)
             {
                 StopStartProgramConfirmed(_programStart, _startPivot);
             }
             else
             {
                 var cell = this.GetCell(_programStart) as ProgramListTableViewCell;
                 if (cell != null)
                 {
                     _programStart.Starting = false;
                     cell.LoadCellValues(_programStart);
                 }
             }
         }, okButtonText: _startPivot?StringLiterals.Start: StringLiterals.Stop);
     });
 }
Beispiel #21
0
 private void StopStartProgram(ProgramViewModel program, bool start)
 {
     ExceptionUtility.Try(() =>
     {
         string title = start ? StringLiterals.StartStationConfirmationTitle : StringLiterals.StopProgramConfirmationTitle;
         AlertUtility.ShowConfirmationAlert(title, StringLiterals.FormatStartStopProgramConfirmationMessage(start, program.Name, program.Id), (b) =>
         {
             if (b)
             {
                 StopStartProgramConfirmed(program, start);
             }
             else
             {
                 var cell = this._tableViewController.GetCell(program) as ProgramListTableViewCell;
                 if (cell != null)
                 {
                     program.Starting = false;
                     cell.LoadCellValues(program);
                 }
             }
         }, okButtonText: start?StringLiterals.Start: StringLiterals.Stop);
     });
 }
 private void ShowError(string errorMsg)
 {
     AlertUtility.ShowAlert(StringLiterals.Error, errorMsg);
 }
        private async void SubmitForm()
        {
            try
            {
                _connectingManually = true;

                if (this._navBarView.DoneButtonEnabled)
                {
                    //var oldUsername = User.Current?.Username;
                    //var oldPassword = User.Current?.Password;
                    //var oldServerUri = User.Current?.ServerUri;

                    var username  = this._tableViewController.Username;
                    var password  = this._tableViewController.Password;
                    var serverUri = this._tableViewController.ServerUri;

                    //set default if no server uri provided
                    if (String.IsNullOrEmpty(serverUri))
                    {
                        serverUri = AppSettings.GetAppSettingValue(AppSettings.DefaultAppServerUriAppSettingName, String.Empty);
                        this._tableViewController.ServerUri = serverUri;
                    }

                    //translate server alias to a uri
                    serverUri = ServerAliases.AliasToUri(serverUri);

                    bool newUser   = false;
                    bool newServer = false;

                    if (User.Current == null)
                    {
                        User.Current = new User();
                    }
                    else
                    {
                        //check if current user is different from prev user
                        newUser   = ((User.Current.Username != null) && User.Current.Username.Trim().ToLower() != username.Trim().ToLower());
                        newServer = ((User.Current.ServerUri != null) && User.Current.ServerUri.Trim().ToLower() != serverUri.Trim().ToLower());
                    }

                    if (newServer || newUser)
                    {
                        await this.LogoutInternal();
                    }

                    User.Current.Username  = username;
                    User.Current.Password  = password;
                    User.Current.ServerUri = serverUri;

                    if (User.Current != null)
                    {
                        await ProgressUtility.SafeShow("Connecting to Server", async() =>
                        {
                            //if reconnect process is running, cancel it
                            if (ConnectionManager.IsReconnecting)
                            {
                                await ConnectionManager.CancelReconnecting();
                            }

                            //here, if we are voluntarily connecting to a new server or new user, we must suppress the automatic reconnect attempt on closing connection
                            if (newUser || newServer)
                            {
                                ConnectionManager.Deinitialize();
                            }

                            WebSocketsClient.ResetWebSocketsClientUrl(new WebSocketsClientIos(), serverUri);
                            ConnectionManager.Initialize();

                            var deviceListVc = DeviceListViewController.CreateInstance();

                            //test connection
                            var response = await ServiceContainer.UserService.RequestConnection(username, password);
                            ProgressUtility.Dismiss();

                            this.ShowError(response);

                            if (response != null && response.IsSuccessful)
                            {
                                //only save the changes after successful login
                                //User.Current.Save();

                                //this.NavigateTo(deviceListVc, inCurrentNavController: false);
                                //PresentViewController(new AquamonixNavController(deviceListVc), true, null);
                                LogUtility.Enabled = true;
                            }
                            else
                            {
                                if (response?.ErrorBody != null && response.ErrorBody.ErrorType == ErrorResponseType.ConnectionTimeout)
                                {
                                    if (DataCache.HasDevices)
                                    {
                                        deviceListVc.ShowConnectionError = true;
                                        this.NavigateTo(deviceListVc, inCurrentNavController: false);
                                    }
                                    else
                                    {
                                        AlertUtility.ShowErrorAlert(StringLiterals.ConnectionError, StringLiterals.UnableToEstablishConnection);
                                        ConnectionManager.CancelReconnecting();
                                    }
                                }
                                // Edited //
                                if (response?.ErrorBody != null && response.ErrorBody.ErrorType == ErrorResponseType.AuthFailure)
                                {
                                    AlertUtility.ShowErrorAlert(StringLiterals.ConnectionError, StringLiterals.AuthFailureMessage);
                                    Caches.ClearCachesForAuthFailure();
                                }

                                this.LoadData();
                            }
                        });
                    }
                }
            }
            catch (Exception e)
            {
                LogUtility.LogException(e);
            }
        }
Beispiel #24
0
        /// <summary>
        /// The most important method of this class; makes a server call and then asynchronously waits for the response.
        /// </summary>
        /// <param name="request">The request object</param>
        /// <param name="onConnectionResume">Action to execute if the connection is broken, then resumed, during execution of this call.</param>
        /// <param name="silentMode">If true, will not display any popups or alerts for any reason.</param>
        /// <returns>Task result with the response</returns>
        public async Task <TResponse> DoRequestAsync <TRequest, TResponse>(TRequest request, Action onConnectionResume, bool silentMode = false)
            where TRequest : IApiRequest
            where TResponse : IApiResponse, new()
        {
            TResponse response = default(TResponse);

            try
            {
                bool cancelRequest = false;
                //is connection closed?
                if (_client.ReadyState == ReadyState.Closed || _client.ReadyState == ReadyState.Closing)
                {
                    if (!(request is Aquamonix.Mobile.Lib.Domain.Requests.ConnectionRequest))
                    {
                        this.FireRequestFailureEvent(request, null, RequestFailureReason.Network, onConnectionResume, (!silentMode));
                        cancelRequest = true;
                    }
                    else
                    {
                        _client.Dispose();
                        this.SetUrl(_url);
                    }
                }


                if (!cancelRequest)
                {
                    //attempt to open connection if not already
                    if (_client.ReadyState != ReadyState.Open)
                    {
                        bool opened = await this.Open(request.Header.Channel, silentMode);

                        if (!opened)
                        {
                            //if not a connection request, we want to fire an event
                            if (!(request is Aquamonix.Mobile.Lib.Domain.Requests.ConnectionRequest))
                            {
                                //fire the event
                                this.FireRequestFailureEvent(request, null, RequestFailureReason.Network, onConnectionResume, !(silentMode));
                            }

                            return(ResponseFactory.FabricateConnectionTimeoutResponse <TResponse>(request));
                        }
                        //NEW: this 'else' clause is new
                        else
                        {
                            //if not a connection request, then we want to make a connection request now
                            if (!(request is Aquamonix.Mobile.Lib.Domain.Requests.ConnectionRequest))
                            {
                                // make a request connection, if it fails it doesnt matter as it will be picked up below
                                await ServiceContainer.UserService.RequestConnection(
                                    User.Current.Username,
                                    User.Current.Password,
                                    silentMode : true
                                    );
                            }
                        }
                    }

                    //send the request and wait for response
                    response = await this.Send <TResponse>(request, request.Header.Channel, silentMode);

                    //if response is null or unsuccessful, handle
                    if (response == null || !response.IsSuccessful)
                    {
                        if (response != null && response.IsReconnectResponse)
                        {
                            LogUtility.LogMessage("Received a Reconnect response from server; will reconnect");
                            this.FireRequestFailureEvent(request, response, RequestFailureReason.ServerRequestedReconnect, onConnectionResume, (!silentMode));
                        }
                        else
                        {
                            //if response is a timeout, handle
                            if (response != null && response.IsTimeout)
                            {
                                this.FireRequestFailureEvent(request, response, RequestFailureReason.Timeout, onConnectionResume, (!silentMode));
                            }
                            else
                            {
                                if (response != null)
                                {
                                    //if server is down, handle
                                    if (response.IsServerDownResponse)
                                    {
                                        this.FireRequestFailureEvent(request, response, RequestFailureReason.ServerDown, onConnectionResume, (!silentMode));
                                    }
                                    else if (response.IsAuthFailure)
                                    {
                                        this.FireRequestFailureEvent(request, response, RequestFailureReason.Auth, onConnectionResume, (!silentMode));
                                    }
                                    else
                                    {
                                        this.FireRequestFailureEvent(request, response, RequestFailureReason.Error, onConnectionResume, (!silentMode));

                                        //show error
                                        AlertUtility.ShowAppError(response?.ErrorBody);
                                    }
                                }
                                else
                                {
                                    this.FireRequestSucceededEvent(request, response);
                                }
                            }
                        }
                    }
                    else
                    {
                        this.FireRequestSucceededEvent(request, response);
                    }
                }
            }
            catch (Exception e)
            {
                LogUtility.LogException(e);
            }

            return(response);
        }
Beispiel #25
0
        //edited
        private void DismissAlertsConfirmed()
        {
            ExceptionUtility.Try(() =>
            {
                if (this.HasAccessLevelToDelete())
                {
                    if (String.IsNullOrEmpty(_searchBoxView.Text))
                    {
                        //var activeAlertIds = this.GetActiveAlertIds();
                        var activeAlerts = GetActiveAlert();
                        //check all the active alers have correct access with device
                        var deletingAlertsIds = CheckAlertDeletePermission(activeAlerts);

                        if (deletingAlertsIds.Count < activeAlerts.Count())
                        {
                            AlertUtility.ShowConfirmationAlert(StringLiterals.Alert, StringLiterals.ActiveAlertsNotAccessForDissmiss(), (b) =>
                            {
                                if (b)
                                {
                                    ServiceContainer.AlertService.DismissGlobalAlerts(deletingAlertsIds, onReconnect: () => { DismissAlertsConfirmed(); }).ContinueWith((r) =>
                                    {
                                        MainThreadUtility.InvokeOnMain(() =>
                                        {
                                            ProgressUtility.Dismiss();
                                        });
                                    });
                                }
                            }, StringLiterals.Dismiss);
                        }
                        else
                        {
                            ServiceContainer.AlertService.DismissGlobalAlerts(deletingAlertsIds, onReconnect: () => { DismissAlertsConfirmed(); }).ContinueWith((r) =>
                            {
                                MainThreadUtility.InvokeOnMain(() =>
                                {
                                    ProgressUtility.Dismiss();
                                });
                            });
                        }
                    }
                    else
                    {
                        //var activeAlertIds = this.GetActiveAlertIds();
                        var activeAlerts = GetActiveAlertsFromSearchList();
                        //check all the active alers have correct access with device
                        var deletingAlertsIds = CheckAlertDeletePermission(activeAlerts);

                        if (deletingAlertsIds.Count < activeAlerts.Count())
                        {
                            AlertUtility.ShowConfirmationAlert(StringLiterals.Alert, StringLiterals.ActiveAlertsNotAccessForDissmiss(), (b) =>
                            {
                                if (b)
                                {
                                    ServiceContainer.AlertService.DismissGlobalAlerts(deletingAlertsIds, onReconnect: () => { DismissAlertsConfirmed(); }).ContinueWith((r) =>
                                    {
                                        MainThreadUtility.InvokeOnMain(() =>
                                        {
                                            ProgressUtility.Dismiss();
                                        });
                                    });
                                }
                            }, StringLiterals.Dismiss);
                        }
                        else
                        {
                            ServiceContainer.AlertService.DismissGlobalAlerts(deletingAlertsIds, onReconnect: () => { DismissAlertsConfirmed(); }).ContinueWith((r) =>
                            {
                                MainThreadUtility.InvokeOnMain(() =>
                                {
                                    ProgressUtility.Dismiss();
                                });
                            });
                        }
                    }
                }
            });
        }
Beispiel #26
0
 public VehicleController(ILogger <VehicleController> logger, IRepositoryWrapper repositoryWrapper)
 {
     _logger    = logger;
     repository = repositoryWrapper;
     alertU     = new AlertUtility(repositoryWrapper);
 }