Exemple #1
0
        public async Task <Contact> RetrieveExistingContactAsync(XConnectClient client)
        {
            Contact existingContact = null;

            try
            {
                IdentifiedContactReference reference = new IdentifiedContactReference(CollectionConst.XConnect.ContactIdentifiers.Sources.Twitter, CollectionConst.XConnect.ContactIdentifiers.ExampleData.MyrtleIdentifier);

                var interactions = new RelatedInteractionsExpandOptions(IpInfo.DefaultFacetKey)
                {
                    StartDateTime = DateTime.MinValue,
                    EndDateTime   = DateTime.MaxValue
                };

                var targetedFacets = new string[]
                {
                    PersonalInformation.DefaultFacetKey
                };

                var contactExpandOptions = new ContactExpandOptions(targetedFacets)
                {
                    Interactions = interactions
                };

                existingContact = await client.GetAsync <Contact>(reference, contactExpandOptions);
            }
            catch (Exception ex)
            {
                throw;
            }

            return(existingContact);
        }
        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();
            }
        }
        public Contact IdentifyKnownContact(IdentifiedContactReference identifiedReference)
        {
            Contact toReturn = null;

            if (identifiedReference != null)
            {
                var expandOptions = new ContactExpandOptions(AllFacetKeys)
                {
                    Interactions = new RelatedInteractionsExpandOptions()
                    {
                        StartDateTime = DateTime.MinValue,
                        Limit         = int.MaxValue
                    }
                };

                using (var Client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
                {
                    try
                    {
                        toReturn = Client.Get(identifiedReference, expandOptions);
                    }
                    catch (XdbExecutionException ex)
                    {
                        Sitecore.Diagnostics.Log.Error(Constants.Logger.LoggingPrefix, ex, this);
                    }
                }
            }
            else
            {
                Sitecore.Diagnostics.Log.Warn(Constants.Logger.LoggingPrefix + "Identified Reference was null", this);
            }

            return(toReturn);
        }
Exemple #4
0
        public async Task <RecoResult> Recommendtion(string id)
        {
            var result = new RecoResult();

            using (XConnectClient client
                       = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                var reference = new ContactReference(Guid.Parse(id));

                var expandOptions = new ContactExpandOptions(CollectionModel.FacetKeys.PersonalInformation, ProductRecommendationFacet.DefaultFacetKey)
                {
                    Interactions = new RelatedInteractionsExpandOptions()
                };

                Task <Contact> contactTask = client.GetAsync <Contact>(reference, expandOptions);

                Contact contact = await contactTask;

                if (contact != null)
                {
                    result.FirstName = contact.Personal()?.FirstName;
                    result.LastName  = contact.Personal()?.LastName;
                    var purchaseOutcome = contact.Interactions.Select(i => i.Events.OfType <ProductPurchasedOutcome>()).FirstOrDefault();
                    result.PurchasedProductId = purchaseOutcome.FirstOrDefault().ProductId;
                    var recommendationFacet = contact.GetFacet <ProductRecommendationFacet>();
                    if (recommendationFacet != null)
                    {
                        result.Recommends = recommendationFacet.ProductRecommendations;
                    }
                }
            }
            return(result);
        }
Exemple #5
0
        private async Task LoadContact()
        {
            Console.WriteLine("Enter the contact's demo identifier");
            var identifier    = Console.ReadLine();
            var reference     = new IdentifiedContactReference("demo", identifier);
            var expandOptions = new ContactExpandOptions(SurakFacet.DefaultFacetName, PersonalInformation.DefaultFacetKey);

            using (var client = await CreateXConnectClient())
            {
                _contact = await client.GetContactAsync(reference, expandOptions);
            }

            if (_contact == null)
            {
                Console.WriteLine("Contact not found");
                return;
            }

            Console.WriteLine("Contact loaded");

            foreach (var id in _contact.Identifiers)
            {
                Console.WriteLine($"identifier: ({id.Source}, {id.Identifier})");
            }

            var personalFacet = _contact.Personal() ?? new PersonalInformation();;

            Console.WriteLine($"First name: {personalFacet.FirstName}");
            Console.WriteLine($"Last name: {personalFacet.LastName}");
        }
Exemple #6
0
        private void IdentifyContact(string source, string firstName, string lastName, string jobTitle, string email)
        {
            using (var client = this.CreateClient())
            {
                try
                {
                    var id = Tracker.Current.Contact.ContactId.ToString("N");

                    Tracker.Current.Session.IdentifyAs(source, id);

                    var trackerIdentifier = new IdentifiedContactReference(source, id);
                    var expandOptions     = new ContactExpandOptions(
                        CollectionModel.FacetKeys.PersonalInformation,
                        CollectionModel.FacetKeys.EmailAddressList);

                    Contact contact = client.Get(trackerIdentifier, expandOptions);

                    SetPersonalInformation(firstName, lastName, jobTitle, contact, client);
                    SetEmail(email, contact, client);

                    client.Submit();
                }
                catch (Exception ex)
                {
                    Log.Error(ex.Message, ex, this);
                }
            }
        }
        public ActivityResult Invoke(IContactProcessingContext context)
        {
            var contact = context.Contact;

            if (!contact.IsKnown)
            {
                return((ActivityResult) new SuccessMove());
            }

            if (!contact.ExpandOptions.FacetKeys.Contains(PersonalInformation.DefaultFacetKey))
            {
                var expandOptions = new ContactExpandOptions(PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey);
                contact = Services.Collection.GetContactAsync(contact, expandOptions).ConfigureAwait(false).GetAwaiter().GetResult();
            }

            var emailFacets  = contact.GetFacet <EmailAddressList>();
            var personalInfo = contact.GetFacet <PersonalInformation>();
            var fields       = "{" +
                               "\"Email\": \"" + emailFacets.PreferredEmail?.SmtpAddress + "\", " +
                               "\"FirstName\": \"" + personalInfo.FirstName + "\", " +
                               "\"MiddleName\": \"" + personalInfo.MiddleName + "\", " +
                               "\"LastName\": \"" + personalInfo.LastName + "\", " +
                               "\"PreferredLanguage\": \"" + personalInfo.PreferredLanguage + "\", " +
                               "\"Title\": \"" + personalInfo.Title + "\", " +
                               "\"JobTitle\": \"" + personalInfo.JobTitle + "\" " +
                               "}";

            Task.Run(() => PostRequest(triggerAddress, fields));

            return((ActivityResult) new SuccessMove());
        }
        /// <summary>
        /// Find ID values for all contacts that have not had any activity since a specified DateTime.
        /// If a bound is not provided, the logic assumes current time - 30 days.
        ///
        /// Based on documentation example: https://doc.sitecore.com/developers/92/sitecore-experience-platform/en/search-contacts.html
        /// </summary>
        /// <param name="cfg">The client configuration for connecting</param>
        /// <param name="lastActivity">The time to look for the contact's last activity</param>
        /// <returns>The matching contact object</returns>
        public virtual async Task <List <System.Guid> > GetContactIdsByLastActivity(XConnectClientConfiguration cfg, DateTime?lastActivity)
        {
            //Create a collection that will store the IDs of the results
            List <System.Guid> matchingContactIds = new List <System.Guid>();

            //Establish a timebound to search for. If not provided, default to a value.
            DateTime searchStartTime = lastActivity.HasValue ? lastActivity.Value : DateTime.Now.AddDays(-30);

            Logger.WriteLine("Retrieving all Contacts without interactions since:" + searchStartTime.ToShortDateString());

            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(cfg))
            {
                try
                {
                    //Set up options to restrict the number of interactions we return for each contact
                    var contactExpandOptions = new ContactExpandOptions();
                    contactExpandOptions.Interactions = new RelatedInteractionsExpandOptions()
                    {
                        Limit = 20
                    };

                    //Create a queryable to search by the date
                    IAsyncQueryable <Contact> queryable = client.Contacts
                                                          .Where(c => (!c.Interactions.Any()) || !c.Interactions.Any(x => x.StartDateTime > searchStartTime))
                                                          .WithExpandOptions(contactExpandOptions);

                    //Invoke the query
                    var enumerator = await queryable.GetBatchEnumerator(10);

                    //Collect all the matching contact IDs
                    while (await enumerator.MoveNext())
                    {
                        foreach (var contact in enumerator.Current)
                        {
                            if (contact.Id.HasValue)
                            {
                                matchingContactIds.Add(contact.Id.Value);
                            }
                        }
                    }


                    Logger.WriteLine(">> Total number of matches found '{0}'", matchingContactIds.Count);
                }
                catch (XdbExecutionException ex)
                {
                    // Deal with exception
                    Logger.WriteError("Exception executing search", ex);
                }
            }

            return(matchingContactIds);
        }
        private void GetTableFromContactXconnect(DataTable rawTable, Guid contactID, Guid?interactionID = null)
        {
            string[] strArray = new string[3]
            {
                "IpInfo",
                "WebVisit",
                "UserAgentInfo"
            };
            ContactExpandOptions contactExpandOptions = new ContactExpandOptions(Array.Empty <string>())
            {
                Interactions = new RelatedInteractionsExpandOptions(strArray)
                {
                    Limit         = new int?(int.MaxValue),
                    StartDateTime = new DateTime?(DateTime.MinValue)
                }
            };
            List <Interaction> list = Enumerable.ToList <Interaction>(
                (IEnumerable <Interaction>)Enumerable.OrderByDescending <Interaction, DateTime>(
                    (IEnumerable <Interaction>) this.GetContactByOptions(
                        contactID,
                        (ExpandOptions)contactExpandOptions
                        ).Interactions,
                    (Func <Interaction, DateTime>)(p => p.StartDateTime)
                    )
                );

            if (interactionID.HasValue)
            {
                Interaction curInteraction = Enumerable.FirstOrDefault <Interaction>((IEnumerable <Interaction>)list, (Func <Interaction, bool>)(p =>
                {
                    Guid?id   = p.Id;
                    Guid guid = interactionID.Value;
                    if (!id.HasValue)
                    {
                        return(false);
                    }
                    if (!id.HasValue)
                    {
                        return(true);
                    }
                    return(id.GetValueOrDefault() == guid);
                }));
                int index = list.IndexOf(curInteraction) + 1;
                this.FillTableWithRow(rawTable, curInteraction, index);
            }
            else
            {
                foreach (Interaction curInteraction in list)
                {
                    int index = list.IndexOf(curInteraction) + 1;
                    this.FillTableWithRow(rawTable, curInteraction, index);
                }
            }
        }
        /// <summary>
        /// Retrieves the Contacts from xConnect for each matching contactID
        /// </summary>
        /// <param name="cfg">The configuration to use to open connections to xConnect</param>
        /// <param name="contactIds">The list of contacts to retrieve</param>
        /// <returns></returns>
        public virtual async Task <List <Contact> > GetMultipleContacts(XConnectClientConfiguration cfg, List <Guid> contactIds)
        {
            if (contactIds == null)
            {
                contactIds = new List <Guid>();
            }
            Logger.WriteLine("Getting Multiple Contacts: [{0}]", contactIds.Count);

            var contacts = new List <Contact>();

            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(cfg))
            {
                try
                {
                    //Configure the options to extract the personal information facet
                    var contactOptions = new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey });

                    //Get a list of reference objects for the contactIds provided
                    var references = new List <IEntityReference <Contact> >();
                    foreach (var contactId in contactIds)
                    {
                        references.Add(new ContactReference(contactId));
                    }

                    //Get all the matches
                    var contactsResult = await client.GetAsync <Contact>(references, contactOptions);

                    //Get the Contact objects from the results
                    foreach (var result in contactsResult)
                    {
                        if (result.Exists)
                        {
                            contacts.Add(result.Entity);
                        }
                    }

                    //Output information about the contact list
                    if (client.LastBatch != null)
                    {
                        Logger.WriteOperations(client.LastBatch);
                    }
                    Logger.WriteLine("> Retrieved {0} matching Contacts.", contacts.Count);
                }
                catch (XdbExecutionException ex)
                {
                    // Deal with exception
                    Logger.WriteError("Exception retrieving contact", ex);
                }
            }

            return(contacts);
        }
 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();
         }
     }
 }
