Copied to clipboard

Flag this post as spam?

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


  • Giu 23 posts 141 karma points
    Oct 21, 2017 @ 10:16
    Giu
    0

    MemberService Created & Saved Event not displaying custom properties

    Version number: 7.6.8

    Pluggins I use:

    • Articulate (v3)
    • Diplo Audit Log Viewer
    • Diplo Trace Log Viewer
    • Diplo God Mode
    • Model Builder
    • Nested Content
    • uSync

    I was trying to use MemberService.Created / .Saved events to send email notifications to users and I realized the IMember I retrieved doesn't have any of its custom properties set.

    I also tried to use the IPublishedContent api to get the properties but I still get null or empty string for my properties.

    public class MembersEventHandler : ApplicationEventHandler
    {
        protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
        {
            MemberService.Saving += Geolocation_Update;
            MemberService.Created += CustomerCreated_EmailNotification;
    
            base.ApplicationStarted(umbracoApplication, applicationContext);
        }
    
        private void CustomerCreated_EmailNotification(IMemberService sender, NewEventArgs<IMember> e)
        {
            //whole try catch as the welcome email is a nice-to-have
            try
            {
                var typeAlias = e.Entity.ContentTypeAlias;
    
                //not a customer ? Nothing to mention
                if (typeAlias != Helpers.Constants.CustomerMemberTypeAlias)
                    return;
    
                var uContext = UmbracoContext.Current;
                var home = uContext.ContentCache.GetAtRoot().FirstOrDefault(x => x is HomePage) as HomePage;
                var customer = new MembershipHelper(uContext).GetById(e.Entity.Id) as Customer;
    
                if (home.WelcomeCustomerEmail == null || string.IsNullOrWhiteSpace(home.WelcomeCustomerEmail.ToHtmlString()))
                {
                    LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "The welcome customer email is empty !!", new ArgumentNullException("home.WelcomeCustomerEmail"));
                    return;
                }
    
                var customerEmail = e.Entity.Email;
    
                 //empty string
                 var firstNameTest = e.Entity.GetValue<string>("firstName");
    
                //null
                var firstNameCache = customer.FirstName;
    
                var adminEmail = ConfigurationManager.AppSettings["adminEmail"];
    
                Expression<Action> emailToCustomer = () => EmailHelper.SendCustomerWelcomeEmail(customerEmail, home.WelcomeCustomerEmail.ToHtmlString(), firstName, adminEmail);
                HangfireHelper.AddToQueue(emailToCustomer);
            }
    
            catch (Exception ex)
            {
                LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, ex.Message, ex);
                return;
            }
        }
    

    It looks like the cache is not ready when the event occurs and the entity object doesn't contains all the properties.

    The code I use to register my object:

            [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult HandleRegister(RegisterViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return CurrentUmbracoPage();
            }
    
            if(model.TermsAndConditionApproved != "on")
            {
                ModelState.AddModelError("RegisterForm.", "Please check the terms and condition checkbox to register");
                return CurrentUmbracoPage();
            }
    
            //Model valid let's create the member
            try
            {
                var regModel = Members.CreateRegistrationModel(Constants.CustomerMemberTypeAlias);
    
                regModel.Email = model.EmailAddress;
                regModel.LoginOnSuccess = true;
                regModel.Name = $"{model.FirstName} {model.LastName}";
                regModel.Password = model.RegisterPassword;
                regModel.UsernameIsEmail = true;
                regModel.MemberTypeAlias = Constants.CustomerMemberTypeAlias;
                regModel.MemberProperties = new System.Collections.Generic.List<UmbracoProperty>()
                {
                    new UmbracoProperty() 
                    {
                        Alias = "firstName",
                        Value = model.FirstName
                    }, 
                    new UmbracoProperty()
                    {
                        Alias = "lastName", 
                        Value = model.LastName
                    },
                    new UmbracoProperty()
                    {
                        Alias = "addressLine1",
                        Value = model.AddressLine1
                    },
                    new UmbracoProperty()
                    {
                        Alias = "addressLine2",
                        Value = model.AddressLine2
                    },
                    new UmbracoProperty()
                    {
                        Alias = "postCode",
                        Value = model.Postcode
                    },
                    new UmbracoProperty()
                    {
                        Alias = "city",
                        Value = model.City
                    },
                    new UmbracoProperty()
                    {
                        Alias = "phoneNumber",
                        Value = model.PhoneNumber
                    }
                };
    
                MembershipCreateStatus status;
                var user = Members.RegisterMember(regModel, out status);
    
                if (status == MembershipCreateStatus.Success)
                {
                    Services.MemberService.AssignRole(user.UserName, Constants.CustomerRoleAlias);
    
                    return RedirectToUmbracoPage(bookingPage);
                }
    
                else
                {
                    var errorText = string.Empty;
                    switch (status)
                    {
                        case MembershipCreateStatus.InvalidUserName:
                            errorText = "Invalid username";
                            break;
    
                        //etc 
    
                        default:
                            break;
                    }
    
                    ModelState.AddModelError("RegisterForm.", errorText);
                    return CurrentUmbracoPage();
                }
            }
    
            catch (Exception ex)
            {
                LogHelper.Error(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, $"Error while creating the user", ex);
    
                TempData["Notification"] = new NotificationViewModel()
                {
                    NotificationType = NotificationTypes.Error,
                    Title = "An error occured",
                    Text = "Oh no! It looks like an error occured when you tried to book an attempt. If the problem persists please contact us"
                };
    
                return CurrentUmbracoPage();
            }
        }
    

    Anybody had the issue before ?

  • Matt Darby 28 posts 391 karma points c-trib
    Oct 22, 2017 @ 09:24
    Matt Darby
    0

    Hey Giu,

    You should be able to access the properties on the Saved event, but not Created. Check out this discussion, Shannon explains why: http://issues.umbraco.org/issue/U4-6366#comment=67-26382

  • Giu 23 posts 141 karma points
    Oct 28, 2017 @ 21:35
    Giu
    1

    I tried with .Saved event as well, the custom properties don't return values:

    MemberService.Saved += CustomerCreated_EmailNotification;
    

    enter image description here

    If that's an expected behavior, that looks a bit limited.

  • Olivier Morency 1 post 71 karma points
    Oct 20, 2021 @ 22:33
    Olivier Morency
    0

    Hi Giu, I am facing the exact same problem in the saved event my properties aren't loaded. I see it's been a long time, have you been able to find a solution?

Please Sign in or register to post replies

Write your reply to:

Draft