private async Task GetAllCompletedProjects_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); var userManager = this.GetMockUserManager().Object; this.adminService = new AdminService(userManager, context); var project = await this.adminService.GetAllProjectsInProgress(); var projectInputModel = new ProjectEditInputModel { Id = project[0].Id, IsPublic = project[0].IsPublic, Name = "Test-Edited", Status = ProjectStatus.Completed, }; await this.adminService.EditProject(projectInputModel); var completedProjects = await this.adminService.GetAllCompletedProjects(); Assert.Single(completedProjects); }
protected override void Load(ContainerBuilder builder) { var connection = Environment.GetEnvironmentVariable("GRAPHQL_CONN"); builder.RegisterAssemblyTypes(typeof(InfrastructureException).Assembly) .Where(type => type.Namespace.Contains("PostgresDataAccess")) .AsImplementedInterfaces() .InstancePerLifetimeScope(); builder.RegisterAssemblyTypes(typeof(InfrastructureException).Assembly) .Where(t => t.Namespace.Contains("PostgresDataAccess") && typeof(Profile).IsAssignableFrom(t) && !t.IsAbstract && t.IsPublic) .As <Profile>(); builder.Register(c => new MapperConfiguration(cfg => { foreach (var profile in c.Resolve <IEnumerable <Profile> >()) { cfg.AddProfile(profile); } })).AsSelf().SingleInstance(); builder.Register(c => c.Resolve <MapperConfiguration>() .CreateMapper(c.Resolve)) .As <IMapper>() .InstancePerLifetimeScope(); if (!string.IsNullOrEmpty(connection)) { using (var context = new Context()) { context.Database.Migrate(); ContextInitializer.Seed(context); } } }
private async Task CreateReview_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); this.reviewService = new ReviewService(context); var review = new ProjectReview { ProjectId = "bb2bd817-98cd-4cf3-a80a-53ea0cd9c200", CustomerId = new Guid("cb2bd817-98cd-4cf3-a80a-53ea0cd9c200").ToString(), Review = "Second Review", }; var reviewCreate = new ReviewCreateModel { CustomerId = review.CustomerId, ProjectId = review.ProjectId, Review = "Second Review Text", }; var result = await this.reviewService.CreateReview(reviewCreate); Assert.Equal("Review was successfully created!", result); }
private async Task CreateProject_ShouldCorrectlyAddProject() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); var userManager = this.GetMockUserManager().Object; this.adminService = new AdminService(userManager, context); var model = new ProjectCreateInputModel { Designer = new ApplicationUser { Email = "*****@*****.**", PasswordHash = 5.GetHashCode().ToString(), }, Customer = new ApplicationUser { Email = "*****@*****.**", PasswordHash = 5.GetHashCode().ToString(), }, Name = "Test1", IsPublic = true, }; var result = await this.adminService.CreateProject(model); Assert.Equal("New project created successfuly!", result.ToString()); }
public static async Task Main(string[] args) { var host = CreateHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { //var services = scope.ServiceProvider; //var context = services.GetRequiredService<OssDbContext>(); //try //{ // var userManager = services.GetRequiredService<UserManager<UserDbModel>>(); // var roleManager = services.GetRequiredService<RoleManager<IdentityRole>>(); // var tmp = services.GetRequiredService<UserService>(); // Initializer initializer = new Initializer(); // await initializer.RoleInitializer(context, roleManager); // await initializer.UserInitializer(context, userManager); // await initializer.ItemInitializer(context); //} //catch (Exception e) //{ // var logger = services.GetRequiredService<ILogger<Program>>(); // logger.LogError(e, "An error occurred while seeding the database."); //} var services = scope.ServiceProvider; await ContextInitializer.Initialize(services); } host.Run(); }
CodeTypeReference GenerateServiceContractTypeInternal(ContractDescription contractDescription) { if (contractDescription == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("contractDescription"); } Type existingType; if (referencedTypes.TryGetValue(contractDescription, out existingType)) { return(GetCodeTypeReference(existingType)); } ServiceContractGenerationContext context; CodeNamespace ns = this.NamespaceManager.EnsureNamespace(contractDescription.Namespace); if (!generatedTypes.TryGetValue(contractDescription, out context)) { context = new ContextInitializer(this, new CodeTypeFactory(this, options.IsSet(ServiceContractGenerationOptions.InternalTypes))).CreateContext(contractDescription); ExtensionsHelper.CallContractExtensions(GetBeforeExtensionsBuiltInContractGenerators(), context); ExtensionsHelper.CallOperationExtensions(GetBeforeExtensionsBuiltInOperationGenerators(), context); ExtensionsHelper.CallBehaviorExtensions(context); ExtensionsHelper.CallContractExtensions(GetAfterExtensionsBuiltInContractGenerators(), context); ExtensionsHelper.CallOperationExtensions(GetAfterExtensionsBuiltInOperationGenerators(), context); generatedTypes.Add(contractDescription, context); } return(context.ContractTypeReference); }
private async Task AddDesignReference_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); this.designBoardServce = new DesignBoardService(context); var designBoard = new DesignBoardCreateInputModel { ProjectId = "bb2bd817-98cd-4cf3-a80a-53ea0cd9c200", CustomerId = new Guid("cb2bd817-98cd-4cf3-a80a-53ea0cd9c200").ToString(), Name = "Test Design Board", }; var designRefernce = new ReferenceInputModel { CustomerId = new Guid("cb2bd817-98cd-4cf3-a80a-53ea0cd9c200").ToString(), ImageUrl = "https://test.test", DesignBoardId = "de2bd817-98cd-4cf3-a80a-53ea0cd9c200", }; await this.designBoardServce.AddDesignBoard(designBoard); var result = await this.designBoardServce.AddDesignReference(designRefernce); Assert.Equal("DesignReference created successfully!", result); }
public StandartContext Create() { var contextInitializer = new ContextInitializer(); var connectionName = ConnectionManager.GetConnectionManager().ConnectionStrings["BeautyDatabase"]; return(new StandartContext(contextInitializer, connectionName)); }
public void Seed_ShouldInitializeDatabase() { var stores = 10; var persons = 10; var transactions = 10; var productsPerStore = 100; var purchasesPerTransaction = 10; var options = new DbContextOptionsBuilder <DummyContext>() .UseInMemoryDatabase(Guid.NewGuid().ToString()) .Options; using var context = new DummyContext(options); var initializer = new ContextInitializer(persons, stores, productsPerStore, purchasesPerTransaction, transactions); initializer.Seed(context); Assert.AreEqual(persons, context.Persons.Count()); Assert.AreEqual(stores, context.Stores.Count()); Assert.AreEqual(productsPerStore, context.Stores.First().Products.Count()); Assert.AreEqual(productsPerStore, context.Stores.Last().Products.Count()); Assert.AreEqual(purchasesPerTransaction, context.Transactions.Include(o => o.Purchases).First().Purchases.Count()); Assert.AreEqual(purchasesPerTransaction, context.Transactions.Include(o => o.Purchases).Last().Purchases.Count()); Assert.AreEqual(transactions, context.Persons.First().Transactions.Count()); Assert.AreEqual(transactions, context.Persons.Last().Transactions.Count()); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseBrowserLink(); app.UseDeveloperExceptionPage(); using (var scope = app.ApplicationServices.CreateScope()) { var services = scope.ServiceProvider; var context = services.GetRequiredService <SchoolContext>(); ContextInitializer.Initialize(context); } } else { app.UseExceptionHandler("/Home/Error"); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
protected void Application_Start() { ContextInitializer.Init(); AreaRegistration.RegisterAllAreas(); RegisterGlobalFilters(GlobalFilters.Filters); RegisterRoutes(RouteTable.Routes); }
public App() { var context = ContextInitializer.Init(); context.EventAggregator.Dispatcher = Dispatcher; TaskScheduler.UnobservedTaskException += TaskSchedulerUnobservedTaskException; AppDomain.CurrentDomain.UnhandledException += CurrentDomainUnhandledException; Current.DispatcherUnhandledException += CurrentDispatcherUnhandledException; }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllers(); ContextInitializer.Init(services, Configuration); BrokerInitializer.Init(services, Configuration); ServicesInitializer.Init(services, Configuration); }
public async Task Should_Call_DietDecisionMaker_Allow_Banana(string message) { using (var context = new DietContext(_options)) { ContextInitializer.Initialize(context); var textMessageProcessor = new TextMessageProcessor(context, new NullLogger <TextMessageProcessor>()); var result = await textMessageProcessor.Process(message); Assert.False(string.IsNullOrEmpty(result.Content)); } }
private async Task GetCurrentDesignBoard_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); this.designBoardServce = new DesignBoardService(context); var result = await this.designBoardServce.GetCurrentDesignBoard("bb2bd817-98cd-4cf3-a80a-53ea0cd9c330"); Assert.Equal("Test Design Board", result.Name); }
private async Task GetDesignBoardReferences_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); this.designBoardServce = new DesignBoardService(context); var result = await this.designBoardServce.GetDesignBoardReferences("bb2bd817-98cd-4cf3-a80a-53ea0cd9c330"); Assert.Equal(1, result.Count); }
private async Task GetActiveCustomerProjects_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); this.projectService = new ProjectService(context); var result = this.projectService.GetActiveCustomerProjects("cb2bd817-98cd-4cf3-a80a-53ea0cd9c200"); Assert.Single(result); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ContextInitializer dbInitializer) { if (env.IsDevelopment()) { //If calling api and some exception occures, following will return html page string as response. So, in api this will not display exception page //app.UseDeveloperExceptionPage(); } else { //Use this if you want to redirect to error page form asp and not from angular app //app.UseExceptionHandler("/Error"); app.UseHsts(); } app.ConfigureExceptionHandler(Configuration, env); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseStaticFiles(new StaticFileOptions { FileProvider = new PhysicalFileProvider(AppCommon.UserfilesFolderPath), RequestPath = AppCommon.UserfilesRequestName }); app.UseSpaStaticFiles(); app.UseAuthentication(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller}/{action=Index}/{id?}"); }); app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 spa.Options.SourcePath = "ClientApp"; if (env.IsDevelopment()) { spa.UseAngularCliServer(npmScript: "start"); } }); var isAutoMigrationOn = Convert.ToBoolean(Configuration["IsAutoMigrationOn"]); dbInitializer.InitDb(isAutoMigrationOn).Wait(); }
public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var serviceProvider = scope.ServiceProvider; ContextInitializer.InitializeContext(serviceProvider); } host.Run(); }
private async Task GetCurrentProjectFiles_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); this.projectService = new ProjectService(context); var result = await this.projectService.GetCurrentProjectFiles("bb2bd817-98cd-4cf3-a80a-53ea0cd9c200"); Assert.Equal(1, result.Count); }
public async Task GetPublicProjects_ShouldReturnCorrectNumber() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); this.portfolioService = new PortfolioService(context); var result = this.portfolioService.GetPublicProjectFiles().Count; Assert.Equal(2, result); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, ContextInitializer seeder) { loggerFactory.AddConsole(_config.GetSection("Logging")); loggerFactory.AddDebug(); loggerFactory.AddFile("Logs/userControl-{Date}.txt"); app.UseCors(config => config.AllowAnyHeader() .AllowAnyMethod() .WithOrigins(_config["Tokens:Issuer"]) ); app.UseIdentity(); app.UseJwtBearerAuthentication(new JwtBearerOptions() { AutomaticAuthenticate = true, AutomaticChallenge = true, TokenValidationParameters = new TokenValidationParameters() { ValidIssuer = _config["Tokens:Issuer"], ValidAudience = _config["Tokens:Audience"], IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(_config["Tokens:Key"])), ValidateLifetime = true } }); app.UseFacebookAuthentication(new FacebookOptions { AppId = _config["Authentication:Facebook:AppId"], AppSecret = _config["Authentication:Facebook:AppSecret"], //CallbackPath = new PathString("/api/auth/signinFacebook") }); app.UseMvc(); seeder.Seed().Wait(); if (env.IsDevelopment()) { Debug.WriteLine("DEVELOPMENT MODE."); Debug.WriteLine("\tConnectionString=" + _config.GetSection("ConnectionString").Value); var authMessage = _config.GetSection("AuthMessageSenderOptions").Get <AuthMessageSenderOptions>(); Debug.WriteLine("\tSendGrid:User="******"\tTokens:Issuer=" + _config.GetSection("Tokens:Issuer").Value); Debug.WriteLine("\tTokens:Audience=" + _config.GetSection("Tokens:Audience").Value); Debug.WriteLine("\tAdminUser:Name=" + _config["AdminUser:Name"]); Debug.WriteLine("\tAdminUser:Email=" + _config["AdminUser:Email"]); } }
private void MapForm_Load(object sender, EventArgs e) { this.BackColor = Color.FromArgb(255, 255, 161, 176); this.DoubleBuffered = true; _contextInitializer = new ContextInitializer(); IProcessInitializer initializer = new FormInitializer(_contextInitializer.Context); initializer.Start(); this.WindowState = FormWindowState.Maximized; this.Paint += new PaintEventHandler(DrawMap); this.Refresh(); }
private async Task GetAllProjectsInProgress_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); var userManager = this.GetMockUserManager().Object; this.adminService = new AdminService(userManager, context); var project = await this.adminService.GetAllProjectsInProgress(); Assert.Single(project); }
private async Task GetCurrentProject_ShouldReturnNull() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); var cloudinary = new Mock <CloudinaryService>().Object; this.projectFileService = new ProjectFileService(cloudinary, context); var result = await this.projectFileService.GetCurrentProjectFile("ab3bd817-98cd-4cf3-a80a-53ea0cd9c200"); Assert.Null(result); }
protected void Application_Start() { ContextInitializer.Initialize(); AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //Populate Feed Repository FeedRepositoryConfig.ConsumeFeed(); }
private async Task GetCurrentProjectDesignBoards_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); this.projectService = new ProjectService(context); var result = await this.projectService.GetCurrentProjectDesignBoards("bb2bd817-98cd-4cf3-a80a-53ea0cd9c200"); var designReferenceUrl = result[0].DesignReferences.FirstOrDefault().ImageUrl; Assert.Equal(1, result[0].DesignReferences.Count); Assert.Equal("https://test.test", designReferenceUrl); }
private async Task CreateProject_ShouldThrowExeption() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); var userManager = this.GetMockUserManager().Object; this.adminService = new AdminService(userManager, context); var test1 = new ProjectCreateInputModel { Designer = new ApplicationUser { Email = "*****@*****.**", PasswordHash = 5.GetHashCode().ToString(), }, Customer = new ApplicationUser { Email = "*****@*****.**", PasswordHash = 5.GetHashCode().ToString(), }, Name = "Test", IsPublic = true, }; var test2 = new ProjectCreateInputModel { Designer = new ApplicationUser { Email = "*****@*****.**", PasswordHash = 5.GetHashCode().ToString(), }, Customer = new ApplicationUser { Email = "*****@*****.**", PasswordHash = 5.GetHashCode().ToString(), }, Name = "Test", IsPublic = true, }; await this.adminService.CreateProject(test1); var result2 = await this.adminService.CreateProject(test2); Assert.Equal("Project with name Test alreday exists!", result2.ToString()); }
private async Task GetCurrentProject_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); var cloudinary = new Mock <CloudinaryService>().Object; this.projectFileService = new ProjectFileService(cloudinary, context); var result = await this.projectFileService.GetCurrentProjectFile("ab2bd817-98cd-4cf3-a80a-53ea0cd9c200"); Assert.Equal("TestProjectFile.jpg", result.Name); Assert.True(result.IsPublic); Assert.False(result.IsApproved); }
private async Task DeleteProject_ShouldWorkFine() { var context = ContextInitializer.InitializeContext(); await this.SeedData(context); var userManager = this.GetMockUserManager().Object; this.adminService = new AdminService(userManager, context); var project = await this.adminService.GetAllProjectsInProgress(); await this.adminService.DeleteProject(project[0].Id); var result = await this.adminService.GetAllProjectsInProgress(); Assert.Empty(result); }
public Context(ContextInitializer init) { Database.SetInitializer<Context>(init); this.Configuration.LazyLoadingEnabled = false; }
/// <summary> /// Prepares the controller giving it mock implementations /// of the service it requires to function normally. /// </summary> /// <param name="controller">The controller.</param> /// <param name="areaName">Name of the area (cannot be null).</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="contextInitializer">The context initializer.</param> protected void PrepareController(Controller controller, string areaName, string controllerName, string actionName, ContextInitializer contextInitializer) { if (controller == null) { throw new ArgumentNullException("controller", "'controller' cannot be null"); } if (areaName == null) { throw new ArgumentNullException("areaName"); } if (controllerName == null) { throw new ArgumentNullException("controllerName"); } if (actionName == null) { throw new ArgumentNullException("actionName"); } cookies = new Dictionary<string, HttpCookie>(StringComparer.InvariantCultureIgnoreCase); BuildEngineContext(areaName, controllerName, actionName, contextInitializer); controllerContext = services.ControllerContextFactory.Create(areaName, controllerName, actionName, services.ControllerDescriptorProvider.BuildDescriptor(controller)); controller.Contextualize(Context, controllerContext); controller.CreateStandardHelpers(); controller.Initialize(); }
/// <summary> /// Prepares the controller giving it mock implementations /// of the service it requires to function normally. /// </summary> /// <param name="controller">The controller.</param> /// <param name="contextInitializer">The context initializer.</param> protected void PrepareController(Controller controller, ContextInitializer contextInitializer) { PrepareController(controller, "", "Controller", "Action", contextInitializer); }
/// <summary> /// Constructs a mock context. /// </summary> /// <param name="areaName">Name of the area.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="contextInitializer">The context initializer.</param> protected void BuildEngineContext(string areaName, string controllerName, string actionName, ContextInitializer contextInitializer) { var info = BuildUrlInfo(areaName, controllerName, actionName); services = BuildServices(); request = BuildRequest(); request.RawUrl = info.UrlRaw; response = BuildResponse(info); trace = BuildTrace(); context = BuildRailsEngineContext(request, response, services, trace, info); AddEmailServices( context ); contextInitializer(context); }