Exemple #13
0
        public async Task <List <RecoResult> > Recommendtions()
        {
            var result = new List <RecoResult>();

            using (XConnectClient client
                       = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                var query = client.Contacts.Where(contact =>
                                                  contact.Interactions.Any(interaction =>
                                                                           interaction.Events.OfType <ProductPurchasedOutcome>().Any() &&
                                                                           interaction.StartDateTime > DateTime.UtcNow.AddDays(-1) //Only for outcome happened in past 24 hours
                                                                           )
                                                  );

                var expandOptions = new ContactExpandOptions(CollectionModel.FacetKeys.PersonalInformation, ProductRecommendationFacet.DefaultFacetKey)
                {
                    Interactions = new RelatedInteractionsExpandOptions()
                };

                query = query.WithExpandOptions(expandOptions);

                var contacts = await query.ToList();

                if (contacts.Any())
                {
                    foreach (var c in contacts)
                    {
                        var purchaseOutcome     = c.Interactions.Select(i => i.Events.OfType <ProductPurchasedOutcome>()).FirstOrDefault();
                        var purchasedId         = purchaseOutcome.FirstOrDefault().ProductId;
                        var recommendationFacet = c.GetFacet <ProductRecommendationFacet>();

                        var r = new RecoResult()
                        {
                            FirstName          = c.Personal()?.FirstName,
                            LastName           = c.Personal()?.LastName,
                            PurchasedProductId = purchasedId
                        };

                        if (recommendationFacet != null)
                        {
                            r.Recommends = recommendationFacet.ProductRecommendations;
                        }

                        result.Add(r);
                    }
                }
            }
            return(result);
        }
        public void ViewSingleContact(string identifier)
        {
            var expandOptions = new ContactExpandOptions()
            {
                Interactions = new RelatedInteractionsExpandOptions(Tweet.FacetName)
                {
                    EndDateTime   = DateTime.UtcNow,
                    StartDateTime = DateTime.UtcNow.AddDays(-10)
                }
            };

            var contactReference = new IdentifiedContactReference("twitter", identifier);
            var contact          = _client.Get(contactReference, expandOptions);

            if (contact == null)
            {
                _logger.WriteLine("Contact not found");
                return;
            }

            _logger.WriteLine("####################################");
            foreach (var interaction in contact.Interactions)
            {
                var date      = string.Empty;
                var phrase    = string.Empty;
                var tweetText = string.Empty;

                var tweet = interaction.GetFacet <Tweet>();
                if (tweet != null)
                {
                    date      = interaction.StartDateTime.ToShortDateString();
                    tweetText = tweet.Text;
                }

                var tweetEvent = interaction.Events.FirstOrDefault(x => x is TweetEvent) as TweetEvent;
                if (tweetEvent != null)
                {
                    phrase = tweetEvent.TargetPhrase;
                }

                //_logger.WriteLine($"{date}\t\t{phrase}\t\t{tweetText}");
                _logger.WriteLine($"Date:\t{date}");
                _logger.WriteLine($"Phrase:\t{phrase}");
                _logger.WriteLine($"Tweet:\t{tweetText}");
                _logger.WriteLine("####################################");
                _logger.WriteLine("");
                _logger.WriteLine("Press any key to continue...");
            }
        }
