Exemplo n.º 1
0
        /// <summary>
        /// Attempts to log the user in
        /// </summary>
        /// <param name="parameter">The <see cref="SecureString"/> passed in from the view for the users password</param>
        /// <returns></returns>
        public async Task LoginAsync(LoginCredentials loginFields, bool loginIsRunning)
        {
            await Task.Run(async() =>
            {
                var result = await WebRequests.PostAsync <LoginResultApiModel>
                             (
                    "http://localhost:5000/api/auth/login",
                    loginFields
                             );

                if (await result.DisplayErrorIfFailedAsync("Login Failed"))
                {
                    return;
                }

                var userData = result.ServerResponse.User;
                var token    = result.ServerResponse.Token;

                var loginCredentials   = IoC.Mapper.Map <LoginCredentialsDataModel>(userData);
                loginCredentials.Token = token;


                await IoC.ClientDataStore.StoreLoginCredentialsAsync(loginCredentials);
            });
        }
Exemplo n.º 2
0
        public async Task Login(object parameter)
        {
            await RunCommand(() => this.LoginIsRunning, async() =>
            {
                var result = await WebRequests.PostAsync <ApiResponse <LoginResultApiModel> >(
                    "http://localhost:56748/api/login",
                    new LoginCredentialsApiModel
                {
                    UsernameOrEmail = Email,
                    Password        = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                if (result == null || result.ServerResponse == null || !result.ServerResponse.Successful)
                {
                    var message = "Unknown error from server call";

                    if (result?.ServerResponse != null)
                    {
                        message = result.ServerResponse.ErrorMessage;
                    }
                    else if (string.IsNullOrWhiteSpace(result?.RawServerResponse))
                    {
                        message = $"Unexpected response from server. {result.RawServerResponse}";
                    }
                    else if (result != null)
                    {
                        message = $"Falied to communicate with server. Status code{result.StatusCode}. {result.StatusDescription}";
                    }

                    await IoC.UI.ShowMessage(new MessageBoxDialogViewModel
                    {
                        Title   = "Login Failed",
                        Message = message
                    });

                    return;
                }

                var userData = result.ServerResponse.Response;

                IoC.Settings.Name = new TextEntryViewModel {
                    Label = "Name", OriginalText = $"{userData.FirstName} {userData.LastName}"
                };
                IoC.Settings.Username = new TextEntryViewModel {
                    Label = "Username", OriginalText = userData.Username
                };
                IoC.Settings.Password = new PasswordEntryViewModel {
                    Label = "Password", FakePassword = "******"
                };
                IoC.Settings.Email = new TextEntryViewModel {
                    Label = "Email", OriginalText = userData.Email
                };

                // Go to chat page
                IoC.Application.GoToPage(ApplicationPage.Chat);

                //var email = this.Email;
                //var pass = (parameter as IHavePassword).SecurePassword.Unsecure();
            });
        }
        /// <summary>
        /// Loads the enterprise settings from database
        /// </summary>
        /// <returns></returns>
        public async Task LoadEnterPriseSettingsAsync()
        {
            // Lock this command to ignore any other requests while processing
            await RunCommandAsync(() => Loading, async() =>
            {
                ErrorLoading = false;
                ErrorText    = default(string);
                // Get the current known credentials
                var credentials = await ClientDataStore.GetLoginCredentialsAsync();

                var result = await WebRequests.PostAsync <ApiResponse <EnterpriseSettingResultApiModel> >(
                    url: RouteHelpers.GetAbsoluteRoute(ApiRoutes.GetEnterpriseSetting),
                    bearerToken: credentials.Token
                    );


                // If the response has an error...don't mind to continue
                if (await result.HandleErrorIfFailedAsync())
                {
                    ErrorLoading = true;
                    ErrorText    = result.ErrorMessage;
                    return;
                }


                var dataModel = result.ServerResponse.Response;

                CompanyName = dataModel.CompanyName;
            });
        }
        /// <summary>
        /// Save enterprise settings
        /// </summary>
        /// <returns></returns>
        public async Task SaveSettingAsync()
        {
            await RunCommandAsync(() => Saving, async() =>
            {
                if (HasErrors)
                {
                    return;
                }

                var credentials = await ClientDataStore.GetLoginCredentialsAsync();
                var result      = await WebRequests.PostAsync <ApiResponse>(
                    url: RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateEnterpriseSetting),
                    content: new UpdateEnterpriseSettingsApiModel
                {
                    CompanyName = CompanyName
                },
                    bearerToken: credentials.Token
                    );

                // If the response has an error...
                if (await result.HandleErrorIfFailedAsync("Update failed"))
                {
                    // We are done
                    return;
                }
            });
        }
Exemplo n.º 5
0
        /// <summary>
        /// Attempts to log the user in
        /// </summary>
        /// <param name="parameter">The <see cref="SecureString"/> passed in from the view for the users password</param>
        /// <returns></returns>
        public async Task LoginAsync(object parameter)
        {
            await RunCommandAsync(() => LoginIsRunning, async() =>
            {
                // Call the server and attempt to login with credentials
                // TODO: Move all URLs and API routes to static class in core
                var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                    "http://localhost:5000/api/login",
                    new LoginCredentialsApiModel
                {
                    UsernameOrEmail = Email,
                    Password        = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync("Login Failed"))
                {
                    // We are done
                    return;
                }

                // OK successfully logged in... now get users data
                var loginResult = result.ServerResponse.Response;

                // Let the application view model handle what happens
                // with the successful login
                await ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
            });
        }
Exemplo n.º 6
0
        /// <summary>
        /// Attempts to register a new user
        /// </summary>
        /// <param name="parameter"></param>
        /// <returns></returns>
        private async Task RegisterAsync(object parameter)
        {
            await RunCommandAsync(() => this.RegisterIsRunning, async() =>
            {
                // Call the server and attempt to register with credentials
                // TODO: Move all URLs and API routes to static class in core
                var result = await WebRequests.PostAsync <ApiResponse <RegisterResultApiModel> >("https://localhost:44325/api/register",
                                                                                                 new RegisterCredentialsApiModel
                {
                    Username = Username,
                    Email    = Email,
                    //// IMPORTANT: never store unsecure password in variable like this
                    Password = (parameter as IHasPassword).SecurePassword.Unsecure(),
                });

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync("Register Failed"))
                {
                    // We are done
                    return;
                }

                // OK successfully registered (and logged in)... now get users data
                var loginResult = result.ServerResponse.Response;

                // Let the application view model handle what happens
                // with the successful login
                await DI.ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
            });
        }
        /// <summary>
        /// Attempts to register a new user
        /// </summary>
        /// <param name="parameter">The <see cref="SecureString"/> passed in from the view for the users password</param>
        /// <returns></returns>
        public async Task RegisterAsync(object parameter)
        {
            await RunCommandAsync(() => this.RegisterIsRunning, async() =>
            {
                // Call the server and attempt to register with the provided credentials
                // TODO: Move all URLs and API rroutes to static class in core
                var result = await WebRequests.PostAsync <ApiResponse <RegisterResultApiModel> >("https://localhost:5000/api/register",
                                                                                                 new RegisterCredentialsApiModel
                {
                    Username = Username,
                    Email    = Email,
                    Password = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                // If there was no response, bad data, or a response with an error message...
                if (await result.DisplayErrorIfFailedAsync("Register Failed"))
                {
                    return;
                }

                // OK successfully registered and logged in ... now get users data
                var loginResult = result.ServerResponse.Response;

                // Let the application view model handle what happens
                // with the successful login
                await ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
            });
        }
Exemplo n.º 8
0
        /// <summary>
        /// Attempts to register a new user
        /// </summary>
        /// <param name="parameter">The <see cref="SecureString"/>passed in from the view for the users password</param>
        /// <returns></returns>
        public async Task RegisterAsync(object parameter)
        {
            // Call the server and attempt to register with the provided credentials
            var result = await WebRequests.PostAsync <ApiResponse <RegisterResultApiModel> >(
                // Set URL
                RouteHelpers.GetAbsoluteRoute(ApiRoutes.Register),
                // Create api model
                new RegisterCredentialsApiModel
            {
                Username = Username,
                Email    = Email,
                Password = (parameter as IHavePassword).SecurePassword.Unsecure()
            });

            // If the reposne has an error...
            if (await result.DisplayErrorIfFailedAsync("Register failed"))
            {
                //We are done
                return;
            }

            // OK successfully registered (and logged in)... now get users data
            var loginResult = result.ServerResponse.ResponseT;

            // Let the application view model handle what happens
            // With the successful login
            await ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Attempts to log the user in
        /// </summary>
        /// <param name="parameter"> The <see cref="SecureString"/> passed in from the view for the users password </param>
        /// <returns></returns>
        public async Task LoginAsync(object parameter)
        {
            await RunCommandAsync(() => LoginIsRunning, async() =>
            {
                // Call the server and attempt to login with credentials
                // TODO: Move all URLs and API routes to static class in core
                var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.Login),
                    // Create API model
                    new LoginCredentialsApiModel
                {
                    UsernameOrEmail = Email,
                    Password        = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync("Login Failed"))
                {
                    // We are done
                    return;
                }

                // Ok successfully registered (and logged in)... now get users data
                var loginResult = result.ServerResponse.ResponseGeneric;

                // Let the application view model handle what happens
                // with the successful login
                await IoC.Application.HandleSuccessfulLoginAsync(loginResult);

                ////IMPORTANT: Never store unsecure password in variable like this
                //var pass = (parameter as IHavePassword).SecurePassword.Unsecure();
            });
        }
Exemplo n.º 10
0
        /// <summary>
        /// Tries to log the user in by making an API call to our website
        /// </summary>
        /// <param name="email">The user's email</param>
        /// <param name="password">The user's password</param>
        /// <returns>
        ///     In case login fails, the returned string is an error message to display
        ///     Otherwise, null string is returned
        /// </returns>
        public async Task <string> LogInAsync(string email, string password)
        {
            // Prepare user data to send
            var url         = "https://localhost:44306/" + ApiRoutes.LoginRoute; // TODO: Put host in configuration
            var credentials = new LoginCredentialsApiModel
            {
                Email    = email,
                Password = password
            };

            // Make a POST request to the API and catch the response
            var result = await WebRequests.PostAsync <ApiResponse <LoginResultApiModel> >(url, credentials);

            // If response was null
            if (result?.ServerResponse == null)
            {
                return(LocalizationResource.UnableToConnectWithWeb);
            }

            // We got the response, check if we successfully logged in
            if (result.ServerResponse.Successful)
            {
                // User is logged in, store the data in database
                var user = mUserMapper.Map(result.ServerResponse.Response);
                mUserRepository.SaveNewUserData(user);

                // Return no error
                return(null);
            }

            // We got the response, but logging in didnt succeed, return the error
            return(result.ServerResponse.ErrorMessage);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Attempts to log the user in
        /// </summary>
        /// <param name="parameter">The <see cref="SecureString"/> passed in from the view for the users password</param>
        /// <returns></returns>
        public async Task LoginAsync(object parameter)
        {
            await RunCommandAsync(() => LoginIsRunning, async() =>
            {
                // Call the server and attempt to login with credentials
                var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.Login),
                    // Create api model
                    new LoginCredentialsApiModel
                {
                    UsernameOrEmail = Email,
                    Password        = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync("Login Failed"))
                {
                    // We are done
                    return;
                }

                // OK successfully logged in... now get users data
                var loginResult = result.ServerResponse.Response;

                // Let the application view model handle what happens
                // with the successful login
                await CoinFlipper.DI.ViewModelApplication.HandleSuccessfulLoginAsync(loginResult);
            });
        }
Exemplo n.º 12
0
        /// <summary>
        /// Updates a specific value from the client data store for the user profile details
        /// and attempts to update the server tomatch those details.
        /// for example, updating the first name of the user.
        /// </summary>
        /// <param name="displayName"> The display name for logging and display purposes of the property we are updating </param>
        /// <param name="propertyToUpdate"> The property from the <see cref="LoginCredentialsDataModel" to be updated /></param>
        /// <param name="newValue"> The new value to update the property to </param>
        /// <param name="setApiModel"> setes the correct property in the <see cref="UpdateUserProfileApiModel"/> that this property maps to </param>
        /// <returns></returns>
        private async Task <bool> UpdateUserCredentialsValueAsync(string displayName, Expression <Func <LoginCredentialsDataModel, string> > propertyToUpdate, string newValue, Action <UpdateUserProfileApiModel, string> setApiModel)
        {
            // Log it
            IoC.Logger.Log($"Saving {displayName}...", LogLevel.Debug);

            // Get the current known credentials
            var credentials = await IoC.ClientDataStore.GetLoginCredentialsAsync();

            // Get the property to update from the credentials
            var toUpdate = propertyToUpdate.GetPropertyValue(credentials);

            // Log it
            IoC.Logger.Log($"{displayName} currently {toUpdate}, updating to {newValue}", LogLevel.Debug);

            // Check if the value is the same...
            if (toUpdate == newValue)
            {
                // Log it
                IoC.Logger.Log($"{displayName} is the same, ignoring...", LogLevel.Debug);

                return(true);
            }

            // Set the property
            propertyToUpdate.SetPropertyValue(newValue, credentials);

            // Create update details
            var updateApiModel = new UpdateUserProfileApiModel();

            // Ask caller to set appropriate value
            setApiModel(updateApiModel, newValue);

            // Update the server awith the details
            var result = await WebRequests.PostAsync <ApiResponse>(
                // Set URL
                RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateUserProfile),
                // Pass the Api model
                updateApiModel,
                // Pass in user token
                bearerToken : credentials.Token);

            // If the response has an error...
            if (await result.DisplayErrorIfFailedAsync($"Update {displayName}"))
            {
                // Log it
                IoC.Logger.Log($"Failed to update {displayName}. {result.ErrorMessage}", LogLevel.Debug);

                return(false);
            }

            // Log it
            IoC.Logger.Log($"Successfully updated {displayName}. Saving to local database cache...", LogLevel.Debug);

            // Store the new user credentials to the data store
            await IoC.ClientDataStore.SaveLoginCredentialsAsync(credentials);

            // Return successful
            return(true);
        }
Exemplo n.º 13
0
        /// <summary>
        /// Saves the new Password to the server
        /// </summary>
        /// <returns>Returns true if successful, false otherwise</returns>
        public async Task <bool> SavePasswordAsync()
        {
            // Lock this command to ignore any other requests while processing
            return(await RunCommandAsync(() => PasswordIsChanging, async() =>
            {
                // Log it
                Logger.LogDebugSource($"Changing password...");

                // Get the current known credentials
                var credentials = await ClientDataStore.GetLoginCredentialsAsync();

                // Make sure the user has entered the same password
                if (Password.NewPassword.Unsecure() != Password.ConfirmPassword.Unsecure())
                {
                    // Display error
                    await UI.ShowMessage(new MessageBoxDialogViewModel
                    {
                        // TODO: Localize
                        Title = "Password Mismatch",
                        Message = "New password and confirm password must match"
                    });

                    // Return fail
                    return false;
                }

                // Update the server with the new password
                var result = await WebRequests.PostAsync <ApiResponse>(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.UpdateUserPassword),
                    // Create API model
                    new UpdateUserPasswordApiModel
                {
                    CurrentPassword = Password.CurrentPassword.Unsecure(),
                    NewPassword = Password.NewPassword.Unsecure()
                },
                    // Pass in user Token
                    bearerToken: credentials.Token);

                // If the response has an error...
                if (await result.DisplayErrorIfFailedAsync($"Change Password"))
                {
                    // Log it
                    Logger.LogDebugSource($"Failed to change password. {result.ErrorMessage}");

                    // Return false
                    return false;
                }

                // Otherwise, we succeeded...

                // Log it
                Logger.LogDebugSource($"Successfully changed password");

                // Return successful
                return true;
            }));
        }
