Exemplo n.º 1
0
        /// <summary>
        /// Executes a service request, and returns the response.
        /// </summary>
        /// <param name="request">Encapsulates the request to send.</param>
        /// <param name="withCaching">Specifies whether or not to allow service-level caching for this call</param>
        /// <param name="onReconnect">What to do if the connection is broken, then resumed</param>
        /// <param name="silentMode">If true, will not display any alerts or popups</param>
        /// <returns>The server response</returns>
        protected async Task <TResponse> DoRequest <TRequest, TResponse>(TRequest request, bool withCaching = false, Action onReconnect = null, bool silentMode = false)
            where TRequest : IApiRequest
            where TResponse : IApiResponse, new()
        {
            bool fromCache = false;

            var response = withCaching ? this.GetFromCache(request) : null;

            if (response == null || !(response is TResponse))
            {
                response = await WebSocketsClient.DoRequestAsync <TRequest, TResponse>(request, onReconnect, silentMode : silentMode);
            }
            else
            {
                fromCache = true;
            }

            if (response?.Header?.ServerVersion != null)
            {
                _lastServerVersion = ServerVersion.Parse(response.Header.ServerVersion);
            }

            if (fromCache)
            {
                LogUtility.LogMessage("Response for service request " + request?.Header?.Type + " returned from cache [Channel : " + request?.Header?.Channel + "].");
            }

            if (!fromCache && withCaching)
            {
                LogUtility.LogMessage("Caching response for service request " + request?.Header?.Type + " [Channel : " + request?.Header?.Channel + "].");
                this.CacheResponse(request, response);
            }

            return((TResponse)response);
        }
Exemplo n.º 2
0
        private void RetryConnection()
        {
            ProgressUtility.SafeShow("Connecting", () =>
            {
                WebSocketsClient.ResetWebSocketsClientUrl(new WebSocketsClientIos(), User.Current.ServerUri);
                ConnectionManager.Initialize();

                ServiceContainer.UserService.RequestConnection(User.Current.Username, User.Current.Password).ContinueWith((r) =>
                {
                    MainThreadUtility.InvokeOnMain(() =>
                    {
                        ProgressUtility.Dismiss();

                        if (r.Result != null && r.Result.IsSuccessful)
                        {
                            this.NavigateHome();
                        }
                        //else {
                        //	if (r.Result.HasError)
                        //		AlertUtility.ShowAppError(r.Result?.ErrorBody);
                        //}
                    });
                });
            }, true);
        }
        public IWebSocketsClient CreateClient(WebSocket webSocket, string client)
        {
            var socketsClient = new WebSocketsClient(webSocket, client, _jsonSerializer);

            _clients.TryAdd(socketsClient.Id, socketsClient);

            return(socketsClient);
        }
Exemplo n.º 4
0
        public async Task <ConnectionResponse> RequestConnection(string username, string password, bool silentMode = false)
        {
            try
            {
                string timestamp = null;
                if (DataCache.ApplicationMetadata?.TimeStamp != null)
                {
                    timestamp = DataCache.ApplicationMetadata.TimeStamp.ToString();
                }

                //TODO: how to determine the value of the app version
                var request = new ConnectionRequest(username, password, "1", timestamp: timestamp, sessionId: User.Current?.SessionId);

                var output = await WebSocketsClient.DoRequestAsync <ConnectionRequest, ConnectionResponse>(request, silentMode : silentMode);

                ServiceContainer.InvalidateCache();
                if (output != null && output.Body != null)
                {
                    if (User.Current != null)
                    {
                        User.Current.SessionId = output.Body.SessionId;

                        if (output.Body.Devices != null)
                        {
                            if (output.Body.MetaData != null)
                            {
                                DataCache.ApplicationMetadata = output.Body.MetaData;
                            }

                            if (output.Body.User?.Name != null)
                            {
                                User.Current.Name = output.Body.User?.Name;
                            }

                            if (output.Body.User?.DevicesAccess != null)
                            {
                                User.Current.DevicesAccess = output.Body.User?.DevicesAccess;
                            }

                            DataCache.SetDeviceOrder(output.Body?.Devices?.Keys?.ToList());
                            DataCache.CacheDevicesResponse(output.Body?.Devices?.Items);
                            DataCache.SetActiveAlertsCount(output.Body?.AlertsCount);
                            DataCache.SyncCommandProgresses(output.Body?.CommandProgresses);
                        }

                        User.Current.Save();
                    }
                }

                return(output);
            }
            catch (Exception e)
            {
                LogUtility.LogException(e);
            }

            return(null);
        }
