Example #1
0
        public Person Insert(Person person)
        {
            _context.Person.Add(person);
            _context.SaveChanges();

            return(person);
        }
        public IActionResult CreateApplication(string demandNO, string resourceNO)
        {
            log.Debug("CreateApplication");
            var cnt = _context.TPostApplication.Count <TPostApplication>(opt => opt.DemandNo == demandNO && opt.ResourceNo == resourceNO);

            if (cnt == 0)
            {
                var application = new TPostApplication()
                {
                    ApplyDate    = DateTime.Now,
                    DemandNo     = demandNO,
                    ResourceNo   = resourceNO,
                    Status       = ((int)ApplicationStatus.Apply).ToString(),
                    RegisterDate = DateTime.Now,
                    UpdateDate   = DateTime.Now
                };
                _context.Add <TPostApplication>(application);
                _context.SaveChanges();

                OkObjectResult ret = new OkObjectResult(application);
                Response.StatusCode = (int)HttpStatusCode.Created;
                return(ret);
            }
            else
            {
                var result = new ContentResult();
                result.StatusCode = (int)HttpStatusCode.NotAcceptable;
                result.Content    = "不可以重复申请。";
                return(result);
            }
        }
Example #3
0
        public ApiResponse <Post> Add(Post obj)
        {
            try
            {
                var apiResponse = UploadPost(obj, obj.PostGuid, new MemoryStream(obj.PostImage));
                if (!apiResponse.IsSuccess)
                {
                    return(apiResponse);
                }

                obj.UrlPostImage = Crypto.Encryption(apiResponse.Data.ToString());

                _context.Post.Add(obj);
                apiResponse.IsSuccess  = _context.SaveChanges() > 0;
                apiResponse.Message    = apiResponse.IsSuccess ? "Post realizado" : "Falha ao enviar postar";
                apiResponse.StatusCode = apiResponse.IsSuccess ? HttpStatusCode.OK : HttpStatusCode.InternalServerError;
                apiResponse.Data       = obj;

                return(apiResponse);
            }
            catch (NpgsqlException exc)
            {
                return(new ApiResponse <Post>(null, exc));
            }
            catch (Exception exc)
            {
                return(new ApiResponse <Post>(null, exc));
            }
        }
Example #4
0
        public ApiResponse <User> Add(User obj)
        {
            var apiResponse = GetByObj(obj);

            try
            {
                if (apiResponse.IsSuccess)
                {
                    apiResponse.IsSuccess = false;
                    apiResponse.Message   = "Usuário já cadastrado";
                    return(apiResponse);
                }

                if (!apiResponse.IsSuccess && apiResponse.StatusCode == HttpStatusCode.NotFound)
                {
                    apiResponse.Message = null;

                    _context.User.Add(obj);
                    apiResponse.IsSuccess  = _context.SaveChanges() > 0;
                    apiResponse.Message    = apiResponse.IsSuccess ? "Usuário adicionado" : "Falha ao criar usuário";
                    apiResponse.StatusCode = apiResponse.IsSuccess ? HttpStatusCode.OK : HttpStatusCode.InternalServerError;
                    apiResponse.Data       = obj;
                }
            }
            catch (NpgsqlException exc)
            {
                return(new ApiResponse <User>(null, exc));
            }
            catch (Exception exc)
            {
                return(new ApiResponse <User>(null, exc));
            }

            return(apiResponse);
        }
        public ActionResult Delet(int delete)
        {
            var data = _ctxpost.Ogrenci.Find(delete);

            _ctxpost.Ogrenci.Remove(data);
            _ctxpost.SaveChanges();

            return(RedirectToAction("Grid", "Home"));
        }
        public ISession Add(ISession session)
        {
            var entity = _mapper.Map <DalSession>(session);
            var result = _context.Add(entity);

            _context.SaveChanges(true);

            return(_mapper.Map <Session>(result.Entity));
        }
Example #7
0
        public IMove Add(IMove move)
        {
            var entity = _mapper.Map <DalMove>(move);
            var result = _context.Add(entity);

            _context.SaveChanges(true);

            //TODO exception handling
            return(_mapper.Map <Move>(result.Entity));
        }
Example #8
0
        public T Create(T item)
        {
            try {
                dataset.Add(item);
                _context.SaveChanges();
            } catch (Exception ex) {
                throw ex;
            }

            return(item);
        }
