//private LiteBase storageDB;

        public AccountController(
            ILogger <AccountController> logger,
            IEncryptor encryptor,
            DataLite dataLite,
            StorageDbContext storageContext)
        {
            this.logger         = logger;
            this.encryptor      = encryptor;
            this.dataLite       = dataLite;
            this.storageContext = storageContext;
            //storageDB = new LiteBase();
        }
Ejemplo n.º 2
0
        public async Task <Article> UpdateArticleAsync(int id, Article article)
        {
            Article articleToUpdate;

            using (var context = new StorageDbContext())
            {
                articleToUpdate = context.Articles.Include("Author").Include("Comments").Include("Author").Where(a => a.Id == id).FirstOrDefault();

                MergeArticles(articleToUpdate, article, context);
                await context.SaveChangesAsync();
            }
            return(articleToUpdate);
        }
Ejemplo n.º 3
0
 public void Create(List <IngredientsForProduct> newIngredientsForProduct)
 {
     using (StorageDbContext context = new StorageDbContext())
     {
         context.Configuration.AutoDetectChangesEnabled = false;
         foreach (var element in newIngredientsForProduct ?? throw new ArgumentNullException())
         {
             context.IngredientsForProducts.Add(element);
         }
         context.ChangeTracker.DetectChanges();
         context.SaveChanges();
     }
 }
Ejemplo n.º 4
0
        public async Task <int> CreateStorage(string nameParam)
        {
            var entityToCreate = new Data.Entities.Storage
            {
                Name = nameParam
            };

            using var ctx = new StorageDbContext();
            ctx.Storages.Add(entityToCreate);
            await ctx.SaveChangesAsync();

            return(entityToCreate.Id);
        }
Ejemplo n.º 5
0
        public async Task <Article> CreateArticleAsync(Article article)
        {
            Article savedArticle;

            using (var context = new StorageDbContext())
            {
                savedArticle = context.Articles.Add(article);
                await context.SaveChangesAsync();

                savedArticle = context.Articles.Include("Author").Include("Comments").Include("Author").Where(a => a.Id == savedArticle.Id).FirstOrDefault();
            }

            return(savedArticle);
        }
Ejemplo n.º 6
0
        public void Configuration(IAppBuilder app)
        {
            var config = new HttpConfiguration();

            // Setting up configuration
            RouteConfig.RegisterRoutes(config);
            FormatterConfig.RegisterFormatters(config);
            UnityConfig.RegisterComponents(config);

            // Creating context first time
            var storageDb = new StorageDbContext();

            app.UseWebApi(config);
        }
Ejemplo n.º 7
0
 public void BackupData(string patch)
 {
     using (var context = new StorageDbContext())
     {
         patch = patch + "database" + "-" + DateTime.Now.ToString("yyyy-MM-dd--HH-mm-ss") + ".bak";
         if (!File.Exists(patch))
         {
             var file = File.Create(patch);
             file.Close();
         }
         context.Database.ExecuteSqlCommand(
             TransactionalBehavior.DoNotEnsureTransaction,
             "BACKUP DATABASE " + context.Database.Connection.Database + " TO DISK = \'" + patch + "\' WITH INIT;");
     }
 }
Ejemplo n.º 8
0
 private void MergeArticles(Article articleToUpdate, Article article, StorageDbContext context)
 {
     articleToUpdate.Title      = article.Title;
     articleToUpdate.Likes      = article.Likes;
     articleToUpdate.LastEdited = article.LastEdited;
     articleToUpdate.Body       = article.Body;
     foreach (var comment in article.Comments)
     {
         // Comment wasn't added
         if (comment.Id == 0)
         {
             articleToUpdate.Comments.Add(comment);
         }
     }
 }
