| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298 |
- using System;
- using System.Collections.Generic;
- using System.Data.Common;
- using System.Data.Entity;
- using System.Linq;
- using System.Threading.Tasks;
- using Abp;
- using Abp.Configuration.Startup;
- using Abp.Domain.Uow;
- using Abp.Runtime.Session;
- using Abp.TestBase;
- using WePlatform.Authorization.Users;
- using WePlatform.MultiTenancy;
- using Castle.MicroKernel.Registration;
- using Effort;
- using EntityFramework.DynamicFilters;
- using WePlatform.EF;
- using WePlatform.SeedData;
- using IwbZero.Authorization.Base.Users;
- using IwbZero.MultiTenancy;
- namespace WePlatform
- {
- public abstract class WePlatformTestBase : AbpIntegratedTestBase<WePlatformTestModule>
- {
- private DbConnection _hostDb;
- private Dictionary<int, DbConnection> _tenantDbs; //only used for db per tenant architecture
- protected WePlatformTestBase()
- {
- //Seed initial data for host
- //AbpSession.TenantId = null;
- //UsingDbContext(context =>
- //{
- // new InitialDbBuilder(context).Create();
- //});
- ////Seed initial data for default tenant
- //AbpSession.TenantId = 1;
- //UsingDbContext(context =>
- //{
- // new RoleAndUserCreator(context).Create();
- //});
- //UsingDbContext(context =>
- //{
- // new TestDataBuilder(context).Create();
- //});
- LoginAsDefaultTenantAdmin();
- }
- protected override void PreInitialize()
- {
- base.PreInitialize();
- /* You can switch database architecture here: */
- UseSingleDatabase();
- //UseDatabasePerTenant();
- }
- /* Uses single database for host and all tenants.
- */
- private void UseSingleDatabase()
- {
- _hostDb = DbConnectionFactory.CreateTransient();
- LocalIocManager.IocContainer.Register(
- Component.For<DbConnection>()
- .UsingFactoryMethod(() => _hostDb)
- .LifestyleSingleton()
- );
- }
- /* Uses single database for host and Default tenant,
- * but dedicated databases for all other tenants.
- */
- private void UseDatabasePerTenant()
- {
- _hostDb = DbConnectionFactory.CreateTransient();
- _tenantDbs = new Dictionary<int, DbConnection>();
- LocalIocManager.IocContainer.Register(
- Component.For<DbConnection>()
- .UsingFactoryMethod((kernel) =>
- {
- lock (_tenantDbs)
- {
- var currentUow = kernel.Resolve<ICurrentUnitOfWorkProvider>().Current;
- var abpSession = kernel.Resolve<IAbpSession>();
- var tenantId = currentUow != null ? currentUow.GetTenantId() : abpSession.TenantId;
- if (tenantId == null || tenantId == 1) //host and default tenant are stored in host db
- {
- return _hostDb;
- }
- if (!_tenantDbs.ContainsKey(tenantId.Value))
- {
- _tenantDbs[tenantId.Value] = DbConnectionFactory.CreateTransient();
- }
- return _tenantDbs[tenantId.Value];
- }
- }, true)
- .LifestyleTransient()
- );
- }
- #region UsingDbContext
- protected IDisposable UsingTenantId(int? tenantId)
- {
- var previousTenantId = AbpSession.TenantId;
- AbpSession.TenantId = tenantId;
- return new DisposeAction(() => AbpSession.TenantId = previousTenantId);
- }
- protected void UsingDbContext(Action<WePlatformDbContext> action)
- {
- UsingDbContext(AbpSession.TenantId, action);
- }
- protected Task UsingDbContextAsync(Func<WePlatformDbContext, Task> action)
- {
- return UsingDbContextAsync(AbpSession.TenantId, action);
- }
- protected T UsingDbContext<T>(Func<WePlatformDbContext, T> func)
- {
- return UsingDbContext(AbpSession.TenantId, func);
- }
- protected Task<T> UsingDbContextAsync<T>(Func<WePlatformDbContext, Task<T>> func)
- {
- return UsingDbContextAsync(AbpSession.TenantId, func);
- }
- protected void UsingDbContext(int? tenantId, Action<WePlatformDbContext> action)
- {
- using (UsingTenantId(tenantId))
- {
- using (var context = LocalIocManager.Resolve<WePlatformDbContext>())
- {
- context.DisableAllFilters();
- action(context);
- context.SaveChanges();
- }
- }
- }
- protected async Task UsingDbContextAsync(int? tenantId, Func<WePlatformDbContext, Task> action)
- {
- using (UsingTenantId(tenantId))
- {
- using (var context = LocalIocManager.Resolve<WePlatformDbContext>())
- {
- context.DisableAllFilters();
- await action(context);
- await context.SaveChangesAsync();
- }
- }
- }
- protected T UsingDbContext<T>(int? tenantId, Func<WePlatformDbContext, T> func)
- {
- T result;
- using (UsingTenantId(tenantId))
- {
- using (var context = LocalIocManager.Resolve<WePlatformDbContext>())
- {
- context.DisableAllFilters();
- result = func(context);
- context.SaveChanges();
- }
- }
- return result;
- }
- protected async Task<T> UsingDbContextAsync<T>(int? tenantId, Func<WePlatformDbContext, Task<T>> func)
- {
- T result;
- using (UsingTenantId(tenantId))
- {
- using (var context = LocalIocManager.Resolve<WePlatformDbContext>())
- {
- context.DisableAllFilters();
- result = await func(context);
- await context.SaveChangesAsync();
- }
- }
- return result;
- }
- #endregion
- #region Login
- protected void LoginAsHostAdmin()
- {
- LoginAsHost(UserBase.AdminUserName);
- }
- protected void LoginAsDefaultTenantAdmin()
- {
- LoginAsTenant(TenantBase.DefaultTenantName, UserBase.AdminUserName);
- }
- protected void LogoutAsDefaultTenant()
- {
- LogoutAsTenant(TenantBase.DefaultTenantName);
- }
- protected void LoginAsHost(string userName)
- {
- AbpSession.TenantId = null;
- var user =
- UsingDbContext(
- context =>
- context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
- if (user == null)
- {
- throw new Exception("There is no user: " + userName + " for host.");
- }
- AbpSession.UserId = user.Id;
- }
- protected void LogoutAsHost()
- {
- Resolve<IMultiTenancyConfig>().IsEnabled = true;
- AbpSession.TenantId = null;
- AbpSession.UserId = null;
- }
- protected void LoginAsTenant(string tenancyName, string userName)
- {
- var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
- if (tenant == null)
- {
- throw new Exception("There is no tenant: " + tenancyName);
- }
- AbpSession.TenantId = tenant.Id;
- var user =
- UsingDbContext(
- context =>
- context.Users.FirstOrDefault(u => u.TenantId == AbpSession.TenantId && u.UserName == userName));
- if (user == null)
- {
- throw new Exception("There is no user: " + userName + " for tenant: " + tenancyName);
- }
- AbpSession.UserId = user.Id;
- }
- protected void LogoutAsTenant(string tenancyName)
- {
- var tenant = UsingDbContext(context => context.Tenants.FirstOrDefault(t => t.TenancyName == tenancyName));
- if (tenant == null)
- {
- throw new Exception("There is no tenant: " + tenancyName);
- }
- AbpSession.TenantId = tenant.Id;
- AbpSession.UserId = null;
- }
- #endregion
- /// <summary>
- /// Gets current user if <see cref="IAbpSession.UserId"/> is not null.
- /// Throws exception if it's null.
- /// </summary>
- protected async Task<User> GetCurrentUserAsync()
- {
- var userId = AbpSession.GetUserId();
- return await UsingDbContext(context => context.Users.SingleAsync(u => u.Id == userId));
- }
- /// <summary>
- /// Gets current tenant if <see cref="IAbpSession.TenantId"/> is not null.
- /// Throws exception if there is no current tenant.
- /// </summary>
- protected async Task<Tenant> GetCurrentTenantAsync()
- {
- var tenantId = AbpSession.GetTenantId();
- return await UsingDbContext(context => context.Tenants.SingleAsync(t => t.Id == tenantId));
- }
- }
- }
|