public void LoadPersonTest() { //Arrange var context = new UPSContext(UPSContext.StringConnectToMainServer); string nameOfClient = Guid.NewGuid().ToString(); string nameOfEmp = Guid.NewGuid().ToString(); string passwordOrID = Guid.NewGuid().ToString(); string wrongPassword = passwordOrID + "X6X6X6"; //Act //Сохранение новых пользователей. Client newClient = ClientController.RegistrationOfPerson <Client>(nameOfClient, passwordOrID, context) as Client; Employee newEmployee = ClientController.RegistrationOfPerson <Employee>(nameOfEmp, passwordOrID, context) as Employee; //Изменение и сохранение данных текущего клиента. ClientController.UpBalance(newClient, 500, context); //Загрузка данных сохранённого клиента (изменения должны быть применены). Client loadedClient = ClientController.LoadOfPerson <Client>(nameOfClient, passwordOrID, context) as Client; Employee loadedEmployee = ClientController.LoadOfPerson <Employee>(nameOfEmp, passwordOrID, context) as Employee; Client loadedClientWrongPassword = ClientController.LoadOfPerson <Client>(nameOfClient, wrongPassword, context) as Client; Employee loadedEmployeeWrongSecName = ClientController.LoadOfPerson <Client>(nameOfClient, wrongPassword, context) as Employee; //Assert Assert.IsTrue(newClient.Equals(loadedClient)); Assert.AreEqual(newEmployee.ToString(), loadedEmployee.ToString()); Assert.IsNull(loadedClientWrongPassword); Assert.IsNull(loadedEmployeeWrongSecName); }
public void AddProductsTest() { //Arrange var context = new UPSContext(UPSContext.StringConnectToMainServer); List <Product> prodFromDb = context.Products.ToList(); var product = new Product($"TEST {Guid.NewGuid()}", 10); var productNullName = new Product(null, 10); var productMinusCost = new Product($"TEST {Guid.NewGuid()}", -1); var productNull = new Product(null, 0); //Act ProductController.AddProducts(context, product, prodFromDb); ProductController.AddProducts(context, productNullName, prodFromDb); ProductController.AddProducts(context, productMinusCost, prodFromDb); ProductController.AddProducts(context, productNull, prodFromDb); //Assert Assert.IsTrue(context.Products.Any(prod => prod.Name == product.Name)); Assert.IsFalse(context.Products.Any(prod => prod.Name == null)); Assert.IsFalse(context.Products.Any(prod => prod.Cost == -1)); Assert.IsFalse(context.Products.Any(prod => prod.Name == null && prod.Cost == 0), "В базе данных есть экземпляры Product с Null значениями имени и стоимости!"); }
public void SetCostTest() { //Arrange decimal oldCost = 10; decimal newCost = 15; var context = new UPSContext(UPSContext.StringConnectToMainServer); var product = new Product(Guid.NewGuid().ToString(), oldCost); if (ProductController.AddProducts(context, product, context.Products.ToList()) is false) { Assert.Fail("Изменяемый продукт не был добавлен в БД!"); } //Act decimal newCostOfThisProduct = ProductController.SetCost(newCost, product, context); decimal minusCostResult = ProductController.SetCost(-1, product, context); decimal nullCostResult = ProductController.SetCost(0, product, context); decimal nullProductResult = ProductController.SetCost(newCost, null, context); //Assert Assert.AreEqual(newCost, newCostOfThisProduct); Assert.IsTrue(minusCostResult == -1); Assert.IsTrue(nullCostResult == -1); Assert.IsTrue(nullProductResult == -1); }
public void SetNameTest() { //Arrange var context = new UPSContext(UPSContext.StringConnectToMainServer); string oldNameOfProduct = "OldNameTest"; string newNameOfProduct = "NewNameTest"; var product = new Product(oldNameOfProduct, 10); if (ProductController.AddProducts(context, product, context.Products.ToList()) is false) { Assert.Fail("Изменяемый продукт не был добавлен в БД!"); } //Act string newNameOfThisProduct = ProductController.SetName(newNameOfProduct, product, context); string nullNameOfThisProduct = ProductController.SetName(null, product, context); string nullProduct = ProductController.SetName(newNameOfProduct, null, context); //Assert Assert.AreEqual(newNameOfProduct, newNameOfThisProduct); Assert.IsNull(nullNameOfThisProduct); Assert.IsNull(nullProduct); }
/// <summary> /// Изменяет поле Cost экземпляра Product. /// </summary> /// <param name="newCost"> Новое значение Cost для экземпляра Product. </param> /// <param name="product"> Экземпляр Product который будет изменён. </param> public static decimal SetCost(decimal newCost, Product product, UPSContext context) { if (newCost > 0 && context != null && product != null) { product.Cost = newCost; if (SaveProduct(product, context)) { return(product.Cost); } } return(-1); }
/// <summary> /// Приватный метод, необходимый для сохранения (синхронизации) данных об экземпляре Client после операций. /// </summary> /// <param name="inputClient"> Экземпляр Client, данные которого будут синхронизированы с БД. </param> /// <param name="context"> Экземпляр контекста, необходимый для работы с БД. </param> private static void SaveClient(Client inputClient, UPSContext context) { try { var clientFromDb = context.Clients.Find(inputClient.Id); clientFromDb = inputClient; context.SaveChanges(); } catch (Exception ex) { Console.WriteLine("Не удалось сохранить данные после операции!" + ex); Thread.Sleep(5000); } }
/// <summary> /// Изменяет поле Name экземпляра Product. /// </summary> /// <param name="newName">Новое имя экземпляра Product.</param> /// <param name="product">Экземпляр Product который будет изменён.</param> /// <returns> Текущее имя этого экземпляра Product, если операция была успешно совершена, иначе - null. </returns> public static string SetName(string newName, Product product, UPSContext context) { if (string.IsNullOrWhiteSpace(newName) is false && context != null && product != null) { product.Name = newName; if (SaveProduct(product, context)) { return(product.Name); } } return(null); }
/// <summary> /// Увеличивает баланс экземпляра Client и сохраняет изменения. /// </summary> /// <param name="client"> Экземпляр Client, для которого будет произведено пополнение. </param> /// <param name="money"> Сумма пополнения. </param> /// <returns> Если входные аргументы корректны и операция удалась, возвращает текущий баланс входного Client. /// Иначе возвращает -1. </returns> public static decimal UpBalance(Client client, decimal money, UPSContext context) { //Да, да, тут должна быть переадресация на платёжные системы и т.д. if (money > 0 && client != null) { client.Balance += money; SaveClient(client, context); return(client.Balance); } else { Console.WriteLine("Сумма пополнения менее или равна нулю или аккаунт повреждён!"); return(-1); } }
/// <summary> /// Добавляет экземпляр Product в БД. /// </summary> /// <param name="context"> Экземпляр контекста, необходимый для сохранения изменений в базе данных. </param> /// <param name="newProduct"> Добавляемый экземпляр Product. </param> /// <param name="productsFromDb"> Данные о экземплярах Product из БД, /// необходимые для защиты от ошибок (добавление уже существующего экземпляра и т.п). /// </param> /// <returns> True - если входные аргументы корректны, операция удалась и этот продукт не содержался в БД, иначе - false. </returns> public static bool AddProducts(UPSContext context, Product newProduct, List <Product> productsFromDb) { if (productsFromDb.Find(prod => prod.Name == newProduct.Name) is null && context != null && productsFromDb != null) { if (string.IsNullOrWhiteSpace(newProduct.Name) is false && newProduct.Cost > 0) { context.Products.Add(newProduct); context.SaveChanges(); return(true); } } return(false); }
/// <summary> /// Возвращает все экземпляры Product из базы данных. /// </summary> /// <param name="context"> Экземпляр контекста, необходимый для сохранения изменений в базе данных. </param> /// <returns> Если входные аргументы корректны и операция удалась - возвращает лист Product, /// иначе - null. /// </returns> public static List <Product> LoadProducts(UPSContext context) { try { if (context.Products.Count() > 0) { var products = context.Products.ToList(); return(products); } else { throw new Exception("Не удалось загрузить список продуктов. Был создан список по умолчанию."); } } catch (Exception) { var productsNull = new List <Product>(); return(productsNull); } }
public void UpBalanceTest() { //Arrange decimal sum = 500; var context = new UPSContext(UPSContext.StringConnectToMainServer); var client = new Client("NewClient", "TEST"); decimal clientBalanceBeforeUp = client.Balance; //Act decimal uppedBalance = ClientController.UpBalance(client, sum, context); decimal uppedBalanceNullClient = ClientController.UpBalance(null, sum, context); decimal uppedBalanceMinusBalance = ClientController.UpBalance(client, -100500, context); //Assert Assert.AreEqual(clientBalanceBeforeUp + sum, uppedBalance); Assert.IsTrue(uppedBalanceNullClient == -1); Assert.IsTrue(uppedBalanceMinusBalance == -1); }
/// <summary> /// Выполняет операцию покупки, удаляя из экземпляра Basket все объекты Product /// и вычитает их сумму их баланса объекта Client, который содержится в Basket. /// </summary> /// <param name="basket"> Объект Basket. </param> /// <param name="context"> Экземпляр контекста, необходимый для сохранения изменений в базе данных. </param> /// <returns> True - если входные аргументы корректны и операция удалась, иначе - false. </returns> public static bool Buy(Basket basket, UPSContext context) { if (basket != null && basket.Client != null && basket.Products != null && basket.Products.Count > 0) { var sumCost = basket.Products.Select(x => x.Cost) .Sum(); if (basket.Client.Balance >= sumCost) { basket.Client.Balance -= sumCost; basket.Products = new List <Product>(); SaveClient(basket.Client, context); return(true); } } return(false); }
public void RegistrationOfPersonTest() { //Arrange var context = new UPSContext(UPSContext.StringConnectToMainServer); string nameOfNewClient = Guid.NewGuid().ToString(); string nameOfNewEmp = Guid.NewGuid().ToString(); string passwordOrID = Guid.NewGuid().ToString(); //Act Client client = ClientController.RegistrationOfPerson <Client>(nameOfNewClient, passwordOrID, context) as Client; Employee employee = ClientController.RegistrationOfPerson <Employee>(nameOfNewEmp, passwordOrID, context) as Employee; Client clientNullName = ClientController.RegistrationOfPerson <Client>(null, passwordOrID, context) as Client; Client clientNullPassword = ClientController.RegistrationOfPerson <Client>(nameOfNewClient, null, context) as Client; Client clientNullArguments = ClientController.RegistrationOfPerson <Client>(null, null, context) as Client; Client alreadyRegisteredClient = ClientController.RegistrationOfPerson <Client>(nameOfNewClient, passwordOrID, context) as Client; Client clientWhereTypeIsPerson = ClientController.RegistrationOfPerson <Person>(nameOfNewClient, passwordOrID, context) as Client; Employee employeeNullName = ClientController.RegistrationOfPerson <Client>(null, passwordOrID, context) as Employee; Employee employeetNullPassword = ClientController.RegistrationOfPerson <Client>(nameOfNewClient, null, context) as Employee; Employee employeetNullArguments = ClientController.RegistrationOfPerson <Client>(null, null, context) as Employee; Employee alreadyRegisteredEmployee = ClientController.RegistrationOfPerson <Client>(nameOfNewClient, passwordOrID, context) as Employee; Employee employeetWhereTypeIsPerson = ClientController.RegistrationOfPerson <Person>(nameOfNewClient, passwordOrID, context) as Employee; //Assert Assert.IsNotNull(client); Assert.IsNotNull(employee); Assert.IsNull(clientNullName); Assert.IsNull(clientNullPassword); Assert.IsNull(clientNullArguments); Assert.IsNull(alreadyRegisteredClient); Assert.IsNull(clientWhereTypeIsPerson); Assert.IsNull(employeeNullName); Assert.IsNull(employeetNullPassword); Assert.IsNull(employeetNullArguments); Assert.IsNull(alreadyRegisteredEmployee); Assert.IsNull(employeetWhereTypeIsPerson); }
/// <summary> /// Приватный метод, необходимый для сохранения (синхронизации) изменений экземпляра Product с ним же в базе данных. /// </summary> /// <param name="product"> Изменяемый экземпляр Product. </param> /// <param name="context"> Экземпляр контекста, необходимый для сохранения изменений в базе данных. </param> /// <returns> True - если входные аргументы корректны и операция удалась, иначе - false. </returns> private static bool SaveProduct(Product product, UPSContext context) { try { var prodFromDb = context.Products.Find(product.Id); prodFromDb.Name = product.Name; prodFromDb.Cost = product.Cost; context.SaveChanges(); if (prodFromDb.Name == product.Name && prodFromDb.Cost == product.Cost) { return(true); } return(false); } catch (Exception ex) { Console.WriteLine(ex); return(false); } }
public DataRepository(UPSContext context) { _context = context; }
/// <summary> /// Добавляет в БД объект, наследника от Person. /// </summary> /// <typeparam name="T"> Тип выгружаемого объекта. Должен наследоваться от Person. </typeparam> /// <param name="nameOfPerson"> Имя выгружаемого объекта. </param> /// <param name="passwordOrSecondName"> Пароль или фамилия выгружаемого объекта. </param> /// <param name="context"> Экземпляр контекста, необходимый для работы с БД. </param> /// <returns> Если входные аргументы корректны и операция удалась - возвращает загруженный объект, /// иначе - null. /// </returns> public static Person RegistrationOfPerson <T>(string nameOfPerson, string passwordOrSecondName, UPSContext context) { if (string.IsNullOrWhiteSpace(nameOfPerson) is false && string.IsNullOrWhiteSpace(passwordOrSecondName) is false) { var nameOfPersonType = typeof(T); try { if (nameOfPersonType == typeof(Client)) { if (context.Clients.FirstOrDefault(clint => clint.Name == nameOfPerson) == default) { var newClient = new Client(nameOfPerson, passwordOrSecondName); if (newClient.Name != null && newClient.PasswordOrSecondName != null) { context.Clients.Add(newClient); context.SaveChanges(); return(newClient); } } } else if (nameOfPersonType == typeof(Employee)) { if (context.Employees.FirstOrDefault(clint => clint.Name == nameOfPerson) == default) { var newEmployee = new Employee(nameOfPerson, passwordOrSecondName); if (newEmployee.Name != null && newEmployee.PasswordOrSecondName != null) { context.Employees.Add(newEmployee); context.SaveChanges(); return(newEmployee); } } } else { return(null); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } } return(null); }
public UserRepository(UPSContext context) { this.context = context; }
public RoleRepository(UPSContext context) { this.context = context; }
public GenericRepository(UPSContext context) { _context = context; }
/// <summary> /// Загружает объект, наследника Person, из БД. /// </summary> /// <typeparam name="T"> Тип выгружаемого объекта. Должен наследоваться от Person. </typeparam> /// <param name="nameOfPerson"> Имя выгружаемого объекта. </param> /// <param name="passwordOrSecondName"> Пароль или фамилия выгружаемого объекта. </param> /// <param name="context"> Экземпляр контекста, необходимый для работы с БД. </param> /// <returns> Если входные аргументы корректны и операция удалась - возвращает загруженный объект, /// иначе - null. /// </returns> public static Person LoadOfPerson <T>(string nameOfPerson, string passwordOrSecondName, UPSContext context) where T : Person { if (string.IsNullOrWhiteSpace(nameOfPerson) == false && string.IsNullOrWhiteSpace(passwordOrSecondName) == false) { var nameOfType = typeof(T); try { if (nameOfType == typeof(Client)) { var clientFromDb = context.Clients.FirstOrDefault(clint => clint.Name == nameOfPerson && clint.PasswordOrSecondName == passwordOrSecondName); if (clientFromDb != default) { return(clientFromDb); } } else if (nameOfType == typeof(Employee)) { var employeeFromDb = context.Employees.FirstOrDefault(emp => emp.Name == nameOfPerson && emp.PasswordOrSecondName == passwordOrSecondName); if (employeeFromDb != default) { return(employeeFromDb); } } else { return(null); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(null); } } return(null); }
private static void Main() { #region preliminaryData var context = new UPSContext(UPSContext.StringConnectToMainServer); Employee employee = null; #endregion #region authentication while (employee is null) { Console.WriteLine("Здравствуйте сотрудник, введите ваш ID."); if (int.TryParse(Console.ReadLine(), out int inputID) == false) { continue; } employee = context.Employees.Find(inputID); } #endregion var productsFromDb = context.Products.ToList(); #region actions while (true) { Console.Clear(); Console.WriteLine($"Добро пожаловать, {employee.Name}!"); Console.WriteLine("Вам доступно добавление продуктов, нажмите на A что-бы добавить их."); switch (Console.ReadKey(true).Key) { #region key A (adding new product) case ConsoleKey.A: var newProduct = new Product(); Console.Write("Название: "); newProduct.Name = (Console.ReadLine()); Console.Write("Стоимость (в рублях): "); newProduct.Cost = Convert.ToDecimal(Console.ReadLine()); if (string.IsNullOrWhiteSpace(newProduct.Name) == false && newProduct.Cost > 0) { if (ProductController.AddProducts(context, newProduct, productsFromDb)) { Console.WriteLine("Продукт был успешно добавлен."); } else { Console.WriteLine("Продукт не был добавлен!"); } } else { Console.WriteLine("Проверьте корректность вводимых данных!"); } Thread.Sleep(6000); break; #endregion } } #endregion }
private static void Main() { UPSContext context = new UPSContext(UPSContext.StringConnectToMainServer); Client сlient = default; Basket basket = new Basket(сlient); #region Authorization while (true) { Console.Clear(); Console.WriteLine("Здравствуйте уважаемый пользователь! Если вы зарегистрированы, введите L и введите свои данные."); Console.WriteLine("Или если вы не зарегистрированы, введите R и введите данные о вас."); switch (Console.ReadKey(true).Key) { #region key L (log-in) case ConsoleKey.L: Console.Write("Имя: "); string newName = Console.ReadLine(); Console.Write("Пароль: "); string newPassword = Console.ReadLine(); сlient = ClientController.LoadOfPerson <Client>(newName, newPassword, context) as Client; if (сlient is null) { Console.Write("Данные некорректны (пустое имя/пароль/в них только символы разделители или они неверны)."); continue; } else { basket.Client = сlient; Console.WriteLine($"Добро пожаловать, {сlient}!"); } Thread.Sleep(6000); break; #endregion #region key R (registration) case ConsoleKey.R: Console.Write("Ваше новое имя: "); string name = Console.ReadLine(); Console.Write("Ваш новый пароль: "); string password = Console.ReadLine(); сlient = ClientController.RegistrationOfPerson <Client>(name, password, context) as Client; if (сlient is null) { Console.Write("Данные некорректны (пустое имя/пароль/в них только символы разделители), "); Console.WriteLine("или пользователь с таким именем уже существует!"); Thread.Sleep(6000); continue; } basket.Client = сlient; Thread.Sleep(6000); break; #endregion } break; } #endregion var products = ProductController.LoadProducts(context); while (true) { bool productsIsAvailable = false; Console.Clear(); if (products.Count > 0) { productsIsAvailable = true; Console.WriteLine("Нам доступны следующие продукты:"); foreach (var product in products) { Console.WriteLine($"{ProductController.GetName(product)}, "); Console.Write($"стоимость: {ProductController.GetCost(product)} рублей. \n\n"); } Console.WriteLine("Нажмите A(англ), если хотите добавить один из продуктов в корзину."); Console.WriteLine("Если ваша корзина уже заполнена, нажмите Y, что бы совершить покупку."); Console.WriteLine("Если хотите удалить продукт из корзины, нажмите D, после чего вы введёте его имя."); } Console.WriteLine("\nНажмите Q, если хотите пополнить счёт."); Console.WriteLine("(раскладка не учитывается)"); switch (Console.ReadKey(true).Key) { #region key A (adding product) case ConsoleKey.A: if (productsIsAvailable) { Console.WriteLine("Введите полное название продукта."); string inputNameOfProduct = Console.ReadLine(); var product = products.FirstOrDefault(prod => prod.Name == inputNameOfProduct); if (product != default) { if (ClientController.AddProductInBasket(basket, product)) { Console.WriteLine($"Продукт с именем {product} добавлен в корзину!"); } } else { Console.WriteLine("Продукта с таким именем не существует в продаже!"); } Thread.Sleep(6000); } break; #endregion #region key Y (buy) case ConsoleKey.Y: if (productsIsAvailable) { const string constYes = "yes"; Console.Clear(); Console.WriteLine($@"Вы уверены, что хотите совершить покупку? Введите ""{constYes}"", если согласны."); Console.WriteLine("(регистр не учитывается)"); if (Console.ReadLine().ToLower() == constYes) { if (ClientController.Buy(basket, context)) { Console.WriteLine("Покупка успешно совершена. Ваши данные после покупки:"); Console.WriteLine($"Баланс: {ClientController.GetBalance(сlient)} рублей."); Thread.Sleep(6000); } else { Console.Write("Ваш баланс меньше чем общая стоимость корзины с учётом коэффициента скидки, "); Console.Write("ваш аккаунт повреждён или корзина пуста! \n"); } Thread.Sleep(6000); } } break; #endregion #region key D (deleting product) case ConsoleKey.D: if (productsIsAvailable) { Console.Write("Название удаляемого продукта: "); string name = Console.ReadLine(); if (ClientController.DeleteProductFromBasket(basket, name)) { Console.WriteLine($"Продукт {name} был удалён из корзины."); } else { Console.WriteLine("Продукт не был удалён!"); } Thread.Sleep(6000); } break; #endregion #region key Q (upping balance) case ConsoleKey.Q: Console.Write("Сумма пополнения в рублях: "); if (decimal.TryParse(Console.ReadLine(), out decimal input) == false) { Console.WriteLine("Были введены некорректные данные!"); Thread.Sleep(3000); continue; } if (ClientController.UpBalance(сlient, input, context) != -1) { Console.WriteLine($"Ваш баланс пополнен на {input} рублей и теперь составляет {ClientController.GetBalance(сlient)} рублей."); Thread.Sleep(6000); } break; #endregion } } }