Example #1
0
        public static void TestInit(TestContext context)
        {
            //TextWriterTraceListener myCreator = new TextWriterTraceListener(System.Console.Out);
            //Trace.Listeners.Add(myCreator);
            string logFolder = ConfigurationManager.AppSettings["LogPath"];
            var logPath = Path.Combine(logFolder, string.Format("{0}Trace.txt", DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")));
            Trace.Listeners.Add(new TextWriterTraceListener(logPath));

            IServiceContext serviceContext = ServiceContext.NewServiceContext("*****@*****.**", "", "", "Arcserve", DataProtectInterface.TaskType.Catalog);
            serviceContext.CurrentMailbox = "*****@*****.**";
            var dataAccess = CatalogFactory.Instance.NewCatalogDataAccessInternal(serviceContext.Argument, serviceContext.AdminInfo.OrganizationName);
            dataAccess.ResetAllStorage(serviceContext.CurrentMailbox);

            if (!FactoryBase.IsRunningOnAzureOrStorageInAzure())
            {

                using (CatalogDbContext dbContext = new CatalogDbContext(new SqlDbImpl.Model.OrganizationModel() { Name = "Arcserve" }))
                {
                    dbContext.Folders.RemoveRange(dbContext.Folders);
                    dbContext.ItemLocations.RemoveRange(dbContext.ItemLocations);
                    dbContext.Items.RemoveRange(dbContext.Items);
                    dbContext.Catalogs.RemoveRange(dbContext.Catalogs);
                    dbContext.Mailboxes.RemoveRange(dbContext.Mailboxes);

                    dbContext.SaveChanges();
                }
            }
        }
Example #2
0
 public void DeleteDatabase(string organization)
 {
     using (CatalogDbContext context = new CatalogDbContext(new OrganizationModel() { Name = organization }))
     {
         if(context.Database.Exists())
         {
             context.Database.Delete();
         }
     }
 }
Example #3
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, CatalogDbContext catalogDbContext, IBrokerEndpointsConfigurationBuilder endpoints, JobScheduler jobScheduler)
        {
            ConfigureRequestPipeline(app);

            catalogDbContext.Database.Migrate();

            endpoints
            .AddOutbound <IIntegrationEvent>(
                FileSystemEndpoint.Create("catalog-events", _configuration["Broker:Path"]))
            .Connect();

            jobScheduler.AddJob("outbound-queue-worker", TimeSpan.FromMilliseconds(100),
                                s => s.GetRequiredService <OutboundQueueWorker>().ProcessQueue());

            // Configure outbound worker
        }
        private ICatalogRepository GetInMemoryCatalogRepository()
        {
            // Some default objects are seeded in the CatalogDbContext/OnModelCreating

            DbContextOptions <CatalogDbContext> options;
            var builder = new DbContextOptionsBuilder <CatalogDbContext>();

            builder.UseInMemoryDatabase(databaseName: "CatalogServiceTestDatabase");
            options = builder.Options;
            CatalogDbContext catalogDbContext = new CatalogDbContext(options);

            catalogDbContext.Database.EnsureDeleted();
            catalogDbContext.Database.EnsureCreated();

            return(new CatalogRepository(catalogDbContext));
        }
Example #5
0
        public async Task Get_AuthorById_Success200()
        {
            // Arrange.
            var ctx        = new CatalogDbContext(_dbOptions);
            var controller = new AuthorsController(ctx);
            var id         = 1;

            // Act.
            var result = await controller.GetAuthorById(id);

            // Assert.
            var a = Assert.IsAssignableFrom <AuthorOutputViewModel>(result.Value);

            Assert.Equal(id, a.Id);
            Assert.Equal("Peter", a.Name);
        }
Example #6
0
        public BooksControllerTest()
        {
            _dbOptions = new DbContextOptionsBuilder <CatalogDbContext>()
                         .UseInMemoryDatabase("inmemory").Options;

            using var ctx = new CatalogDbContext(_dbOptions);
            ctx.Database.EnsureDeleted();

            var authors = GetFakeAuthorsCatalog();

            ctx.Authors.AddRange(authors);
            var books = GetFakeBooksCatalog();

            ctx.Books.AddRange(books);
            AssignFakeBookAuthorCatalogToBooks(authors, books);
            ctx.SaveChanges();
        }
Example #7
0
        public static async Task Seed(CatalogDbContext dbContext)
        {
            var products = new List <Product>();

            for (var index = 1; index <= 26; index++)
            {
                products.Add(new Product
                {
                    Id        = Guid.NewGuid(),
                    Name      = $"Product {index}",
                    Model     = $"Model {index}",
                    Price     = 10,
                    Quantity  = 100,
                    DateAdded = DateTime.UtcNow,
                    Status    = Status.Published
                });
            }

            var product = new Product
            {
                Id        = new Guid("85db18f3-9c27-47d8-bd45-86dd67068960"),
                Name      = "Product 111",
                Model     = "Model ABA",
                Price     = 50,
                Quantity  = 100,
                DateAdded = DateTime.UtcNow,
                Status    = Status.Published
            };

            products.Add(product);
            var supplier = new Supplier
            {
                Id           = new Guid("83fd9e15-eadd-44da-8c1a-e7626a767775"),
                ContactName  = "Nguyen Van A",
                CompanyName  = "Company A",
                ContactTitle = "Provider",
                AddressInfo  = new AddressInfo(Guid.NewGuid(), "123 Addrress", "HCM", "Region A", "7000", "VN"),
                ContactInfo  = new ContactInfo(Guid.NewGuid(), "123456789", "1234567890", "*****@*****.**"),
                Products     = products
            };

            await dbContext.Set <Supplier>().AddAsync(supplier);

            await dbContext.SaveChangesAsync();
        }
Example #8
0
        /// <summary>
        /// Registers the new shard.
        /// Verify if shard exists for the tenant. If not then create new shard and add tenant details to Tenants table in catalog
        /// </summary>
        /// <param name="tenantName">Name of the tenant.</param>
        /// <param name="tenantId">The tenant identifier.</param>
        /// <param name="tenantServer">The tenant server.</param>
        /// <returns></returns>
        public static bool RegisterNewShard(int tenantId, string tenantName, string tenantServer, bool needToSaveOnDB = false)
        {
            try
            {
                ShardLocation shardLocation = new ShardLocation(tenantServer, tenantName);

                if (!ShardMap.TryGetShard(shardLocation, out Shard shard))
                {
                    //create shard if it does not exist
                    shard = ShardMap.CreateShard(shardLocation);
                }

                // Register the mapping of the tenant to the shard in the shard map.
                // After this step, DDR on the shard map can be used
                if (!ShardMap.TryGetMappingForKey(tenantId, out PointMapping <int> mapping))
                {
                    var pointMapping = ShardMap.CreatePointMapping(tenantId, shard);

                    if (needToSaveOnDB)
                    {
                        //convert from int to byte[] as tenantId has been set as byte[] in Tenants entity
                        var key = ShardHelper.ConvertIntKeyToBytesArray(pointMapping.Value);

                        //add tenant to Tenants table
                        var tenant = new Tenants
                        {
                            TenantId    = key,
                            TenantName  = tenantName,
                            LastUpdated = DateTime.Now
                        };

                        var db = new CatalogDbContext();
                        db.Tenants.Add(tenant);
                        db.SaveChanges();
                    }
                }

                return(true);
            }
            catch (Exception exception)
            {
                Trace.TraceError(exception.Message, "Error in registering new shard.");
                return(false);
            }
        }
Example #9
0
        public void Setup()
        {
            var options = new DbContextOptionsBuilder <CatalogDbContext>()
                          .UseInMemoryDatabase($"{nameof(ProductServiceTests)}-{Guid.NewGuid()}").Options;

            _catalogDbContext = new CatalogDbContext(options);

            _productService = new ProductService(_catalogDbContext, new ProductValidator(_catalogDbContext));

            _catalogDbContext.Brands.Add(new Brand()
            {
                Id = 1, Name = "Test Brand 1"
            });
            _catalogDbContext.Suppliers.Add(new Supplier()
            {
                Id = 1, Name = "Test Brand 1"
            });
        }
Example #10
0
        public async Task Get_Books_Empty200()
        {
            // Arrange.
            var ctx        = new CatalogDbContext(_dbOptions);
            var controller = new BooksController(ctx);
            var pageSize   = 20;
            var pageIndex  = 20;

            // Act.
            var result = await controller.GetBooks(pageSize, pageIndex);

            // Assert.
            var pi = Assert.IsType <PaginatedItemsViewModel <BookOutputViewModel> >(result.Value);

            Assert.Equal(pageSize, pi.PageSize);
            Assert.Equal(pageIndex, pi.PageIndex);
            Assert.Empty(pi.Data);
            Assert.Equal(GetFakeBooksCatalog().Count, pi.Count);
        }
Example #11
0
        public async Task Get_BookById_Success200()
        {
            // Arrange.
            var ctx        = new CatalogDbContext(_dbOptions);
            var controller = new BooksController(ctx);
            var id         = 1;

            // Act.
            var result = await controller.GetBookById(id);

            // Assert.
            var b = Assert.IsAssignableFrom <BookOutputViewModel>(result.Value);

            Assert.Equal(id, b.Id);
            Assert.Equal("Title", b.Title);
            Assert.Equal("9780394415760", b.Isbn);
            Assert.Equal(52, b.NumberOfPages);
            Assert.Contains(b.Authors, a => a.Name == "Peter");
        }
Example #12
0
        public async Task Put_Author_Success204()
        {
            // Arrange.
            var ctx        = new CatalogDbContext(_dbOptions);
            var controller = new AuthorsController(ctx);
            var id         = 1;
            var name       = "TestS204";
            var upd        = new AuthorInputViewModel {
                Name = name
            };

            // Act.
            var result = await controller.UpdateAuthorAsync(id, upd);

            // Assert.
            Assert.IsType <NoContentResult>(result);
            var updatedA = ctx.Authors.Find(id);

            Assert.Equal(name, updatedA.Name);
        }
Example #13
0
        // DELETE: Tenant
        public ActionResult Delete(string tenantName)
        {
            HttpContext.Server.ScriptTimeout = 600;

            tenantName = tenantName.ToLower();

            var db     = new CatalogDbContext();
            var tenant = db.Tenants.FirstOrDefault(t => t.TenantName == tenantName);

            if (tenant != null)
            {
                ShardHelper.DeleteTenantShard(DatabaseConfigHelper.GetServerNameFull(), tenantName);
                DeleteDb(tenantName);

                db.Tenants.Remove(tenant);
                db.SaveChanges();
            }

            return(RedirectToAction("List"));
        }
Example #14
0
        public async Task Get_Authors_Success200()
        {
            // Arrange.
            var ctx        = new CatalogDbContext(_dbOptions);
            var controller = new AuthorsController(ctx);
            var pageSize   = 3;
            var pageIndex  = 1;

            // Act.
            var result = await controller.GetAuthorsAsync(pageSize, pageIndex);

            // Assert.
            var pi = Assert.IsType <PaginatedItemsViewModel <AuthorOutputViewModel> >(result.Value);

            Assert.Equal(pageSize, pi.Data.Count());
            Assert.Equal(GetFakeAuthorsCatalog().Count(), pi.Count);
            Assert.Equal(pageSize, pi.PageSize);
            Assert.Equal(pageIndex, pi.PageIndex);
            Assert.Contains(pi.Data, i => new int[] { 4, 5, 6 }.Contains(i.Id));
        }
Example #15
0
        public async Task Post_CreateBook_Success201()
        {
            // Arrange.
            var ctx        = new CatalogDbContext(_dbOptions);
            var controller = new BooksController(ctx);
            var t          = "201Title";
            var isbn       = "2123213";
            var numPages   = (short)600;
            var authorIds  = new int[] { 100, 200 };
            var inputVM    = new BookInputViewModel
            {
                Title = t, Isbn = isbn, NumberOfPages = numPages, AuthorsIds = authorIds
            };

            // Act.
            var result = await controller.CreateBookAsync(inputVM);

            // Assert.
            Assert.IsType <CreatedAtActionResult>(result);
        }
Example #16
0
        public async Task SeedAsync(CatalogDbContext context, IHostingEnvironment env, IOptions <CatalogSettings> settings, ILogger <CatalogContextSeed> logger)
        {
            var policy = CreatePolicy(logger, nameof(CatalogContextSeed));

            await policy.ExecuteAsync(async() =>
            {
                var useCustomizationData = settings.Value.UseCustomizationData;
                var contentRootPath      = env.ContentRootPath;
                var picturePath          = env.WebRootPath;

                if (!context.CatalogBrands.Any())
                {
                    await context.CatalogBrands.AddRangeAsync(useCustomizationData
                                                ? GetCatalogBrandsFromFile(contentRootPath, logger)
                                                : GetPreconfiguredCatalogBrands());

                    await context.SaveChangesAsync();
                }

                if (!context.CatalogTypes.Any())
                {
                    await context.CatalogTypes.AddRangeAsync(useCustomizationData
                                                ? GetCatalogTypesFromFile(contentRootPath, logger)
                                                : GetPreconfiguredCatalogTypes());

                    await context.SaveChangesAsync();
                }

                if (!context.CatalogItems.Any())
                {
                    await context.CatalogItems.AddRangeAsync(useCustomizationData
                                                ? GetCatalogItemsFromFile(contentRootPath, context, logger)
                                                : GetPreconfiguredItems());

                    await context.SaveChangesAsync();

                    GetCatalogItemPictures(contentRootPath, picturePath);
                }
            });
        }
 public static void InitializeDbForTests(CatalogDbContext context)
 {
     context.Categories.Add(new Category()
     {
         Id   = 1,
         Code = "001",
         Name = "Lenovo Thinkpad 1"
     });
     context.Categories.Add(new Category()
     {
         Id   = 2,
         Code = "002",
         Name = "Lenovo Thinkpad 2"
     });
     context.Categories.Add(new Category()
     {
         Id   = 3,
         Code = "003",
         Name = "Lenovo Thinkpad 3"
     });
     context.SaveChanges();
 }
Example #18
0
        public async Task Post_CreateAuthor_Success201()
        {
            // Arrange.
            var name = "Test name";
            var a    = new AuthorInputViewModel {
                Name = name
            };
            var ctx        = new CatalogDbContext(_dbOptions);
            var controller = new AuthorsController(ctx);

            // Act.
            var result = await controller.CreateAuthorAsync(a);

            // Assert.
            var ar        = Assert.IsType <CreatedAtActionResult>(result.Result);
            var returnedA = Assert.IsType <AuthorOutputViewModel>(ar.Value);

            Assert.Equal(name, returnedA.Name);
            var createdA = ctx.Authors.Find(returnedA.Id);

            Assert.Equal(name, createdA.Name);
        }
Example #19
0
        public ActionResult Create(FormCollection collection)
        {
            try
            {
                HttpContext.Server.ScriptTimeout = 600;

                var tenantName = collection.Get("tenantName");
                if (string.IsNullOrEmpty(tenantName))
                {
                    ViewBag.ErrorMsg = "Tenant name is invalid";
                    return(View());
                }

                tenantName = tenantName.ToLower();

#if DEBUG
                if (!tenantName.ToLower().StartsWith("dev-"))
                {
                    ViewBag.ErrorMsg = "Tenant name need to start with dev-";
                    return(View());
                }
#endif

                var db     = new CatalogDbContext();
                var tenant = db.Tenants.FirstOrDefault(t => t.TenantName == tenantName);
                if (tenant == null)
                {
                    CopyDbTemplate(tenantName);
                    ShardHelper.RegisterTenantShard(DatabaseConfigHelper.GetServerNameFull(), tenantName);
                }

                return(RedirectToAction("List"));
            }
            catch (Exception ex)
            {
                ViewBag.ErrorMsg = ex.Message;
                return(View());
            }
        }
        public static CatalogDbContext Create()
        {
            var options = new DbContextOptionsBuilder <CatalogDbContext>()
                          .UseInMemoryDatabase(Guid.NewGuid().ToString())
                          .Options;

            var context = new CatalogDbContext(options);

            context.Categories.Add(new Api.Entities.Category()
            {
                Id   = 1,
                Code = "001",
                Name = "Lenovo Thinkpad"
            });
            context.SaveChanges();



            context.Database.EnsureCreated();

            return(context);
        }
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, CatalogDbContext context)
        {
            app.UseSwagger();

            context.Database.EnsureCreated();

            // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
            // specifying the Swagger JSON endpoint.
            app.UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "My API V1");
                c.RoutePrefix = string.Empty;
            });

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // app.UseHttpsRedirection();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });

            app.UseStaticFiles(new StaticFileOptions
            {
                FileProvider = new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "Images")),
                RequestPath = "/productcatalog/images"
            });
        }