Exemplo n.º 5
0
        /// <summary>
        /// Registers a callback to receive updates when ProgressResponse updates are received for a specific async command.
        /// </summary>
        /// <param name="response">The first ProgressResponse received; we're saying that we want further updates related to
        /// this response.</param>
        /// <param name="callback">The callback to call when udpates are received</param>
        protected void RegisterForProgressUpdates(ProgressResponse response, Action <ProgressResponse> callback)
        {
            if (response != null && callback != null)
            {
                if (response.IsFinal)
                {
                    callback(response);
                }
                else
                {
                    if (response.CommandId != null)
                    {
                        Action <ProgressResponse> superCallback = (p) =>
                        {
                            ServiceContainer.InvalidateCache();
                            callback(p);
                        };

                        WebSocketsClient.RegisterForProgressUpdates(response.CommandId, superCallback);
                    }
                }
            }
        }
Exemplo n.º 6
0
        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);
            }
        }
Exemplo n.º 7
0
        public override bool FinishedLaunching(UIApplication application, NSDictionary launchOptions)
        {
            // Override point for customization after application launch.
            // If not required for your application you can safely delete this method

#if INCLUDE_HOCKEYAPP
            Configure HockeyApp for crash reporting
            var manager = BITHockeyManager.SharedHockeyManager;
            manager.Configure(HockeyAppIdentifier);
            manager.StartManager();
            manager.Authenticator.AuthenticateInstallation();
#endif

            // Code to start the Xamarin Test Cloud Agent
#if ENABLE_TEST_CLOUD
            Xamarin.Calabash.Start();
#endif

            //User.Initialize();

            LogUtility.StartLogging();
            LogUtility.LogMessage("Starting app", LogSeverity.Info);

            //UIApplication.SharedApplication.Windows[0].RootViewController = new Aquamonix.Mobile.IOS.ViewControllers.StartViewController();

            DataCache.Initialize();
            UserCache.Initialize();

            if (User.Current != null && !String.IsNullOrEmpty(User.Current.ServerUri))
            {
                WebSocketsClient.ResetWebSocketsClientUrl(new WebSocketsClientIos(), User.Current.ServerUri);
                ConnectionManager.Initialize();
            }

            MainThreadUtility.Instance.SetMainThread(
                Thread.CurrentThread,
                action1 => InvokeOnMainThread(new Action(action1)),
                action2 => BeginInvokeOnMainThread(new Action(action2))
                );



            LogUtility.LogMessage(String.Format("Screen bounds {0} x {1} (h x w)", UIKit.UIScreen.MainScreen.NativeBounds.Size.Height, UIKit.UIScreen.MainScreen.NativeBounds.Size.Width), LogSeverity.Info);

            if (UIApplication.SharedApplication.KeyWindow != null)
            {
                double top    = 0;
                double bottom = 0;
                if (UIDevice.CurrentDevice.CheckSystemVersion(11, 0))
                {
                    top    = UIApplication.SharedApplication.KeyWindow.SafeAreaInsets.Top;
                    bottom = UIApplication.SharedApplication.KeyWindow.SafeAreaInsets.Bottom;
                }

                LogUtility.LogMessage(String.Format("KeyWindow SafeAreaInsets {0},{1} (top,bottom)", top, bottom), LogSeverity.Info);
            }

            //var window = new UIWindow(UIScreen.MainScreen.Bounds);
            //var navController = new Aquamonix.Mobile.IOS.ViewControllers.AquamonixNavController(new ViewControllers.StartViewController());
            //window.RootViewController = navController;
            //window.MakeKeyAndVisible();

#if DETECT_SLEEP_CONDITION
            CFNotificationCenter.Darwin.AddObserver(
                name: SleepNotificationName,
                objectToObserve: null,
                notificationHandler: (name, userInfo) =>
            {
                ExceptionUtility.Try(() =>
                {
                    // this check should really only be necessary if you reuse this one callback method
                    // for multiple Darwin notification events
                    if (name.Equals(SleepNotificationName, StringComparison.Ordinal))
                    {
                        Console.WriteLine("screen has either gone dark, or been turned back on!");
                    }
                });
            },
                suspensionBehavior: CFNotificationSuspensionBehavior.DeliverImmediately);
#endif

            return(true);
        }
Exemplo n.º 8
0
        public async Task LogOut()
        {
            await WebSocketsClient.Disconnect();

            Caches.ClearCachesForLogout();
        }