Exemple #15
0
        private async static Task <Contact> CreateOrUpdateContact(XConnectClient client)
        {
            var identifiedContactReference = new IdentifiedContactReference(_fakeContact.Source, _fakeContact.EmailAddress);

            var options = new ContactExpandOptions(PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey, AddressList.DefaultFacetKey, PhoneNumberList.DefaultFacetKey, Avatar.DefaultFacetKey);

            Task <Contact> contactTask = client.GetAsync <Contact>(identifiedContactReference, options);
            Contact        contact     = await contactTask;

            if (contact == null)
            {
                contact = new Sitecore.XConnect.Contact(new Sitecore.XConnect.ContactIdentifier(_fakeContact.Source, _fakeContact.EmailAddress, Sitecore.XConnect.ContactIdentifierType.Known));
                client.AddContact(contact);
            }

            return(contact);
        }
Exemple #16
0
        /// <summary>
        /// Retrieve a created contact with interactions within the range provided
        /// </summary>
        /// <param name="cfg">The client configuration for connecting</param>
        /// <param name="twitterId">The identifier of the contact to create</param>
        /// <param name="interactionStartTime">The start range of interactions to return</param>
        /// <param name="interactionEndTime">The end range of interactions to return</param>
        /// <returns>The matching contact object</returns>
        public virtual async Task <Contact> GetContactWithInteractions(XConnectClientConfiguration cfg, string twitterId, DateTime?interactionStartTime, DateTime?interactionEndTime)
        {
            Contact existingContact = null;

            Logger.WriteLine("Retrieving Contact with Identifier:" + twitterId);

            // Initialize a client using the validated configuration
            using (var client = new XConnectClient(cfg))
            {
                try
                {
                    var contactOptions = new ContactExpandOptions(new string[] { PersonalInformation.DefaultFacetKey });

                    //Add interaction range if necessary
                    if (interactionStartTime.HasValue || interactionEndTime.HasValue)
                    {
                        contactOptions.Interactions = new RelatedInteractionsExpandOptions(IpInfo.DefaultFacetKey)
                        {
                            StartDateTime = interactionStartTime,
                            EndDateTime   = interactionEndTime
                        };
                    }

                    //Build up options for the query
                    var reference = new IdentifiedContactReference("twitter", twitterId);
                    // Get a known contact
                    existingContact = await client.GetAsync <Contact>(reference, contactOptions);

                    if (existingContact == null)
                    {
                        Logger.WriteLine("No contact found with ID '{0}'", twitterId);
                        return(null);
                    }

                    //Output information about the contact
                    Logger.WriteContact(existingContact);
                }
                catch (XdbExecutionException ex)
                {
                    // Deal with exception
                    Logger.WriteError("Exception retrieving contact", ex);
                }
            }

            return(existingContact);
        }
        protected override bool Execute(UpdateContactData data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(data, nameof(data));
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));

            var firstNameField = GetFieldById(data.FirstNameFieldId, formSubmitContext.Fields);
            var lastNameField  = GetFieldById(data.LastNameFieldId, formSubmitContext.Fields);
            var emailField     = GetFieldById(data.EmailFieldId, formSubmitContext.Fields);

            if (firstNameField == null && lastNameField == null && emailField == null)
            {
                return(false);
            }

            using (var client = CreateClient())
            {
                try
                {
                    var source = "Subscribe.Form";
                    var id     = CurrentTracker.Contact.ContactId.ToString("N");

                    CurrentTracker.Session.IdentifyAs(source, id);
                    var trackerIdentifier = new IdentifiedContactReference(source, id);

                    var expandOptions = new ContactExpandOptions(
                        PersonalInformation.DefaultFacetKey,
                        CollectionModel.FacetKeys.EmailAddressList);

                    XConnectContact contact = client.Get(trackerIdentifier, expandOptions);

                    SetPersonalInformation(GetValue(firstNameField), GetValue(lastNameField), contact, client);

                    SetEmail(GetValue(emailField), contact, client);
                    client.Submit();
                    return(true);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.Message, ex);
                    return(false);
                }
            }
        }