Example #22
0
        private static async Task PopulateTruckCategories(CatalogDbContext dbContext)
        {
            int[] decades = new int[4] {
                1980, 1990, 2000, 2010
            };
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < decades.Length; i++)
            {
                var truckCategorySql = await TruckCategorySqlByDecade(dbContext, decades[i]);

                if (truckCategorySql != string.Empty)
                {
                    sb.Append(truckCategorySql);
                }
            }
            if (sb.Length > 0)
            {
                sb.Insert(0, "insert into category_truck(categories_category_id, trucks_truck_id) values ");
                sb.Replace(",", ";", sb.Length - 1, 1);

                await dbContext.Database.ExecuteSqlRawAsync(sb.ToString());
            }
        }
Example #23
0
 public CategoryRepository(CatalogDbContext catalogDbContext)
 {
     _catalogDbContext = catalogDbContext;
 }
 public ProductRepository(CatalogDbContext context)
 {
     _context = context;
 }
Example #25
0
 public ProductService(CatalogDbContext catalogDbContext)
 {
     _catalogDbContext = catalogDbContext;
 }
Example #26
0
 public EventRepository(CatalogDbContext catalogDbContext)
 {
     _catalogDbContext = catalogDbContext;
 }
        public static void Destroy(CatalogDbContext context)
        {
            context.Database.EnsureDeleted();

            context.Dispose();
        }
