I need to get sitecore information that collected from anonymous users to give him availability to export it or opt out - [GDPR]
any idea about contact ID for anonymous !
The way of doing it is dependent on the sitecore version.
Sitcore 9 you can use right to be forgotten
Sitecore 8+ you have to implement the feature from scratch.
Regarding Anonymous user - If the user is really anonymous, then you done need to worry about the GDPR (my view). But sometimes we map user email and sensitive personal info to anonymous user by using forms or WFFM. You can use email address of that user to query xDB (Contact Identifiers) to get the contact and contactID. Then reset informations.
Also: please note that based on WFFFM save action config, anonymous user will store in Core DB and Contact List.
To forget a user, you can use the following code. It will execute the ExecuteRightToBeForgotten function on the contact and scrub their data.
Forget User
public bool ForgetUser()
{
var id = _contactIdentificationRepository.GetContactId();
if (id == null)
{
return false;
}
var contactReference = new IdentifiedContactReference(id.Source, id.Identifier);
using (var client = _contactIdentificationRepository.CreateContext())
{
var contact = client.Get(contactReference, new ContactExpandOptions());
if (contact != null)
{
client.ExecuteRightToBeForgotten(contact);
client.Submit();
}
}
return false;
}
Fake up some data
public void FakeUserInfo()
{
var contactReference = _contactIdentificationRepository.GetContactReference();
using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
// we can have 1 to many facets
// PersonalInformation.DefaultFacetKey
// EmailAddressList.DefaultFacetKey
// Avatar.DefaultFacetKey
// PhoneNumberList.DefaultFacetKey
// AddressList.DefaultFacetKey
// plus custom ones
var facets = new List<string> { PersonalInformation.DefaultFacetKey };
// get the contact
var contact = client.Get(contactReference, new ContactExpandOptions(facets.ToArray()));
// pull the facet from the contact (if it exists)
var facet = contact.GetFacet<PersonalInformation>(PersonalInformation.DefaultFacetKey);
// if it exists, change it, else make a new one
if (facet != null)
{
facet.FirstName = $"Myrtle-{DateTime.Now.Date.ToString(CultureInfo.InvariantCulture)}";
facet.LastName = $"McSitecore-{DateTime.Now.Date.ToString(CultureInfo.InvariantCulture)}";
// set the facet on the client connection
client.SetFacet(contact, PersonalInformation.DefaultFacetKey, facet);
}
else
{
// make a new one
var personalInfoFacet = new PersonalInformation()
{
FirstName = "Myrtle",
LastName = "McSitecore"
};
// set the facet on the client connection
client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInfoFacet);
}
if (contact != null)
{
// submit the changes to xConnect
client.Submit();
// reset the contact
_contactIdentificationRepository.Manager.RemoveFromSession(Analytics.Tracker.Current.Contact.ContactId);
Analytics.Tracker.Current.Session.Contact = _contactIdentificationRepository.Manager.LoadContact(Analytics.Tracker.Current.Contact.ContactId);
}
}
}
ContactIdentificationRepository
using System.Linq;
using Sitecore.Analytics;
using Sitecore.Analytics.Model;
using Sitecore.Analytics.Tracking;
using Sitecore.Configuration;
using Sitecore.XConnect;
using Sitecore.XConnect.Client.Configuration;
namespace Sitecore.Foundation.Accounts.Repositories
{
public class ContactIdentificationRepository
{
private readonly ContactManager contactManager;
public ContactManager Manager => contactManager;
public ContactIdentificationRepository()
{
contactManager = Factory.CreateObject("tracking/contactManager", true) as ContactManager;
}
public IdentifiedContactReference GetContactReference()
{
// get the contact id from the current contact
var id = GetContactId();
// if the contact is new or has no identifiers
var anon = Tracker.Current.Contact.IsNew || Tracker.Current.Contact.Identifiers.Count == 0;
// if the user is anon, get the xD.Tracker identifier, else get the one we found
return anon
? new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"))
: new IdentifiedContactReference(id.Source, id.Identifier);
}
public Analytics.Model.Entities.ContactIdentifier GetContactId()
{
if (Tracker.Current?.Contact == null)
{
return null;
}
if (Tracker.Current.Contact.IsNew)
{
// write the contact to xConnect so we can work with it
this.SaveContact();
}
return Tracker.Current.Contact.Identifiers.FirstOrDefault();
}
public void SaveContact()
{
// we need the contract to be saved to xConnect. It is only in session now
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
this.contactManager.SaveContactToCollectionDb(Tracker.Current.Contact);
}
public IXdbContext CreateContext()
{
return SitecoreXConnectClientConfiguration.GetClient();
}
}
}
Related
How to get anonymous contact ID using Sitecore API?
I'm using this code but can't find the contact ID in xconnect DB.
using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
{
try
{
// var enumerator = client.Interactions.Where(x => x.DeviceProfile.Id == contactId).GetBatchEnumeratorSync(10);
Event ev = new Event(Guid.NewGuid(), DateTime.UtcNow) { Duration = new TimeSpan(20) };
var reference = new ContactReference(contactId);
Contact contact = client.Get<Contact>(reference, new ContactExpandOptions() { });
if (contact != null)
{
client.ExecuteRightToBeForgotten(contact);
client.Submit();
}
}
catch (XdbExecutionException ex)
{
// Manage exceptions
}
}
You can get it with the code new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N")) This is the xDB identifier which is the identifier anonymous contacts get.
Here is the code I use _contactIdentificationRepository is in a Foundation repository. _contactIdentificationRepository.GetContactReference() will get the anonymous or identified contact reference.
Call xConnect
var contactReference = _contactIdentificationRepository.GetContactReference();
using (var client = SitecoreXConnectClientConfiguration.GetClient())
{
// we can have 1 to many facets
// PersonalInformation.DefaultFacetKey
// EmailAddressList.DefaultFacetKey
// Avatar.DefaultFacetKey
// PhoneNumberList.DefaultFacetKey
// AddressList.DefaultFacetKey
// plus custom ones
var facets = new List<string> { PersonalInformation.DefaultFacetKey };
// get the contact
var contact = client.Get(contactReference, new ContactExpandOptions(facets.ToArray()));
.....
}
_contactIdentificationRepository
private readonly ContactManager contactManager;
public ContactManager Manager => contactManager;
public ContactIdentificationRepository()
{
contactManager = Factory.CreateObject("tracking/contactManager", true) as ContactManager;
}
public IdentifiedContactReference GetContactReference()
{
// get the contact id from the current contact
var id = GetContactId();
// if the contact is new or has no identifiers
var anon = Tracker.Current.Contact.IsNew || Tracker.Current.Contact.Identifiers.Count == 0;
// if the user is anon, get the xD.Tracker identifier, else get the one we found
return anon
? new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, Tracker.Current.Contact.ContactId.ToString("N"))
: new IdentifiedContactReference(id.Source, id.Identifier);
}
public Analytics.Model.Entities.ContactIdentifier GetContactId()
{
if (Tracker.Current?.Contact == null)
{
return null;
}
if (Tracker.Current.Contact.IsNew)
{
// write the contact to xConnect so we can work with it
this.SaveContact();
}
return Tracker.Current.Contact.Identifiers.FirstOrDefault();
}
public void SaveContact()
{
// we need the contract to be saved to xConnect. It is only in session now
Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
this.contactManager.SaveContactToCollectionDb(Tracker.Current.Contact);
}
I recently upgraded from jetty 9.3.11 to 9.4.6 . Since 9.4.x does not support HashSessionManager, I created my own custom SessionHandler. But when i attach this SessionHandler to the WebAppContext then the context becomes null when trying to access from servlets. there are no errors thrown in the logs.
Relevant section of code:
MyCustomSessionHandler sessionHandler = new MyCustomSessionHandler();
HandlerCollection handlers_ = new HandlerCollection(true);
COntextHandlerCollection chc_ = new ContextHandlerCollection();
for(WebAppConfig wap: webAppConfigs) //webappconfig a POJO from where I am getting webapp configs
{
String path = wap.getPath();
String warFile = wap.getWarFile();
WebAppContext context =
new WebAppContext(chc_, warFile, path);
// context.setSessionHandler(new SessionHandler()); // this one works.
context.setSessionHandler(sessionHandler); // this one doesnt work.
for (ServletConfig servletConfig: wap.getServletConfigs()) //ServletConfig is another POJO to get servlet configs
{
String servletName = servletConfig.getName();
String servletPath = servletConfig.getPath();
Servlet servlet = servletConfig.getServlet();
ServletHolder servletHolder = new ServletHolder(servlet);
context.addServlet(servletHolder, servletPath);
}
}
handlers_.setHandlers(new Handler[] { chc_, new DefaultHandler()});
server_.setHandler(handlers_);
Sample of my custom Session handler
public class MyCUstomSessionHandler extends SessionHandler
{
public MyCustomSessionHandler()
{
super();
}
public void setSecureCookies(boolean secureCookies)
{
getSessionCookieConfig().setSecure(secureCookies);
}
public void setHttpOnly(boolean httpOnly)
{
getSessionCookieConfig().setHttpOnly(httpOnly);
}
public void setMaxCookieAge(int age)
{
getSessionCookieConfig().setMaxAge(age);
}
}
Further clarification: It happens because I create a singleton sessionhandler and share it across different WepAppContext as a way of sharing sessions among them. This method seemed work fine without issues in 9.3 but doesn't work with new session management in 9.4.
Any help to solve this problem is appreciated.
I solved it by
setting cookie path to root ("/")
extending the getSession() function of SessionHandler to loop through all the contexts to check if session is created for the cookie in any other context.
/* check all contexts for sessions*/
public Session getSession(String id)
{
Session session = getLocalSession(id);
if (session == null)
{
for (SessionHandler manager: getSessionIdManager().getSessionHandlers())
{
if (manager.equals(this) ||
!(manager instanceof CustomSessionHandler))
{
continue;
}
session = ((CustomSessionHandler)manager).getLocalSession(id);
if (session != null)
{
break;
}
}
// should we duplicate sessions in each context?
// will we end up with inconsistent sessions?
/*
if (externalSession != null)
{
try
{
getSessionCache().put(id, externalSession);
}
catch (Exception e)
{
LOG.warn("Unable to save session to local cache.");
}
}
*/
}
return session;
}
/* ------------------------------------------------------------ */
/**
* Get a known existing session
* #param id The session ID stripped of any worker name.
* #return A Session or null if none exists.
*/
public Session getLocalSession(String id)
{
return super.getSession(id);
}
Hej Guys
I have a rather large problem, I've been tasked with creating a Custom Data Provider for extracting Stock Keeping Units(SKUs) from a SOLR database into sitecore, without actually populating the database with items.
I've created a data provider, which succesfully pulls data from the SOLR database a "creates" the items in sitecore, by using the following code:
public class SkuDataProvider : DataProvider, ISkuDataProvider
{
private readonly string _targetDatabaseName = "master";
private readonly string _idTablePrefix = "Skus";
private readonly ID _skuTemplateId = new ID("{F806B403-BDAF-4C60-959D-E706A82FC1DC}");
private readonly ID _skuRootTemplateId = new ID("{9767BC47-0A95-40E9-A2DE-3766FF241411}");
private readonly IEnumerable<SkuItemInfo> _skus;
public SkuDataProvider(/*IProductPageService productPageService*/)
{
_skus = new MockDataForSkuDataProvider().GetSimpleSkuCollection();
}
public override ItemDefinition GetItemDefinition(ID itemId, CallContext context)
{
Assert.ArgumentNotNull(itemId, "itemID");
// Retrieve the sku id from Sitecore's IDTable
var skuId = GetSkuIdFromIdTable(itemId);
if (!string.IsNullOrEmpty(skuId))
{
// Retrieve the sku data from the skus collection
var sku = _skus.FirstOrDefault(o => o.SkuId == skuId);
if (sku != null)
{
// Ensure the sku item name is valid for the Sitecore content tree
var itemName = ItemUtil.ProposeValidItemName($"{sku.SkuId}_{sku.Name}");
// Return a Sitecore item definition for the sku using the sku template
return new ItemDefinition(itemId, itemName, ID.Parse(_skuTemplateId), ID.Null);
}
}
return null;
}
private string GetSkuIdFromIdTable(ID itemId)
{
var idTableEntries = IDTable.GetKeys(_idTablePrefix, itemId);
if (idTableEntries.Any())
return idTableEntries[0].Key.ToString();
return null;
}
public override IDList GetChildIDs(ItemDefinition parentItem, CallContext context)
{
if (CanProcessParent(parentItem.ID))
{
var itemIdList = new IDList();
foreach (var sku in _skus)
{
var skuId = sku.SkuId;
// Retrieve the Sitecore item ID mapped to his sku
IDTableEntry mappedId = IDTable.GetID(_idTablePrefix, skuId) ??
IDTable.GetNewID(_idTablePrefix, skuId, parentItem.ID);
itemIdList.Add(mappedId.ID);
}
context.DataManager.Database.Caches.DataCache.Clear();
return itemIdList;
}
return base.GetChildIDs(parentItem, context);
}
private bool CanProcessParent(ID id)
{
var item = Factory.GetDatabase(_targetDatabaseName).Items[id];
bool canProcess = item.Paths.IsContentItem && item.TemplateID == _skuRootTemplateId && item.ID == new ID("{F37753A0-BC79-4FF7-B975-A8F142AACD76}");
return canProcess;
}
public override ID GetParentID(ItemDefinition itemDefinition, CallContext context)
{
var idTableEntries = IDTable.GetKeys(_idTablePrefix, itemDefinition.ID);
if (idTableEntries.Any())
{
return idTableEntries.First().ParentID;
}
return base.GetParentID(itemDefinition, context);
}
public override FieldList GetItemFields(ItemDefinition itemDefinition, VersionUri version, CallContext context)
{
var fields = new FieldList();
var idTableEntries = IDTable.GetKeys(_idTablePrefix, itemDefinition.ID);
if (idTableEntries.Any())
{
if (context.DataManager.DataSource.ItemExists(itemDefinition.ID))
{
ReflectionUtil.CallMethod(typeof(ItemCache), CacheManager.GetItemCache(context.DataManager.Database), "RemoveItem", true, true, new object[] { itemDefinition.ID });
}
var template = TemplateManager.GetTemplate(_skuTemplateId, Factory.GetDatabase(_targetDatabaseName));
if (template != null)
{
var skuId = GetSkuIdFromIdTable(itemDefinition.ID);
if (!string.IsNullOrEmpty(skuId))
{
var sku = _skus.FirstOrDefault(o => o.SkuId == skuId);
if (sku != null)
{
foreach (var field in GetDataFields(template))
{
fields.Add(field.ID, GetFieldValue(field, sku));
}
}
}
}
}
return fields;
}
protected virtual IEnumerable<TemplateField> GetDataFields(Template template)
{
return template.GetFields().Where(ItemUtil.IsDataField);
}
private string GetFieldValue(TemplateField field, SkuItemInfo sku)
{
string fieldValue = string.Empty;
switch (field.Name)
{
case "Name":
fieldValue = sku.Name;
break;
case "SkuId":
fieldValue = sku.SkuId;
break;
default:
break;
}
return fieldValue;
}
}
}
The problem emerges when accessing the Sitecore backend, where all items appears below the bucket item in a hierarchly-way.
I've checked that the Root item is set a bucket and that the template used is bucketable.
Furthermore when inserting manually in the backend, the item is correctly inserted in the bucket.
Do anyone got an idea for me, on how to fix this issue?
Best Regards
Nicolai
You need to set the Is Bucketable flag on the standard values of the template item rather than the template item itself.
Also, the way that items get "bucketed" is via events when the item is being created or saved. Sitecore then creates the bucket folders to store the items in. In your case as you have virtual items, you will need to handle their path via the data provider.
If you just want them hidden in the same way that they are in a standard bucket, then I would suggest creating a bucket folder under your SKU Root folder and using that item as the parent for all SKU virtual items. That way the bucket folder will be hidden by sitecore and you will get the same view as a standard bucket.
This is the template to use:
I am building an API for login and registration using loopback framework.
Loopback provides, by default, model User for login, register and other similar stuff. Default way to provide user's credentials in LoopBack is username-password/email-password but I want to use mobileNo-password/email-password as user's login credentials. So how can I do that? How can I change default credential option in User model?
You can achieve that in two ways:
If not using username field in User model, you can use it to store mobile number, mobileNo.
You have to edit user.js to accept mobileNo field as login credentials. User.login and User.normalizeCredentials are used for login process, so you can edit them like provided in the code snippet.
Note: Don't forget to add mobileNo to user.json
User.normalizeCredentials method
`User.normalizeCredentials = function(credentials, realmRequired, realmDelimiter) {
var query = {};
credentials = credentials || {};
if (!realmRequired) {
if (credentials.email) {
query.email = credentials.email;
} else if (credentials.mobileNo) {
query.mobileNo = credentials.mobileNo;
}
} else {
if (credentials.realm) {
query.realm = credentials.realm;
}
var parts;
if (credentials.email) {
parts = splitPrincipal(credentials.email, realmDelimiter);
query.email = parts[1];
if (parts[0]) {
query.realm = parts[0];
}
} else if (credentials.mobileNo) { //added mobileNo.
parts = splitPrincipal(credentials.mobileNo, realmDelimiter);
query.mobileNo = parts[1];
if (parts[0]) {
query.realm = parts[0];
}
}
}
return query;
};`
User.login method
`User.login = function(credentials, include, fn) {
.
.
.
.
.
if (!query.email && !query.mobileNo) {
var err2 = new Error('Mobile number or email is required');
err2.statusCode = 400;
err2.code = 'MOBILE_NUMBER_EMAIL_REQUIRED';
fn(err2);
return fn.promise;
}
}`
I am going to write a small program that query Amazon web service for book information.
Given some sample I found online, I wrote;
namespace TestWCF
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter keyword: ");
var line = Console.ReadLine();
if (line == null)
{
return;
}
using (var svc = new AmazonSearchPortClient())
{
var keywordReq = new KeywordRequest
{
locale = "us",
type = "lite",
sort = "reviewrank",
mode = "books",
keyword = line,
tag = "associate-id",
devtag = "????????????"
};
var productInfo = svc.KeywordSearchRequest(keywordReq);
foreach(var detail in productInfo.Details)
{
Console.WriteLine(detail.ProductName);
}
}
}
}
This does not work as it returns authenticate failure at the line;
var productInfo = svc.KeywordSearchRequest(keywordReq);
I am not sure what information I should put into the tag and devtag fields. Someone says I should put associate ID but what I shall put into the devtag?
Many thanks,
Regards.
}