Exemple #18
0
        protected override bool Execute(UpdateContactData data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(data, nameof(data));
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));
            var firstNameField      = GetFieldById(data.FirstNameFieldId, formSubmitContext.Fields);
            var lastNameField       = GetFieldById(data.LastNameFieldId, formSubmitContext.Fields);
            var emailField          = GetFieldById(data.EmailFieldId, formSubmitContext.Fields);
            var twitterAccountField = GetFieldById(data.TwitterAccountFieldId, formSubmitContext.Fields);

            var twitterAccount = GetValue(twitterAccountField);

            if (!string.IsNullOrEmpty(twitterAccount))
            {
                Tracker.Current.Session.IdentifyAs("twitter", twitterAccount);
            }

            if (firstNameField == null && lastNameField == null && emailField == null)
            {
                return(false);
            }

            using (var client = CreateClient())
            {
                try
                {
                    var trackerIdentifier = new IdentifiedContactReference("twitter", twitterAccount);
                    var expandOptions     = new ContactExpandOptions(
                        CollectionModel.FacetKeys.PersonalInformation,
                        CollectionModel.FacetKeys.EmailAddressList);
                    var contact = client.Get(trackerIdentifier, expandOptions);
                    SetPersonalInformation(GetValue(firstNameField), GetValue(lastNameField), GetValue(twitterAccountField), contact, client);
                    SetEmail(GetValue(emailField), contact, client);
                    client.Submit();
                    return(true);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.Message, ex);
                    return(false);
                }
            }
        }
Exemple #19
0
        private async Task SearchInteractionsAsync()
        {
            var xConnectClient = await CreateXConnectClient();

            var query = xConnectClient.Contacts.Where(contact =>
                                                      contact.Interactions.Any(interaction =>
                                                                               interaction.Events.OfType <MusicPurchaseOutcome>().Any() &&
                                                                               interaction.EndDateTime > DateTime.UtcNow.AddMinutes(-TimeoutIntervalMinutes)
                                                                               )
                                                      );

            var expandOptions = new ContactExpandOptions
            {
                Interactions = new RelatedInteractionsExpandOptions()
            };

            query = query.WithExpandOptions(expandOptions);

            var batchEnumerator = await query.GetBatchEnumerator();

            System.Console.WriteLine($"Found {batchEnumerator.TotalCount} interactions");

            while (await batchEnumerator.MoveNext())
            {
                foreach (var contact in batchEnumerator.Current)
                {
                    System.Console.WriteLine("====================================");
                    System.Console.WriteLine($"Contact ID {contact.Id}");

                    var outcomes = contact.Interactions.SelectMany(i => i.Events.OfType <MusicPurchaseOutcome>());
                    foreach (var outcome in outcomes)
                    {
                        var album = outcome.Album;
                        System.Console.WriteLine("------------------------------------");
                        System.Console.WriteLine($"Album Id: {album.AlbumId}");
                        System.Console.WriteLine($"Album Name: {album.AlbumName}");
                        System.Console.WriteLine($"Artist Id: {album.ArtistId}");
                        System.Console.WriteLine($"Artist Name: {album.ArtistName}");
                    }
                }
            }
        }
        private async Task <Contact> RetrieveContactAsync(XConnectClient client, string MarketingIdentifier)
        {
            Contact toReturn = null;

            try
            {
                var identifierContactReference = new IdentifiedContactReference(MarketingConst.XConnect.ContactIdentifiers.Sources.Marketing, MarketingIdentifier);
                var expandOptions = new ContactExpandOptions(
                    AddressList.DefaultFacetKey,
                    EmailAddressList.DefaultFacetKey,
                    CinemaBusinessMarketing.DefaultFacetKey,
                    PersonalInformation.DefaultFacetKey
                    );

                toReturn = await client.GetAsync(identifierContactReference, expandOptions);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            return(toReturn);
        }
Exemple #21
0
        public bool IsGoalTriggered(ID goalId, decimal hours)
        {
            Assert.IsNotNull(Tracker.Current, "Tracker.Current");
            Assert.IsNotNull(Tracker.Current.Session, "Tracker.Current.Session");
            Assert.IsNotNull(goalId, "goalId");
            Assert.IsNotNull(hours, "hours");

            using (XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    var time = Decimal.ToDouble(hours);
                    var allInteractionsExpandOptions = new ContactExpandOptions()
                    {
                        Interactions = new RelatedInteractionsExpandOptions()
                        {
                            Limit = int.MaxValue
                        }
                    };

                    var reference     = new IdentifiedContactReference("xDB.Tracker", Tracker.Current.Session.Contact.ContactId.ToString("N"));
                    var actualContact = client.Get(reference, allInteractionsExpandOptions);

                    var interactions = actualContact.Interactions;
                    var goals        = interactions.Select(x => x.Events.OfType <Goal>()).SelectMany(x => x).OrderByDescending(x => x.Timestamp);

                    var desiredGoal = goals.FirstOrDefault(x => TypeExtensions.ToID(x.DefinitionId) == goalId);

                    return(desiredGoal?.Timestamp.AddHours(time) >= DateTime.UtcNow);
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error(ex.Message, ex, this);
                }
            }
            return(false);
        }
