Below is the code which we wrote for creating the Tenant. We copied from the existing code and made some modification. We are adding an Organization Id to the tenant.
Also it's withing the same database and the database is not local.
public async Task<int> CreateWithAdminUserAsync(string tenancyName, string name, string adminPassword, string adminEmailAddress, bool isActive, int? editionId, bool shouldChangePasswordOnNextLogin,
bool sendActivationEmail, long? organizationId, int? sourcetenantId, List<string> entityList)
{
int newTenantId;
long newAdminId;
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
var connectionstringUnit = await (from org in _organizationRepository.GetAll()
join constr in _connectionStringRepository.GetAll() on org.ConnectionStringId equals
constr.Id
where org.Id == organizationId
select constr).FirstOrDefaultAsync();
//Create tenant
var tenant = new Tenant(tenancyName, name)
{
IsActive = isActive,
EditionId = editionId,
ConnectionString = ReferenceEquals(connectionstringUnit, null) ? null : connectionstringUnit.ConnectionString,
OrganizationUnitId = organizationId
};
CheckErrors(await CreateAsync(tenant));
await _unitOfWorkManager.Current.SaveChangesAsync(); //To get new tenant's id.
//Create tenant database
_abpZeroDbMigrator.CreateOrMigrateForTenant(tenant);
//We are working entities of new tenant, so changing tenant filter
using (_unitOfWorkManager.Current.SetTenantId(tenant.Id))
{
//Create static roles for new tenant
CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));
await _unitOfWorkManager.Current.SaveChangesAsync(); //To get static role ids
//grant all permissions to admin role
var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin);
await _roleManager.GrantAllPermissionsAsync(adminRole);
//User role should be default
var userRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.User);
userRole.IsDefault = true;
CheckErrors(await _roleManager.UpdateAsync(userRole));
//Create admin user for the tenant
if (adminPassword.IsNullOrEmpty())
{
adminPassword = User.CreateRandomPassword();
}
var adminUser = User.CreateTenantAdminUser(tenant.Id, adminEmailAddress, adminPassword);
adminUser.ShouldChangePasswordOnNextLogin = shouldChangePasswordOnNextLogin;
adminUser.IsActive = isActive;
CheckErrors(await _userManager.CreateAsync(adminUser));
await _unitOfWorkManager.Current.SaveChangesAsync(); //To get admin user's id
//Assign admin user to admin role!
CheckErrors(await _userManager.AddToRoleAsync(adminUser.Id, adminRole.Name));
//Notifications
await _appNotifier.WelcomeToTheApplicationAsync(adminUser);
//Send activation email
if (sendActivationEmail)
{
adminUser.SetNewEmailConfirmationCode();
await _userEmailer.SendEmailActivationLinkAsync(adminUser, adminPassword);
}
await _unitOfWorkManager.Current.SaveChangesAsync();
await _demoDataBuilder.BuildForAsync(tenant);
newTenantId = tenant.Id;
newAdminId = adminUser.Id;
}
if (sourcetenantId.HasValue)
await CloneTenantData(newTenantId, sourcetenantId, entityList);
await uow.CompleteAsync();
}
//Used a second UOW since UOW above sets some permissions and _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync needs these permissions to be saved.
using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
{
using (_unitOfWorkManager.Current.SetTenantId(newTenantId))
{
await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(new UserIdentifier(newTenantId, newAdminId));
await _unitOfWorkManager.Current.SaveChangesAsync();
await uow.CompleteAsync();
}
}
return newTenantId;
}
Do you find any issue with this code ?
Any update on this ? I am really having a hard time figuring out the issue
I now downloaded the latest template from AspnetZero and started backward integration into my project . On doing so I came across the below issue :
Component Abp.Web.Configuration.AbpWebModuleConfiguration could not be registered. There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: Castle.MicroKernel.ComponentRegistrationException: Component Abp.Web.Configuration.AbpWebModuleConfiguration could not be registered. There is already a component with that name. Did you want to modify the existing component instead? If not, make sure you specify a unique name.
Source Error:
Line 25: );
Line 26:
Line 27: base.Application_Start(sender, e);
Line 28: }
Line 29: }
Please help
Hi Hilkan -
I had a requirement to track changes to few property of a Entity which I am able to do overriding ApplyABpConcepts.
I am filtering the tracking by filtering the Entity name, but the problem is when I am trying to insert a record based on the calculation from previous and new values and try to insert into another table then again the ApplyAbpConcepts is called which now has the entity which I am tracking and the new entity to which I am inserting a record. As a result I am getting into an infinite loop.
Is there a way where i can stop tracking for an entity ?
I initially started with using Organization Unit as Companies then I am frequently running into issues while extending Roles/Settings/Users/etc..
So today I reversed my approach, now I am treating each company as a Tenant and grouping them under one organization.
Is there a way I can share the same user/roles between tenants. If not I basically have to create two users for each of the tenant and link them up.
I Wish we could extend the scope of users/roles/settings to Organizations without any additional work.
0.9.6. I upgrade as soon it's released
I am using Abp 9.7 and latest version of Abp Zero. I wasn't using the test cases before and decided to start using it now, so can't say what could have broke this. Here is the complete exception :
Test Name: XXXXX.YYYYYYY.Tests.Auditing.AuditLogAppService_Tests.Test1(cultureName: "en") Test FullName: XXXXX.YYYYYYY.Tests.Auditing.AuditLogAppService_Tests.Test1 (0519c3fdd562f69227b885ca8782c51d90c41c79) Test Source: C:\Source Code\ZZZZZ\DEVCODE\Tests\XXXXX.YYYYYYY.Tests\Auditing\AuditLogAppService_Tests.cs : line 30 Test Outcome: Failed Test Duration: 0:00:00.001
Result StackTrace:
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstanceCore(ConstructorCandidate constructor, Object[] arguments, Type implType)
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstance(CreationContext context, ConstructorCandidate constructor, Object[] arguments)
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.Instantiate(CreationContext context)
at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.InternalCreate(CreationContext context)
at Castle.MicroKernel.ComponentActivator.AbstractComponentActivator.Create(CreationContext context, Burden burden)
at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.CreateInstance(CreationContext context, Boolean trackedExternally)
at Castle.MicroKernel.Lifestyle.AbstractLifestyleManager.Resolve(CreationContext context, IReleasePolicy releasePolicy)
at Castle.MicroKernel.Handlers.DefaultHandler.ResolveCore(CreationContext context, Boolean requiresDecommission, Boolean instanceRequired, Burden& burden)
at Castle.MicroKernel.Handlers.DefaultHandler.Resolve(CreationContext context, Boolean instanceRequired)
at Castle.MicroKernel.Handlers.AbstractHandler.Resolve(CreationContext context)
at Castle.MicroKernel.DefaultKernel.ResolveComponent(IHandler handler, Type service, IDictionary additionalArguments, IReleasePolicy policy)
at Castle.MicroKernel.DefaultKernel.Castle.MicroKernel.IKernelInternal.Resolve(Type service, IDictionary arguments, IReleasePolicy policy)
at Castle.MicroKernel.DefaultKernel.Resolve(Type service, IDictionary arguments)
at Castle.Windsor.WindsorContainer.ResolveT
at Abp.Dependency.IocManager.ResolveT in D:\Halil\GitHub\aspnetboilerplate\src\Abp\Dependency\IocManager.cs:line 160
at XXXXX.YYYYYYY.Tests.AppTestBase.UsingDbContext(Nullable1 tenantId, Action
1 action) in C:\Source Code\ZZZZZ\DEVCODE\Tests\XXXXX.YYYYYYY.Tests\AppTestBase.cs:line 157
at XXXXX.YYYYYYY.Tests.AppTestBase.UsingDbContext(Action1 action) in C:\Source Code\ZZZZZ\DEVCODE\Tests\XXXXX.YYYYYYY.Tests\AppTestBase.cs:line 135 at XXXXX.YYYYYYY.Tests.AppTestBase..ctor() in C:\Source Code\ZZZZZ\DEVCODE\Tests\XXXXX.YYYYYYY.Tests\AppTestBase.cs:line 42 at XXXXX.YYYYYYY.Tests.Auditing.AuditLogAppService_Tests..ctor() in C:\Source Code\ZZZZZ\DEVCODE\Tests\XXXXX.YYYYYYY.Tests\Auditing\AuditLogAppService_Tests.cs:line 20 ----- Inner Stack Trace ----- at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeConstructorInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.FastCreateInstance(Type implType, Object[] arguments, ConstructorCandidate constructor) at Castle.MicroKernel.ComponentActivator.DefaultComponentActivator.CreateInstanceCore(ConstructorCandidate constructor, Object[] arguments, Type implType) ----- Inner Stack Trace ----- at System.Linq.Enumerable.Single[TSource](IEnumerable
1 source, Func2 predicate) at System.Data.Entity.Utilities.DbProviderManifestExtensions.GetStoreTypeFromName(DbProviderManifest providerManifest, String name) at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.ConfigureColumn(EdmProperty column, EntityType table, DbProviderManifest providerManifest) at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(EdmProperty column, EntityType table, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration) at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.<>c__DisplayClass4.<Configure>b__3(Tuple
2 pm)
at System.Data.Entity.Utilities.IEnumerableExtensions.Each[T](IEnumerable1 ts, Action
1 action)
at System.Data.Entity.ModelConfiguration.Configuration.Properties.Primitive.PrimitivePropertyConfiguration.Configure(IEnumerable1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride, Boolean fillFromExistingConfiguration) at System.Data.Entity.ModelConfiguration.Configuration.Types.StructuralTypeConfiguration.ConfigurePropertyMappings(IList
1 propertyMappings, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.ConfigurePropertyMappings(DbDatabaseMapping databaseMapping, EntityType entityType, DbProviderManifest providerManifest, Boolean allowOverride)
at System.Data.Entity.ModelConfiguration.Configuration.Types.EntityTypeConfiguration.Configure(EntityType entityType, DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest)
at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.ConfigureEntityTypes(DbDatabaseMapping databaseMapping, ICollection1 entitySets, DbProviderManifest providerManifest) at System.Data.Entity.ModelConfiguration.Configuration.ModelConfiguration.Configure(DbDatabaseMapping databaseMapping, DbProviderManifest providerManifest) at System.Data.Entity.DbModelBuilder.Build(DbProviderManifest providerManifest, DbProviderInfo providerInfo) at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection) at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext) at System.Data.Entity.Internal.RetryLazy
2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.ForceOSpaceLoadingForKnownEntityTypes()
at System.Data.Entity.DbContext.System.Data.Entity.Infrastructure.IObjectContextAdapter.get_ObjectContext()
at Abp.EntityFramework.AbpDbContext.RegisterToChanges() in D:\Halil\GitHub\aspnetboilerplate\src\Abp.EntityFramework\EntityFramework\AbpDbContext.cs:line 126
at Abp.Zero.EntityFramework.AbpZeroDbContext`3..ctor(DbConnection dbConnection, Boolean contextOwnsConnection) in D:\Halil\GitHub\module-zero\src\Abp.Zero.EntityFramework\Zero\EntityFramework\AbpZeroDbContext.cs:line 81
at XXXXX.YYYYYYY.EntityFramework.YYYYYYYDbContext..ctor(DbConnection dbConnection) in C:\Source Code\ZZZZZ\DEVCODE\XXXXX.YYYYYYY.EntityFramework\EntityFramework\YYYYYYYDbContext.cs:line 689
Result Message:
Castle.MicroKernel.ComponentActivator.ComponentActivatorException : ComponentActivator: could not instantiate XXXXX.YYYYYYY.EntityFramework.YYYYYYYDbContext
---- System.Reflection.TargetInvocationException : Exception has been thrown by the target of an invocation.
-------- System.InvalidOperationException : Sequence contains no matching element
Thanks Hilkan the new release fixed it
I made this change and it works :
public async Task<PagedResultOutput<AuditLogListDto>> GetAuditLogs(GetAuditLogsInput input) { var query = CreateAuditLogAndUsersQuery(input); var resultCount = await query.CountAsync(); var results = await query // .AsNoTracking() .OrderBy(input.Sorting) .PageBy(input) .ToListAsync(); var auditLogListDtos = ConvertToAuditLogListDtos(results); return new PagedResultOutput<AuditLogListDto>(resultCount, auditLogListDtos); }
Is this correct?
I am not sure what resolved it, but when I deleted all the resources and tried again it worked.