Ejemplo n.º 9
0
 public static void FormatingAllData()
 {
     using (var context = new StorageDbContext())
     {
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "TRUNCATE TABLE ProductStatistic");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "TRUNCATE TABLE IngredientStatistic");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "TRUNCATE TABLE IngredientsForProducts");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "TRUNCATE TABLE Conteiners");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "TRUNCATE TABLE Packages");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "TRUNCATE TABLE Tares");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "TRUNCATE TABLE Clients");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "TRUNCATE TABLE Securities");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, @"DELETE FROM Ingredients WHERE ID != -1");
         context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, @"DELETE FROM Products WHERE ID != -1");
     }
 }
 public void Create(Ingredient newIngredient)
 {
     using (StorageDbContext context = new StorageDbContext())
     {
         var ingredient = context.Ingredients.FirstOrDefault(element => element.Name == newIngredient.Name);
         if (ingredient == null)
         {
             context.Ingredients.Add(newIngredient);
             context.SaveChanges();
         }
         else
         {
             throw new ArgumentException($"Цей інгредієнт вже існує.");
         }
     }
 }
Ejemplo n.º 11
0
        public async Task Handle(IDomainEvent <BoxAggregate, BoxId, BoxCreatedEvent> domainEvent)
        {
            var entity = new BoxEntity
            {
                AggregateId = domainEvent.AggregateIdentity.Value,
                Barcode     = domainEvent.AggregateEvent.Barcode.Value,
                Created     = domainEvent.Timestamp,
                Modified    = domainEvent.Timestamp
            };

            using (var db = new StorageDbContext(_dbContextOptions))
            {
                await db.AddAsync(entity).ConfigureAwait(false);

                await db.SaveChangesAsync().ConfigureAwait(false);
            }
        }
Ejemplo n.º 12
0
        public ActionResult DoUpload(IFormFile file)
        {
            using (var stream = file.OpenReadStream())
            {
                var xs      = new XmlSerializer(typeof(StorageModel));
                var storage = (StorageModel)xs.Deserialize(stream);


                using (var db = new StorageDbContext())
                {
                    var dbs = new DbStorage()
                    {
                        Name        = storage.Name,
                        Capacity    = storage.Capacity,
                        Address     = storage.Address,
                        StorageType = storage.StorageType,
                    };
                    dbs.Items = new Collection <DbItem>();
                    foreach (var item in storage.Items)
                    {
                        dbs.Items.Add(new DbItem()
                        {
                            Name         = item.Name,
                            Price        = item.Price,
                            Units        = item.Units,
                            Manufacturer = item.Manufacturer
                        });
                    }
                    dbs.Workers = new Collection <DbWorkers>();
                    foreach (var worker in storage.Workers)
                    {
                        dbs.Workers.Add(new DbWorkers()
                        {
                            Name       = worker.Name,
                            Position   = worker.Position,
                            Experience = worker.Experience,
                        });
                    }
                    db.StorageFacilities.Add(dbs);
                    db.SaveChanges();
                }

                return(View(storage));
            }
        }
        public void Delete(Ingredient ingredient)
        {
            using (StorageDbContext context = new StorageDbContext())
            {
                context.Configuration.AutoDetectChangesEnabled = false;
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        PackageRepository package           = new PackageRepository();
                        ProductRepository productRepository = new ProductRepository();
                        IngredientsForProductRepository ingredientsForProductRepository = new IngredientsForProductRepository();

                        package.Delete(ingredient);

                        var allReceiptsWithEntryIngredients = ingredientsForProductRepository.GetDataSource().Where(n => n.IngredientId == ingredient.Id).ToList();
                        if (allReceiptsWithEntryIngredients != null)
                        {
                            foreach (var oneIngredientForProductInReceipt in allReceiptsWithEntryIngredients)
                            {
                                Product productWithEntryIngredientInReceipt = productRepository.GetDataSource().First(n => n.Id == oneIngredientForProductInReceipt.ProductId);

                                productRepository.Delete(productWithEntryIngredientInReceipt);
                            }
                        }

                        context.Configuration.ValidateOnSaveEnabled = false;
                        context.Ingredients.Attach(ingredient);
                        context.Entry(ingredient).State = EntityState.Deleted;
                        context.ChangeTracker.DetectChanges();
                        context.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception)
                    {
                        transaction.Rollback();
                        throw new InvalidOperationException("Помилка видалення.");
                    }
                    finally
                    {
                        context.Configuration.ValidateOnSaveEnabled = true;
                    }
                }
            }
        }