Exemple #22
0
        private async Task RegisterRecommendationTaskAsync()
        {
            _taskIds.Clear();

            var taskManager    = GetTaskManager();
            var xConnectClient = await CreateXConnectClient();

            var taskTimeout    = TimeSpan.FromMinutes(10);
            var storageTimeout = TimeSpan.FromMinutes(30);

            // Prepare data source query
            var query = xConnectClient.Contacts.Where(contact =>
                                                      contact.Interactions.Any(interaction =>
                                                                               interaction.Events.OfType <MusicPurchaseOutcome>().Any() &&
                                                                               interaction.EndDateTime > DateTime.UtcNow.AddMinutes(-TimeoutIntervalMinutes)
                                                                               )
                                                      );

            var expandOptions = new ContactExpandOptions
            {
                Interactions = new RelatedInteractionsExpandOptions()
            };

            query = query.WithExpandOptions(expandOptions);

            var searchRequest = query.GetSearchRequest();

            // Task for projection
            var dataSourceOptions = new ContactSearchDataSourceOptionsDictionary(
                searchRequest, // searchRequest
                30,            // maxBatchSize
                50             // defaultSplitItemCount
                );

            var projectionOptions = new ContactProjectionWorkerOptionsDictionary(
                typeof(AlbumRecommendationModel).AssemblyQualifiedName, // modelTypeString
                storageTimeout,                                         // timeToLive
                "recommendation",                                       // schemaName
                new Dictionary <string, string>                         // modelOptions
            {
                { AlbumRecommendationModel.OptionTableName, "contactArtists" }
            }
                );

            var projectionTaskId = await taskManager.RegisterDistributedTaskAsync(
                dataSourceOptions, // datasourceOptions
                projectionOptions, // workerOptions
                null,              // prerequisiteTaskIds
                taskTimeout        // expiresAfter
                );

            _taskIds.Add(projectionTaskId);

            // Task for merge
            var mergeOptions = new MergeWorkerOptionsDictionary(
                "contactArtistsFinal", // tableName
                "contactArtists",      // prefix
                storageTimeout,        // timeToLive
                "recommendation"       // schemaName
                );

            var mergeTaskId = await taskManager.RegisterDeferredTaskAsync(
                mergeOptions, // workerOptions
                new[]         // prerequisiteTaskIds
            {
                projectionTaskId
            },
                taskTimeout // expiresAfter
                );

            _taskIds.Add(mergeTaskId);

            // Task for recommendation
            var recommendationOptions = new DeferredWorkerOptionsDictionary(
                typeof(AlbumRecommendationWorker).AssemblyQualifiedName, // workerType
                new Dictionary <string, string>                          // options
            {
                { AlbumRecommendationWorker.OptionSourceTableName, "contactArtistsFinal" },
                { AlbumRecommendationWorker.OptionTargetTableName, "contactRecommendations" },
                { AlbumRecommendationWorker.OptionSchemaName, "recommendation" },
                { AlbumRecommendationWorker.OptionLimit, "5" }
            }
                );

            var recommendationTaskId = await taskManager.RegisterDeferredTaskAsync(
                recommendationOptions, // workerOptions
                new[]                  // prerequisiteTaskIds
            {
                mergeTaskId
            },
                taskTimeout // expiresAfter
                );

            _taskIds.Add(recommendationTaskId);

            // Task to store facet
            var storeFacetOptions = new DeferredWorkerOptionsDictionary(
                typeof(RecommendationFacetStorageWorker).AssemblyQualifiedName, // workerType
                new Dictionary <string, string>                                 // options
            {
                { RecommendationFacetStorageWorker.OptionTableName, "contactRecommendations" },
                { RecommendationFacetStorageWorker.OptionSchemaName, "recommendation" }
            }
                );

            var storeFacetTaskId = await taskManager.RegisterDeferredTaskAsync(
                storeFacetOptions, // workerOptions
                new[]              // prerequisiteTaskIds
            {
                recommendationTaskId
            },
                taskTimeout // expiresAfter
                );

            _taskIds.Add(storeFacetTaskId);

            foreach (var taskId in _taskIds)
            {
                System.Console.WriteLine($"Registered task {taskId}");
            }
        }