Exemplo n.º 14
0
        /// <summary>
        /// Sets the settings view model properties based on the data in the client data store
        /// </summary>
        public async Task LoadAsync()
        {
            // Lock this command to ignore any other requests while processing
            await RunCommandAsync(() => SettingsLoading, async() =>
            {
                // Store single transcient instance of client data store
                var scopedClientDataStore = ClientDataStore;

                // Update values from local cache
                await UpdateValuesFromLocalStoreAsync(scopedClientDataStore);

                // Get the user token
                var token = (await scopedClientDataStore.GetLoginCredentialsAsync())?.Token;

                // If we don't have a token (so we are not logged in...)
                if (string.IsNullOrEmpty(token))
                {
                    // Then do nothing more
                    return;
                }
                else
                {
                    ViewModelApplication.LoginDetailsVisible = true;
                }


                return;

                // Load user profile details form server
                var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                    // Set URL
                    RouteHelpers.GetAbsoluteRoute(ApiRoutes.GetUserProfile),
                    // Pass in user Token
                    bearerToken: token);

                // If the response has an error...
                if (await result.HandleErrorIfFailedAsync("Load User Details Failed"))
                {
                    // We are done
                    return;
                }

                // TODO: Should we check if the values are different before saving?

                // Create data model from the response
                var dataModel = result.ServerResponse.Response.ToLoginCredentialsDataModel();

                // Re-add our known token
                dataModel.Token = token;

                // Save the new information in the data store
                await scopedClientDataStore.SaveLoginCredentialsAsync(dataModel);

                // Update values from local cache
                await UpdateValuesFromLocalStoreAsync(scopedClientDataStore);
            });
        }
        /// <summary>
        /// Attempts to log the user in
        /// </summary>
        /// <param name="parameter">The <see cref="SecureString"/> passed in from the view for the users password</param>
        /// <returns></returns>
        public async Task LoginAsync(object parameter)
        {
            await RunCommandAsync(() => LoginIsRunning, async() =>
            {
                // Call the server and attempt to login with credentials
                // TODO: Move all URLs and API routes to static class in core
                var result = await WebRequests.PostAsync <ApiResponse <LoginResultApiModel> >(
                    "http://localhost:5000/api/login",
                    new LoginCredentialsApiModel
                {
                    UsernameOrEmail = Email,
                    Password        = (parameter as IHavePassword).SecurePassword.Unsecure()
                });

                // If there was no response, bad data, or a response with a error message...
                if (result == null || result.ServerResponse == null || !result.ServerResponse.Successful)
                {
                    // Default error message
                    // TODO: Localize strings
                    var message = "Unknown error from server call";

                    // If we got a response from the server...
                    if (result?.ServerResponse != null)
                    {
                        // Set message to servers response
                        message = result.ServerResponse.ErrorMessage;
                    }
                    // If we have a result but deserialize failed...
                    else if (!string.IsNullOrWhiteSpace(result?.RawServerResponse))
                    {
                        // Set error message
                        message = $"Unexpected response from server. {result.RawServerResponse}";
                    }
                    // If we have a result but no server response details at all...
                    else if (result != null)
                    {
                        // Set message to standard HTTP server response details
                        message = $"Failed to communicate with server. Status code {result.StatusCode}. {result.StatusDescription}";
                    }



                    // We are done
                    //return;
                }

                // OK successfully logged in... now get users data
                var userData = result.ServerResponse.Response;

                //IoC.Settings.Name = new TextEntryViewModel { Label = "Name", OriginalText = $"{userData.FirstName} {userData.LastName}" };
                //IoC.Settings.Username = new TextEntryViewModel { Label = "Username", OriginalText = userData.Username };
                //IoC.Settings.Email = new TextEntryViewModel { Label = "Email", OriginalText = userData.Email };


                IoC.Get <ApplicationViewModel>().GoToPage(ApplicationPage.Content);
            });
        }
