Example #1
0
        private async Task LoadProjectsAsync()
        {
            if (_isLoading)
            {
                return;
            }

            try
            {
                _isLoading = true;
                _projectsDataSource.Clear();
                _projectsAdapter.NotifyDataSetChanged();

                _progressBar.Visibility = ViewStates.Visible;

                var authContext       = new AuthenticationContext(Constants.HyprsoftAzureActiveDirectoryUrl);
                var clientCredentials = new ClientCredential(Constants.MobileServiceClientId, Constants.MobileServiceClientSecret);
                var authResult        = await authContext.AcquireTokenAsync(Constants.MobileServiceUrl, clientCredentials);

                _mobileServiceClient?.Dispose();
                _mobileServiceClient = new MobileServiceClient(Constants.MobileServiceUrl);
                await _mobileServiceClient.LoginAsync(MobileServiceAuthenticationProvider.WindowsAzureActiveDirectory, new JObject(new JProperty("access_token", authResult.AccessToken)));

                var table = _mobileServiceClient.GetTable <Project>();
                _projectsDataSource.AddRange(await table.OrderBy(p => p.CreatedAt).ToListAsync());

                var hubConnection = new HubConnection(Constants.MobileServiceUrl);
                hubConnection.Headers.Add("X-ZUMO-AUTH", _mobileServiceClient.CurrentUser.MobileServiceAuthenticationToken);
                _hubProxy = hubConnection.CreateHubProxy("ProjectsHub");
                _hubProxy.On <Project>("projectAdded", (project) => RunOnUiThread(() =>
                {
                    _projectsDataSource.Add(project);
                    _projectsAdapter.NotifyDataSetChanged();
                }));
                _hubProxy.On <string>("projectRemoved", (id) => RunOnUiThread(() =>
                {
                    var project = _projectsDataSource.SingleOrDefault(p => p.Id == id);
                    if (project != null)
                    {
                        _projectsDataSource.Remove(project);
                        _projectsAdapter.NotifyDataSetChanged();
                    }
                }));
                await hubConnection.Start();

                _projectsAdapter.NotifyDataSetChanged();
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, $"An unexpected error occurred: {ex.Message}", ToastLength.Long).Show();
            }
            finally
            {
                _progressBar.Visibility = ViewStates.Gone;
                _isLoading = false;
            }
        }