Пример #1
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, SQLiteDBContext dbContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }
            app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
            dbContext.Database.Migrate();
        }
        public string GetSummary()
        {
            SummaryDataWsResponce summaryDataWsResponce = new SummaryDataWsResponce();

            try
            {
                using (var db = new SQLiteDBContext())
                {
                    var query = db.SummaryData
                                .Where(t => t.DayDate >= DateTime.Now.Date)
                                .Where(t => t.DayDate < DateTime.Now.AddHours(24 - DateTime.Now.Hour));
                    summaryDataWsResponce.SummaryData = query.ToArray();
                }
                summaryDataWsResponce.BaseResponse = new BaseResponse {
                    ErorInfo = ErorCode.Success, MessageInfo = "Succes Process"
                };
            }
            catch (Exception ex)
            {
                summaryDataWsResponce.BaseResponse = new BaseResponse {
                    ErorInfo = ErorCode.Error, MessageInfo = "Error Process!. Detail " + ex.Message
                };
            }

            return(JsonConvert.SerializeObject(summaryDataWsResponce));
        }
Пример #3
0
 public PhaseSetsGetter(SQLiteDBContext dbContext, IImageIndexesGetter imageIndexesGetter, ICollectionRandomizer collectionRandomizer, IOptions <Config> config)
 {
     _dbContext            = dbContext;
     _imageIndexesGetter   = imageIndexesGetter;
     _collectionRandomizer = collectionRandomizer;
     _config = config.Value;
 }
Пример #4
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            using var client = new SQLiteDBContext();
            client.Database.EnsureCreated();
            Seed.InitiateSeed(client).Wait();
        }
Пример #5
0
 public TransfersController(SQLiteDBContext context, IAccountService accountservice, ITransactionService transactionservice, ITransactionsViewModel viewModel, ITransactions transaction)
 {
     _context            = context;
     _accountService     = accountservice;
     _transactionService = transactionservice;
     _viewModel          = viewModel;
     _transaction        = transaction;
 }
Пример #6
0
        public int AddPurchaseOrder(Order order)
        {
            using (var db = new SQLiteDBContext())
            {
                db.Orders.Add(order);
                db.SaveChanges();
            }

            return(order.Id);
        }
Пример #7
0
        public static UnitOfWork Create()
        {
            string path                    = $"FileName={Path.Combine(TestContext.CurrentContext.TestDirectory, @"Data\SQLiteDB.db")}";
            var    context                 = new SQLiteDBContext(path);
            var    cacheStorage            = new MemoryCacheStorage(new MemoryCache(new MemoryCacheOptions()));
            var    configurationRepository = new TestConfRepository();
            var    cachingRepository       = new CachingRepositoryFactory(new RepositoryFactory(context), cacheStorage, configurationRepository);

            return(new UnitOfWork(context, cachingRepository));
        }
        public async Task <BlogPostVM> GetBySlug(string slug)
        {
            using var db = new SQLiteDBContext();

            var result = await db.BlogPosts.Include(bp => bp.Tags).FirstOrDefaultAsync(k => k.Slug == slug) ?? throw new NotFoundException(slug);

            var post = mapper.Map <BlogPostVM>(result);

            return(post);
        }
        public async Task <bool> Delete(string slug)
        {
            using var db = new SQLiteDBContext();

            var result = await db.BlogPosts.FindAsync(slug) ?? throw new NotFoundException(slug);

            db.BlogPosts.Remove(result);
            await db.SaveChangesAsync();

            return(true);
        }
        public async Task <BlogPostVM> Update(BlogPostUpdateVM request, string slug)
        {
            using var db = new SQLiteDBContext();

            var blogPost = await db.BlogPosts.Include(x => x.Tags).FirstOrDefaultAsync(bp => bp.Slug == slug) ?? throw new NotFoundException(slug);

            #region IfTitleHasChanged

            if (request.Title != blogPost.Title && !string.IsNullOrEmpty(request.Title))
            {
                var tags = new List <BlogPostTag>(blogPost.Tags);
                //Delete all referenced entities
                foreach (var item in blogPost.Tags)
                {
                    db.BlogPostTags.Remove(item);
                }
                await db.SaveChangesAsync();

                blogPost.Tags = null;
                db.BlogPosts.Remove(blogPost);
                await db.SaveChangesAsync();

                //Add the post again with all the tags
                SlugHelper helper = new SlugHelper();
                blogPost.Slug = helper.GenerateSlug(request.Title);

                await db.BlogPosts.AddAsync(blogPost);

                await db.SaveChangesAsync();

                foreach (var tag in tags)
                {
                    var postTag = new BlogPostTag()
                    {
                        TagId = tag.TagId, BlogPostId = blogPost.Slug
                    };
                    await db.BlogPostTags.AddAsync(postTag);
                }
                await db.SaveChangesAsync();

                blogPost.Tags = tags;
            }
            #endregion

            blogPost.UpdatedAt = DateTime.UtcNow;
            mapper.Map(request, blogPost);

            db.BlogPosts.Update(blogPost);
            await db.SaveChangesAsync();

            var response = mapper.Map <BlogPostVM>(blogPost);

            return(response);
        }