Ejemplo n.º 14
0
        public static void Seed(StorageDbContext context)
        {
            var listCountry = new List <SearchProvider>
            {
                new SearchProvider {
                    Id = 1, Name = "Google"
                },
                new SearchProvider {
                    Id = 2, Name = "Bing"
                },
                new SearchProvider {
                    Id = 3, Name = "Yandex"
                }
            };

            context.Providers.AddRange(listCountry);
            context.SaveChanges();
        }
        public List <IngredientPackage> GetIngredientPackageDataSource()
        {
            List <IngredientPackage> dataSource;

            using (var dbcontext = new StorageDbContext())
            {
                dataSource = dbcontext.Packages.
                             Join(
                    dbcontext.Ingredients,
                    package => package.IngredientId,
                    ingredient => ingredient.Id,
                    (package, ingredient) => new IngredientPackage()
                {
                    Name   = ingredient.Name,
                    Weight = package.Weight
                }).OrderBy(n => n.Name).ToList();
            }
            return(dataSource);
        }
Ejemplo n.º 16
0
        public bool VerifyPassword(string password)
        {
            bool result = false;

            using (StorageDbContext dbContext = new StorageDbContext())
            {
                Security currPassword = dbContext.Securities.FirstOrDefault();

                if (currPassword == null)
                {
                    dbContext.Securities.Add(new Security());
                    currPassword = dbContext.Securities.FirstOrDefault();
                }

                result = currPassword.Pass == Security.GetHashPass(password);
            }

            return(result);
        }
Ejemplo n.º 17
0
        static void Main(string[] args)
        {
            IConfiguration config = ConfigLoader.LoadConfig("appsettings.json");

            Logger.Debug("Starting app");
            var productCatalogClient = new ProductCatalogClient(config);

            var contextOptions = new DbContextOptionsBuilder().UseSqlServer(config.GetConnectionString("StorageDb")).Options;
            var dbContext      = new StorageDbContext(contextOptions);

            var productRepository = new AvailableProductRepository(dbContext);
            var unitOfWork        = new UnitOfWork(dbContext);

            var b        = new ProductCacheManager(productCatalogClient, productRepository, unitOfWork);
            var listener = b.BeginEventListener();

            Logger.Debug("Event Listening begun.");

            Task.WaitAll(listener);
        }
Ejemplo n.º 18
0
        public List <ProductConteiner> GetProductConteinerDataSource()
        {
            List <ProductConteiner> dataSource;

            using (var dbcontext = new StorageDbContext())
            {
                dataSource = dbcontext.Conteiners.
                             Join(
                    dbcontext.Products,
                    conteiner => conteiner.ProductId,
                    product => product.Id,
                    (conteiner, product) => new ProductConteiner()
                {
                    Name   = product.Name,
                    Weight = conteiner.Weight,
                    Amount = conteiner.Amount
                }).OrderBy(n => n.Weight).ToList().OrderBy(n => n.Name).ToList();
            }
            return(dataSource);
        }
Ejemplo n.º 19
0
        public void Add(Tare tare)
        {
            using (StorageDbContext dbContext = new StorageDbContext())
            {
                using (var transaction = dbContext.Database.BeginTransaction())
                {
                    try
                    {
                        dbContext.Tares.First(n => n.Name == tare.Name).Amount += tare.Amount;

                        dbContext.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw new Exception(ex.Message);
                    }
                }
            }
        }
