public IEnumerable <SubmittedOrderOutcome> GetSubmittedOrderOutcomes(double?pastDaysAmount) { var submittedOrderOutcomes = new List <SubmittedOrderOutcome>(); using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { var fullUserName = Sitecore.Context.GetUserName(); var domainStrip = fullUserName.Split('\\'); var userName = domainStrip.Count() > 1 ? domainStrip[1] : domainStrip[0]; var contactReference = new IdentifiedContactReference("username", userName); 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 <Contact>(contactReference, new ContactExpandOptions(contactFacets.ToArray()) { Interactions = new RelatedInteractionsExpandOptions(interactionFacets.ToArray()) { EndDateTime = DateTime.MaxValue, StartDateTime = DateTime.MinValue } }); if (contact != null) { foreach (var interaction in contact.Interactions) { var submittedOrderEvents = interaction.Events.OfType <SubmittedOrderOutcome>().OrderBy(ev => ev.Timestamp).ToList(); if (pastDaysAmount.HasValue) { submittedOrderEvents = submittedOrderEvents.Where(ev => ev.Timestamp > DateTime.Now.AddDays(-(pastDaysAmount.Value))).ToList(); } submittedOrderOutcomes.AddRange(submittedOrderEvents); } } } return(submittedOrderOutcomes); }
public bool getInteractionFacets(Guid contactId, string chatId, string questionId, string answerId) { using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { try { //Contact reference from ID var reference = new Sitecore.XConnect.ContactReference(contactId); // Retrieve contact var results = client.Get <Contact>(reference, new Sitecore.XConnect.ContactExpandOptions() { Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions(ChatBotAnalytics.DefaultFacetKey) { } }); var interactionFacet = results?.Interactions.Where(x => x.GetFacet <ChatBotAnalytics>()?.ChatId == chatId && x.GetFacet <ChatBotAnalytics>()?.Question == questionId && x.GetFacet <ChatBotAnalytics>()?.Answer == answerId); if (interactionFacet != null && interactionFacet.Count() > 0) { return(true); } } catch (XdbExecutionException ex) { // Manage exceptions } } return(false); }
public void RecordAnalytics(string[] contactDetails, string channel = null, string goalId = null, string chatId = null, string questionId = null, string answerId = null) { using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { try { Contact contact = null, existingContact = null; //// Retrieve contact existingContact = client.Get <Contact>(new IdentifiedContactReference(contactDetails[0], contactDetails[1]), new ContactExpandOptions()); if (existingContact != null) { contact = existingContact; } else { contact = new Contact(new ContactIdentifier(contactDetails[0], contactDetails[1], ContactIdentifierType.Known)); client.AddContact(contact); } if (contact != null) { var result = getInteractionFacets(contact.Id.GetValueOrDefault(), chatId, questionId, answerId); if (!result && !String.IsNullOrEmpty(answerId)) { var channelId = Guid.Parse(channel); string userAgent = HttpContext.Current.Request.UserAgent; Interaction interaction = new Interaction(contact, InteractionInitiator.Brand, channelId, userAgent); ChatBotAnalytics CBData = new ChatBotAnalytics() { ChatId = chatId, Question = questionId, Answer = answerId }; client.SetFacet <ChatBotAnalytics>(interaction, ChatBotAnalytics.DefaultFacetKey, CBData); var offlineGoal = Guid.Parse(goalId); var xConnectEvent = new Goal(offlineGoal, DateTime.UtcNow); interaction.Events.Add(xConnectEvent); client.AddInteraction(interaction); client.Submit(); } } } catch (Exception ex) { Log.Info(ex.ToString(), this); } } }
public Sitecore.XConnect.Contact GetContact(string email) { try { using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { try { if (IsContactInSession(email)) { var reference = new Sitecore.XConnect.ContactReference(Tracker.Current.Session.Contact.ContactId); var contact = client.Get(reference, new Sitecore.XConnect.ContactExpandOptions() { }); return(contact); } // Retrieve contact Sitecore.XConnect.Contact existingContact = client.Get(new IdentifiedContactReference("hubspotFormUser", email), new Sitecore.XConnect.ContactExpandOptions(ScoreFacet.DefaultFacetKey, ScoreNameFacet.DefaultFacetKey, PersonalInformation.DefaultFacetKey, EmailAddressList.DefaultFacetKey)); if (existingContact != null) { return(existingContact); } return(null); } catch (XdbExecutionException) { return(null); } } } catch (Exception ex) { Sitecore.Diagnostics.Log.Error("Error updating contact score facet with the email:" + email, ex, this); return(null); } }
public void RegisterGoal(Guid channelID, Guid goalID, string userAgent) { using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { try { // var contact = new Sitecore.XConnect.Contact(); //Guid channelID = Guid.NewGuid(); //string userAgent = "Sample User Agent"; //string globalCookie = Request.Cookies["SC_ANALYTICS_GLOBAL_COOKIE"].Value; //var reference = new IdentifiedContactReference(Sitecore.XConnect.Constants.AliasIdentifierSource, globalCookie.Split('|')[0]); string trackerID = Sitecore.Analytics.Tracker.Current.Contact.ContactId.ToString(); //var reference = new IdentifiedContactReference(Sitecore.XConnect.Constants.AliasIdentifierSource,trackerID); var reference = new IdentifiedContactReference("xDB.Tracker", trackerID); Sitecore.XConnect.Contact contact = client.Get <Sitecore.XConnect.Contact>(reference, new ContactExpandOptions() { }); if (contact == null) { contact = new Sitecore.XConnect.Contact(); } var interaction = new Sitecore.XConnect.Interaction(contact, InteractionInitiator.Brand, channelID, userAgent); // Guid goalID = Guid.Parse("{9B6DC6A2-EB41-47B5-B10F-39AC37DE214F}"); // ID of goal item var goal = new Goal(goalID, DateTime.UtcNow); goal.EngagementValue = 20; // Manually setting engagement value rather than going to defintion item interaction.Events.Add(goal); client.AddContact(contact); client.AddInteraction(interaction); client.Submit(); } catch (XdbExecutionException ex) { // Handle exception } } }
public List <ChatInfo> GetLastStoredChat(string chatId = null, string contactId = null) { List <ChatInfo> chatInfo = new List <ChatInfo>(); using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { try { //Contact reference from ID var reference = new IdentifiedContactReference(Sitecore.Analytics.XConnect.DataAccess.Constants.IdentifierSource, contactId); // Retrieve contact var results = client.Get <Contact>(reference, new Sitecore.XConnect.ContactExpandOptions() { Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions(ChatBotAnalytics.DefaultFacetKey) { } }); if (chatId != null) { var interactionFacet = results?.Interactions.Where(x => x.GetFacet <ChatBotAnalytics>()?.ChatId == chatId); if (interactionFacet != null && interactionFacet.Count() > 0) { foreach (var i in interactionFacet) { ChatBotAnalytics ipInfoFacet = i.GetFacet <ChatBotAnalytics>(ChatBotAnalytics.DefaultFacetKey); chatInfo.Add(new ChatInfo { ChatId = ipInfoFacet.ChatId, QuestionId = ipInfoFacet.Question, AnswerId = ipInfoFacet.Answer, LastModified = ipInfoFacet.LastModified.GetValueOrDefault() }); } } } chatInfo = chatInfo.GroupBy(x => x.QuestionId).Select(latest => latest.OrderByDescending(x => x.LastModified).First()).ToList(); } catch (Exception ex) { Log.Info(ex.ToString(), this); } } return(chatInfo); }
public FileContentResult ExportProfile(string startDate, string endDate) { try { List <ExperienceProfileDetail> export = new List <ExperienceProfileDetail>(); string[] paramiters = { WebVisit.DefaultFacetKey, LocaleInfo.DefaultFacetKey, IpInfo.DefaultFacetKey }; var interactionsobj = new RelatedInteractionsExpandOptions(paramiters); DateTime sdate = DateTime.Now; DateTime edate = DateTime.Now; if (!string.IsNullOrEmpty(startDate) && DateTime.TryParse(startDate, out sdate)) { interactionsobj.StartDateTime = sdate.AddDays(1).ToUniversalTime(); } else { interactionsobj.StartDateTime = DateTime.UtcNow.AddDays(-30); } if (!string.IsNullOrEmpty(endDate) && DateTime.TryParse(endDate, out edate)) { interactionsobj.EndDateTime = edate.AddDays(1).ToUniversalTime(); } else { interactionsobj.EndDateTime = DateTime.UtcNow; } interactionsobj.Limit = int.MaxValue; ExportDataResult exportResult; using (Sitecore.XConnect.Client.XConnectClient client = SitecoreXConnectClientConfiguration.GetClient()) { List <Contact> contactList = new List <Contact>(); bool includeAnonymous = false; var settingvalue = Sitecore.Configuration.Settings.GetSetting("IncludeAnonymous"); bool.TryParse(settingvalue, out includeAnonymous); var Contactsid = client.Contacts.Where(d => d.Interactions.Any(i => i.StartDateTime >= interactionsobj.StartDateTime && i.EndDateTime <= interactionsobj.EndDateTime)).AsAsyncQueryable(); if (!includeAnonymous) { Contactsid = Contactsid.Where(c => c.Identifiers.Any(t => t.IdentifierType == Sitecore.XConnect.ContactIdentifierType.Known)); } contactList = Contactsid.ToList().Result; var references = new List <IEntityReference <Sitecore.XConnect.Contact> >(); references.AddRange(contactList); var contacts = client.Get <Contact>(references, new Sitecore.XConnect.ContactExpandOptions(PersonalInformation.DefaultFacetKey) { Interactions = interactionsobj }.Expand <EmailAddressList>().Expand <AddressList>().Expand <PhoneNumberList>()); exportResult = new ExportDataResult() { Content = GenerateFileContent(contacts), FileName = GenerateFileName(interactionsobj.StartDateTime.Value, interactionsobj.EndDateTime.Value), MediaType = "application/octet-stream" }; } FileContentResult fileresult; if (exportResult != null) { fileresult = new FileContentResult(exportResult.Content, exportResult.MediaType); fileresult.FileDownloadName = exportResult.FileName; } else { fileresult = new FileContentResult(null, "application/octet-stream") { FileDownloadName = "NoData.csv" }; } return(fileresult); } catch (Exception ex) { Log.Error("ERROR IN EXPORT PROFILE GETDATA:", ex.Message); return(new FileContentResult(null, "application/octet-stream") { FileDownloadName = "NoData.csv" }); } }
public HttpResponseMessage GetContactData(string id) { if (string.IsNullOrEmpty(id)) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } try { Guid contactId = new Guid(id); using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { try { var contactReference = new ContactReference(contactId); // Get all available contact facets in current model var contactFacets = client.Model.Facets.Where(c => c.Target == EntityType.Contact).Select(x => x.Name); // Get all available interaction facets in current model var interactionFacets = client.Model.Facets.Where(c => c.Target == EntityType.Interaction).Select(x => x.Name); var contact = client.Get <Contact>(contactReference, new ContactExpandOptions(contactFacets.ToArray()) { Interactions = new RelatedInteractionsExpandOptions(interactionFacets.ToArray()) { // Get all interactions EndDateTime = DateTime.MaxValue, StartDateTime = DateTime.MinValue } }); // Serialize response // Note special XdbJsonContractResolver - mandatory for serializing xConnect entities var serializerSettings = new JsonSerializerSettings { ContractResolver = new XdbJsonContractResolver(client.Model, serializeFacets: true, serializeContactInteractions: true), Formatting = Formatting.Indented, DateTimeZoneHandling = DateTimeZoneHandling.Utc, DefaultValueHandling = DefaultValueHandling.Ignore }; string allData = JsonConvert.SerializeObject(contact, serializerSettings); var fileBytes = Encoding.Default.GetBytes(allData); var response = new HttpResponseMessage(HttpStatusCode.OK) { Content = new ByteArrayContent(fileBytes) }; response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = "ContactData.json", }; response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json"); return(response); } catch (XdbExecutionException) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } } } catch (XdbExecutionException) { return(new HttpResponseMessage(HttpStatusCode.NotFound)); } }
/// Executes the specified rule context. /// <param name="ruleContext">The rule context.</param> /// <returns> /// <c>True</c>, if the condition succeeds, otherwise <c>false</c>. /// </returns> protected override bool Execute(T ruleContext) { Assert.ArgumentNotNull((object)ruleContext, nameof(ruleContext)); Assert.IsNotNull((object)Tracker.Current, "Tracker.Current is not initialized"); Assert.IsNotNull((object)Tracker.Current.Session, "Tracker.Current.Session is not initialized"); Assert.IsNotNull((object)Tracker.Current.Session.Interaction, "Tracker.Current.Session.Interaction is not initialized"); try { this.GoalGuid = new Guid(this.GoalId); } catch { Log.Warn(string.Format("Could not convert value to guid: {0}", (object)this.GoalId), (object)this.GetType()); return(false); } try { this.PageGuid = new Guid(this.PageId); } catch { Log.Warn(string.Format("Could not convert value to guid: {0}", (object)this.PageId), (object)this.GetType()); return(false); } HttpCookie globalCookie = HttpContext.Current.Request.Cookies["sc_analytics_global_cookie"]; if (globalCookie != null) { // Find the Cookie Value string cookieValue = globalCookie.Value.Substring(0, 32); // Convert the Cookie value to Guid Guid contactid = Guid.Parse(cookieValue); using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { var reference = new Sitecore.XConnect.ContactReference(contactid); Contact contact = client.Get <Contact>(reference, new Sitecore.XConnect.ContactExpandOptions() { }); if (contact != null) { // Identify the the Known contact if (contact.IsKnown) { DateTime currentDateTime = DateTime.Now; DateTime pastDateTime = currentDateTime.AddYears(-10); //Find out if there are any interaction from past date var results = client.Get <Sitecore.XConnect.Contact>(reference, new Sitecore.XConnect.ContactExpandOptions() { Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions() { StartDateTime = pastDateTime, EndDateTime = currentDateTime, } }); if (results == null) { return(false); } else { List <Goal> goals = new List <Goal>(); foreach (var intercation in results.Interactions) { goals.AddRange(intercation.Events.OfType <Goal>().Where(c => c.ItemId == this.PageGuid && c.DefinitionId == this.GoalGuid)); } return(goals.Any()); } } } } } return(false); }
/// Executes the specified rule context. /// <param name="ruleContext">The rule context.</param> /// <returns> /// <c>True</c>, if the condition succeeds, otherwise <c>false</c>. /// </returns> protected override bool Execute(T ruleContext) { // Get the Global Cookie HttpCookie globalCookie = HttpContext.Current.Request.Cookies["sc_analytics_global_cookie"]; // Number of days which user has not logged in int value; if (!int.TryParse(this.Value, out value)) { Log.Debug(string.Format("Specified number [{0}] was not a valid Number", this.Value)); return(false); } if (globalCookie != null) { // Find the Cookie Value string cookieValue = globalCookie.Value.Substring(0, 32); // Convert the Cookie value to Guid Guid contactid = Guid.Parse(cookieValue); // Get the Contact using Golable Cookie using (Sitecore.XConnect.Client.XConnectClient client = Sitecore.XConnect.Client.Configuration.SitecoreXConnectClientConfiguration.GetClient()) { var reference = new Sitecore.XConnect.ContactReference(contactid); Contact contact = client.Get <Contact>(reference, new Sitecore.XConnect.ContactExpandOptions() { }); if (contact != null) { // Identify the the Known contact if (contact.IsKnown) { DateTime currentDateTime = DateTime.Now; DateTime pastDateTime = currentDateTime.AddDays(-value); //Find out if there are any interaction from past date var results = client.Get <Sitecore.XConnect.Contact>(reference, new Sitecore.XConnect.ContactExpandOptions() { Interactions = new Sitecore.XConnect.RelatedInteractionsExpandOptions() { StartDateTime = pastDateTime, EndDateTime = currentDateTime, } }); if (results == null) { return(true); } } } } } return(false); }