Base solution for your next web application

Activities of "mentium"

Hi

I have created a method similar to the tenant registration page but when i run the code and it breaks after the first changes the transaction dosen't role back.

Register in controller:

    [HttpPost]
    [UnitOfWork]
    public virtual async Task<ActionResult> Register(WorkerRegistrationViewModel model)
    {
        try
        {
            if (UseCaptchaOnRegistration())
            {
                var recaptchaHelper = this.GetRecaptchaVerificationHelper();
                if (recaptchaHelper.Response.IsNullOrEmpty())
                {
                    throw new UserFriendlyException(L("CaptchaCanNotBeEmpty"));
                }

                if (recaptchaHelper.VerifyRecaptchaResponse() != RecaptchaVerificationResult.Success)
                {
                    throw new UserFriendlyException(L("IncorrectCaptchaAnswer"));
                }
            }

            //Getting host-specific settings
            var isNewRegisteredTenantActiveByDefault = await SettingManager.GetSettingValueForApplicationAsync<bool>(AppSettings.TenantManagement.IsNewRegisteredTenantActiveByDefault);
            var isEmailConfirmationRequiredForLogin = await SettingManager.GetSettingValueForApplicationAsync<bool>(AbpZeroSettingNames.UserManagement.IsEmailConfirmationRequiredForLogin);
            var defaultEditionIdValue = await SettingManager.GetSettingValueForApplicationAsync(AppSettings.TenantManagement.DefaultEdition);
            Guid? defaultEditionId = null;

            if (!string.IsNullOrEmpty(defaultEditionIdValue) && (await _editionManager.FindByIdAsync(Guid.Parse(defaultEditionIdValue)) != null))
            {
                defaultEditionId = Guid.Parse(defaultEditionIdValue);
            }

            Guid tenantId = AbpSession.TenantId.Value;

            CurrentUnitOfWork.SetTenantId(tenantId);


            ViewBag.UseCaptcha = UseCaptchaOnRegistration();

            var tenant = await _tenantManager.GetByIdAsync(tenantId);


            DateTime? dateOfBirth = null;
            try
            {
                dateOfBirth = DateTime.Parse($"{model.Dob_Year}-{model.Dob_Month}-{model.Dob_Day}");
            }
            catch (Exception)
            {
                throw new UserFriendlyException(L("DateOfBirthFormatError"));
            }

            var userId = await _candidateManager.CreateCandidateAsync(tenantId,
                model.UserName,
                model.FirstName,
                model.LastName,
                dateOfBirth.Value,
                model.Password,
                model.EmailAddress,
                true);

            var user = await _userManager.FindByIdAsync(userId);

            //Directly login if possible
            if (tenant.IsActive && user.IsActive && (user.IsEmailConfirmed || !isEmailConfirmationRequiredForLogin))
            {
                var loginResult = await GetLoginResultAsync(user.UserName, model.Password, tenant.TenancyName);

                if (loginResult.Result == AbpLoginResultType.Success)
                {
                    await SignInAsync(loginResult.User, loginResult.Identity);
                    return Redirect(Url.Action("Index", "Application"));
                }

                Logger.Warn("New registered user could not be login. This should not be normally. login result: " + loginResult.Result);
            }

            //await _appNotifier.NewTenantRegisteredAsync(tenant);

            return View("RegisterResult", new WorkerRegisterResultViewModel
            {
                TenancyName = tenant.TenancyName,
                Name = model.FirstName,
                UserName = Authorization.Users.User.AdminUserName,
                EmailAddress = model.EmailAddress,
                IsActive = isNewRegisteredTenantActiveByDefault,
                IsEmailConfirmationRequired = isEmailConfirmationRequiredForLogin
            });


        }
        catch (UserFriendlyException ex)
        {
            ViewBag.UseCaptcha = UseCaptchaOnRegistration();
            ViewBag.ErrorMessage = ex.Message;

            return View("Index", model);
        }
    }

I have wrote this code to create the candidate

    public async Task<Guid> CreateCandidateAsync(Guid tenantId, string userName, string firstName, string lastName, DateTime dateOfBirth, string password, string emailAddress, bool isActive, Guid? editionId = null, bool shouldChangePasswordOnNextLogin = false, bool sendActivationEmail = false)
    {
        Guid newUserId;

        using (var uow = _unitOfWorkManager.Begin(TransactionScopeOption.RequiresNew))
        {
            using (_unitOfWorkManager.Current.SetTenantId(tenantId))
            {
                //Create admin user for the tenant
                if (password.IsNullOrEmpty())
                {
                    password = User.CreateRandomPassword();
                }

                var user = User.CreateCandidateUser(tenantId, userName, firstName, lastName, emailAddress, password);
                user.ShouldChangePasswordOnNextLogin = shouldChangePasswordOnNextLogin;
                user.IsActive = isActive;

                CheckErrors(await _userManager.CreateAsync(user));
                await _unitOfWorkManager.Current.SaveChangesAsync(); //To get candidate user's id

                var userRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Candidate);

                //Assign admin user to admin role!
                CheckErrors(await _userManager.AddToRoleAsync(user.Id, userRole.Name));

                var ca = new Candidate();
                ca.Id = user.Id;
                ca.TenantId = tenantId;
                ca.Number = 1;
                ca.FirstName = firstName;
                ca.LastName = lastName;
                ca.Address = new Address();
                ca.MobileNumber = new PhoneNumber();
                ca.PhoneNumber = new PhoneNumber();
                await _candidateRepository.InsertAsync(ca);
                await _unitOfWorkManager.Current.SaveChangesAsync(); //To get candidate's id

<span style="color:#FF0000">//Is is here the exception is thrown</span>

                //Notifications
                await _appNotifier.WelcomeToTheApplicationAsync(user);

                //Send activation email
                if (sendActivationEmail)
                {
                    user.SetNewEmailConfirmationCode();
                    await _userEmailer.SendEmailActivationLinkAsync(user, password);
                }

                await _unitOfWorkManager.Current.SaveChangesAsync();

                newUserId = user.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(tenantId))
            {
                await _notificationSubscriptionManager.SubscribeToAllAvailableNotificationsAsync(new UserIdentifier(tenantId, newUserId));
                await _unitOfWorkManager.Current.SaveChangesAsync();
                await uow.CompleteAsync();
            }
        }

        return newUserId;
    }