Ejemplo n.º 20
0
 public void Add(int ingredientId, int typeEvent, double weight, DateTime dateTime)
 {
     using (var context = new StorageDbContext())
     {
         using (var transaction = context.Database.BeginTransaction())
         {
             try
             {
                 context.IngredientStatistics.Add(
                     new IngredStatElement(ingredientId, typeEvent, weight, dateTime)
                     );
                 context.SaveChanges();
                 transaction.Commit();
             }
             catch (Exception)
             {
                 transaction.Rollback();
             }
         }
     }
 }
Ejemplo n.º 21
0
        public void Edit(IngredientsForProduct newIngredientsForProduct)
        {
            using (StorageDbContext context = new StorageDbContext())
            {
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        context.IngredientsForProducts.First(n => n.Id == newIngredientsForProduct.Id).IngredientId = newIngredientsForProduct.IngredientId;

                        context.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception ex)
                    {
                        transaction.Rollback();
                        throw new Exception(ex.Message);
                    }
                }
            }
        }
Ejemplo n.º 22
0
 public void Remove(int index, DateTime dateRemove, int typeEvent, int amount = 1)
 {
     using (StorageDbContext context = new StorageDbContext())
     {
         using (var transaction = context.Database.BeginTransaction())
         {
             try
             {
                 context.Configuration.AutoDetectChangesEnabled = false;
                 context.Conteiners.Find(index).Amount         -= amount;
                 var res = context.Conteiners.Find(index);
                 if (res.Amount < 0)
                 {
                     throw new ArgumentOutOfRangeException();
                 }
                 if (res.Amount == 0)
                 {
                     var someConteiner = context.Conteiners.Find(index);
                     context.Configuration.ValidateOnSaveEnabled = false;
                     context.Conteiners.Attach(someConteiner);
                     context.Entry(someConteiner).State = EntityState.Deleted;
                 }
                 context.ProductStatistics.Add(new ProdStatElement(res.ProductId, typeEvent, res.Weight * amount, dateRemove));
                 context.ChangeTracker.DetectChanges();
                 context.SaveChanges();
                 transaction.Commit();
             }
             catch (Exception)
             {
                 transaction.Rollback();
                 throw new ArgumentException();
             }
             finally
             {
                 context.Configuration.ValidateOnSaveEnabled = true;
             }
         }
     }
 }
Ejemplo n.º 23
0
        public void Edit(Product newProduct, Dictionary <Ingredient, double> newReceipt)
        {
            using (StorageDbContext context = new StorageDbContext())
            {
                context.Configuration.AutoDetectChangesEnabled = false;
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        IngredientsForProductRepository ingredientsForProductRepository = new IngredientsForProductRepository();

                        var currentProduct = context.Products.FirstOrDefault(element => element.Id == newProduct.Id);

                        if (currentProduct == null)
                        {
                            throw new ArgumentNullException("Цей продукт не існує");
                        }

                        currentProduct.Name = newProduct.Name;

                        ingredientsForProductRepository.Delete(currentProduct);

                        foreach (var element in newReceipt)
                        {
                            context.IngredientsForProducts.Add(new IngredientsForProduct(currentProduct, element.Key, element.Value));
                        }

                        context.ChangeTracker.DetectChanges();
                        context.SaveChanges();
                        transaction.Commit();
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();
                        throw new ArgumentException(e.Message);
                    }
                }
            }
        }