Пример #11
0
        public List <Order> GetAllOrders()
        {
            var result = new List <Order>();

            using (var db = new SQLiteDBContext())
            {
                result = db.Orders.Include("Address").Include("Products").ToList();
            }

            return(result);
        }
Пример #12
0
        public void MenologyDayLoading_ItemText_and_Dates()
        {
            string path       = Path.Combine(TestContext.CurrentContext.TestDirectory, @"FileName=Data\SQLiteDB.db");
            var    context    = new SQLiteDBContext(path);
            var    unitOfWork = new UnitOfWork(context, new RepositoryFactory(context));

            MenologyDay entity = unitOfWork.Repository <MenologyDay>().GetAll().FirstOrDefault();

            Assert.IsFalse(entity.Date.IsEmpty);
            Assert.IsFalse(entity.DateB.IsEmpty);
        }
Пример #13
0
        public async Task <TagVM> Get()
        {
            using var db = new SQLiteDBContext();

            TagVM tags = new TagVM()
            {
                Tags = await db.Tags.Select(k => k.Name).ToListAsync()
            };

            return(tags);
        }
Пример #14
0
        public void DayWorshipLoading_ItemTexts()
        {
            string path       = Path.Combine(TestContext.CurrentContext.TestDirectory, @"FileName=Data\SQLiteDB.db");
            var    context    = new SQLiteDBContext(path);
            var    unitOfWork = new UnitOfWork(context, new RepositoryFactory(context));

            //TODO: переделать
            DayWorship entity = null;// unitOfWork.Repository<DayWorship>().Get(c => c.Id == 155);

            Assert.IsFalse(entity.WorshipName.IsEmpty);
            Assert.Pass(entity.WorshipName.StringExpression);
        }
        public async Task <BlogPostVM> Insert(BlogPostAddVM request)
        {
            using var db = new SQLiteDBContext();

            var result = mapper.Map <BlogPost>(request);

            SlugHelper helper = new SlugHelper();

            result.Slug = helper.GenerateSlug(result.Title);

            result.CreatedAt = DateTime.UtcNow;
            await db.BlogPosts.AddAsync(result);

            await db.SaveChangesAsync();

            #region MappingTagsToDB
            //If tags are added check if they exist in db, if not save them
            //Add BlogPostTags middle table elements and save them to db
            string[] tagList = null;
            if (request.TagList != null && request.TagList.Length > 0)
            {
                int tagCount = request.TagList.Length;
                tagList = new string[tagCount];

                for (int i = 0; i < tagCount; i++)
                {
                    tagList[i] = request.TagList[i];
                    // If the Tag is not in the database persist it
                    if (await db.Tags.FindAsync(request.TagList[i]) == null)
                    {
                        await tagService.Insert(new Tag()
                        {
                            Name = request.TagList[i]
                        });
                    }

                    //Add tags to post and save to db
                    BlogPostTag temp = new BlogPostTag()
                    {
                        TagId = request.TagList[i], BlogPostId = result.Slug
                    };
                    await db.BlogPostTags.AddAsync(temp);
                }
                await db.SaveChangesAsync();
            }
            #endregion

            var response = mapper.Map <BlogPostVM>(result);
            response.TagList = tagList;

            return(response);
        }