Example #9
0
        public void Add(TestTable testTable)
        {
            // Pretend description is required
            if (string.IsNullOrEmpty(testTable.Testdescription))
            {
                throw new InvalidInputException("Required field missing.");
            }

            _context.TestTable.Add(testTable);
            _context.SaveChanges();
        }
        public bool RevokeToken(string userName)
        {
            var user = _context.Users.SingleOrDefault(u => u.UserName == userName);

            if (user is null)
            {
                return(false);
            }
            user.RefreshToken = null;
            _context.SaveChanges();
            return(true);
        }
        public Ogrenci Authenticate(int OgrenciNo, string sifre)
        {
            //var user = _ctxpost.ogrenciToken.Where(s => s.ogrenciNo == OgrenciNo);
            //var user = _ctxpost.ogrenciToken.Find(41);

            var user = _ctxpost.Ogrenci.Where(s => s.Numara == OgrenciNo && s.Sifre == sifre).FirstOrDefault();


            if (user == null)
            {
                return(null);
            }

            // Authentication(Yetkilendirme) başarılı ise JWT token üretilir.
            var tokenHandler    = new JwtSecurityTokenHandler();
            var key             = Encoding.ASCII.GetBytes(_appSettings.Secret);
            var tokenDescriptor = new SecurityTokenDescriptor
            {
                Subject = new ClaimsIdentity(new Claim[]
                {
                    new Claim(ClaimTypes.Name, user.Numara.ToString())
                }),
                Expires            = DateTime.UtcNow.AddDays(7),
                SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
            };
            var token = tokenHandler.CreateToken(tokenDescriptor);

            user.Token = tokenHandler.WriteToken(token);
            _ctxpost.SaveChanges();

            // Sifre null olarak gonderilir.


            return(user);
        }
Example #12
0
 public static void InitializeDbForTests(PostgresContext db)
 {
     db.Users.Add(BuildUser());
     db.Recipes.Add(BuildRecipe());
     db.Lists.Add(BuildShoppingList());
     db.SaveChanges();
 }
Example #13
0
        public void Delete(long id)
        {
            try
            {
                T item = dataset.Find(id);

                if (item != null)
                {
                    dataset.Remove(item);
                    _context.SaveChanges();
                }
            } catch (Exception ex)
            {
                throw ex;
            }
        }
Example #14
0
        public ApiResponse <Account> Add(Account obj)
        {
            var apiResponse = new ApiResponse <Account>();

            try
            {
                // realiza upload da imagem de perfil no firestorage
                apiResponse = Upload(obj, obj.GuidKey, new MemoryStream(obj.ProfileImage));
                if (!apiResponse.IsSuccess)
                {
                    return(apiResponse);
                }

                // criptogra a url da imagem de perfil
                obj.UrlProfileImage = Crypto.Encryption(apiResponse.Data.ToString());

                // valida informações da conta
                apiResponse = Accessor.AccountBusinessLibrary.InputEntryIsValid(obj);
                if (!apiResponse.IsSuccess)
                {
                    return(apiResponse);
                }

                _context.Account.Add(obj);
                apiResponse.IsSuccess = _context.SaveChanges() > 0;

                if (apiResponse.IsSuccess)
                {
                    _context.User.Update(obj.User);
                    apiResponse.IsSuccess = _context.SaveChanges() > 0;
                }

                apiResponse.Message    = apiResponse.IsSuccess ? "Contra criada" : "Falha ao criar conta";
                apiResponse.StatusCode = apiResponse.IsSuccess ? HttpStatusCode.OK : HttpStatusCode.InternalServerError;
                apiResponse.Data       = obj;
            }
            catch (NpgsqlException exc)
            {
                return(new ApiResponse <Account>(null, exc));
            }
            catch (Exception exc)
            {
                return(new ApiResponse <Account>(null, exc));
            }

            return(apiResponse);
        }
        public int Add(Error error)
        {
            var result = _context.Add(new DalError
            {
                CreationDate     = error.CreationDate,
                BriefDescription = error.BriefDescription,
                FullDescription  = error.FullDescription,
                Status           = error.Status,
                Priority         = error.Priority,
                Seriousness      = error.Seriousness,
                DalUserId        = error.UserId
            });

            _context.SaveChanges(true);

            return(result.Entity.Id);
        }
