I\'m hoping I\'ve not gotten the wrong end of the stick here (as always the sitecore documentation is woeful!)
I wanted a way to store information against a visitor,
After a great deal of debugging, fiddling and testing I finally figured this out. My issue, it turned out, wasn't the writing to mongo it was in the reading back out of mongo once it had been written.
The sitecore documentation seems (as usual) to completely miss a rather fundamental part of the working of this. About a third of the way down the docs it states:
public EmployeeData() { base.EnsureAttribute<string>(FIELD_EMPLOYEE_ID); }
The "EnsureAttribute" method is the equivalent of declaring a value-type variable.
Ok, this is very misleading. What this EnsureAttribute
appears to do is load the data for the facet into the current class from mongo. If you don't do this for every property in your facet then it does not set the value from the mongoDb! This was my mistake, I hadn't "ensured" every property in the class.
So what was happening is,
SC_ANALYTICS_GLOBAL_COOKIE
does this for you)So the EnsureAttribute
does not "declare a value type" (this is just totally wrong in my opinion) it loads the data out of mongodb and into the current Session
.
I think the step you might be missing here is the Tracker.Current.Session.Identify()
method to identify a known contact. The data in the Tracker api only lasts for the current session and you need to load the contact into the session.
The implementation of xDB relies on a contact identifying themselves when they visit the site, by logging in or registering for example.
Once they have logged in you can use a unique identifier e.g email address and pass this to the identify method -Tracker.Current.Session.Identify("Email Address of the visitor")
.
Once you have called this method, if the user has identified themselves previously, the contact data will be loaded into the current session and any existing facet information will be available in the Tracker Api.
Your problem lays in regards how you pulling the contact: If you are in a page request, you should access the current contact via Tracker.Current.Contact. your code is not in a page request, but the user may have a live session, use the ContactManager with the methods described above. If the contact is not in a live session right now, you should use ContactRepository. See an example on how to use it here. Copied from https://sitecore.stackexchange.com/questions/3319/why-are-custom-xdb-facets-being-overwritten-on-session-end answered by Dmitry Shevchenko.