Example #28
0
 public GenericRepository(CatalogDbContext context)
 {
     _context = context;
 }
Example #29
0
 public CatalogController(CatalogDbContext catalogContext,
                          ICatalogIntegrationEventService catalogIntegrationEventService)
 {
     this._catalogContext = catalogContext;
     this._catalogIntegrationEventService = catalogIntegrationEventService;
 }
Example #30
0
        private void BeforeBackup()
        {
            IServiceContext serviceContext = ServiceContext.NewServiceContext(txtAdminUser.Text, "", "", txtOrg.Text, DataProtectInterface.TaskType.Catalog);
            serviceContext.CurrentMailbox = txtAdminUser.Text;
            var dataAccess = CatalogFactory.Instance.NewCatalogDataAccessInternal(serviceContext.Argument, serviceContext.AdminInfo.OrganizationName);
            dataAccess.ResetAllStorage(serviceContext.CurrentMailbox);

            if (!FactoryBase.IsRunningOnAzureOrStorageInAzure())
            {

                using (CatalogDbContext dbContext = new CatalogDbContext(new SqlDbImpl.Model.OrganizationModel() { Name = txtOrg.Text }))
                {
                    AppendToTextbox1(dbContext.Database.Connection.ConnectionString);
                    dbContext.Database.ExecuteSqlCommand("TRUNCATE TABLE CatalogInformation");
                    dbContext.Database.ExecuteSqlCommand("TRUNCATE TABLE MailboxInformation");
                    dbContext.Database.ExecuteSqlCommand("TRUNCATE TABLE ItemLocation");
                    dbContext.Database.ExecuteSqlCommand("TRUNCATE TABLE ItemInformation");
                    dbContext.Database.ExecuteSqlCommand("TRUNCATE TABLE FolderInformation");
                    dbContext.SaveChanges();
                }
            }
        }
 public QueryCatalogExportsByFilter(CatalogDbContext dbContext)
 {
     _dbContext = dbContext;
 }
 public ProductsController(CatalogDbContext context)
 {
     _context = context;
 }
Example #33
0
 public AdditionallyInfoRepository()
 {
     _dbContext = new CatalogDbContext();
 }