Exemple #23
0
        protected override bool Execute(EmailCampaignData data, FormSubmitContext formSubmitContext)
        {
            var evt = new CreateTeamEvent();

            evt.Name                 = (formSubmitContext.Fields.First(c => c.Name == "Team Name") as StringInputViewModel).Value;
            evt.ContactEmail         = (formSubmitContext.Fields.First(c => c.Name == "Main Email") as StringInputViewModel).Value;
            evt.ContactGitHubProfile = (formSubmitContext.Fields.First(c => c.Name == "GitHub Username") as StringInputViewModel).Value;
            evt.Country              = (formSubmitContext.Fields.First(c => c.Name == "Country") as StringInputViewModel).Value;

            var teamMember1 = new TeamMember
            {
                Name     = (formSubmitContext.Fields.First(c => c.Name == "FirstUserName") as StringInputViewModel).Value,
                GitHub   = (formSubmitContext.Fields.First(c => c.Name == "FirstUserGitHub") as StringInputViewModel).Value,
                LinkedIn = (formSubmitContext.Fields.First(c => c.Name == "FirstUserLinkedIn") as StringInputViewModel).Value,
                Twitter  = (formSubmitContext.Fields.First(c => c.Name == "FirstUserTwitter") as StringInputViewModel).Value,
            };

            var teamMember2 = new TeamMember
            {
                Name     = (formSubmitContext.Fields.First(c => c.Name == "SecondUserName") as StringInputViewModel).Value,
                GitHub   = (formSubmitContext.Fields.First(c => c.Name == "SecondUserGitHub") as StringInputViewModel).Value,
                LinkedIn = (formSubmitContext.Fields.First(c => c.Name == "SecondUserLinkedIn") as StringInputViewModel).Value,
                Twitter  = (formSubmitContext.Fields.First(c => c.Name == "secondUserTwitter") as StringInputViewModel).Value,
            };

            var teamMember3 = new TeamMember
            {
                Name     = (formSubmitContext.Fields.First(c => c.Name == "ThirdUserName") as StringInputViewModel).Value,
                GitHub   = (formSubmitContext.Fields.First(c => c.Name == "ThirdUserGitHub") as StringInputViewModel).Value,
                LinkedIn = (formSubmitContext.Fields.First(c => c.Name == "ThirdUserLinkedIn") as StringInputViewModel).Value,
                Twitter  = (formSubmitContext.Fields.First(c => c.Name == "ThirdUserTwitter") as StringInputViewModel).Value,
            };

            evt.TeamMembers = new List <TeamMember>
            {
                teamMember1,
                teamMember2,
                teamMember3
            };

            evt.EmailCampaignId = data.EmailCampaignId;

            using (var client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    Tracker.Current.Session.IdentifyAs("saveteam", evt.ContactEmail);
                    var trackerIdentifier = new IdentifiedContactReference("saveteam", evt.ContactEmail);
                    var expandOptions     = new ContactExpandOptions(CollectionModel.FacetKeys.PersonalInformation, CollectionModel.FacetKeys.EmailAddressList);

                    var contact = client.Get(trackerIdentifier, expandOptions);

                    SetEmail(GetValue(evt.ContactEmail), contact, client);

                    client.Submit();

                    var manager = Factory.CreateObject("tracking/contactManager", true) as Sitecore.Analytics.Tracking.ContactManager;
                    manager.RemoveFromSession(Tracker.Current.Contact.ContactId); // Use tracker ID, not xConnect ID
                    Tracker.Current.Session.Contact = manager.LoadContact(Tracker.Current.Contact.ContactId);

                    evt.Identifier = contact.Identifiers.FirstOrDefault(i => i.Identifier == evt.ContactEmail);
                }
                catch (Exception ex)
                {
                }
            }
            Sitecore.Eventing.EventManager.RaiseEvent(evt);
            return(true);
        }
