private void SetPreferredEmail(string key, string email)
        {
            var reference = this.GetCurrentContactReference();

            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var contact = client.Get(reference, new ExpandOptions(EmailAddressList.DefaultFacetKey));

                var emailAddress     = new EmailAddress(email, true);
                var emailAddressList = contact.GetFacet <EmailAddressList>(EmailAddressList.DefaultFacetKey);
                if (emailAddressList == null)
                {
                    emailAddressList = new EmailAddressList(emailAddress, key);
                }
                else
                {
                    emailAddressList.PreferredKey   = key;
                    emailAddressList.PreferredEmail = emailAddress;
                }

                client.SetFacet(contact, EmailAddressList.DefaultFacetKey, emailAddressList);

                client.Submit();
            }
        }
        public ActionResult RegisterGoal(string goalId, string productId)
        {
            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var goal     = Tracker.MarketingDefinitions.Goals[new Guid(goalId)];
                    var pageData = new Sitecore.Analytics.Data.PageEventData(goal.Alias, goal.Id)
                    {
                        Data    = productId,
                        Text    = "Triggered goal from front-end interaction",
                        DataKey = "productId"
                    };

                    Tracker.Current.CurrentPage.Register(pageData);

                    string result = "{success:true}";
                    return(Json(result));
                }
                catch (XdbExecutionException ex)
                {
                    return(new HttpStatusCodeResult(500, "Unable to log interaction."));
                }
            }
        }
     internal Contact GetContactByOptions(Guid contactId, ExpandOptions options = null)
     {
         using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient("xconnect/clientconfig"))
         {
             if (options == null)
             {
                 options = (ExpandOptions) new ContactExpandOptions(Array.Empty <string>())
                 {
                     Interactions = new RelatedInteractionsExpandOptions(new string[1]
                     {
                         "IpInfo"
                     })
                 }
             }
             ;
             ContactReference contactReference = new ContactReference(contactId);
             Contact          contact          = XConnectSynchronousExtensions.Get <Contact>((IXdbContext)client, (IEntityReference <Contact>)contactReference, options);
             if (contact == null)
             {
                 throw new ContactNotFoundException(string.Format("No Contact with id [{0}] found", (object)contactId));
             }
             return(contact);
         }
     }
 }
        public bool EvaluateProfileKey(string source, string identifier)
        {
            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var reference = new IdentifiedContactReference(source, identifier);
                var contact   = client.Get(reference, new ContactExpandOptions(PersonalInformation.DefaultFacetKey)
                {
                    Interactions = new RelatedInteractionsExpandOptions(LocaleInfo.DefaultFacetKey, ProfileScores.DefaultFacetKey)
                    {
                        EndDateTime = DateTime.MaxValue,
                        Limit       = 3
                    }
                });

                var twoLatests = contact?.Interactions.OrderByDescending(x => x.EndDateTime).Take(2).ToList();

                if (twoLatests?.Count != 2)
                {
                    return(false);
                }

                var last     = GetScore(twoLatests[0]);
                var previous = GetScore(twoLatests[1]);
                int diff     = (int)Math.Ceiling(last - previous);

                return(Compare(diff));
            }
        }
        protected void UpdateXConnectContact(Dictionary <string, Facet> facets)
        {
            var manager = Configuration.Factory.CreateObject("tracking/contactManager", true) as Sitecore.Analytics.Tracking.ContactManager;

            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var contactId = client.GetContactIdFromDevice();
                    if (contactId == null)
                    {
                        Log.Fatal("**HF** AnalyticsServiceBase.UpdateXConnectContact. Cannot resolve contact id from device", this);
                        return;
                    }

                    SetContactFacets(facets, client, contactId);

                    client.Submit();
                    manager.RemoveFromSession(Sitecore.Analytics.Tracker.Current.Contact.ContactId);
                    Tracker.Current.Session.Contact = manager.LoadContact(Sitecore.Analytics.Tracker.Current.Contact.ContactId);
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error("UpdateXConnectContact failed.", ex, this);
                }
            }
        }
        public void UpdateContactFacet <T>(
            IdentifiedContactReference reference,
            ContactExpandOptions expandOptions,
            Action <T> updateFacets,
            Func <T> createFacet)
            where T : Facet
        {
            if (reference == null)
            {
                throw new ArgumentNullException(nameof(reference));
            }

            if (expandOptions == null)
            {
                throw new ArgumentNullException(nameof(expandOptions));
            }

            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var contact = client.Get(reference, expandOptions);
                if (contact == null)
                {
                    return;
                }

                MakeContactKnown(client, contact);

                var facet = contact.GetFacet <T>() ?? createFacet();
                var data  = facet;
                updateFacets(data);
                client.SetFacet(contact, data);
                client.Submit();
            }
        }