Exemplo n.º 16
0
        /// <summary>
        /// Sends an API request and collects the data
        /// </summary>
        private async Task GetAPIData()
        {
            // Send an API request
            var apiResult = await WebRequests.PostAsync <APIWeatherResponse>(GetAPIRoute(), CityName);

            // If we got a data back...
            if (apiResult != null && apiResult.Successful && apiResult.ServerResponse != null)
            {
                // Deserialize json to suitable view model
                APIResponse = apiResult.ServerResponse;
            }
        }
Exemplo n.º 17
0
        public async Task RegisterAsync()
        {
            await RunCommandAsync(() => RegisterIsRunning, async() =>
            {
                // Call the server and attempt to register
                // TODO: Move all URLs and API routes to static class in core
                var result = await WebRequests.PostAsync <ApiResponse <RegisterResultApiModel> >(
                    "http://*****:*****@"pack://application:,,,/Images/EmployeeTypes/Doctor.jpg"
                });
            });

            await Task.Delay(2000);

            SuccessMessage = "";
            ErrorMessage   = "";
        }
        /// <summary>
        /// Saves the changes employee properties to the server
        /// </summary>
        /// <returns>Returns true if successful, false otherwise</returns>
        public async Task <bool> UpdateEmployeeDetailAsync()
        {
            // Lock this command to ignore any other requests while processing
            return(await RunCommandAsync(() => DetailIsSaving, async() =>
            {
                // Get the current known credentials
                var credentials = IoC.Settings;

                var passwordToSave = Password.NewPassword.UnSecure();

                // Update the server with the details
                var result = await WebRequests.PostAsync <ApiResponse <UpdateEmployeeDto> >(
                    // TODO: Move URLs into better place
                    "http://localhost:5000/api/auth/update",
                    new UpdateEmployeeDto
                {
                    FirstName = credentials.FirstName.OriginalText,
                    LastName = credentials.LastName.OriginalText,
                    Username = credentials.Identify.OriginalText,
                    Type = credentials.Type.OriginalText,
                    Specialize = credentials.Specialize.OriginalText,
                    PwzNumber = credentials.PwdNumber.OriginalText,
                    Password = passwordToSave
                }, bearerToken: credentials.Token);

                // If the response has an error
                if (result.DisplayErrorIfFailedAsync())
                {
                    Success = true;
                    ErrorMessage = result.ErrorMessage;
                    await Task.Delay(3000);
                    ErrorMessage = "";
                    Success = false;
                    return false;
                }

                // Get employee data from result
                var employee = result.ServerResponse.Response;

                // Store the new employee first name to data store
                IoC.Settings.Identify.OriginalText = employee.Username;
                await IoC.Employees.LoadEmployees();

                return true;
            }));
        }
