Beispiel #1
0
        protected void setData(KeyValuePair <Guid, string> keyValuePair)
        {
            // Initialize a client using the validated configuration
            using (var client = XConnectHelper.GetClient())
            {
                try
                {
                    var channelId = Guid.Parse("52B75873-4CE0-4E98-B63A-B535739E6180"); // "email newsletter" channel

                    // Create a new contact with the identifier
                    Contact knownContact = new Contact();

                    PersonalInformation personalInfoFacet = new PersonalInformation();

                    personalInfoFacet.FirstName = "Abhi" + Guid.NewGuid().ToString();
                    personalInfoFacet.LastName  = "Marwah";
                    personalInfoFacet.JobTitle  = "Sitecore Architect";
                    personalInfoFacet.Gender    = "Male";
                    personalInfoFacet.Nickname  = "Aussie";
                    client.SetFacet <PersonalInformation>(knownContact, PersonalInformation.DefaultFacetKey, personalInfoFacet);

                    EmailAddressList emails = new EmailAddressList(new EmailAddress("*****@*****.**", true), "Email");

                    client.SetFacet(knownContact, emails);


                    PageViewEvent pageView = new PageViewEvent(DateTime.Now.ToUniversalTime(), keyValuePair.Key, 1, "en");
                    pageView.ItemLanguage            = "en";
                    pageView.Duration                = new TimeSpan(3000);
                    pageView.SitecoreRenderingDevice = new SitecoreDeviceData(new Guid("{fe5d7fdf-89c0-4d99-9aa3-b5fbd009c9f3}"), "Default");
                    pageView.Url = keyValuePair.Value;


                    client.AddContact(knownContact);

                    // Create a new interaction for that contact
                    Interaction interaction = new Interaction(knownContact, InteractionInitiator.Brand, channelId, "");

                    // Add events - all interactions must have at least one event
                    interaction.Events.Add(pageView);

                    IpInfo ipInfo = new IpInfo("127.0.0.1");

                    ipInfo.BusinessName = "Sitecore Consultancy";

                    client.SetFacet <IpInfo>(interaction, IpInfo.DefaultFacetKey, ipInfo);


                    // Add the contact and interaction
                    client.AddInteraction(interaction);

                    // Submit contact and interaction - a total of two operations
                    client.Submit();
                }
                catch (XdbExecutionException ex)
                {
                    // Deal with exception
                }
            }
        }
Beispiel #2
0
        private Interaction CreateOrGetInteraction(string hashtag, Contact contact, TwitterStatus tweet, Goal goal, out bool isNewInteraction)
        {
            Interaction interaction = null;

            isNewInteraction = false;
            using (var client = XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    // Get interaction if it does exists
                    interaction = GetInteraction(hashtag, tweet, contact);
                    if (interaction != null)
                    {
                        return(interaction);
                    }

                    // Create if does not exists
                    isNewInteraction = true;

                    // Item ID of the "Twitter social community" Channel at
                    // /sitecore/system/Marketing Control Panel/Taxonomies/Channel/Online/Social community/Twitter social community
                    var channelId = Guid.Parse("{6D3D2374-AF56-44FE-B99A-20843B440B58}");
                    var userAgent = hashtag;
                    interaction = new Interaction(contact, InteractionInitiator.Brand, channelId, userAgent);

                    // Event - Page View
                    var newEvent = new PageViewEvent(tweet.CreatedDate, Guid.Empty, 1, "en")
                    {
                        DataKey = tweet.IdStr,
                        Text    = tweet.Text,
                        Url     = "https://twitter.com/statuses/" + tweet.IdStr
                    };
                    interaction.Events.Add(newEvent);

                    // Event - Goal
                    if (goal != null)
                    {
                        var newGoal = new XConnect.Goal(goal.ID.Guid, tweet.CreatedDate);
                        interaction.Events.Add(newGoal);
                    }

                    client.AddInteraction(interaction);
                    client.Submit();
                    return(interaction);
                }
                catch (XdbExecutionException ex)
                {
                    // Manage exception
                    Diagnostics.Log.Error(
                        $"[HashTagMonitor] Error creating or retrieving interaction for contact '{contact.Personal().Nickname}' with hashtag '{hashtag}' and tweetId '{tweet.IdStr}'",
                        ex, GetType());
                }
            }

            return(interaction);
        }