Beispiel #7
0
        public async Task <ActionResult> RegisterExportToGoogleBigQuery()
        {
            using (IXdbContext client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var searchRequest = client.Contacts
                                    .Where(c => c.Interactions.Any(i => i.Events.OfType <RunEnded>().Any(x => true)))
                                    .WithExpandOptions(new ContactExpandOptions(RunnerFacet.DefaultFacetKey)
                {
                    Interactions = new RelatedInteractionsExpandOptions
                    {
                        Limit = int.MaxValue
                    }
                })
                                    .GetSearchRequest();

                var dataSourceOptions = new ContactSearchDataSourceOptionsDictionary(searchRequest, 100, 100);

                var workerOptions = new Dictionary <string, string>();

                var taskId = await _taskManager.RegisterDistributedTaskAsync(
                    dataSourceOptions,
                    new DistributedWorkerOptionsDictionary(
                        "Sitecore.Demo.CortexWorkers.ExportToBigQueryWorker, Sitecore.Demo.CortexWorkers", workerOptions),
                    null,
                    TimeSpan.FromHours(1));

                return(new ContentResult {
                    Content = taskId.ToString()
                });
            }
        }
        public virtual async Task <bool> SubscribeContact(string email, IEnumerable <Guid> listIds)
        {
            try
            {
                using (var client = SitecoreXConnectClientConfiguration.GetClient())
                {
                    var contact = await client.GetAsync(new IdentifiedContactReference(Constants.XConnectSourceName, email), new ExpandOptions(ListSubscriptions.DefaultFacetKey)).ConfigureAwait(false);

                    var listSubscriptions = contact.ListSubscriptions() ?? new ListSubscriptions();
                    foreach (var listId in listIds)
                    {
                        if (listSubscriptions.Subscriptions.Any(s => s.ListDefinitionId == listId))
                        {
                            continue;
                        }
                        var subscription = new ContactListSubscription(DateTime.UtcNow, true, listId);
                        listSubscriptions.Subscriptions.Add(subscription);
                    }
                    client.SetListSubscriptions(contact, listSubscriptions);
                    await client.SubmitAsync();

                    return(true);
                }
            }
            catch (Exception)
            {
                return(false);
            }
        }