Exemplo n.º 19
0
        /// <summary>
        /// Attempts to register the user in
        /// </summary>

        public async Task RegisterAsync(RegisterCredentials registerCredentials, bool registerIsRunning)
        {
            await Task.Run(async() =>
            {
                var result = await WebRequests.PostAsync <UserDetailedApiModel>
                             (
                    "http://localhost:5000/api/auth/register",
                    registerCredentials
                             );


                if (await result.DisplayErrorIfFailedAsync("Register Failed"))
                {
                    return;
                }
            });
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Index(ProvideDataViewModel viewModel)
        {
            // Get data from our API
            var apiData = new ShowWeatherViewModel();

            // Send a request
            var apiResult = await WebRequests.PostAsync <ShowWeatherViewModel>(GetAPIRoute(), viewModel.CityName);

            // If we got a data...
            if (apiResult.Successful)
            {
                // Deserialize json to suitable view model
                apiData = apiResult.ServerResponse;
            }

            // Show the page to the user
            return(View(apiData));
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            // Set Up the DNA Framework
            //Framework.Build();
            new DefaultFrameworkConstruction()
            .UseFileLogger()
            .Build();
            var result = WebRequests.PostAsync("http://localhost:1127/api/values/test");

            var result2 = WebRequests.PostAsync <SettingsDataModel>("http://localhost:1127/api/values/test",
                                                                    new SettingsDataModel {
                Id = "some id", Name = "Luke", Value = "10"
            },
                                                                    sendType: KnownContentSerializers.Json,
                                                                    returnType: KnownContentSerializers.Json);
            var a = result;

            Console.WriteLine("Hello World!");
            Console.ReadKey();
        }
Exemplo n.º 22
0
        public async Task <TaskModels <TaskFileResultModels> > Post(object model, string query)
        {
            BodyContentModels bodyContent = new BodyContentModels();

            bodyContent.JsonString = JsonConvert.SerializeObject(model);
            bodyContent.Scheme     = MEDIA_SCHEME.Json;

            var response = await WebRequests.PostAsync(ApiEndpoint + query, bodyContent, AccessToken);

            if (response.StatusCode == System.Net.HttpStatusCode.OK || response.ReasonPhrase == "Created")
            {
                var task = await RetrieveTask <object>(response);

                return(await WaitForTaskComplete <TaskFileResultModels>(task.data.id));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// Sets the settings view model properties based on the data in the client data store
        /// </summary>
        public async Task LoadAsync()
        {
            // Update values from local cache
            await UpdateValuesFromLocalStoreAsync();

            // Get the user token
            var token = (await IoC.ClientDataStore.GetLoginCredentialsAsync()).Token;

            // If we don't have a token (so we are not logged in)...
            if (string.IsNullOrEmpty(token))
            {
                // Then do nothing
                return;
            }

            // Load user profile details from server
            var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                // Set URL
                RouteHelpers.GetAbsoluteRoute(ApiRoutes.GetUserProfile),
                // Pass in user Token
                bearerToken : token);

            // If it was successful...
            if (result.Successful)
            {
                // TODO: Should we check if the values are different before saving
                await Task.Delay(2000);

                // Create data model from the response
                var dataModel = result.ServerResponse.ResponseGeneric.ToLoginCredentialsDataModel();

                // Re-add our known token
                dataModel.Token = token;

                // Store this in the client data store
                await IoC.ClientDataStore.SaveLoginCredentialsAsync(dataModel);

                // Update values from local cache
                await UpdateValuesFromLocalStoreAsync();
            }
        }
Exemplo n.º 24
0
        /// <summary>
        /// Gets all users
        /// </summary>
        /// <returns></returns>
        public async Task GetUsersAsync()
        {
            await RunCommandAsync(() => UsersLoading, async() =>
            {
                await Task.Delay(1);

                var credentials = await ClientDataStore.GetLoginCredentialsAsync();

                var result = await WebRequests.PostAsync <ApiResponse <UserResultApiModel> >(
                    url: RouteHelpers.GetAbsoluteRoute(ApiRoutes.GetEnterpriseSetting),
                    bearerToken: credentials.Token
                    );


                // If the response has an error...don't mind to continue
                if (await result.HandleErrorIfFailedAsync())
                {
                    return;
                }
            });
        }
Exemplo n.º 25
0
        public async Task <TaskModels <TaskFileResultModels> > Import(Byte[] fileBytes, string fileName)
        {
            var url      = commonService.ApiEndpoint + @"/v2/import/upload";
            var response = await WebRequests.PostAsync(url, null, commonService.AccessToken);

            var taskModelWithForm = await commonService.RetrieveTask <TaskFormResultModels>(response);

            long milliseconds             = new DateTimeOffset(DateTime.UtcNow.AddDays(1)).ToUnixTimeMilliseconds();
            BodyContentModels bodyContent = new BodyContentModels();
            var parameters = taskModelWithForm.data.result.form.parameters;

            bodyContent.FormContent = new System.Collections.Generic.List <FormData>
            {
                new FormData(nameof(parameters.acl), parameters.acl ?? ""),
                new FormData(nameof(parameters.key), parameters.key ?? ""),
                new FormData(nameof(parameters.Policy), parameters.Policy ?? ""),
                new FormData(nameof(parameters.success_action_status), parameters.success_action_status ?? ""),
                new FormData(StaticMethods.GetJsonPropertyName <TaskParametersModels>(x => x.XAmzAlgorithm), parameters.XAmzAlgorithm ?? ""),
                new FormData(StaticMethods.GetJsonPropertyName <TaskParametersModels>(x => x.XAmzCredential), parameters.XAmzCredential ?? ""),
                new FormData(StaticMethods.GetJsonPropertyName <TaskParametersModels>(x => x.XAmzDate), parameters.XAmzDate ?? ""),
                new FormData(StaticMethods.GetJsonPropertyName <TaskParametersModels>(x => x.XAmzSignature), parameters.XAmzSignature ?? ""),

                new FormData("file", fileBytes)
                {
                    FileName = fileName
                }
            };
            bodyContent.Scheme = MEDIA_SCHEME.Form;

            response = await WebRequests.PostAsync(taskModelWithForm.data.result.form.url, bodyContent);

            if (response.StatusCode == System.Net.HttpStatusCode.OK || response.ReasonPhrase == "Created")
            {
                return(await RetrieveTask(response, taskModelWithForm));
            }
            else
            {
                return(null);
            }
        }
Exemplo n.º 26
0
        /// <summary>
        /// Sets the settings view model properties based on the data in the client data store
        /// </summary>
        public async Task LoadAsync()
        {
            // Update values from local cache
            await UpdateValuesFromLocalStoreAsync();

            // Get the user token
            var token = (await ClientDataStore.GetLoginCredentialsAsync()).Token;

            // If we don't have a token (so we are not logged in...)
            if (string.IsNullOrEmpty(token))
            {
                // Then do nothing more
                return;
            }

            // Load user profile details form server
            var result = await WebRequests.PostAsync <ApiResponse <UserProfileDetailsApiModel> >(
                "http://localhost:5000/api/user/profile",
                bearerToken : token);

            // If it was successful...
            if (result.Successful)
            {
                // TODO: Should we check if the values are different before saving?

                // Create data model from the response
                var dataModel = result.ServerResponse.Response.ToLoginCredentialsDataModel();

                // Re-add our known token
                dataModel.Token = token;

                // Save the new information in the data store
                await ClientDataStore.SaveLoginCredentialsAsync(dataModel);

                // Update values from local cache
                await UpdateValuesFromLocalStoreAsync();
            }
        }
Exemplo n.º 27
0
        /// <summary>
        /// Configures our application ready for use
        /// </summary>
        private void ApplicationSetup()
        {
            // Setup the Dna Framework
            new DefaultFrameworkConstruction()
            .Configure()
            .UseFileLogger("anewlog.txt")
            .Build();

            Task.Run((System.Func <Task>)(async() =>
            {
                var result = await WebRequests.PostAsync("http://localhost:5000/test", new SettingsDataModel {
                    Id = "from client", Name = "Fasetto", Value = "ha"
                });
                var a = result;
            }));


            // Setup IoC
            IoC.Setup();

            // Bind a logger
            IoC.Kernel.Bind <ILogFactory>().ToConstant(new BaseLogFactory(new[]
            {
                // TODO: Add ApplicationSettings so we can set/edit a log location
                //       For now just log to the path where this application is running
                new Core.FileLogger("Oldlog.txt"),
            }));

            // Add our task manager
            IoC.Kernel.Bind <ITaskManager>().ToConstant(new TaskManager());

            // Bind a file manager
            IoC.Kernel.Bind <IFileManager>().ToConstant(new FileManager());

            // Bind a UI Manager
            IoC.Kernel.Bind <IUIManager>().ToConstant(new UIManager());
        }
Exemplo n.º 28
0
        /// <summary>
        /// Load settings of the selected employee
        /// </summary>
        /// <param name="selected">The selected username employee</param>
        /// <returns></returns>
        private async Task SettingsSelectedEmployeeAsync(object selected)
        {
            // Not allowed for other employees than administrator
            if (IoC.Settings.Type.OriginalText != "Administrator")
            {
                return;
            }


            // Get selected employee data
            var result = await WebRequests.PostAsync <ApiResponse <LoginResultApiModel> > (
                // TODO: Localize URL
                $"http://localhost:5000/api/employee/{selected}",
                bearerToken : IoC.Settings.Token
                );


            var dataEmployee = result.ServerResponse.Response;

            // If all right then
            if (result.Successful)
            {
                // load all need properties
                IoC.Settings.FirstName.OriginalText  = dataEmployee.FirstName;
                IoC.Settings.LastName.OriginalText   = dataEmployee.LastName;
                IoC.Settings.Identify.OriginalText   = dataEmployee.Username;
                IoC.Settings.Type.OriginalText       = dataEmployee.Type;
                IoC.Settings.Specialize.OriginalText = dataEmployee.Specialize;
                IoC.Settings.PwdNumber.OriginalText  = dataEmployee.NumberPwz;

                await IoC.Duties.LoadEmployeeDutiesAsync(IoC.Settings.Identify.OriginalText);

                HideButtonsInOtherProfile();
                IoC.Application.SettingsMenuVisible = true;
            }
        }
Exemplo n.º 29
0
        public async Task Login(object parameter)
        {
            try
            {
                await RunCommand(() => this.IsLoginRunning, async() =>
                {
                    Container.Get <ApplicationViewModel>().IsGifHidden = false;

                    var result = await WebRequests.PostAsync <ApiResponse <LoginResultApiModel> >("http://localhost:5000/api/login", new LoginCredentialApiModel
                    {
                        UsernameOrEmail = Email,
                        Password        = (parameter as IHavePassword).SecurePassword.Unsecure()
                    });

                    if (result == null || result.ServerResponse == null || !result.ServerResponse.Successful)
                    {
                        //TODO Localize
                        var message = "Unknown error";
                        if (result?.ServerResponse != null)
                        {
                            message = result.ServerResponse.ErrorMessage;
                        }
                        else if (string.IsNullOrWhiteSpace(result?.RawServerResponse))
                        {
                            message = $"Unexpected response {result.RawServerResponse}";
                        }
                        else if (result != null)
                        {
                            message = $"Failed to communicate {result.StatusCode} {result.StatusDescription}";
                        }

                        await Container.UI.ShowMessage(new MessageBoxViewModel
                        {
                            //TODO Localize
                            Title   = "Login Failed",
                            Message = message
                        });

                        Container.Get <ApplicationViewModel>().IsGifHidden = true;
                        return;
                    }

                    var userData = result.ServerResponse.Response;

                    await Container.ClientDataStore.SaveLoginCredentialsAsync(new LoginCredentialsDataModel
                    {
                        Email     = userData.Email,
                        FirstName = userData.FirstName,
                        LastName  = userData.LastName,
                        Username  = userData.Username,
                        Token     = userData.Token
                    });

                    Container.Settings.Load();

                    Container.Get <ApplicationViewModel>().IsGifHidden = true;
                    Container.Get <ApplicationViewModel>().GoToPage(ApplicationPage.Chat);
                });
            }
            catch
            {
                await Container.UI.ShowMessage(new MessageBoxViewModel
                {
                    //TODO Localize
                    Title   = "Login Failed",
                    Message = "Cannot connect to the server"
                });

                Container.Get <ApplicationViewModel>().IsGifHidden = true;
                return;
            }
        }
Exemplo n.º 30
0
        /// <summary>
        /// Employee authentication
        /// </summary>
        /// <param name="parameter">The employee password</param>
        /// <returns></returns>
        public async Task LoginAsync(object parameter)
        {
            await RunCommandAsync(() => LoginIsRunning, async() =>
            {
                // Call the server and attempt to login with credentials
                // TODO: Move all URLs and API routes to static class in core
                var result = await WebRequests.PostAsync <ApiResponse <LoginResultApiModel> >(
                    "http://localhost:5000/api/auth/login",
                    new LoginEmployeeDto
                {
                    Identify = MyIdentify,
                    Password = (parameter as IHavePassword)?.SecurePassword.UnSecure()
                });

                // If there was no response, bad data or a response with a error message
                if (result.DisplayErrorIfFailedAsync())
                {
                    Success      = false;
                    ErrorMessage = result.ErrorMessage;
                    return;
                }
                Success = true;

                // Ok successfully logged in.. now get employee data
                var employeeData = result.ServerResponse.Response;

                IoC.Settings.Pesel     = employeeData.Pesel;
                IoC.Settings.Token     = employeeData.Token;
                IoC.Settings.FirstName = new TextEntryViewModel {
                    Label = "Imię", OriginalText = employeeData?.FirstName
                };
                IoC.Settings.LastName = new TextEntryViewModel {
                    Label = "Nazwisko", OriginalText = employeeData?.LastName
                };
                IoC.Settings.Identify = new TextEntryViewModel {
                    Label = "Identyfikator", OriginalText = employeeData?.Username
                };
                IoC.Settings.Type = new TextEntryViewModel {
                    Label = "Posada", OriginalText = employeeData?.Type
                };
                IoC.Settings.Specialize = new TextEntryViewModel {
                    Label = "Specjalizacja", OriginalText = employeeData?.Specialize
                };
                IoC.Settings.PwdNumber = new TextEntryViewModel {
                    Label = "Numer PWD", OriginalText = employeeData?.NumberPwz
                };
                IoC.Settings.Password = new PasswordEntryViewModel {
                    Label = "Hasło", FakePassword = "******", UserPassword = (parameter as IHavePassword)?.SecurePassword
                };

                if (employeeData != null && employeeData.Type == "Administrator")
                {
                    IoC.Settings.IsEmployeeAdm = true;
                }

                // and get employee data
                await IoC.Employees.LoadEmployees();

                await IoC.Duties.LoadDutiesAsync();
                await IoC.Duties.LoadEmployeeDutiesAsync(employeeData.Username);

                await Task.Delay(2000);

                // Go to work page
                IoC.Get <ApplicationViewModel>().GoToPage(ApplicationPage.Work);
            });
        }