Exemple #24
0
        public async Task <object> RegisterTasks()
        {
            //In a core role like Content Management, we can retrive Task Manager like below
            var taskManager = ServiceLocator.ServiceProvider.GetService <ITaskManager>();


            using (XConnectClient client
                       = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                var query = client.Contacts.Where(contact =>
                                                  contact.Interactions.Any(interaction =>
                                                                           interaction.Events.OfType <ProductPurchasedOutcome>().Any() &&
                                                                           interaction.StartDateTime > DateTime.UtcNow.AddDays(-1) //Only for outcome happened in past 24 hours
                                                                           )
                                                  );

                var expandOptions = new ContactExpandOptions
                {
                    Interactions = new RelatedInteractionsExpandOptions()
                };

                query = query.WithExpandOptions(expandOptions);

                var searchRequest = query.GetSearchRequest();
                // Task for projection
                var dataSourceOptions = new ContactSearchDataSourceOptionsDictionary(
                    searchRequest, // searchRequest
                    30,            // maxBatchSize
                    50             // defaultSplitItemCount
                    );

                var projectionOptions = new ContactProjectionWorkerOptionsDictionary(
                    typeof(ProductRecommendationModel).AssemblyQualifiedName, // modelTypeString
                    TimeSpan.FromMinutes(10),                                 // timeToLive
                    "recommendation",                                         // schemaName
                    new Dictionary <string, string>                           // modelOptions
                {
                    { ProductRecommendationModel.OptionTableName, "contactProducts" }
                }
                    );

                var projectionTaskId = await taskManager.RegisterDistributedTaskAsync(
                    dataSourceOptions,       // datasourceOptions
                    projectionOptions,       // workerOptions
                    null,                    // prerequisiteTaskIds
                    TimeSpan.FromMinutes(10) // expiresAfter
                    );

                // Task for merge
                var mergeOptions = new MergeWorkerOptionsDictionary(
                    "contactProductsFinal",   // tableName
                    "contactProducts",        // prefix
                    TimeSpan.FromMinutes(10), // timeToLive
                    "recommendation"          // schemaName
                    );

                var mergeTaskId = await taskManager.RegisterDeferredTaskAsync(
                    mergeOptions, // workerOptions
                    new[]         // prerequisiteTaskIds
                {
                    projectionTaskId
                },
                    TimeSpan.FromMinutes(10) // expiresAfter
                    );

                // Task for predict
                var workerOptions = new DeferredWorkerOptionsDictionary(
                    typeof(ProductRecommendationWorker).AssemblyQualifiedName, // workerType
                    new Dictionary <string, string>                            // options
                {
                    { ProductRecommendationWorker.OptionSourceTableName, "contactProductsFinal" },
                    { ProductRecommendationWorker.OptionTargetTableName, "contactRecommendations" },
                    { ProductRecommendationWorker.OptionSchemaName, "recommendation" },
                    { ProductRecommendationWorker.OptionLimit, "5" }
                });

                var recommendationTaskId = await taskManager.RegisterDeferredTaskAsync(
                    workerOptions, // workerOptions
                    new[]          // prerequisiteTaskIds
                {
                    mergeTaskId
                },
                    TimeSpan.FromMinutes(10) // expiresAfter
                    );

                // Task for storage
                var storageOptions = new DeferredWorkerOptionsDictionary(
                    typeof(RecommendationFacetStorageWorker).AssemblyQualifiedName, // workerType
                    new Dictionary <string, string>                                 // options
                {
                    { RecommendationFacetStorageWorker.OptionTableName, "contactRecommendations" },
                    { RecommendationFacetStorageWorker.OptionSchemaName, "recommendation" }
                });

                var storeFacetTaskId = await taskManager.RegisterDeferredTaskAsync(
                    storageOptions, // workerOptions
                    new[]           // prerequisiteTaskIds
                {
                    recommendationTaskId
                },
                    TimeSpan.FromMinutes(10) // expiresAfter
                    );

                return(new List <Guid>()
                {
                    projectionTaskId, mergeTaskId, recommendationTaskId, storeFacetTaskId
                });
            }
        }
        protected override async Task RecurringExecuteAsync(CancellationToken token)
        {
            using (var scope = _serviceProvider.CreateScope())
            {
                using (var xdbContext = scope.ServiceProvider.GetService <IXdbContext>())

                {
                    // Register the project, merge, predict, storage tasks here
                    var query = xdbContext.Contacts.Where(contact =>
                                                          contact.Interactions.Any(interaction =>
                                                                                   interaction.Events.OfType <ProductPurchasedOutcome>().Any() &&
                                                                                   interaction.StartDateTime > DateTime.UtcNow.AddHours(-1)
                                                                                   )
                                                          );

                    var expandOptions = new ContactExpandOptions
                    {
                        Interactions = new RelatedInteractionsExpandOptions()
                    };

                    query = query.WithExpandOptions(expandOptions);

                    var searchRequest = query.GetSearchRequest();

                    // Task for projection
                    var dataSourceOptions = new ContactSearchDataSourceOptionsDictionary(
                        searchRequest, // searchRequest
                        30,            // maxBatchSize
                        50             // defaultSplitItemCount
                        );

                    var projectionOptions = new ContactProjectionWorkerOptionsDictionary(
                        typeof(ProductRecommendationModel).AssemblyQualifiedName, // modelTypeString
                        TimeSpan.FromMinutes(10),                                 // timeToLive
                        "recommendation",                                         // schemaName
                        new Dictionary <string, string>                           // modelOptions
                    {
                        { ProductRecommendationModel.OptionTableName, "contactProducts" }
                    }
                        );

                    var projectionTaskId = await _taskManager.RegisterDistributedTaskAsync(
                        dataSourceOptions,       // datasourceOptions
                        projectionOptions,       // workerOptions
                        null,                    // prerequisiteTaskIds
                        TimeSpan.FromMinutes(10) // expiresAfter
                        );

                    // Task for merge
                    var mergeOptions = new MergeWorkerOptionsDictionary(
                        "contactProductsFinal",   // tableName
                        "contactProducts",        // prefix
                        TimeSpan.FromMinutes(10), // timeToLive
                        "recommendation"          // schemaName
                        );

                    var mergeTaskId = await _taskManager.RegisterDeferredTaskAsync(
                        mergeOptions, // workerOptions
                        new[]         // prerequisiteTaskIds
                    {
                        projectionTaskId
                    },
                        TimeSpan.FromMinutes(10) // expiresAfter
                        );

                    // Task for predict
                    var workerOptions = new DeferredWorkerOptionsDictionary(
                        typeof(ProductRecommendationWorker).AssemblyQualifiedName, // workerType
                        new Dictionary <string, string>                            // options
                    {
                        { ProductRecommendationWorker.OptionSourceTableName, "contactProductsFinal" },
                        { ProductRecommendationWorker.OptionTargetTableName, "contactRecommendations" },
                        { ProductRecommendationWorker.OptionSchemaName, "recommendation" },
                        { ProductRecommendationWorker.OptionLimit, "5" }
                    });

                    var recommendationTaskId = await _taskManager.RegisterDeferredTaskAsync(
                        workerOptions, // workerOptions
                        new[]          // prerequisiteTaskIds
                    {
                        mergeTaskId
                    },
                        TimeSpan.FromMinutes(10) // expiresAfter
                        );

                    // Task for storage
                    var storageOptions = new DeferredWorkerOptionsDictionary(
                        typeof(RecommendationFacetStorageWorker).AssemblyQualifiedName, // workerType
                        new Dictionary <string, string>                                 // options
                    {
                        { RecommendationFacetStorageWorker.OptionTableName, "contactRecommendations" },
                        { RecommendationFacetStorageWorker.OptionSchemaName, "recommendation" }
                    });

                    var storeFacetTaskId = await _taskManager.RegisterDeferredTaskAsync(
                        storageOptions, // workerOptions
                        new[]           // prerequisiteTaskIds
                    {
                        recommendationTaskId
                    },
                        TimeSpan.FromMinutes(10) // expiresAfter
                        );

                    _logger.LogInformation("***projection task ID: " + projectionTaskId);
                    _logger.LogInformation("***merge task ID: " + mergeTaskId);
                    _logger.LogInformation("***predict task ID: " + recommendationTaskId);
                    _logger.LogInformation("***storage task ID: " + storeFacetTaskId);
                }
            }
        }