Beispiel #9
0
        protected override bool Execute(T ruleContext)
        {
            try
            {
                var id = GetContactId();
                if (id == null)
                {
                    return(false);;
                }
                var contactReference = new IdentifiedContactReference(id.Source, id.Identifier);

                using (var client = SitecoreXConnectClientConfiguration.GetClient())
                {
                    var existingContact = client.Get <XConnect.Contact>(contactReference, new ContactExpandOptions(new string[] { CustomSalesforceContactInformation.DefaultFacetKey }));
                    CustomSalesforceContactInformation customSalesforceFacet = existingContact.GetFacet <CustomSalesforceContactInformation>(CustomSalesforceContactInformation.DefaultFacetKey);
                    if (customSalesforceFacet == null)
                    {
                        return(false);
                    }
                    var journeyStatus = customSalesforceFacet.WelcomeJourneyStatus;
                    return(Compare(journeyStatus, JourneyStatus));
                }
            }
            catch (Exception ex)
            {
                Log.Error($"Error evaluating WelcomeJourneyStatusCondition. ID: {ruleContext.Item.ID}", ex, this);
                return(false);
            }
        }
        public Contact GetContact(Guid contactId)
        {
            Contact result = null;

            using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    result = client.Get <Contact>(new ContactReference(contactId), new ContactExpandOptions(PersonalInformation.DefaultFacetKey, TwitterAccountInfo.DefaultFacetKey)
                    {
                        Interactions = new RelatedInteractionsExpandOptions(LocaleInfo.DefaultFacetKey)
                        {
                            StartDateTime = DateTime.MinValue,
                            EndDateTime   = DateTime.UtcNow,
                            Limit         = 30
                        }
                    });
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exceptions
                }
            }
            return(result);
        }
        /// <summary>
        /// Gets the clicks.
        /// </summary>
        /// <param name="pageId">The page identifier.</param>
        /// <param name="language">The language.</param>
        /// <returns>Async click events</returns>
        public async Task <IEnumerable <IHeatMapClickEventsModel> > GetClicksAsync(Guid pageId, string language)
        {
            try
            {
                using (var client = SitecoreXConnectClientConfiguration.GetClient())
                {
                    var q = client
                            .Interactions
                            .Where(e => e.Events.OfType <ClickEvent>().Any(ce => ce.PageId == pageId && ce.Language == language));

                    var results = await q.ToList();

                    var grouppedResult = results
                                         .SelectMany(r => r.Events.OfType <ClickEvent>())
                                         .GroupBy(e => e.ComponentId)
                                         .Select(g => new HeatMapClickEventsModel {
                        ComponentId = g.Key, Count = g.Count()
                    })
                                         .ToList();

                    return(this.Normalize(grouppedResult));
                };
            }
            catch (Exception e)
            {
                Log.Error(e.Message, e, this);
                return(Enumerable.Empty <IHeatMapClickEventsModel>());
            }
        }
        private Sitecore.XConnect.Contact GetContact(string source, string identifier, string FacetKey)
        {
            using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    if (string.IsNullOrEmpty(FacetKey))
                    {
                        return(client.Get <Sitecore.XConnect.Contact>(new IdentifiedContactReference(source, identifier), new ContactExpandOptions()));
                    }

                    return(client.Get <Sitecore.XConnect.Contact>(new IdentifiedContactReference(source, identifier), new ContactExpandOptions(FacetKey)));
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error($"XConnectContactRepository: Unable to get contact for ID '{identifier}', Source: '{source}', FacetKey: '{FacetKey}'", ex, this);
                    return(null);
                }
                catch (Exception ex)
                {
                    Log.Error("XConnectContactRepository: Error communication with the xConnect colllection service", ex, this);
                    return(null);
                }
            }
        }
