Open Closed

New Tenant Database Issue #8208


1
nitinrpatel created

Hello, I Want to create new tenant with database.For that i have pass connection string but i got error while performing it. Database was successfully created, All the Migration and Seed Files are Successfully Run on that database but after that I am not work further System Gives "An internal error occurred during your request!"I Have Attached Screenshot Of my error page for reference.

Please Help me ASAP.


15 Answer(s)
  • 0
    maliming created
    Support Team

    An internal error occurred during your request

    Please check the logs to see what the specific error is?

  • 0
    nitinrpatel created

    Error Accurs At This Line.

    CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));
    

  • 0
    maliming created
    Support Team

    Please share the complete method code. What is your zero version?

  • 0
    nitinrpatel created

    I Am Using ASP.NET MVC 5.x with AngularJS.

    public async Task<int> CreateWithAdminUserAsync(string tenancyName, string name, string adminPassword, string adminEmailAddress, string connectionString, bool isActive, int? editionId, bool shouldChangePasswordOnNextLogin, bool sendActivationEmail,string fullName, string companyName, string abn, string fax, string phone, string mobile, string email, float stcCharges, string retailerName, string retailerABN)
            {
                int newTenantId;
                long newAdminId;
    
                using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
                {
                    //Create tenant
                    var tenant = new Tenant(tenancyName, name)
                    {
                        IsActive = isActive,
                        EditionId = editionId,
                        ConnectionString = connectionString.IsNullOrWhiteSpace() ? null : SimpleStringCipher.Instance.Encrypt(connectionString),
                        FullName= fullName,
                        CompanyName=companyName,
                        ABN=abn,
                        FAX=fax,
                        Phone=phone,
                        Mobile=mobile,
                        Email=email,
                        STCCharges=stcCharges,
                        RetailerName=retailerName,
                        RetailerABN=retailerABN
                    };
    
                    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))
                    {
                        try
                        {
                            //Create static roles for new tenant
                            CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id));
                            await _unitOfWorkManager.Current.SaveChangesAsync(); //To get static role ids
                        }
                        catch(Exception e)
                        {
    
                        }
                        
    
                        //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 = false;
                        CheckErrors(await _roleManager.UpdateAsync(userRole));
    
                        //Installer role should be default
                        //var installerRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Installer);
                        //installerRole.IsDefault = true;
                        //CheckErrors(await _roleManager.UpdateAsync(installerRole));
    
                        //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 = true;
    
                        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;
                    }
    
                    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;
            }
    
    
    protected virtual void CheckErrors(IdentityResult identityResult)
            {
                identityResult.CheckErrors(LocalizationManager);
            }
    
  • 0
    maliming created
    Support Team

    May be related: https://support.aspnetzero.com/QA/Questions/2169

  • 0
    nitinrpatel created

    After Performing MSDTC Steps on my server the Error doesn't seems to be popup, but I started facing issue like in Database Seed doesn't run now and also I am unble to create any Tenant, also no log files are maintained now.

  • 0
    smry created
            public async Task&lt;int&gt; CreateWithAdminUserAsync(...)
                    {
                        int newTenantId;
                        long newAdminId;
    
            await CheckEditionAsync(editionId, isInTrialPeriod);
    
            using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
            {
                //Create tenant
                var tenant = new Tenant(tenancyName, name)
                {
                    IsActive = isActive,
                    EditionId = editionId,
                    SubscriptionEndDateUtc = subscriptionEndDate?.ToUniversalTime(),
                    IsInTrialPeriod = isInTrialPeriod,
                    ConnectionString = connectionString.IsNullOrWhiteSpace() ? null :                SimpleStringCipher.Instance.Encrypt(connectionString)
                };
    
                try
                {
                await CreateAsync(tenant);
                await _unitOfWorkManager.Current.SaveChangesAsync(); //To get new tenant's id.
    
                //Create tenant database
                _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant);
                }
                catch (Exception ex)
                {
                    //Fails here: {"There is already an object named 'MyPowerToolCreatedEntity' in the database."}
                }
                
    

    Im having this same issue but different failure. It seems to fail due to an entity that was created with the Power Tool. My code fails a few lines above where nitinrpatel's code fails. It creates the database in the right location but _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant); fails saying "There is already an object named 'MyPowerToolCreatedEntity' in the database."

  • 0
    maliming created
    Support Team

    hi @smry Can you share detailed steps to reproduce the problem?

    hi @nitinrpatel

    I am unble to create any Tenant

    What happens when you create a new tenant on the tenant page? Are there any related logs in the application's logs?

  • 0
    nitinrpatel created

    I had performed steps from the below mentin link for MSDTC Settings on my server. https://suneethasdiary.wordpress.com/tag/how-to-start-the-service-msdtc/ But After this changes Error doesn't seems to be popup,Database is Created but all the tables are blank(Before performing MSDTC Steps Seed's are migrated in DB),No Error log & Action log Updated in Log.txt file.

  • 0
    smry created

    @maliming - within the past few days we:

    1. created a tenant with its own DB
    2. added a tenant with shared host db
    3. Added an entity with the Power Tool
    4. Added new Tenant with its own DB
      1. Errors here:
    2019-12-19 10:01:44 | An error occured during migration of tenant database:
    2019-12-19 10:01:44 | Microsoft.Data.SqlClient.SqlException (0x80131904): There is already an object named 'MyEntity' in the database.
       at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
       at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
       at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
       at Microsoft.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean isAsync, Int32 timeout, Boolean asyncWrite)
       at Microsoft.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, Boolean sendToPipe, Int32 timeout, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String methodName)
       at Microsoft.Data.SqlClient.SqlCommand.ExecuteNonQuery()
       at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteNonQuery(RelationalCommandParameterObject parameterObject)
       at Microsoft.EntityFrameworkCore.Migrations.MigrationCommand.ExecuteNonQuery(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
       at Microsoft.EntityFrameworkCore.Migrations.Internal.MigrationCommandExecutor.ExecuteNonQuery(IEnumerable`1 migrationCommands, IRelationalConnection connection)
       at Microsoft.EntityFrameworkCore.Migrations.Internal.Migrator.Migrate(String targetMigration)
       at Microsoft.EntityFrameworkCore.RelationalDatabaseFacadeExtensions.Migrate(DatabaseFacade databaseFacade)
       at Abp.Zero.EntityFrameworkCore.AbpZeroDbMigrator`1.CreateOrMigrate(AbpTenantBase tenant, Action`1 seedAction)
       at Abp.Zero.EntityFrameworkCore.AbpZeroDbMigrator`1.CreateOrMigrateForTenant(AbpTenantBase tenant, Action`1 seedAction)
       at Abp.Zero.EntityFrameworkCore.AbpZeroDbMigrator`1.CreateOrMigrateForTenant(AbpTenantBase tenant)
       at medrx.Migrator.MultiTenantMigrateExecuter.Run(Boolean skipConnVerification) in C:\dev\webProj\medRx-API\src\medrx.Migrator\MultiTenantMigrateExecuter.cs:line 90
    ClientConnectionId:[...]
    Error Number:2714,State:6,Class:16
    2019-12-19 10:01:44 | Skipped this tenant and will continue for others...
    2019-12-19 10:01:44 | Tenant database migration completed. (1 / 2)
    2019-12-19 10:01:44 | --------------------------------------------------------
    

    There were a handful of other minor changes that were also done in-between steps 3 and 4 so I am unfortunately not able to identify a better recreation of steps for the error – I wanted to make sure that this was mentioned since I also saw an issue in the same location that nitinrpatel did – although may ultimately be unrelated

    I’ll make sure to update should I figure out how to clear the error – as of now it does create all databases so I can work around it in some capacity

  • 0
    yekalkan created

    Hi @smry,

    I couldn't reproduce your issue. Logs say that "There is already an object named 'MyEntity' in the database.", is there 'MyEntity' table in tenant database before you run the migrator?

  • 0
    nitinrpatel created

    Hello, @maliming is there any update in my query? Please provide solution for that AEAP.

  • 1
    smry created

    @yekalkan - nope, I deleted the entire DB and on re-build it still fails with that error The only solution I had was to remove migrations back to before the first Entity creation

    Starting from a fresh template and redoing the process, no errors were found.

  • 0
    ismcagdas created
    Support Team

    Thanks for the feedback @smry

  • 0
    ismcagdas created
    Support Team

    Please open a new issue if you are still having this problem.