Beispiel #3
0
        private static void VisitPage(Interaction interaction)
        {
            /// Visit page
            var           homeItemId = Guid.Parse("110d559f-dea5-42ea-9c1c-8a5df7e70ef9");
            PageViewEvent pageView   = new PageViewEvent(DateTime.UtcNow, homeItemId, 1, "en")
            {
                Duration = new TimeSpan(0, 0, 30),
                Url      = "/"
            };

            interaction.Events.Add(pageView);
        }
Beispiel #4
0
        private static void AddInteraction(XConnectClient client, Contact contact)
        {
            // Create a new interaction for the contact
            Guid channelId = new Guid("{1DA15267-B0DB-4BE1-B44F-E57C2EEB8A6B}");

            string userAgent = HttpContext.Current.Request.UserAgent;

            Interaction webInteraction = new Interaction(contact, InteractionInitiator.Contact, channelId, userAgent);

            // Create a new web visit facet model
            var webVisitFacet = new WebVisit();

            // Populate data about the web visit
            HttpBrowserCapabilities browser = HttpContext.Current.Request.Browser;

            webVisitFacet.Browser = new BrowserData()
            {
                BrowserMajorName = browser.Browser, BrowserMinorName = browser.Platform, BrowserVersion = browser.Version
            };
            webVisitFacet.Language        = Sitecore.Context.Language.Name;
            webVisitFacet.OperatingSystem = new OperatingSystemData()
            {
                Name = Environment.OSVersion.VersionString, MajorVersion = Environment.OSVersion.Version.Major.ToString(), MinorVersion = Environment.OSVersion.Version.Minor.ToString()
            };
            webVisitFacet.Referrer = HttpContext.Current.Request.UrlReferrer != null ? HttpContext.Current.Request.UrlReferrer.AbsoluteUri : string.Empty;
            webVisitFacet.Screen   = new ScreenData()
            {
                ScreenHeight = browser.ScreenPixelsHeight, ScreenWidth = browser.ScreenPixelsWidth
            };
            webVisitFacet.SearchKeywords = "wechat";
            webVisitFacet.SiteName       = Sitecore.Context.Site.Name;

            var item = Sitecore.Context.Item;

            //page view
            PageViewEvent pageView = new PageViewEvent(DateTime.UtcNow, item.ID.ToGuid(), item.Version.Number, item.Language.Name)
            {
                Duration = new TimeSpan(0, 0, 30),
                Url      = HttpContext.Current.Request.Url.PathAndQuery
            };

            webInteraction.Events.Add(pageView);

            // Set web visit facet on interaction
            client.SetWebVisit(webInteraction, webVisitFacet);

            // Add interaction
            client.AddInteraction(webInteraction);
        }
Beispiel #5
0
        public static void AddGoal(Guid goalId)
        {
            using (var client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                var newContact = new Contact();
                client.AddContact(newContact);

                var channelId   = Tracker.Current.Interaction.ChannelId;
                var userAgent   = Tracker.Current.Interaction.UserAgent;
                var interaction = new Interaction(newContact, InteractionInitiator.Brand, channelId, userAgent);

                var excludesUrlParts = new[] { "/api/" };
                var pages            = Tracker.Current.Interaction.Pages.Reverse();
                var currentPage      = pages.FirstOrDefault(page => page?.Url?.Path != null && !excludesUrlParts.Any(s => page.Url.Path.Contains(s)));

                if (currentPage != null)
                {
                    var pageViewEvent = new PageViewEvent(DateTime.UtcNow, currentPage.Item.Id, currentPage.Item.Version, currentPage.Item.Language)
                    {
                        Url = currentPage.Url?.Path
                    };

                    interaction.Events.Add(pageViewEvent);

                    var goalFromTracker = Tracker.MarketingDefinitions.Goals[goalId];

                    var goalFromXConnect = new Goal(goalId, DateTime.UtcNow)
                    {
                        EngagementValue = goalFromTracker.EngagementValuePoints,
                        ParentEventId   = pageViewEvent.Id
                    };

                    interaction.Events.Add(goalFromXConnect);

                    client.AddInteraction(interaction);

                    client.Submit();
                }
            }
        }