Beispiel #13
0
        public void UpdateAirQualityForContactsBatch(int size)
        {
            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var goalId = Guid.Parse(RegisterGoalId);
                    IAsyncQueryable <Contact> queryable = client.Contacts
                                                          .Where(c => c.Interactions.Any(f => f.Events.OfType <Goal>().Any(a => a.DefinitionId == goalId)))
                                                          .WithExpandOptions(new ContactExpandOptions()
                    {
                        Interactions = new RelatedInteractionsExpandOptions()
                        {
                            Limit = 10
                        }
                    });

                    var enumerable = queryable.GetBatchEnumeratorSync(size);
                    while (enumerable.MoveNext())
                    {
                        foreach (var contact in enumerable.Current)
                        {
                            UpdateAirQualityForContact(contact);
                        }
                    }
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error($"Error updating air quality in batch", ex, this);
                }
            }
        }
        /// <summary>
        /// Clicks the specified page identifier.
        /// </summary>
        /// <param name="pageId">The page identifier.</param>
        /// <param name="componentId">The component identifier.</param>
        /// <param name="language">The language.</param>
        /// <returns>Async task</returns>
        public async Task ClickAsync(Guid pageId, Guid componentId, string language)
        {
            try
            {
                using (var client = SitecoreXConnectClientConfiguration.GetClient())
                {
                    var contact = new Contact();
                    client.AddContact(contact);

                    var interaction = new Interaction(contact, InteractionInitiator.Brand, ChannelId, string.Empty);

                    var click = new ClickEvent(ClickEvent.EventDefintionId, DateTime.UtcNow)
                    {
                        PageId      = pageId,
                        ComponentId = componentId,
                        Language    = language
                    };

                    interaction.Events.Add(click);


                    client.AddInteraction(interaction);

                    await client.SubmitAsync();
                }
            }
            catch (Exception e)
            {
                Log.Error(e.Message, e, this);
            }
        }
        public ContactFacetData GetContactData()
        {
            ContactFacetData data = new ContactFacetData();

            var id = this.GetContactId();

            if (id != null)
            {
                var contactReference = new IdentifiedContactReference(id.Source, id.Identifier);

                using (var client = SitecoreXConnectClientConfiguration.GetClient())
                {
                    try
                    {
                        var contact = client.Get(contactReference, new ContactExpandOptions(this.facetsToUpdate));

                        if (contact != null)
                        {
                            PersonalInformation personalInformation = contact.Personal();
                            if (personalInformation != null)
                            {
                                data.FirstName  = personalInformation.FirstName;
                                data.MiddleName = personalInformation.MiddleName;
                                data.LastName   = personalInformation.LastName;
                                data.Birthday   = personalInformation.Birthdate.ToString();
                                data.Gender     = personalInformation.Gender;
                                data.Language   = personalInformation.PreferredLanguage;
                            }

                            var email = contact.Emails();
                            if (email != null)
                            {
                                data.EmailAddress = email.PreferredEmail?.SmtpAddress;
                            }

                            var phones = contact.PhoneNumbers();
                            if (phones != null)
                            {
                                data.PhoneNumber = phones.PreferredPhoneNumber?.Number;
                            }

                            if (contact.Facets.ContainsKey(SportType.DefaultKey))
                            {
                                data.SportType = ((SportType)contact.Facets[SportType.DefaultKey]).Value;
                            }
                            if (contact.Facets.ContainsKey(SportName.DefaultKey))
                            {
                                data.SportName = ((SportName)contact.Facets[SportName.DefaultKey]).Value;
                            }
                        }
                    }
                    catch (XdbExecutionException ex)
                    {
                        Log.Error($"Could not get the xConnect contact facets", ex, this);
                    }
                }
            }

            return(data);
        }
        public bool HasPageVisitInPast(string source, string identifier, Guid pageId, DateTime from)
        {
            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var reference = new IdentifiedContactReference(source, identifier);
                    var contact   = client.Get(reference, new ContactExpandOptions(PersonalInformation.DefaultFacetKey)
                    {
                        Interactions = new RelatedInteractionsExpandOptions(LocaleInfo.DefaultFacetKey)
                        {
                            StartDateTime = from,
                            Limit         = int.MaxValue
                        }
                    });

                    if (contact == null)
                    {
                        return(false);
                    }

                    return(contact.Interactions
                           .Any(i => i.Events
                                .Any(e => e.DefinitionId == Foundation.Conditions.Constants.PageViewEventId && e.ItemId == pageId && e.Timestamp >= from)));
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error(ex.Message, ex, this);
                    return(false);
                }
            }
        }
        /// <summary>
        /// Get current contact
        /// </summary>
        /// <returns>Current XConnect.Contact with EmotionFacet</returns>
        public Contact GetCurrentContact()
        {
            if (Factory.CreateObject("tracking/contactManager", true) is ContactManager manager)
            {
                using (var client = SitecoreXConnectClientConfiguration.GetClient())
                {
                    var trackerIdentifier = new IdentifiedContactReference(
                        Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource,
                        Sitecore.Analytics.Tracker.Current.Contact.ContactId.ToString("N"));

                    var contact = client.Get <Contact>(trackerIdentifier,
                                                       new ContactExpandOptions(EmotionFacet.DefaultFacetKey));

                    if (contact == null)
                    {
                        manager.CreateContact(ID.NewID);
                    }

                    if (Sitecore.Analytics.Tracker.Current.Contact.IsNew)
                    {
                        Sitecore.Analytics.Tracker.Current.Contact.ContactSaveMode = ContactSaveMode.AlwaysSave;
                        manager.SaveContactToCollectionDb(Sitecore.Analytics.Tracker.Current.Contact);
                    }

                    return(contact);
                }
            }
            return(null);
        }
        public void UpdateOrCreateXConnectContactWithEmail(IXConnectContactWithEmail xConnectContact)
        {
            if (xConnectContact == null)
            {
                throw new ArgumentNullException(nameof(xConnectContact));
            }

            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var contactReference = new IdentifiedContactReference(xConnectContact.IdentifierSource, xConnectContact.IdentifierValue);
                var contact          = client.Get(contactReference, new ContactExpandOptions(PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey));
                if (contact == null)
                {
                    var newContact = new Sitecore.XConnect.Contact(new ContactIdentifier(contactReference.Source, contactReference.Identifier, ContactIdentifierType.Known));
                    SetEmail(newContact, xConnectContact, client);
                    client.AddContact(newContact);
                    client.Submit();

                    if (Tracker.Current != null && Tracker.Current.Contact != null)
                    {
                        SaveNewContactToCollectionDb(Tracker.Current.Contact);
                    }
                }
                else
                {
                    if (contact.Emails()?.PreferredEmail.SmtpAddress == xConnectContact.IdentifierValue)
                    {
                        return;
                    }

                    SetEmail(contact, xConnectContact, client);
                    client.Submit();
                }
            }
        }
        /// <summary>
        /// Set emotion facet to contact
        /// </summary>
        /// <param name="contact">Contact to be updated</param>
        /// <param name="facet">Facet to be applied to Contact</param>
        public void SetEmotionFacet(Contact contact, EmotionFacet facet)
        {
            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var emotions = contact.GetFacet <EmotionFacet>(EmotionFacet.DefaultFacetKey);
                    if (emotions == null)
                    {
                        client.SetFacet(contact, EmotionFacet.DefaultFacetKey, facet);
                    }
                    else
                    {
                        UpdateFacetValues(facet, emotions);
                        client.SetFacet(contact, EmotionFacet.DefaultFacetKey, emotions);
                    }

                    client.Submit();
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error($"Could not set facet for {contact.Id} contact", ex, this);
                }
            }
        }
        public async Task <ActionResult> RegisterContactsExportToMsSql()
        {
            using (IXdbContext client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var interactionFacets = client.Model.Facets.Where(c => c.Target == EntityType.Interaction).Select(x => x.Name);
                var contactFacets     = client.Model.Facets.Where(c => c.Target == EntityType.Contact).Select(x => x.Name);

                var searchRequest = client.Contacts
                                    .Where(c => c.Interactions.Any())
                                    .WithExpandOptions(new ContactExpandOptions(contactFacets.ToArray())
                {
                    Interactions = new RelatedInteractionsExpandOptions(interactionFacets.ToArray())
                    {
                        //StartDateTime = DateTime.Now.AddDays(-3),
                        //EndDateTime = DateTime.Now,
                        Limit = int.MaxValue
                    }
                })
                                    .GetSearchRequest();

                var dataSourceOptions = new ContactSearchDataSourceOptionsDictionary(searchRequest, 1000, 1000);

                var workerOptions = new Dictionary <string, string>();

                var taskId = await _taskManager.RegisterDistributedTaskAsync(
                    dataSourceOptions,
                    new DistributedWorkerOptionsDictionary(
                        "XcExport.Cortex.Workers.ExportContactsToMsSql, XcExport.Cortex", workerOptions),
                    null,
                    TimeSpan.FromHours(1));

                return(Json(new { TaskId = taskId.ToString() }, JsonRequestBehavior.AllowGet));
            }
        }
        public async Task <ActionResult> RegisterInteractionsExportToJson()
        {
            using (IXdbContext client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var interactionFacets = client.Model.Facets.Where(c => c.Target == EntityType.Interaction).Select(x => x.Name);
                var contactFacets     = client.Model.Facets.Where(c => c.Target == EntityType.Contact).Select(x => x.Name);

                var expandOptions = new InteractionExpandOptions(interactionFacets.ToArray())
                {
                    Contact = new RelatedContactExpandOptions(contactFacets.ToArray())
                };

                InteractionDataSourceOptionsDictionary interactionDataSourceOptionsDictionary =
                    new InteractionDataSourceOptionsDictionary(expandOptions, 1000, 1000);

                var workerOptions = new Dictionary <string, string>();

                var taskId = await _taskManager.RegisterDistributedTaskAsync(
                    interactionDataSourceOptionsDictionary,
                    new DistributedWorkerOptionsDictionary(
                        "XcExport.Cortex.Workers.ExportInteractionsToJson, XcExport.Cortex", workerOptions),
                    null,
                    TimeSpan.FromHours(1));

                return(Json(new { TaskId = taskId.ToString() }, JsonRequestBehavior.AllowGet));
            }
        }
 public Guid?GetContactId(IdentifiedContactReference reference)
 {
     using (var client = SitecoreXConnectClientConfiguration.GetClient())
     {
         var contact = client.Get(reference, new ContactExpandOptions());
         return(contact?.Id);
     }
 }
        public string ExportContactData()
        {
            var id = this.GetContactId();

            if (id == null)
            {
                return(string.Empty);
            }

            var contactReference = new IdentifiedContactReference(id.Source, id.Identifier);

            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var contactFacets = client.Model.Facets.Where(c => c.Target == EntityType.Contact).Select(x => x.Name);

                    var interactionFacets = client.Model.Facets.Where(c => c.Target == EntityType.Interaction).Select(x => x.Name);

                    var contact = client.Get(contactReference, new ContactExpandOptions(contactFacets.ToArray())
                    {
                        Interactions = new RelatedInteractionsExpandOptions(interactionFacets.ToArray())
                        {
                            EndDateTime   = DateTime.MaxValue,
                            StartDateTime = DateTime.MinValue
                        }
                    });

                    if (contact == null)
                    {
                        return(string.Empty);
                    }

                    var serializerSettings = new JsonSerializerSettings
                    {
                        ContractResolver = new XdbJsonContractResolver(client.Model,
                                                                       serializeFacets: true,
                                                                       serializeContactInteractions: true),
                        Formatting           = Formatting.Indented,
                        DateTimeZoneHandling = DateTimeZoneHandling.Utc,
                        DefaultValueHandling = DefaultValueHandling.Ignore
                    };

                    string exportedData = JsonConvert.SerializeObject(contact, serializerSettings);

                    var fileWithExportedData = exportFileService.CreateExportFile();

                    exportFileService.WriteExportedDataIntoFile(fileWithExportedData, exportedData);

                    return(fileWithExportedData);
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error($"Could not export the xConnect contact & interaction data", ex, this);
                    return(string.Empty);
                }
            }
        }
 public void UpdateXDbContactEmail(IXDbContactWithEmail basicContact)
 {
     using (var client = SitecoreXConnectClientConfiguration.GetClient())
     {
         var reference  = new IdentifiedContactReference(basicContact.IdentifierSource, basicContact.IdentifierValue);
         var xDbContact = client.Get(reference, new ContactExpandOptions(CollectionModel.FacetKeys.PersonalInformation, CollectionModel.FacetKeys.EmailAddressList));
         SetEmail(xDbContact, basicContact, client);
         client.Submit();
     }
 }
        /// <summary>
        /// Verify the interations counter is greater than a specific number
        /// </summary>
        /// <param name="maxRecords">Quantity of records to evaluate</param>
        /// <returns></returns>
        public bool VerifyInteractionsUser(int maxRecords)
        {
            bool            returnValue = false;
            List <GoalPage> goalPages   = new List <GoalPage>();

            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var id = this.GetContactId();
                if (id == null)
                {
                    return(false);
                }

                var contactReference = new IdentifiedContactReference(id.Source, id.Identifier);
                //Get the contacts with their interactions
                var contact = client.Get(contactReference, new ContactExpandOptions()
                {
                    Interactions = new RelatedInteractionsExpandOptions()
                    {
                        StartDateTime = DateTime.MinValue,
                        EndDateTime   = DateTime.MaxValue,
                        Limit         = int.MaxValue
                    }
                });

                if (contact == null)
                {
                    return(false);
                }

                var results = contact.Interactions.Where(x => x.Events.OfType <Goal>().Any()).ToList();


                //results.
                foreach (var itemInteraction in results)
                {
                    var events = itemInteraction.Events.Where(x => x.GetType().Name == "Goal");

                    foreach (var itemEvent in events)
                    {
                        goalPages.Add(new GoalPage {
                            TimeStamp = itemEvent.Timestamp, GoalId = itemEvent.DefinitionId, PageId = itemEvent.CustomValues.FirstOrDefault().Value
                        });
                    }
                }


                goalPages   = goalPages.OrderBy(x => x.TimeStamp).ToList();
                returnValue = goalPages.Count >= maxRecords;
            }

            return(returnValue);
        }