Exemple #26
0
        /// <summary>
        /// Executes the action with the specified <paramref name="data" />.
        /// </summary>
        /// <param name="data">The data.</param>
        /// <param name="formSubmitContext">The form submit context.</param>
        /// <returns><c>true</c> if the action is executed correctly; otherwise <c>false</c></returns>
        protected override bool Execute(SendEmailData data, FormSubmitContext formSubmitContext)
        {
            Assert.ArgumentNotNull(data, nameof(data));
            Assert.ArgumentNotNull(formSubmitContext, nameof(formSubmitContext));
            var firstNameField = GetFieldById(data.FirstNameFieldId, formSubmitContext.Fields);
            var lastNameField  = GetFieldById(data.LastNameFieldId, formSubmitContext.Fields);
            var emailField     = GetFieldById(data.EmailFieldId, formSubmitContext.Fields);

            if (firstNameField == null && lastNameField == null && emailField == null)
            {
                return(false);
            }
            using (var client = CreateClient())
            {
                try
                {
                    var source = "Subcribe.Form";
                    var id     = CurrentTracker.Contact.ContactId.ToString("N");
                    CurrentTracker.Session.IdentifyAs(source, id);
                    var trackerIdentifier = new IdentifiedContactReference(source, id);
                    var expandOptions     = new ContactExpandOptions(
                        CollectionModel.FacetKeys.PersonalInformation,
                        CollectionModel.FacetKeys.EmailAddressList);
                    Contact contact = client.Get(trackerIdentifier, expandOptions);
                    SetPersonalInformation(GetValue(firstNameField), GetValue(lastNameField), contact, client);
                    SetEmail(GetValue(emailField), contact, client);
                    client.Submit();
                    if (data.MessageId == Guid.Empty)
                    {
                        Logger.LogError("Empty message id");
                        return(false);
                    }
                    ContactIdentifier contactIdentifier = null;
                    if (contact != null)
                    {
                        contactIdentifier = contact.Identifiers.FirstOrDefault <ContactIdentifier>((ContactIdentifier c) => c.IdentifierType == ContactIdentifierType.Known);
                    }
                    if (contactIdentifier == null)
                    {
                        Logger.LogError("Contact id is null.");
                        return(false);
                    }
                    try
                    {
                        _clientApiService.SendAutomatedMessage(new AutomatedMessage()
                        {
                            ContactIdentifier = contactIdentifier,
                            MessageId         = data.MessageId
                        });
                    }
                    catch (Exception exception1)
                    {
                        Logger.LogError(exception1.Message, exception1);
                    }
                    return(true);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.Message, ex);
                    return(false);
                }
            }
        }
        /// <summary>
        /// This the the core method that runs the whole nine yards for Projection, Merge and Store Recommendations
        /// </summary>
        /// <returns></returns>
        private async Task RegisterRecommendationTaskAsync()
        {
            var taskManager    = GetTaskManager();
            var xConnectClient = GetXConnectClient();
            var taskTimeout    = TimeSpan.FromMinutes(20);
            var storageTimeout = TimeSpan.FromMinutes(30);
            //This ID should be swapped with your custom GOAL ID, should be ideally read from a constants file
            var goalId = new Guid("{56367C18-B211-431B-A2C7-975F9C59372F}");

            //Below will latest interactions on all contacts that belong to custom goal type.  The time here depends on frequency of run of your processing service
            var query = xConnectClient.Contacts.Where(contact =>
                                                      contact.Interactions.Any(interaction =>
                                                                               interaction.Events.OfType <Goal>().Any(x => x.DefinitionId == goalId) &&
                                                                               interaction.EndDateTime > DateTime.UtcNow.AddMinutes(-120)
                                                                               )
                                                      );

            var expandOptions = new ContactExpandOptions
            {
                Interactions = new RelatedInteractionsExpandOptions()
            };

            query = query.WithExpandOptions(expandOptions);

            var searchRequest = query.GetSearchRequest();

            // projection starts here
            var dataSourceOptions = new ContactSearchDataSourceOptionsDictionary(
                searchRequest,
                30,
                50
                );

            var projectionOptions = new ContactProjectionWorkerOptionsDictionary(
                typeof(MovieRecommendationModel).AssemblyQualifiedName,
                storageTimeout,
                "recommendation",
                new Dictionary <string, string>
            {
                { MovieRecommendationModel.OptionTableName, "contactMovies" }
            }
                );


            var projectionTaskId = await taskManager.RegisterDistributedTaskAsync(
                dataSourceOptions,
                projectionOptions,
                null,
                taskTimeout
                );

            //merge starts here
            var mergeOptions = new MergeWorkerOptionsDictionary(
                "contactMoviesFinal", // tableName
                "contactMovies",      // prefix
                storageTimeout,       // timeToLive
                "recommendation"      // schemaName
                );


            var mergeTaskId = await taskManager.RegisterDeferredTaskAsync(
                mergeOptions, // workerOptions
                new[]         // prerequisiteTaskIds
            {
                projectionTaskId
            },
                taskTimeout // expiresAfter
                );

            var workerOptions = new DeferredWorkerOptionsDictionary(
                typeof(MovieRecommendationWorker).AssemblyQualifiedName, // workerType
                new Dictionary <string, string>                          // options
            {
                { MovieRecommendationWorker.OptionSourceTableName, "contactMoviesFinal" },
                { MovieRecommendationWorker.OptionTargetTableName, "contactRecommendations" },
                { MovieRecommendationWorker.OptionSchemaName, "recommendation" },
                { MovieRecommendationWorker.OptionLimit, "20" }
            });


            //recommendation task
            var recommendationTaskId = await taskManager.RegisterDeferredTaskAsync(
                workerOptions, // workerOptions
                new[]          // prerequisiteTaskIds
            {
                mergeTaskId
            },
                taskTimeout // expiresAfter
                );

            //Facet storage
            var storageOptions = new DeferredWorkerOptionsDictionary(
                typeof(RecommendationFacetStorageWorker).AssemblyQualifiedName,
                new Dictionary <string, string>
            {
                { RecommendationFacetStorageWorker.OptionTableName, "contactRecommendations" },
                { RecommendationFacetStorageWorker.OptionSchemaName, "recommendation" }
            });

            var storageTask = await taskManager.RegisterDeferredTaskAsync(
                storageOptions, // workerOptions
                new[]           // prerequisiteTaskIds
            {
                recommendationTaskId
            },
                taskTimeout // expiresAfter
                );
        }