Copied to clipboard

Flag this post as spam?

This post will be reported to the moderators as potential spam to be looked at


  • javafun 16 posts 49 karma points c-trib
    Jan 28, 2019 @ 10:24
    javafun
    0

    Initialize member in IApplicationEventHandler and receive Request is not available in this context

    Hi All

    I am newbie to Umbraco, I want to set up a default member during application start. I have the following code invoked from OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) method.

    private void InitializeMembers(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            string username = "[email protected]";
    
            var memberService = applicationContext.Services.MemberService;
    
            int total;
    
            var existingMember = memberService.FindByUsername(username, 0, 1, out total, Umbraco.Core.Persistence.Querying.StringPropertyMatchType.Exact).FirstOrDefault();
    
            if (existingMember == null)
            {
                var newMember = memberService.CreateWithIdentity(username, username, "Test1234$", "member", true);
                memberService.Save(newMember);
    
            }
        }
    

    The aforementioned code works fine in my controller, but not in IApplicationEventHandler, and I keep getting Request is not available in this context, however the user was created successfully.

    Is there anything I missed in my code?

    Appreciate for your help.

  • javafun 16 posts 49 karma points c-trib
    Jan 29, 2019 @ 00:19
    javafun
    0

    Had anyone experienced this issue? Can anyone give an idea?

    Appreciate for your help.

  • David Challener 80 posts 444 karma points c-trib
    Jan 29, 2019 @ 10:08
    David Challener
    100

    Hi,

    I think it's to do with the "member" memberType passed on the CreateWithIdentity call. However, you'll hit other issues using this version of memberService, namely the password will need to be passed encrypted. I tend to do my membership as follows...(shortened for simplicity, and changed for your example)

    public class Bootstrap : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase app, ApplicationContext ctx)
        {
            InitializeMembers(app, ctx);
        }
    
        private void InitializeMembers(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            string username = "[email protected]";
    
            var memberService = applicationContext.Services.MemberService;
            var memberTypeService = applicationContext.Services.MemberTypeService;
            var memberType = memberTypeService.Get("Member");
    
    
            if (memberService.GetByEmail(username) != null)
            {
                return;
            }
    
            try
            {
                var member = memberService.CreateMemberWithIdentity(username, username, memberType);
    
                // to set the password using Umbraco's hashing you need to call this method
                memberService.SavePassword(member, "Test1234$");
    
                member.IsApproved = true;
                memberService.Save(member);
            }
            catch (Exception ex)
            {
                // Log error
                return;
            }
        }
    }
    

    HTH,

    David

  • javafun 16 posts 49 karma points c-trib
    Jan 30, 2019 @ 11:41
    javafun
    0

    Hi David

    Thanks for your help. The issue doesn't seem coming from the "member" memberType passed on the CreateWithIdentity call.

    I tried CreateMember method with MemberService, and it threw the same exception.

    Having said that, by using your code sample with try and catch, obviously I just can avoid the YSOD, but problem still exists.

     2019-01-30 22:25:18,335 [P7852/D3/T15] ERROR Umbraco.Core.CoreBootManager - An error occurred running OnApplicationStarted for handler UmbracoDemo2.Logic.Application.MyApplicationEventHandler
    System.Web.HttpException (0x80004005): Request is not available in this context
     at System.Web.HttpContext.get_Request()
    at System.Web.HttpContextWrapper.get_Request()
    at Umbraco.Core.HttpContextExtensions.GetCurrentRequestIpAddress(HttpContextBase httpContext)
    at Umbraco.Core.Auditing.AuditEventHandler.get_PerformingIp()
    at Umbraco.Core.Auditing.AuditEventHandler.OnSavedMember(IMemberService sender, SaveEventArgs`1 saveEventArgs)
    at Umbraco.Core.Events.TypedEventHandler`2.Invoke(TSender sender, TEventArgs e)
    at Umbraco.Core.Events.EventDefinition`2.RaiseEvent()
    at Umbraco.Core.Events.ScopeEventDispatcher.ScopeExitCompleted()
    at Umbraco.Core.Events.ScopeEventDispatcherBase.ScopeExit(Boolean completed)
    at Umbraco.Core.Scoping.Scope.<>c__DisplayClass70_0.<RobustExit>b__1()
    at Umbraco.Core.Scoping.Scope.TryFinally(Int32 index, Action[] actions)
    at Umbraco.Core.Scoping.Scope.TryFinally(Int32 index, Action[] actions)
    at Umbraco.Core.Scoping.Scope.RobustExit(Boolean completed, Boolean onException)
    at Umbraco.Core.Scoping.Scope.DisposeLastScope()
    at Umbraco.Core.Scoping.Scope.Dispose()
    at Umbraco.Core.Persistence.UnitOfWork.ScopeUnitOfWork.DisposeResources()
    at Umbraco.Core.DisposableObjectSlim.Dispose(Boolean disposing)
    at Umbraco.Core.DisposableObjectSlim.Dispose()
    at Umbraco.Core.Services.MemberService.CreateMemberWithIdentity(String username, String email, String name, String passwordValue, IMemberType memberType, Boolean isApproved)
    at Umbraco.Core.Services.MemberService.CreateMemberWithIdentity(String username, String email, IMemberType memberType)
    at UmbracoDemo2.Logic.Application.MyApplicationEventHandler.InitializeMembers(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) in C:\dev\XXX\UmbracoDemo2\Logic\Application\MyApplicationEventHandler.cs:line 135
    at UmbracoDemo2.Logic.Application.MyApplicationEventHandler.OnApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext) in C:\dev\XXX\UmbracoDemo2\Logic\Application\MyApplicationEventHandler.cs:line 37
    at Umbraco.Core.CoreBootManager.<Complete>b__38_0(IApplicationEventHandler x)
    
  • Nik 1401 posts 6160 karma points MVP 3x c-trib
    Jan 30, 2019 @ 12:06
    Nik
    0

    Hi Javafun,

    As per my comment on Slack, this is code that has been used in the past to fake a context in the start up events.

    private void EnsureValidUmbracoContext()
    {
        if (UmbracoContext.Current == null)
        {
            var dummyHttpContext = new HttpContextWrapper(new HttpContext(new SimpleWorkerRequest("blah.aspx", "", new StringWriter())));
                UmbracoContext.EnsureContext(
                    dummyHttpContext,
                    ApplicationContext.Current,
                    new WebSecurity(dummyHttpContext, ApplicationContext.Current),
                    UmbracoConfig.For.UmbracoSettings(),
                    UrlProviderResolver.Current.Providers,
                    false);
        }
    }
    

    If you create that method in your class, and call it as the first line in your InitializeMembers method it "might" solve your issue but I'm not sure.

    Nik

  • David Challener 80 posts 444 karma points c-trib
    Jan 31, 2019 @ 11:56
    David Challener
    0

    Lol!

    I should've tested without the try/catch block first, sorry! I would put the try catch back when you're happy the issue has been resolved but try this code.

    private void InitializeMembers(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            string username = "[email protected]";
    
            var memberService = ApplicationContext.Current.Services.MemberService;
            var memberTypeService = ApplicationContext.Current.Services.MemberTypeService;
            var memberType = memberTypeService.Get("Member");
    
    
            if (memberService.GetByEmail(username) != null)
            {
                return;
            }
    
    
            var member = memberService.CreateMemberWithIdentity(username, username, memberType);
    
            // to set the password using Umbraco's hashing you need to call this method
            memberService.SavePassword(member, "Test1234$");
    
            member.IsApproved = true;
            memberService.Save(member);
    
        }
    

    David

Please Sign in or register to post replies

Write your reply to:

Draft