Example #16
0
        public IPlayer Add(IPlayer player)
        {
            var entity = _mapper.Map <DalPlayer>(player);
            var result = _context.Add(entity);

            _context.SaveChanges(true);

            return(_mapper.Map <Player>(result.Entity));
        }
Example #17
0
        public static void Execute(EditScheduledDelivery command, PostgresContext postgresContext)
        {
            foreach (var scheduledDeliveryProduct in command.Products)
            {
                EditProduct(scheduledDeliveryProduct, postgresContext);
            }

            postgresContext.SaveChanges();
        }
Example #18
0
        public IActionResult RealizationPost([FromBody] RealizationVM json)
        {
            try
            {
                var managerId = _postgresContext.Managers.FirstOrDefault(x => x.Name == json.Manager)?.Id ??
                                throw new Exception("Не указан менеджен");

                SaleCreateVM saleCreate = new SaleCreateVM()
                {
                    UserId            = json.UserId,
                    MoneyWorkerId     = json.MoneyWorkerId,
                    Discount          = json.Discount,
                    AdditionalComment = json.AdditionalComment,
                    Comment           = json.Comment,
                    PaymentType       = json.Cashless
                        ? PaymentType.Cashless
                        : PaymentType.Cash,
                    CashSum     = json.CashSum,
                    CashlessSum = json.CashlessSum,
                    Sum         = json.Sum,
                    Products    = json.Products,
                    PartnerId   = json.Buyer == "Обычный покупатель"
                        ? null
                        : _db.Partners.First(p => p.Title == json.Buyer)?.Id,
                    Payment    = json.Payment,
                    ForRussian = json.ForRussian
                };

                var createdSale = _saleService.Create(_db, saleCreate, json.UserId);


                _postgresContext.SaleManagersOld.Add(
                    new SaleManagerOld(managerId, createdSale.Id, DateTime.Now.AddHours(3)));
                _postgresContext.SaveChanges();


                return(RedirectToAction("CheckPrint",
                                        new { saleId = createdSale.Id, operationSum = json.CashSum + json.CashlessSum }));
            }
            catch (Exception e)
            {
                return(BadRequest(new { message = e.Message }));
            }
        }