Пример #16
0
        public async Task <Tag> Insert(Tag tag)
        {
            using var db = new SQLiteDBContext();

            if (!string.IsNullOrEmpty(tag.Name))
            {
                await db.Tags.AddAsync(tag);

                await db.SaveChangesAsync();
            }

            return(tag);
        }
        public async Task <IActionResult> GetLast10()
        {
            try
            {
                using (var db = new SQLiteDBContext())
                {
                    var results = await db.CurrencyConversions.OrderByDescending(x => x.ConvertedAt).Take(10).ToListAsync();

                    return(Ok(results));
                }
            }
            catch (System.Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Failure retrieving information."));
            }
        }
Пример #18
0
        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                engine = new SQLiteDBContext();                                               //база данных context
                /* IQueryable<Product> products = engine.Products.Include(d => d.Category);*/ //метод   Include связывает две таблицы products и categories
                ListBox_ProductWithCategory.ItemsSource       = Products;                     // записываем в самое нижнее поле ListBox Row 5 engine.Products.Include(d => d.Category);
                ComboBox_CategoriesToDelete.ItemsSource       = engine.Categories.ToList();   //записываем в самое нижнее поле Delete engine.Products.Include(d => d.Category);
                ComboBox_CategoriesForProductSave.ItemsSource = engine.Categories.ToList();
                ComboBox_ProductDelete.ItemsSource            = Products;
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                throw;
            }



            #region
            //try
            //{
            //    engine = new SQLiteDBContext();
            //    IQueryable<Product> products = engine.Products.Include(d => d.Category);
            //    Product p = products.FirstOrDefault();
            //    MessageBox.Show(p.Category.Name);
            //    //CategoriesListBox.ItemsSource = engine.Products.ToList();
            //    //CategoriesListBox.ItemsSource = engine.Categories.ToList();
            //}

            //catch (Exception ex)
            //{
            //    MessageBox.Show(ex.Message);
            //    throw;
            //}

            /*foreach (var item in sQLiteDBEngine.Categories.ToList())
             * {
             *  Console.WriteLine(item.Id  + " "  + item.Name) ;
             * }*/

            //engine.Categories.Add(new Category { Name="Пробухал"});
            //engine.SaveChanges();
            #endregion
        }
Пример #19
0
        public void BypassSequenceViewer_Test()
        {
            string path       = Path.Combine(TestContext.CurrentContext.TestDirectory, @"FileName=Data\SQLiteDB.db");
            var    context    = new SQLiteDBContext(path);
            var    unitOfWork = new UnitOfWork(context, new RepositoryFactory(context));

            //BookStorage.Instance = BookStorageFactory.Create(unitOfWork);

            ISequenceViewer viewer = new BypassSequenceViewer(unitOfWork);

            string result = viewer.GetSequence(new GetSequenceRequest()
            {
                TypiconId = 1, Date = DateTime.Today
            }).Sequence;

            Assert.IsNotEmpty(result);
            Assert.Pass(result);
        }
Пример #20
0
        /* Load configuration from db */
        // public void LoadAll(){
        //     /* access db */
        //     using(var db = new SQLiteDBContext()){
        //         /* load all guilds */
        //         foreach(var record in db.GuildConfigs){
        //             LoadGuild(record);
        //         }
        //     }
        // }
        /* (re)load single guild */
        public void LoadSingle(ulong guildId)
        {
            /* access db */
            using (var db = new SQLiteDBContext()){
                /*
                 * If this throws
                 * an exception
                 * look in SQLiteDBContext.cs
                 */

                /* load single record */
                if (db.GuildConfigs.Find(guildId) == null)
                {
                    return;
                }
                LoadGuild(db.GuildConfigs.Find(guildId));
            }
        }