Beispiel #26
0
 public Contact GetContact(Guid contactId, string[] facets)
 {
     using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient("xconnect/clientconfig"))
     {
         ContactReference contactReference = new ContactReference(contactId);
         Contact          contact          = facets == null || facets.Length == 0 ? client.Get <Contact>((IEntityReference <Contact>)contactReference, (ExpandOptions) new ContactExpandOptions(Array.Empty <string>())) : client.Get <Contact>((IEntityReference <Contact>)contactReference, (ExpandOptions) new ContactExpandOptions(facets));
         if (contact == null)
         {
             throw new ContactNotFoundException(string.Format("No Contact with id [{0}] found", (object)contactId));
         }
         return(contact);
     }
 }
 public void UpdateContactFacets(IdentifiedContactReference reference, ContactExpandOptions expandOptions, Action <Contact> updateFacets)
 {
     using (var client = SitecoreXConnectClientConfiguration.GetClient())
     {
         var xDbContact = client.Get(reference, expandOptions);
         if (xDbContact != null)
         {
             //xDbContact.GetFacet<PersonalInformation>()
             updateFacets(xDbContact);
             client.Submit();
         }
     }
 }
 public void UpdateContactFacet <T>(IdentifiedContactReference reference, ContactExpandOptions expandOptions, Action <T> updateFacets, Func <T> createFacet) where T : Facet
 {
     using (var client = SitecoreXConnectClientConfiguration.GetClient())
     {
         var xDbContact = client.Get(reference, expandOptions);
         if (xDbContact != null)
         {
             var facet = xDbContact.GetFacet <T>() ?? createFacet();
             updateFacets(facet);
             client.SetFacet(xDbContact, facet);
             client.Submit();
         }
     }
 }
        /// <summary>
        /// Save goal linked to the contat user
        /// </summary>
        /// <param name="interactionType">Goal type</param>
        /// <param name="productId">Product sitecore id</param>
        public void SaveGoal(InteractionType interactionType, Guid productId)
        {
            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var id = this.GetContactId();
                if (id == null)
                {
                    return;
                }

                var contactReference = new IdentifiedContactReference(id.Source, id.Identifier);
                var contact          = client.Get(contactReference, new ContactExpandOptions()
                {
                    Interactions = new RelatedInteractionsExpandOptions()
                    {
                        StartDateTime = DateTime.MinValue,
                        EndDateTime   = DateTime.MaxValue,
                        Limit         = int.MaxValue
                    }
                });

                if (contact == null)
                {
                    return;
                }

                // Create new interaction for this contact
                Guid   channelId   = Guid.NewGuid(); // Replace with channel ID from Sitecore
                string userAgent   = "Mozilla/5.0 (Nintendo Switch; ShareApplet) AppleWebKit/601.6 (KHTML, like Gecko) NF/4.0.0.5.9 NintendoBrowser/5.1.0.13341";
                var    interaction = new Sitecore.XConnect.Interaction(contact, InteractionInitiator.Brand, channelId, userAgent);

                var goalId = this.GetGoalId(interactionType);

                // Create new instance of goal
                Goal goal = new Goal(goalId, DateTime.UtcNow);

                //Add aditional information like the page id
                goal.CustomValues.Add("page", productId.ToString());

                // Add goal to interaction
                interaction.Events.Add(goal);

                // Add interaction operation to client
                client.AddInteraction(interaction);

                // Submit interaction
                client.Submit();
            }
        }
        public void SetPersonalInfo(PersonalInfo info, IdentifiedContactReference reference)
        {
            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                var contact = client.Get(reference, new ContactExpandOptions(PersonalInformation.DefaultFacetKey));

                var personalInfoFacet = contact.GetFacet <PersonalInformation>(PersonalInformation.DefaultFacetKey);
                personalInfoFacet = personalInfoFacet == null
                    ? this.contactMapper.Map <PersonalInfo, PersonalInformation>(info)
                    : this.contactMapper.MapToPersonalInformation(info, personalInfoFacet);

                client.SetFacet(contact, PersonalInformation.DefaultFacetKey, personalInfoFacet);

                client.Submit();
            }
        }