Example #19
0
        public IActionResult Create(int id, string title, string email, string phone, int order)
        {
            //_supplierService.Create(obj);
            var supplier = _shopContext.Suppliers.Add(new Supplier()
            {
                Id    = id,
                Title = title,
                Email = email,
                Phone = phone,
                Debt  = 0
            });

            _shopContext.SaveChanges();

            _postgresContext.SuppliersInfos.Add(new SupplierInfo(supplier.Entity.Id, order));
            _postgresContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
Example #20
0
        public int Add(User user)
        {
            var result = _context.Add(new DalUser
            {
                Login    = user.Login,
                Password = user.Password
            });

            _context.SaveChanges(true);

            return(result.Entity.Id);
        }
Example #21
0
        public IActionResult AddIncompleteProduct(int productId, int shopId, int amount, string comment)
        {
            _postgresContext.IncompleteProducts
            .Add(new IncompleteProduct(
                     productId,
                     amount,
                     shopId,
                     comment));

            _postgresContext.SaveChanges();

            return(RedirectToAction("Detail", new { id = productId }));
        }
Example #22
0
        public IActionResult Delete(string demandNO)
        {
            var applications = _context.TPostApplication.Where <TPostApplication>(opt => opt.DemandNo == demandNO);

            foreach (var app in applications)
            {
                app.Status     = ((int)ApplicationStatus.DemandDelete).ToString();
                app.UpdateDate = DateTime.Now;
                _context.TPostApplication.UpdateRange(app);
            }
            _context.SaveChanges();
            return(Ok());
        }
        public IActionResult Delete(int id)
        {
            var calculatedScore = _db.CalculatedScores.FirstOrDefault(x => x.Id == id);

            if (calculatedScore == null)
            {
                throw new Exception("Рассчётный счёт не найден");
            }

            _postgresContext.ArchiveCalculatedScores.Add(new ArchiveCalculatedScore(id));
            _postgresContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
Example #24
0
        public ApiResponse <Feed> Add(Feed obj)
        {
            var apiResponse = new ApiResponse <Feed>();

            try
            {
                _context.Feed.Add(obj);
                apiResponse.IsSuccess  = _context.SaveChanges() > 0;
                apiResponse.Message    = apiResponse.IsSuccess ? "Solicitação enviada" : "Falha ao enviar solicitação";
                apiResponse.StatusCode = apiResponse.IsSuccess ? HttpStatusCode.OK : HttpStatusCode.InternalServerError;
                apiResponse.Data       = obj;
            }
            catch (NpgsqlException exc)
            {
                return(new ApiResponse <Feed>(null, exc));
            }
            catch (Exception exc)
            {
                return(new ApiResponse <Feed>(null, exc));
            }

            return(apiResponse);
        }
        public int Add(History history)
        {
            var result = _context.Add(new DalHistory
            {
                Date       = history.Date,
                Action     = history.Action,
                Comment    = history.Comment,
                DalUserId  = history.UserId,
                DalErrorId = history.ErrorId
            });

            _context.SaveChanges(true);

            return(result.Entity.Id);
        }
        public static void Execute(int deliveryId, PostgresContext postgresContext, ShopContext shopContext)
        {
            var deliveredProducts = postgresContext.ScheduledProductDeliveries
                                    .Where(x => x.ScheduledDeliveryId == deliveryId &&
                                           x.SupplyProductId == null &&
                                           x.DeliveryType == ScheduledProductDeliveryType.Delivered)
                                    .ToList();

            var supplyHistory = shopContext.SupplyHistories.Add(new SupplyHistory()).Entity;

            foreach (var deliveredProduct in deliveredProducts)
            {
                DeliverProduct(deliveredProduct, supplyHistory, postgresContext, shopContext);
            }

            postgresContext.SaveChanges();
            shopContext.SaveChanges();
        }
        public IActionResult Delete(int id)
        {
            var cardKeeper = _db.CardKeepers.FirstOrDefault(x => x.Id == id);

            if (cardKeeper == null)
            {
                throw new Exception("Держатель карты не существует");
            }

            cardKeeper.ForManager = false;
            _db.CardKeepers.Update(cardKeeper);
            _db.SaveChanges();

            _postgresContext.ArchiveCardKeepers.Add(new ArchiveCardKeeper(id));
            _postgresContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
        public void Expense(PostgresContext postgresContext, int moneyWorkerId, decimal sum, PaymentType paymentType,
                            int categoryId, string comment, int forId)
        {
            var createdInfoMoney = _infoMoneyService.Create(new InfoMoney()
            {
                MoneyWorkerId      = moneyWorkerId,
                Sum                = -sum,
                MoneyOperationType = MoneyOperationType.Expense,
                PaymentType        = paymentType,
                Comment            = comment
            });

            var expense = _expenseService.Create(new Expense()
            {
                InfoMoneyId       = createdInfoMoney.Id,
                ExpenseCategoryId = categoryId,
            });

            postgresContext.ExpensesOld.Add(new ExpenseOld(expense.Id, forId));
            postgresContext.SaveChanges();
        }
Example #29
0
        public IActionResult Delete(int id)
        {
            Sale sale = _db.Sales
                        .Include(x => x.Partner)
                        .Include(x => x.Shop)
                        .FirstOrDefault(x => x.Id == id);

            var productInformations = _db.ProductInformations
                                      .Where(x => x.SaleId == sale.Id)
                                      .ToList();

            var deletedSale = new DeletedSale()
            {
                Buyer           = sale.Partner?.Title ?? "Обычный покупатель",
                Date            = sale.Date,
                DeletedDate     = DateTime.Now.AddHours(3),
                Discount        = sale.Discount,
                Margin          = sale.Margin,
                Number          = sale.Id,
                ShopId          = sale.ShopId,
                ShopTitle       = sale.Shop.Title,
                Sum             = sale.Sum,
                ProcurementCost = sale.PrimeCost,
                SaleType        = sale.SaleType == SaleType.Sale
                            ? "Обычная продажа"
                            : sale.SaleType == SaleType.SaleFromStock
                                ? "Продажа со склада"
                                : sale.SaleType == SaleType.DefferedSale
                                    ? "Продажа с отложенным платежом"
                                    : sale.SaleType == SaleType.DefferedSaleFromStock
                                        ? "Отложенная продажа со склада поставщика"
                                        : sale.SaleType == SaleType.Booking
                                            ? "Бронирование"
                                            : ""
            };

            foreach (var productInfo in productInformations)
            {
                var supplyProduct = _db.SupplyProducts
                                    .Include(x => x.Product)
                                    .Include(x => x.Supplier)
                                    .FirstOrDefault(x => x.Id == productInfo.SupplyProductId);

                var saleProduct = _db.SalesProducts
                                  .Include(x => x.Product)
                                  .AsNoTracking()
                                  .FirstOrDefault(x => x.SaleId == sale.Id && x.ProductId == productInfo.ProductId);

                deletedSale.Products.Add(new DeletedSaleProduct()
                {
                    Title           = saleProduct.Product.Title,
                    Code            = saleProduct.Product.Code,
                    ProductId       = saleProduct.ProductId,
                    Amount          = productInfo.Amount,
                    Price           = saleProduct.Cost,
                    ProcurementCost = productInfo.ProcurementCost,
                    SupplierId      = supplyProduct?.SupplierId ?? 0,
                    SupplierName    = supplyProduct?.Supplier?.Title ?? ""
                });

                if (productInfo.ForRealization == true && supplyProduct != null)
                {
                    supplyProduct.StockAmount       += productInfo.Amount;
                    supplyProduct.RealizationAmount += productInfo.Amount;

                    var supplier = _supplierService.All().FirstOrDefault(x => x.Id == supplyProduct.SupplierId);

                    if (supplier == null)
                    {
                        throw new Exception("Поставщик не найден");
                    }

                    supplier.Debt -= supplyProduct.ProcurementCost * productInfo.Amount;

                    _supplierService.Update(supplier);
                }
                else if (productInfo.ForRealization == true && supplyProduct == null)
                {
                    var supplierId = _postgresContext.SalesFromStockOld
                                     .FirstOrDefault(x => x.SaleId == sale.Id)?.SupplierId ?? 0;

                    var supplier = _supplierService.All()
                                   .FirstOrDefault(x => x.Id == supplierId);

                    if (supplier == null)
                    {
                        throw new Exception("Поставщик не найден");
                    }

                    var product = deletedSale.Products
                                  .FirstOrDefault(x => x.ProductId == productInfo.ProductId);
                    if (product != null)
                    {
                        product.SupplierId   = supplier.Id;
                        product.SupplierName = supplier.Title;
                    }

                    supplier.Debt -= productInfo.ProcurementCost * productInfo.Amount;

                    _supplierService.Update(supplier);
                }
                else if (supplyProduct != null)
                {
                    supplyProduct.StockAmount += productInfo.Amount;
                }

                if (supplyProduct != null)
                {
                    _supplyProductService.Update(supplyProduct);
                }
            }

            var infoMoneys = _db.InfoMonies
                             .Include(x => x.MoneyWorker)
                             .Where(x => x.SaleId == sale.Id).ToList();

            foreach (var infoMoney in infoMoneys)
            {
                deletedSale.Payments.Add(new DeletedPayment()
                {
                    Sum         = infoMoney.Sum,
                    Account     = infoMoney.MoneyWorker.Title,
                    Comment     = infoMoney.Comment,
                    PaymentType = infoMoney.PaymentType == PaymentType.Cash
                                    ? "Наличный"
                                    : infoMoney.PaymentType == PaymentType.Cashless
                                        ? "Безналичный"
                                        : "Смешанный",
                    Date = infoMoney.Date
                });

                _db.InfoMonies.Remove(infoMoney);
            }

            var salesProducts = _saleProductService.All().Where(x => x.SaleId == sale.Id).ToList();

            foreach (var saleProduct in salesProducts)
            {
                _db.SalesProducts.Remove(saleProduct);
            }

            _db.Sales.Remove(sale);

            _db.SaveChanges();

            _postgresContext.DeletedSalesInfoOld.Add(new DeletedSaleInfoOld()
            {
                Sale = deletedSale
            });
            _postgresContext.SaveChanges();

            return(RedirectToAction("Index"));
        }
Example #30
0
 public void Update(User user)
 {
     users.Update(user);
     context.SaveChanges();
 }