Пример #21
0
        static void Main(string[] args)
        {
            using (var db = new SQLiteDBContext())
            {
                // Insert
                db.VideoGames.Add(new VideoGame {
                    Title = "Pokemon", Platform = "Nintendo", ReleaseYear = 2001
                });
                db.VideoGames.Add(new VideoGame {
                    Title = "Minecraft", Platform = "XBox", ReleaseYear = 2020
                });

                db.SaveChanges();
                Console.WriteLine("Video juego añadido...");

                // Read
                Console.WriteLine("Buscando video juegos...");
                var videogames = db.VideoGames.ToList();

                foreach (var videogame in videogames)
                {
                    Console.WriteLine($"{videogame.Title} - {videogame.Platform} - {videogame.ReleaseYear}");
                    Console.Write(videogame.Title);
                    Console.WriteLine(videogame.Platform);
                }

                // Borrar
                Console.WriteLine("Borrando un video juego...");
                VideoGame vg1 = db.VideoGames.First(); //get un objeto

                db.VideoGames.Remove(vg1);
                db.SaveChanges();


                //Actualizar
                Console.WriteLine("Actualizando un video juego...");
                VideoGame vg2 = db.VideoGames.First(); //get un objeto

                vg2.ReleaseYear = 1990;

                db.SaveChanges();
            }
        }
        public async Task <MultipleBlogPostsVM> Get(string tag = null)
        {
            using var db = new SQLiteDBContext();

            var result = await db.BlogPosts.Include(k => k.Tags).OrderByDescending(k => k.CreatedAt).ToListAsync();

            if (!string.IsNullOrWhiteSpace(tag))//Should use query, but since its just the tag I kept it simple
            {
                result = await db.BlogPostTags.Where(x => x.TagId == tag).Select(k => k.BlogPost).ToListAsync();
            }

            var posts = mapper.Map <List <BlogPostVM> >(result);

            var multiplePosts = new MultipleBlogPostsVM()
            {
                BlogPosts  = posts.ToArray(),
                postsCount = posts.Count
            };

            return(multiplePosts);
        }
        private async Task <IActionResult> CreateRecord(CurrencyConversion conversion)
        {
            try
            {
                using (var db = new SQLiteDBContext())
                {
                    await db.CurrencyConversions.AddAsync(conversion);

                    if (await db.SaveChangesAsync() > 0)
                    {
                        return(Ok());
                    }
                    ;
                }

                return(BadRequest());
            }
            catch (System.Exception)
            {
                return(this.StatusCode(StatusCodes.Status500InternalServerError, "Failure creating record."));
            }
        }
Пример #24
0
        public ViewModel(SQLiteDBContext context, params string[] modelNames)
        {
            foreach (string modelName in modelNames)
            {
                switch (modelName)
                {
                case nameof(Blog):
                    Blogs = context.Blogs.ToList();
                    break;

                case nameof(ContactForm):
                    ContactForm = new ContactForm();
                    break;

                case nameof(Movie):
                    Movies = context.Movies.ToList();
                    break;

                case nameof(SystemConfig):
                    SystemConfigs = context.SystemConfigs.ToList();
                    break;
                }
            }
        }