Beispiel #6
0
        /// <summary>
        /// This method adds the contact details in xdb - right now we are passing hardcoded data.
        /// </summary>
        public void AddContactDetails()
        {
            using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    // New anonymous contact
                    //test
                    var newContact = new Sitecore.XConnect.Contact();
                    client.AddContact(newContact);

                    Guid   channelId = Guid.Parse("86c7467a-d019-460d-9fa9-85d6d5d77fc4"); // Replace with real channel ID GUID
                    string userAgent = "Astha Prasad";

                    // Interaction
                    var interaction = new Interaction(newContact, InteractionInitiator.Brand, channelId, userAgent);

                    var fakeItemID = Guid.Parse("5746c4f3-7e16-40d9-ba1d-14c70875724c"); // Replace with real item ID

                    Sitecore.XConnect.Collection.Model.PageViewEvent pageView = new PageViewEvent(DateTime.UtcNow, fakeItemID, 3, "en")
                    {
                        Duration = new TimeSpan(0, 0, 30),
                        Url      = "/test/url/test/url?query=testing"
                    };

                    interaction.Events.Add(pageView);

                    client.AddInteraction(interaction);

                    client.Submit();
                }
                catch (XdbExecutionException ex)
                {
                    // Handle exception
                }
            }
        }
        // if addWebVisit=true, fake webvisit will be created for interaction
        // it is needed if you want to populate interaction country (to use contacts country for ML data model)
        public async Task <bool> Add(Customer purchase, bool addWebVisit = false)
        {
            using (XConnectClient client = SitecoreXConnectClientConfiguration.GetClient())
            {
                try
                {
                    IdentifiedContactReference reference = new IdentifiedContactReference(IdentificationSource, purchase.CustomerId.ToString());
                    var customer = await client.GetAsync(
                        reference,
                        new ContactExpandOptions(
                            PersonalInformation.DefaultFacetKey,
                            EmailAddressList.DefaultFacetKey,
                            ContactBehaviorProfile.DefaultFacetKey
                            )
                    {
                        Interactions = new RelatedInteractionsExpandOptions
                        {
                            StartDateTime = DateTime.MinValue,
                            EndDateTime   = DateTime.MaxValue,
                            Limit         = 100
                        }
                    }
                        );

                    if (customer == null)
                    {
                        var email = "demo" + Guid.NewGuid().ToString("N") + "@gmail.com";

                        customer = new Contact(new ContactIdentifier(IdentificationSource, purchase.CustomerId.ToString(), ContactIdentifierType.Known));

                        var preferredEmail = new EmailAddress(email, true);
                        var emails         = new EmailAddressList(preferredEmail, "Work");

                        client.AddContact(customer);
                        client.SetEmails(customer, emails);

                        var identifierEmail = new ContactIdentifier(IdentificationSourceEmail, email, ContactIdentifierType.Known);

                        client.AddContactIdentifier(customer, identifierEmail);
                        client.Submit();
                    }

                    var channel     = Guid.Parse("DF9900DE-61DD-47BF-9628-058E78EF05C6");
                    var interaction = new Interaction(customer, InteractionInitiator.Brand, channel, "demo app");

                    if (addWebVisit)
                    {
                        //Add Device profile
                        DeviceProfile newDeviceProfile = new DeviceProfile(Guid.NewGuid())
                        {
                            LastKnownContact = customer
                        };
                        client.AddDeviceProfile(newDeviceProfile);
                        interaction.DeviceProfile = newDeviceProfile;

                        //Add fake Ip info
                        IpInfo fakeIpInfo = new IpInfo("127.0.0.1")
                        {
                            BusinessName = "Home"
                        };
                        var country = purchase.Invoices.FirstOrDefault(x => !string.IsNullOrEmpty(x.Country))?.Country;
                        fakeIpInfo.Country = GetCountryCodeByName(country);

                        client.SetFacet(interaction, IpInfo.DefaultFacetKey, fakeIpInfo);

                        // Add fake webvisit
                        // Create a new web visit facet model
                        var webVisitFacet = new WebVisit
                        {
                            Browser =
                                new BrowserData
                            {
                                BrowserMajorName = "Chrome",
                                BrowserMinorName = "Desktop",
                                BrowserVersion   = "22.0"
                            },
                            Language        = "en",
                            OperatingSystem =
                                new OperatingSystemData {
                                Name = "Windows", MajorVersion = "10", MinorVersion = "4"
                            },
                            Referrer = "https://www.google.com",
                            Screen   = new ScreenData {
                                ScreenHeight = 1080, ScreenWidth = 685
                            },
                            SearchKeywords = "sitecore",
                            SiteName       = "website"
                        };

                        // Populate data about the web visit

                        var itemId      = Guid.Parse("110D559F-DEA5-42EA-9C1C-8A5DF7E70EF9");
                        var itemVersion = 1;

                        // First page view
                        var datetime = purchase.Invoices.FirstOrDefault() == null
                            ? DateTime.Now
                            : purchase.Invoices.First().TimeStamp.ToUniversalTime();
                        PageViewEvent pageView = new PageViewEvent(datetime,
                                                                   itemId, itemVersion, "en")
                        {
                            ItemLanguage = "en",
                            Duration     = new TimeSpan(3000),
                            Url          = "/home"
                        };
                        // client.SetFacet(interaction, WebVisit.DefaultFacetKey, webVisitFacet);

                        interaction.Events.Add(pageView);
                        client.SetWebVisit(interaction, webVisitFacet);
                    }



                    foreach (var invoice in purchase.Invoices)
                    {
                        var outcome = new PurchaseOutcome(PurchaseOutcome.PurchaseEventDefinitionId, invoice.TimeStamp, invoice.Currency, invoice.Price, invoice.Number, invoice.Quantity, purchase.CustomerId, invoice.StockCode);
                        interaction.Events.Add(outcome);
                    }

                    client.AddInteraction(interaction);

                    await client.SubmitAsync();

                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    Log.Error(ex.Message, ex, this);
                    return(false);
                }
            }
        }
        protected async Task <bool> CreateContact(string source, string identifier, string firstName, string lastName,
                                                  string email)
        {
            using (XConnectClient client = GetClient())
            {
                try
                {
                    IdentifiedContactReference reference = new IdentifiedContactReference(source, identifier);


                    var contactTask = client.GetAsync <Contact>(
                        reference,
                        new ContactExpandOptions(
                            PersonalInformation.DefaultFacetKey,
                            EmailAddressList.DefaultFacetKey,
                            PhoneNumberList.DefaultFacetKey)
                        );

                    Contact existingContact = await contactTask;

                    if (existingContact != null)
                    {
                        return(false);
                    }

                    var contactIdentifier = new[]
                    {
                        new ContactIdentifier(source, identifier, ContactIdentifierType.Known)
                    };

                    Contact contact = new Contact(contactIdentifier);

                    var personal = new PersonalInformation
                    {
                        FirstName = firstName,
                        LastName  = lastName
                    };

                    var preferredEmail = new EmailAddress(email, true);
                    var emails         = new EmailAddressList(preferredEmail, "Work email");

                    client.AddContact(contact);
                    client.SetPersonal(contact, personal);
                    client.SetEmails(contact, emails);

                    Interaction interaction = new Interaction(contact, InteractionInitiator.Brand, Guid.NewGuid(), "test");
                    var         ev          = new PageViewEvent(DateTime.UtcNow, Guid.Parse("{11111111-1111-1111-1111-111111111111}"), 1, "en");
                    interaction.Events.Add(ev);

                    client.AddInteraction(interaction);

                    await client.SubmitAsync();

                    return(true);
                }
                catch (XdbExecutionException ex)
                {
                    return(false);
                }
            }
        }
        private static void CopyEvents(Interaction source, Interaction target)
        {
            foreach (Event e in source.Events)
            {
                Event result;
                if (e is CampaignEvent ce)
                {
                    CampaignEvent newEvent = new CampaignEvent(ce.CampaignDefinitionId, ce.Timestamp);
                    result = newEvent;
                }
                else if (e is DownloadEvent de)
                {
                    DownloadEvent newEvent = new DownloadEvent(de.Timestamp, de.ItemId);
                    result = newEvent;
                }
                else if (e is Goal g)
                {
                    Goal newEvent = new Goal(g.DefinitionId, g.Timestamp);
                    result = newEvent;
                }
                else if (e is MVTestTriggered mvt)
                {
                    MVTestTriggered newEvent = new MVTestTriggered(mvt.Timestamp);
                    newEvent.Combination     = mvt.Combination;
                    newEvent.EligibleRules   = mvt.EligibleRules;
                    newEvent.ExposureTime    = mvt.ExposureTime;
                    newEvent.FirstExposure   = mvt.FirstExposure;
                    newEvent.IsSuspended     = mvt.IsSuspended;
                    newEvent.ValueAtExposure = mvt.ValueAtExposure;
                    result = newEvent;
                }
                else if (e is Outcome o)
                {
                    Outcome newEvent = new Outcome(o.DefinitionId, o.Timestamp, o.CurrencyCode, o.MonetaryValue);
                    result = newEvent;
                }
                else if (e is PageViewEvent pve)
                {
                    PageViewEvent newEvent = new PageViewEvent(
                        pve.Timestamp,
                        pve.ItemId,
                        pve.ItemVersion,
                        pve.ItemLanguage);
                    newEvent.SitecoreRenderingDevice = pve.SitecoreRenderingDevice;
                    newEvent.Url = pve.Url;
                    result       = newEvent;
                }
                else if (e is PersonalizationEvent pe)
                {
                    PersonalizationEvent newEvent = new PersonalizationEvent(pe.Timestamp);
                    newEvent.ExposedRules = pe.ExposedRules;
                    result = newEvent;
                }
                else if (e is SearchEvent se)
                {
                    SearchEvent newEvent = new SearchEvent(se.Timestamp);
                    newEvent.Keywords = se.Keywords;
                    result            = newEvent;
                }
                else if (e is BounceEvent be)
                {
                    BounceEvent newEvent = new BounceEvent(be.Timestamp);
                    newEvent.BounceReason = be.BounceReason;
                    newEvent.BounceType   = be.BounceType;
                    result = newEvent;
                }
                else if (e is DispatchFailedEvent dfe)
                {
                    DispatchFailedEvent newEvent = new DispatchFailedEvent(dfe.Timestamp);
                    newEvent.FailureReason = dfe.FailureReason;
                    result = newEvent;
                }
                else if (e is EmailClickedEvent ece)
                {
                    EmailClickedEvent newEvent = new EmailClickedEvent(ece.Timestamp);
                    newEvent.Url = ece.Url;
                    result       = newEvent;
                }
                else if (e is EmailOpenedEvent eoe)
                {
                    EmailOpenedEvent newEvent = new EmailOpenedEvent(eoe.Timestamp);
                    result = newEvent;
                }
                else if (e is EmailSentEvent ese)
                {
                    EmailSentEvent newEvent = new EmailSentEvent(ese.Timestamp);
                    result = newEvent;
                }
                else if (e is SpamComplaintEvent sce)
                {
                    SpamComplaintEvent newEvent = new SpamComplaintEvent(sce.Timestamp);
                    result = newEvent;
                }
                else if (e is UnsubscribedFromEmailEvent uee)
                {
                    UnsubscribedFromEmailEvent newEvent = new UnsubscribedFromEmailEvent(uee.Timestamp);
                    result = newEvent;
                }
                else
                {
                    result = new Event(e.DefinitionId, e.Timestamp);
                }

                // Many of the above are derived from EmailEvent, so only copy relevant properties once
                if (e is EmailEvent ee && result is EmailEvent nee)
                {
                    nee.EmailAddressHistoryEntryId = ee.EmailAddressHistoryEntryId;
                    nee.InstanceId      = ee.InstanceId;
                    nee.ManagerRootId   = ee.ManagerRootId;
                    nee.MessageId       = ee.MessageId;
                    nee.MessageLanguage = ee.MessageLanguage;
                    nee.TestValueIndex  = ee.TestValueIndex;
                }

                result.Data            = e.Data;
                result.DataKey         = e.DataKey;
                result.Duration        = e.Duration;
                result.EngagementValue = e.EngagementValue;
                result.Id            = e.Id;
                result.ParentEventId = e.ParentEventId;
                result.Text          = e.Text;
                foreach (KeyValuePair <string, string> customValue in e.CustomValues)
                {
                    result.CustomValues.Add(customValue.Key, customValue.Value);
                }

                if (result != null)
                {
                    target.Events.Add(result);
                }
            }
        }