Ejemplo n.º 24
0
        public void Create(Product newProduct, Dictionary <Ingredient, double> receipt)
        {
            using (StorageDbContext context = new StorageDbContext())
            {
                context.Configuration.AutoDetectChangesEnabled = false;
                using (var transaction = context.Database.BeginTransaction())
                {
                    try
                    {
                        var product = context.Products.Where(element => element.Name == newProduct.Name);
                        if (!product.Any())
                        {
                            context.Products.Add(newProduct);
                            context.ChangeTracker.DetectChanges();
                            context.SaveChanges();
                            var currentProduct = context.Products.FirstOrDefault(buffProduct => buffProduct.Name == newProduct.Name);

                            foreach (var element in receipt)
                            {
                                context.IngredientsForProducts.Add(new IngredientsForProduct(currentProduct, element.Key, element.Value));
                            }
                            context.ChangeTracker.DetectChanges();
                            context.SaveChanges();
                            transaction.Commit();
                        }
                        else
                        {
                            throw new ArgumentException("Цей продукт вже існує.");
                        }
                    }
                    catch (Exception e)
                    {
                        transaction.Rollback();
                        throw new ArgumentException(e.Message);
                    }
                }
            }
        }
Ejemplo n.º 25
0
 public void Delete(Product product)
 {
     using (StorageDbContext context = new StorageDbContext())
     {
         try
         {
             context.Configuration.ValidateOnSaveEnabled    = false;
             context.Configuration.AutoDetectChangesEnabled = false;
             var recept = context.IngredientsForProducts.Where(element => element.ProductId == product.Id);
             foreach (var elementOfRecept in recept)
             {
                 context.IngredientsForProducts.Attach(elementOfRecept);
                 context.Entry(elementOfRecept).State = EntityState.Deleted;
             }
             context.ChangeTracker.DetectChanges();
             context.SaveChanges();
         }
         finally
         {
             context.Configuration.ValidateOnSaveEnabled = true;
         }
     }
 }
Ejemplo n.º 26
0
 public void Remove(DateTime date1, DateTime date2)
 {
     using (var context = new StorageDbContext())
     {
         try
         {
             context.Configuration.ValidateOnSaveEnabled    = false;
             context.Configuration.AutoDetectChangesEnabled = false;
             var listOfStatistics = context.IngredientStatistics.Where(element => element.Date <= date2 && element.Date >= date1);
             foreach (var someConteiner in listOfStatistics)
             {
                 context.IngredientStatistics.Attach(someConteiner);
                 context.Entry(someConteiner).State = EntityState.Deleted;
             }
             context.ChangeTracker.DetectChanges();
             context.SaveChanges();
         }
         finally
         {
             context.Configuration.ValidateOnSaveEnabled = true;
         }
     }
 }
Ejemplo n.º 27
0
 public void DeleteByWeight(Conteiner oneConteiner)
 {
     using (StorageDbContext context = new StorageDbContext())
     {
         try
         {
             context.Configuration.ValidateOnSaveEnabled    = false;
             context.Configuration.AutoDetectChangesEnabled = false;
             var listOfConteiner = context.IngredientsForProducts.Where(element =>
                                                                        element.ProductId == oneConteiner.ProductId & element.Weight == oneConteiner.Weight);
             foreach (var someConteiner in listOfConteiner)
             {
                 context.IngredientsForProducts.Attach(someConteiner);
                 context.Entry(someConteiner).State = EntityState.Deleted;
             }
             context.ChangeTracker.DetectChanges();
             context.SaveChanges();
         }
         finally
         {
             context.Configuration.ValidateOnSaveEnabled = true;
         }
     }
 }
Ejemplo n.º 28
0
 public async Task <Contracts.Storage> GetStorage(int idParam)
 {
     using var ctx = new StorageDbContext();
     return(_mapper.Map <Contracts.Storage>(await ctx.Storages
                                            .FirstOrDefaultAsync(x => x.Id == idParam)));
 }
Ejemplo n.º 29
0
 public StoragesModel(ILogger <StoragesModel> logger, IMapper mapper, StorageDbContext context)
 {
     _logger  = logger;
     _mapper  = mapper;
     _context = context;
 }
Ejemplo n.º 30
0
 public StorageRepositoryAsync(StorageDbContext dbContext) : base(dbContext)
 {
     _items = dbContext.Set <Item>();
 }