Пример #25
0
        public void Do()
        {
            string conf = Environment.GetEnvironmentVariable("DATA_PATH");
            string path = Path.Combine(Path.GetDirectoryName(conf) ?? throw new NullReferenceException("data path is null"), "catalog_product_entity.json");
            string json = File.ReadAllText(path);

            try
            {
                CatalogProductEntities tblarticoliObj = JsonConvert.DeserializeObject <CatalogProductEntities>(json);

                int rowSum = 0;
                foreach (CatalogProductEntity element in tblarticoliObj.CatalogProductEntity.OrderBy(o => o.CodArt))
                {
                    var sku   = element.CodArt;
                    var ean   = element.CodEan;
                    var descr = element.DescArticolo;

                    if (string.IsNullOrEmpty(ean))
                    {
                        continue;
                    }

                    int.TryParse(sku, out int n);
                    if (n < GetLastItem())
                    {
                        continue;
                    }

                    using (var db = new SQLiteDBContext())
                    {
                        var product = db.Products
                                      .FirstOrDefault(b => b.Sku == sku);

                        DateTime foo      = DateTime.Today;
                        int      unixTime = Convert.ToInt32(((DateTimeOffset)foo).ToUnixTimeSeconds());

                        if (product is null)
                        {
                            db.Products.Add(new Products {
                                Sku = sku, Attempts = 1, UpdatedAt = unixTime
                            });
                            db.SaveChanges();
                        }
                        else
                        {
                            if (product.Attempts < 100 && product.UpdatedAt < unixTime)
                            {
                                product.Attempts += 1;
                                product.UpdatedAt = unixTime;
                                db.SaveChanges();
                            }
                            else
                            {
                                continue;
                            }
                        }
                    }

                    if (rowSum % 25 == 0)
                    {
                        if (_driver is IWebDriver)
                        {
                            _driver.Manage().Cookies.DeleteAllCookies();
                            _driver.Close();
                        }

                        DateTime time = DateTime.Now.AddYears(1);
                        _driver = InitBrowser();
                        _driver.Navigate().GoToUrl("https://www.cosicomodo.it");
                        _driver.Manage().Cookies.AddCookie(new Cookie(
                                                               "cosicomodo_provisionalcap",
                                                               "\"37030 - Montecchia di Crosara\"",
                                                               "www.cosicomodo.it",
                                                               "/",
                                                               time
                                                               ));

                        _driver.Manage().Cookies.AddCookie(new Cookie(
                                                               "familanord_anonymous_preferred_base_store",
                                                               "MAXIDI_FAMILA_019861",
                                                               "www.cosicomodo.it",
                                                               "/",
                                                               time
                                                               ));

                        _driver.Manage().Cookies.AddCookie(new Cookie(
                                                               "familanord_provisionalcap",
                                                               "\"37030 - Montecchia di Crosara\"",
                                                               "www.cosicomodo.it",
                                                               "/",
                                                               time
                                                               ));

                        _driver.Manage().Cookies.AddCookie(new Cookie(
                                                               "is_provisionalcap_from_aggregator",
                                                               "true",
                                                               "www.cosicomodo.it",
                                                               "/",
                                                               time
                                                               ));

                        _driver.Manage().Cookies.AddCookie(new Cookie(
                                                               "cookies-disclaimer-v1",
                                                               "true",
                                                               "www.cosicomodo.it",
                                                               "/",
                                                               time
                                                               ));
                    }


                    Console.WriteLine($"Cerco l'articolo {sku}: {descr}");
                    string        searchPageUrl = $"https://www.cosicomodo.it/familanord/san-bonifacio-villanova/ricerca?q={ean}";
                    WebDriverWait wait          = new WebDriverWait(_driver, TimeSpan.FromSeconds(25));
                    _driver.Navigate().GoToUrl(searchPageUrl);

                    IWebElement         firstResult = wait.Until(ExpectedConditions.ElementExists(By.CssSelector(".dobody-container .listing")));
                    IList <IWebElement> links       = firstResult.FindElements(By.TagName("a"));

                    if (!links.Any())
                    {
                        rowSum++;
                        continue;
                    }

                    IWebElement link           = links.First(e => e.GetAttribute("href") != "#");
                    string      productPageUrl = link.GetAttribute("href");
                    if (string.IsNullOrEmpty(productPageUrl))
                    {
                        rowSum++;
                        continue;
                    }
                    Console.WriteLine(productPageUrl);

                    _driver.Navigate().GoToUrl(productPageUrl);
                    IWebElement         secondResult = wait.Until(ExpectedConditions.ElementExists(By.CssSelector(".image-container")));
                    IList <IWebElement> images       = secondResult.FindElements(By.CssSelector(".image-container .slick-slide a.mfp-zoom"));

                    for (int i = 0; i < images.Count() && i < 5; i++)
                    {
                        string image = images.ElementAt(i).GetAttribute("href");
                        if (string.IsNullOrEmpty(image))
                        {
                            continue;
                        }
                        Console.WriteLine(image);
                        SaveImage(image, sku + "_" + i + ".jpg", ImageFormat.Jpeg);
                    }

                    rowSum++;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            finally
            {
                Thread.Sleep(3000);
            }
        }
Пример #26
0
 public ProjectController(ILogger <ProjectController> logger, SQLiteDBContext sqlContext)
 {
     _logger     = logger;
     _sqlContext = sqlContext;
 }
Пример #27
0
 public PhoneBookRepository(SQLiteDBContext dbContext)
 {
     this.dbContext = dbContext;
 }
Пример #28
0
 public UsuariaService(SQLiteDBContext context)
 {
     _dBContext = context;
 }
Пример #29
0
 public PSQIRepository(SQLiteDBContext dbContext)
 {
     _dbContext = dbContext;
 }
Пример #30
0
 public UsersRepository(SQLiteDBContext context)
 {
     _context = context;
 }