Hope somone can help.

Thanks for the answer.

I have used the method Register from TenantRegistrationController, would this code not role back either?

Hi

I have some problems with publishing to Azure, i have created a defult aso.net core/angular comnbined template, then i'm running it in local it runs fine, but when i publish to Azure i get this error:

ERROR 2017-10-02 14:57:10,741 [4 ] Microsoft.AspNetCore.Server.Kestrel - Connection id "0HL89KMMA21CB", Request id "0HL89KMMA21CB:00000007": An unhandled exception was thrown by the application. System.Reflection.ReflectionTypeLoadException: Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information. at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module) at System.Reflection.RuntimeAssembly.get_DefinedTypes() at Microsoft.AspNetCore.Mvc.ApplicationParts.AssemblyPart.get_Types() at Microsoft.AspNetCore.Mvc.Controllers.ControllerFeatureProvider.PopulateFeature(IEnumerable1 parts, ControllerFeature feature) at Microsoft.AspNetCore.Mvc.ApplicationParts.ApplicationPartManager.PopulateFeature[TFeature](TFeature feature) at Microsoft.AspNetCore.Mvc.Internal.ControllerActionDescriptorProvider.GetControllerTypes() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionDescriptorProvider.BuildModel() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionDescriptorProvider.GetDescriptors() at Microsoft.AspNetCore.Mvc.Internal.ControllerActionDescriptorProvider.OnProvidersExecuting(ActionDescriptorProviderContext context) at Microsoft.AspNetCore.Mvc.Internal.ActionDescriptorCollectionProvider.UpdateCollection() at Microsoft.AspNetCore.Mvc.Internal.ActionDescriptorCollectionProvider.get_ActionDescriptors() at Microsoft.AspNetCore.Mvc.Internal.AttributeRoute.GetTreeRouter() at Microsoft.AspNetCore.Mvc.Internal.AttributeRoute.RouteAsync(RouteContext context) at Microsoft.AspNetCore.Routing.RouteCollection.<RouteAsync>d__9.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Builder.RouterMiddleware.<Invoke>d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.Owin.Mapping.MapMiddleware.<Invoke>d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Owin.WebSocketAcceptAdapter.<>c__DisplayClass6_0.<<AdaptWebSockets>b__0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Localization.RequestLocalizationMiddleware.<Invoke>d__4.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at VikarProgram.Web.Startup.Startup.<>c.<<Configure>b__4_1>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at VikarProgram.Web.Authentication.JwtBearer.JwtTokenMiddleware.<>c.<<UseJwtTokenMiddleware>b__0_0>d.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.<Invoke>d__6.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Cors.Infrastructure.CorsMiddleware.<Invoke>d__7.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Server.IISIntegration.IISMiddleware.<Invoke>d__11.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.AspNetCore.Hosting.Internal.RequestServicesContainerMiddleware.<Invoke>d__3.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task) at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.Frame1.<ProcessRequestsAsync>d__2.MoveNext()

Anybody knows why i get this error?

Hi @ismcagdas

I've fund the error, it was the cors url where was wrog.

Question

Hi

When are you planing to release the next version of ASP.NET Zero Angular?

Question

Hi

How can I logon as host when i use subdomain to define tenant name?

Answer

Yes, but it us used for frontend/sales website, do you know if there is a way to map for example admin.site.com to the hot part of the site?

Answer

I haven't set it up on azure yet, so I don't know. I just thought i would be a problem.

Hi

I've tryed these steps but i stil getting error.

I'm using asp.net core / angular

2018-03-01T11:35:07.3784052Z ============================================================================== 2018-03-01T11:35:07.3784278Z Task : Command Line 2018-03-01T11:35:07.3784373Z Description : Run a command line with arguments 2018-03-01T11:35:07.3784465Z Version : 1.1.3 2018-03-01T11:35:07.3784594Z Author : Microsoft Corporation 2018-03-01T11:35:07.3784696Z Help : [More Information](<a class="postlink" href="https://go.microsoft.com/fwlink/?LinkID=613735">https://go.microsoft.com/fwlink/?LinkID=613735</a>) 2018-03-01T11:35:07.3784825Z ============================================================================== 2018-03-01T11:35:07.3889844Z ##[command]D:\a\3\s\node_modules.bin\ng.cmd build -prod 2018-03-01T11:35:07.4077115Z The system cannot find the path specified. 2018-03-01T11:35:08.4407169Z ##[error]Process completed with exit code 1.

Steps: 1: Use Yarn 2: Yarn 3: npm build (working folder: "$/PROJECTNAME/Master", npm command: install, arguments: -g @angular/cli) 4: CLI (Tool: $(Build.SourcesDirectory)\node_modules.bin\ng.cmd, arguments: build -prod)

Anybody knows what i'm missing?

@kythor, wierd, i've actualy tried that also.

Showing 1 to 10 of 14 entries