public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { _log = Sitecore.Diagnostics.LoggerFactory.GetLogger("LogFileAppender"); var name = adaptedFields.GetEntryByName("Full Name"); var contactno = adaptedFields.GetEntryByName("Contact Number"); var email = adaptedFields.GetEntryByName("Email Address"); var Age = adaptedFields.GetEntryByName("Age"); var Company = adaptedFields.GetEntryByName("Company"); var Designation = adaptedFields.GetEntryByName("Designation"); _log.Info("Writing comment to database"); HttpContext.Current.Session["Email"] = email; /// var goal = new PageEventData("My Custom Goal", Guid.Parse("{47FF654B-76B2-49EF-A6AA-C61AE6093768}")); // Tracker.Current.CurrentPage.Register(goal); LockAttemptResult <Contact> lockResult; ContactRepository contactRepository = Sitecore.Configuration.Factory.CreateObject("tracking/contactRepository", true) as ContactRepository; ContactManager contactManager = Sitecore.Configuration.Factory.CreateObject("tracking/contactManager", true) as ContactManager; var contact = Tracker.Current?.Contact; if (contact == null) { lockResult = new LockAttemptResult <Contact>(LockAttemptStatus.NotFound, null, null); contact = contactRepository.CreateContact(Sitecore.Data.ID.NewID); contact.Identifiers.AuthenticationLevel = Sitecore.Analytics.Model.AuthenticationLevel.None; contact.Identifiers.Identifier = "*****@*****.**"; contact.Identifiers.IdentificationLevel = ContactIdentificationLevel.Known; contact.System.Value = 0; contact.System.VisitCount = 0; contact.ContactSaveMode = ContactSaveMode.AlwaysSave; contactManager.FlushContactToXdb(contact); // VisitorIdentification s = new VisitorIdentification(); } else { lockResult = contactManager.TryLoadContact(contact.ContactId); contact = lockResult.Object; } if (contact != null) { var contactEmailAddresses = contact.GetFacet <IContactCommentsFacet>("Contact Details"); if (!contactEmailAddresses.CustomerDetails.Contains("Contact Details")) { contactEmailAddresses.CustomerDetails.Create("Contact Details"); contactEmailAddresses.CustomerDetails["Contact Details"].Age = "18"; contactEmailAddresses.CustomerDetails["Contact Details"].Company = "Companyemarr"; contactEmailAddresses.CustomerDetails["Contact Details"].FullName = "Designationdsddf"; contactEmailAddresses.CustomerDetails["Contact Details"].Email = "Emailaddress"; } var leaseOwner = new LeaseOwner(GetType() + Guid.NewGuid().ToString(), LeaseOwnerType.OutOfRequestWorker); contactManager.SaveAndReleaseContactToXdb(contact); } }
public virtual void Execute(ID formId, AdaptedResultList fields, object[] data) { Assert.ArgumentNotNull(formId, "formid"); Assert.ArgumentNotNull(data, "data"); try { ID sessionId = ID.Null; if ((data != null) && (data.Length > 0)) { ID.TryParse(data[0], out sessionId); } _formReposiotry.Insert(formId, fields, sessionId, ((data != null) && (data.Length > 1)) ? data[0].ToString() : null); } catch (EntityCommandExecutionException entityCommandExecutionException) { Exception innerException = entityCommandExecutionException; if (entityCommandExecutionException.InnerException != null) { innerException = entityCommandExecutionException.InnerException; } Log.Error("Save To Database failed.", innerException, innerException); throw innerException; } catch (Exception exception) { Log.Error("Save To Database failed.", exception, exception); throw; } }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { try { if (Tracker.Current == null) { return; } ID id = Sitecore.Data.ID.NewID; ID interactionId = Sitecore.Data.ID.NewID; ID contactId = Sitecore.Data.ID.NewID; // definition item for Marketing Lead var definitionId = Site.Foundation.Analytics.FoundationAnalyticsConstants.Outcomes.MarketingLeadOutcomeId; var outcome = new Sitecore.Analytics.Outcome.Model.ContactOutcome(id, definitionId, contactId) { DateTime = DateTime.UtcNow.Date, MonetaryValue = 0, InteractionId = interactionId }; Tracker.Current.RegisterContactOutcome(outcome); Log.Audit("WFFMTriggerOutcome : Outcome recorded ", this); } catch (Exception e) { Log.Error("WFFMTriggerOutcome : Exception occured while triggering outcome " + e.Message, this); } }
public void Execute(ID formid, AdaptedResultList fields, params object[] data) { string email=string.Empty; string firstName = string.Empty; string lastName = string.Empty; foreach (AdaptedControlResult field in fields) { if (field.FieldID == "{4ADF830B-CDFB-415D-AD78-0098CE32BC62}") { email = field.Value; } else if (field.FieldID == "{1DBD36AF-6438-43B6-90A6-562321E5FB20}") { firstName = field.Value; } else if (field.FieldID == "{59111201-17F6-4121-8D22-395A876FD731}") { lastName = field.Value; } } var contact = this.contactService.CreateContact(Guid.NewGuid().ToString(), firstName, lastName, email, Sitecore.Context.Language.Name); this.dispatchService.SendTriggeredMessageToXDB(Guid.Parse("{F4319C24-BD2C-4450-93F1-32922FA4EEA4}"), contact.ContactId); }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { Assert.ArgumentNotNull(adaptedFields, "adaptedFields"); Assert.IsNotNullOrEmpty(this.ContactsLists, "Empty contact list."); //Assert.IsNotNull(this.analyticsTracker.CurrentContact, "Tracker.Current.Contact"); Log.Info("[Wheelbarrowex] Save action triggered", this); //identify the user if it is not if (this.analyticsTracker.CurrentContact.Identifiers.Identifier == null) { identifyCurrentUser(adaptedFields); } //Now Let's add the contact to the list if (!adaptedFields.IsTrueStatement(this.ExecuteWhen)) { return; } List <string> list = (from x in this.ContactsLists.Split(new char[] { ',' }) select ID.Parse(x).ToString()).ToList <string>(); using (new SecurityDisabler()) { Contact currentContact = this.analyticsTracker.CurrentContact; foreach (string current in list) { currentContact.Tags.Set("ContactLists", current); } this.contactRepository.SaveContact(currentContact, true, null, new TimeSpan?(new TimeSpan(1000L))); } }
public void Execute(ID formid, AdaptedResultList fields, params object[] data) { string email = string.Empty; string firstName = string.Empty; string lastName = string.Empty; foreach (AdaptedControlResult field in fields) { if (field.FieldID == "{4ADF830B-CDFB-415D-AD78-0098CE32BC62}") { email = field.Value; } else if (field.FieldID == "{1DBD36AF-6438-43B6-90A6-562321E5FB20}") { firstName = field.Value; } else if (field.FieldID == "{59111201-17F6-4121-8D22-395A876FD731}") { lastName = field.Value; } } var contact = this.contactService.CreateContact(Guid.NewGuid().ToString(), firstName, lastName, email, Sitecore.Context.Language.Name); this.dispatchService.SendTriggeredMessageToXDB(Guid.Parse("{F4319C24-BD2C-4450-93F1-32922FA4EEA4}"), contact.ContactId); }
/// <summary> /// Sets the properties of the entity. /// </summary> /// <param name="entity"> /// The entity. /// </param> /// <param name="fields"> /// The fields. /// </param> protected virtual void SetProperties(ICrmEntity entity, AdaptedResultList fields) { if (entity != null && fields != null) { foreach (XCrmField field in this.EntitySettings.Fields) { string value = this.GetValue(field, fields); if (value == null) { Log.Warn( "'Create crm {0}' action: the {1} field requires some more settings defined.".FormatWith( this.EntitySettings.EntityName, field.Name), this); continue; } string previouse = this.GetPropertyValue(entity, field.Name); bool allowedToEdit = fields.IsTrueStatement(field.EditMode); if (allowedToEdit) { if (this.EntitySettings.OverwriteNotEmptyField || string.IsNullOrEmpty(previouse)) { this.SetProperty( field.Name, field.AttributeType, value, entity, field.EntityReference, this.EntitySettings.EntityName, this.EntitySettings.PrimaryKey); } } if (string.Compare(value, previouse, true) != 0 || this.isCreated) { bool isUpdated = allowedToEdit && (this.EntitySettings.OverwriteNotEmptyField || string.IsNullOrEmpty(previouse)); if (isUpdated) { this.AuditUpdatedField(this.GetValueSource(field, fields), field.Name, value); } else { this.AuditSkippedField(this.GetValueSource(field, fields), field.Name, value); } } } if (this.IsAuditEnabled) { string audit = this.DumpAuditInfomration(this.GetPropertyValue(entity, this.EntitySettings.Audit)); if (!string.IsNullOrEmpty(audit)) { this.SetProperty(this.EntitySettings.Audit, this.EntitySettings.AuditAttributeType, audit, entity); } } } }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { Assert.ArgumentNotNull(adaptedFields, nameof(adaptedFields)); var requestor = new Requestor(); var fields = GetFieldsJson(adaptedFields); Task.Run(() => requestor.PostRequest(TriggerAddress, fields)); }
public void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { string FirstName = adaptedFields.GetEntryByName("FirstName").Value; string LastName = adaptedFields.GetEntryByName("LastName").Value; string Message = adaptedFields.GetEntryByName("Message").Value; string Date = adaptedFields.GetEntryByName("Date").Value; string Email = adaptedFields.GetEntryByName("Email").Value; Log.Info("New Form has been submited", this); }
/// <summary> /// Initializes a new instance of the <see cref="SetCustomCrmPropertyArgs"/> class. /// </summary> /// <param name="formId"> /// The form id. /// </param> /// <param name="fields"> /// The fields. /// </param> /// <param name="entity"> /// The entity. /// </param> public SetCustomCrmPropertyArgs(ID formId, AdaptedResultList fields, ICrmEntity entity) { Assert.ArgumentNotNull(formId, "formId"); Assert.ArgumentNotNull(fields, "fields"); Assert.ArgumentNotNull(entity, "entity"); this.FormID = formId; this.Fields = fields; this.CrmEntity = entity; }
protected virtual void CreateItemByFields(ID formid, AdaptedResultList fields) { Sitecore.Workflows.WorkflowContextStateSwitcher test = new WorkflowContextStateSwitcher(WorkflowContextState.Enabled); if (StaticSettings.MasterDatabase == null) { Log.Warn("The Create Item action : the master database is unavailable", (object)this); } TemplateItem template = StaticSettings.MasterDatabase.GetTemplate(this.Template); Error.AssertNotNull((object)template, string.Format(ResourceManager.GetString("NOT_FOUND_TEMPLATE"), (object)this.Template)); Item destination = StaticSettings.MasterDatabase.GetItem(this.Destination); Error.AssertNotNull((object)destination, string.Format(ResourceManager.GetString("NOT_FOUND_ITEM"), (object)this.Destination)); var itemName = DateTime.Today.Year.ToString("0000") + "" + DateTime.Today.Month.ToString("00") + "" + DateTime.Today.Day.ToString("00") + "" + fields.ToList()[1].Value; Item obj = ItemManager.CreateItem(itemName, destination, template.ID); NameValueCollection nameValueCollection = StringUtil.ParseNameValueCollection(this.Mapping, '|', '='); obj.Editing.BeginEdit(); foreach (AdaptedControlResult adaptedControlResult in fields) { if (nameValueCollection[adaptedControlResult.FieldID] != null) { string index = nameValueCollection[adaptedControlResult.FieldID]; if (obj.Fields[index] != null) { string str = string.Join("|", new List <string>(FieldReflectionUtil.GetAdaptedListValue(new FieldItem(StaticSettings.ContextDatabase.GetItem(adaptedControlResult.FieldID)), adaptedControlResult.Value, false)).ToArray()); //Check to see if the file being uploaded is an image, if it is then format it correctly //if (str.Contains("sitecore://master/")) //{ //todo:this will not work when using a different template // if (template.OwnFields[3].Type == "Image") // { // string[] result = str.Split('{'); // string id = result[1].Split('}').First(); // str = "<image mediaid=\"{" + id + "}\" />"; // } //} obj.Fields[index].Value = str; if (index == Sitecore.FieldIDs.DisplayName.ToString()) { obj.Name = Sitecore.Data.Items.ItemUtil.ProposeValidItemName(adaptedControlResult.Value); } } else { Log.Warn(string.Format("The Create Item action : the template does not contain field: {0}", (object)index), (object)this); } } } obj.Editing.EndEdit(); }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { HttpCookie cookie = new HttpCookie(Constants.GatedAccessCookeName) { Value = Constants.AccessGrantedCookieValue, Expires = DateTime.Now.AddDays(Utility.GetCookieLifeSpan()) }; HttpContext.Current.Response.Cookies.Add(cookie); }
public void Insert(ID formId, AdaptedResultList fields, ID sessionID, string data) { Assert.ArgumentNotNull(formId, "formId"); Assert.ArgumentNotNull(fields, "fields"); Infrastructure.Data.Form form = _formFactory.Create(formId, fields, sessionID, data); using (WebFormForMarketersDataContext webFormForMarketersDataContext = new WebFormForMarketersDataContext(ConnectionString)) { webFormForMarketersDataContext.Forms.InsertOnSubmit(form); webFormForMarketersDataContext.SubmitChanges(); } }
protected void SetCustomCrmProperties(ID formId, AdaptedResultList fields, ICrmEntity entity) { Assert.ArgumentNotNull(formId, "guid"); Assert.ArgumentNotNull(entity, "entity"); var args = new SetCustomCrmPropertyArgs(formId, fields, entity) { CanBeOverwritten = this.CanBeOverwritten, OverwriteNotEmptyField = this.EntitySettings != null ? this.EntitySettings.OverwriteNotEmptyField : false }; CorePipeline.Run("setCustomCrmProperty", args); }
/// <summary> /// Submits an email to the user who wants to reset the password on the user account. /// </summary> /// <param name="formid">The formid.</param> /// <param name="fields">The fields.</param> /// <param name="data">The data.</param> public void Execute(ID formid, AdaptedResultList fields, params object[] data) { NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); string encryptKey = HttpContext.Current.Request.QueryString["key"]; encryptKey = Uri.UnescapeDataString(encryptKey); if (string.IsNullOrEmpty(encryptKey)) { return; } string decryptKey = Crypto.DecryptTripleDES(encryptKey, EncryptKey); string[] values = decryptKey.Split('|'); string username = values[0]; string password = values[1]; string userName = string.Format("{0}\\{1}", Sitecore.Context.Domain.Name, username); MembershipUser membershipUser = Membership.GetUser(userName); // Checks that the user information is correct for the user who want's to change password if (!AuthenticationManager.Login(userName, password) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { return; } // We can continue if the information is correct if (membershipUser == null) { return; } string newPassword = form["Password"]; ICustomerManager <CustomerInfo> customerProvider = Context.Entity.Resolve <ICustomerManager <CustomerInfo> >(); CustomerInfo customerInfo = customerProvider.GetCustomerInfo(username); string email = customerInfo.Email; if (!membershipUser.ChangePassword(password, newPassword)) { return; } IMail mailProvider = Context.Entity.Resolve <IMail>(); mailProvider.SendMail(MailTemplateNamePasswordReset, new { Recipient = email }, string.Empty); }
private void identifyCurrentUser(AdaptedResultList adaptedFields) { //Select the email address from form input data var theEmail = (from x in adaptedFields where x.FieldName == EmialFieldName select x.Value).FirstOrDefault(); //Identify the user using email - U can do with name as well but here we go with the email try { Sitecore.Analytics.Tracker.Current.Session.Identify(theEmail); }catch (Exception e) { Log.Error("[Wheelbarrow] User could not be identified", this); throw e; } var contact = Sitecore.Analytics.Tracker.Current.Session.Contact; // get the personal facet var contactPersonalInfo = contact.GetFacet <Sitecore.Analytics.Model.Entities.IContactPersonalInfo>("Personal"); // set the contact's name contactPersonalInfo.FirstName = (from x in adaptedFields where x.FieldName == FirstNameFieldName select x.Value).FirstOrDefault(); //add this part if u have surname //contactPersonalInfo.Surname = (from x in adaptedFields // where x.FieldName == "Last Name" // select x.Value).FirstOrDefault(); // get the email facet var contactEmail = contact.GetFacet <Sitecore.Analytics.Model.Entities.IContactEmailAddresses>("Emails"); // Create an email if not already present. // This can be named anything, but must be the same as "Preferred" if you want // this email to show in the Experience Profiles backend. if (!contactEmail.Entries.Contains("Home")) { contactEmail.Entries.Create("Home"); } // set the email var email = contactEmail.Entries["Home"]; email.SmtpAddress = theEmail; contactEmail.Preferred = "Home"; }
/// <summary> /// Redirects to the login menu if the user exists. /// Otherwise returns an error message / exception. /// </summary> /// <param name="formid"> The formid. </param> /// <param name="fields"> The fields. </param> /// <exception cref="ValidatorException">Username or password was wrong. Please try again.</exception> protected override void CreateItemByFields(ID formid, AdaptedResultList fields) { AnalyticsUtil.AuthentificationClickedLoginButton(); NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); ICustomerManager <CustomerInfo> customerManager = Context.Entity.Resolve <ICustomerManager <CustomerInfo> >(); if (Sitecore.Context.User.IsAuthenticated) { AuthenticationManager.Logout(); customerManager.ResetCurrentUser(); } string fullNickName = Sitecore.Context.Domain.GetFullName(form["UserName"]); bool loginResult = customerManager.LogInCustomer(fullNickName, form["Password"]); if (loginResult) { AnalyticsUtil.AuthentificationUserLoginSucceeded(fullNickName); try { string loginPath = ItemUtil.GetNavigationLinkPath("Login"); if (!string.IsNullOrEmpty(loginPath)) { HttpContext.Current.Response.Redirect(loginPath); } else { if (HttpContext.Current.Request.UrlReferrer != null) { HttpContext.Current.Response.Redirect(HttpContext.Current.Request.UrlReferrer.AbsolutePath); } } } catch (NavigateLinkNotFoundException) { HttpContext.Current.Response.Redirect(LinkManager.GetItemUrl(Sitecore.Context.Item)); } } else { AnalyticsUtil.AuthentificationUserLoginFailed(fullNickName); throw new ValidatorException("Username or password was wrong. Please try again."); } }
public virtual void Execute(ID formid, AdaptedResultList fields, object[] data = null) { SecurityDisabler securityDisabler = (SecurityDisabler)null; if (!this.CheckSecurity) securityDisabler = new SecurityDisabler(); try { this.CreateItemByFields(formid, fields); } finally { if (securityDisabler != null) securityDisabler.Dispose(); } }
/// <summary> /// Submits an email to the user who wants to reset the password on the user account. /// </summary> /// <param name="formid">The formid.</param> /// <param name="fields">The fields.</param> /// <param name="data">The data.</param> public void Execute(ID formid, AdaptedResultList fields, params object[] data) { NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); string encryptKey = HttpContext.Current.Request.QueryString["key"]; encryptKey = Uri.UnescapeDataString(encryptKey); if (string.IsNullOrEmpty(encryptKey)) { return; } string decryptKey = Crypto.DecryptTripleDES(encryptKey, EncryptKey); string[] values = decryptKey.Split('|'); string username = values[0]; string password = values[1]; string userName = string.Format("{0}\\{1}", Sitecore.Context.Domain.Name, username); MembershipUser membershipUser = Membership.GetUser(userName); // Checks that the user information is correct for the user who want's to change password if (!AuthenticationManager.Login(userName, password) || string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password)) { return; } // We can continue if the information is correct if (membershipUser == null) { return; } string newPassword = form["Password"]; ICustomerManager<CustomerInfo> customerProvider = Context.Entity.Resolve<ICustomerManager<CustomerInfo>>(); CustomerInfo customerInfo = customerProvider.GetCustomerInfo(username); string email = customerInfo.Email; if (!membershipUser.ChangePassword(password, newPassword)) { return; } IMail mailProvider = Context.Entity.Resolve<IMail>(); mailProvider.SendMail(MailTemplateNamePasswordReset, new { Recipient = email }, string.Empty); }
/// <summary> /// Redirects to the login menu if the user exists. /// Otherwise returns an error message / exception. /// </summary> /// <param name="formid"> The formid. </param> /// <param name="fields"> The fields. </param> /// <exception cref="ValidatorException">Username or password was wrong. Please try again.</exception> protected override void CreateItemByFields(ID formid, AdaptedResultList fields) { AnalyticsUtil.AuthentificationClickedLoginButton(); NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); ICustomerManager<CustomerInfo> customerManager = Context.Entity.Resolve<ICustomerManager<CustomerInfo>>(); if (Sitecore.Context.User.IsAuthenticated) { AuthenticationManager.Logout(); customerManager.ResetCurrentUser(); } string fullNickName = Sitecore.Context.Domain.GetFullName(form["UserName"]); bool loginResult = customerManager. LogInCustomer(fullNickName, form["Password"]); if (loginResult) { AnalyticsUtil.AuthentificationUserLoginSucceeded(fullNickName); try { string loginPath = ItemUtil.GetNavigationLinkPath("Login"); if (!string.IsNullOrEmpty(loginPath)) { HttpContext.Current.Response.Redirect(loginPath); } else { if (HttpContext.Current.Request.UrlReferrer != null) { HttpContext.Current.Response.Redirect(HttpContext.Current.Request.UrlReferrer.AbsolutePath); } } } catch (NavigateLinkNotFoundException) { HttpContext.Current.Response.Redirect(LinkManager.GetItemUrl(Sitecore.Context.Item)); } } else { AnalyticsUtil.AuthentificationUserLoginFailed(fullNickName); throw new ValidatorException("Username or password was wrong. Please try again."); } }
public AdaptedResultList Excise(AdaptedResultList fields) { if(fields == null || fields.Count() < 1) { return fields; } List<AdaptedControlResult> adaptedControlResults = new List<AdaptedControlResult>(); foreach(AdaptedControlResult field in fields) { adaptedControlResults.Add(GetExtractValueFieldIfApplicable(field)); } return adaptedControlResults; }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { _log = Sitecore.Diagnostics.LoggerFactory.GetLogger("LogFileAppender"); var name = adaptedFields.GetEntryByName("Name"); var email = adaptedFields.GetEntryByName("Email"); var comment = adaptedFields.GetEntryByName("Comment"); _log.Info("Writing comment to database"); HttpContext.Current.Session["Email"] = email; var goal = new PageEventData("My Custom Goal", Guid.Parse("{47FF654B-76B2-49EF-A6AA-C61AE6093768}")); Tracker.Current.CurrentPage.Register(goal); var contact = Tracker.Current?.Contact; if (contact != null) { var commentCounterTag = contact.Tags.Find("CommentCounter"); if (commentCounterTag == null) { contact.Tags.Set("CommentCounter", "1"); } else { int originalValue = 0; int newValue = 0; var counter = commentCounterTag.Values.FirstOrDefault(); if (counter != null) { if (Int32.TryParse(counter.Value, out originalValue)) { newValue = originalValue + 1; contact.Tags.Remove("CommentCounter", originalValue.ToString()); contact.Tags.Set("CommentCounter", newValue.ToString()); } } if (originalValue < 10 && newValue >= 10) { contact.Extensions.SimpleValues["ContributionLevel"] = "Fanboy"; } } } }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { if (string.IsNullOrEmpty(this.Outcome) || !ID.IsID(this.Outcome)) { Log.Warn("Can't register an outcome. Outcome isn't set",this); return; } var outcomeItem = Context.Database.GetItem(new ID(this.Outcome)); if (outcomeItem == null || outcomeItem.TemplateID != Constants.OutcomeTemplateId) { Log.Warn("Can't register an outcome. Wrong outcome definition", this); return; } this.trackerService.TrackOutcome(new ID(this.Outcome)); }
private static string GetFieldsJson(AdaptedResultList adaptedFields) { var sb = new StringBuilder(); sb.Append("{"); var fieldDescriptors = new List <string>(); foreach (AdaptedControlResult adaptedField in adaptedFields) { fieldDescriptors.Add(" \"" + adaptedField.FieldName + "\" : \"" + HttpUtility.JavaScriptStringEncode(adaptedField.Value) + "\" "); } sb.Append(fieldDescriptors.Aggregate((i, j) => i + "," + j)); sb.Append("}"); return(sb.ToString()); }
public void Execute(ID formid, AdaptedResultList fields, params object[] data) { Log.Info("Sending to marketo", this); try { var firstName = fields.GetEntryByName("First name").Value; var email = fields.GetEntryByName("Email").Value; var postcode = fields.GetEntryByName("Postcode").Value; this.CreateUpdateLead(firstName, email, postcode); Log.Info("Sending to marketo succeeded", this); } catch (Exception ex) { Log.Error("Marketo Update failed", ex, this); } }
/// <summary> Updates the customer information in both Sitecore and in session </summary> /// <param name="formid"> The formid. </param> /// <param name="fields">The fields.</param> /// <param name="data">The data.</param> public void Execute(ID formid, AdaptedResultList fields, params object[] data) { if (StaticSettings.MasterDatabase == null) { Log.Warn("'Create Item' action : master database is unavailable", this); } NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, this.ProcessField); ICustomerManager <CustomerInfo> customerManager = Context.Entity.Resolve <ICustomerManager <CustomerInfo> >(); CustomerInfo customerInfo = customerManager.GetCustomerInfo(customerManager.CurrentUser.NickName); if (customerInfo == null) { return; } customerInfo.CustomerId = customerManager.CurrentUser.CustomerId; customerInfo.BillingAddress.Name = form["Name"]; customerInfo.BillingAddress.Address = form["Address"]; customerInfo.BillingAddress.Zip = form["Zip"]; customerInfo.BillingAddress.City = form["City"]; customerInfo.BillingAddress.State = form["State"]; if (!string.IsNullOrEmpty(form["Country"])) { IEntityProvider <Country> countryProvider = Context.Entity.Resolve <IEntityProvider <Country> >(); customerInfo.BillingAddress.Country = countryProvider.Get(form["Country"]); } foreach (string key in form.AllKeys) { customerInfo[key] = form[key]; } EntityHelper entityHepler = Context.Entity.Resolve <EntityHelper>(); AddressInfo targetAddressInfo = customerInfo.ShippingAddress; entityHepler.CopyPropertiesValues(customerInfo.BillingAddress, ref targetAddressInfo); customerManager.CurrentUser = customerInfo; customerManager.UpdateCustomerProfile(customerInfo); }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { if (string.IsNullOrEmpty(Level)) { Log.Error("The level of Gated Access has not been set on the Save Action - " + ActionID.ToString() + ". Please ensure it is set correct i.e. <Level>1</Level> in the parameters field", this); Level = string.Empty; } HttpCookie cookie = new HttpCookie(Utility.DefineCookieName()) { Value = Level, Expires = DateTime.Now.AddDays(Utility.GetCookieLifeSpan()) }; HttpContext.Current.Response.Cookies.Add(cookie); }
/// <summary> Updates the customer information in both Sitecore and in session </summary> /// <param name="formid"> The formid. </param> /// <param name="fields"> The fields. </param> public void Submit(ID formid, AdaptedResultList fields) { if (StaticSettings.MasterDatabase == null) { Log.Warn("'Create Item' action : master database is unavailable", this); } NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, this.ProcessField); ICustomerManager<CustomerInfo> customerManager = Context.Entity.Resolve<ICustomerManager<CustomerInfo>>(); CustomerInfo customerInfo = customerManager.GetCustomerInfo(customerManager.CurrentUser.NickName); if (customerInfo == null) { return; } customerInfo.CustomerId = customerManager.CurrentUser.CustomerId; customerInfo.BillingAddress.Name = form["Name"]; customerInfo.BillingAddress.Address = form["Address"]; customerInfo.BillingAddress.Zip = form["Zip"]; customerInfo.BillingAddress.City = form["City"]; customerInfo.BillingAddress.State = form["State"]; if (!string.IsNullOrEmpty(form["Country"])) { IEntityProvider<Country> countryProvider = Context.Entity.Resolve<IEntityProvider<Country>>(); customerInfo.BillingAddress.Country = countryProvider.Get(form["Country"]); } foreach (string key in form.AllKeys) { customerInfo[key] = form[key]; } EntityHelper entityHepler = Context.Entity.Resolve<EntityHelper>(); AddressInfo targetAddressInfo = customerInfo.ShippingAddress; entityHepler.CopyPropertiesValues(customerInfo.BillingAddress, ref targetAddressInfo); customerManager.CurrentUser = customerInfo; customerManager.UpdateCustomerProfile(customerInfo); }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { if (string.IsNullOrEmpty(this.Outcome) || !ID.IsID(this.Outcome)) { Log.Warn("Can't register an outcome. Outcome isn't set", this); return; } var outcomeItem = Context.Database.GetItem(new ID(this.Outcome)); if (outcomeItem == null || outcomeItem.TemplateID != Constants.OutcomeTemplateId) { Log.Warn("Can't register an outcome. Wrong outcome definition", this); return; } this.trackerService.TrackOutcome(new ID(this.Outcome)); }
protected virtual void CreateItemByFields(ID formid, AdaptedResultList fields) { Sitecore.Workflows.WorkflowContextStateSwitcher test = new WorkflowContextStateSwitcher(WorkflowContextState.Enabled); if (StaticSettings.MasterDatabase == null) Log.Warn("The Create Item action : the master database is unavailable", (object)this); TemplateItem template = StaticSettings.MasterDatabase.GetTemplate(this.Template); Error.AssertNotNull((object)template, string.Format(ResourceManager.GetString("NOT_FOUND_TEMPLATE"), (object)this.Template)); Item destination = StaticSettings.MasterDatabase.GetItem(this.Destination); Error.AssertNotNull((object)destination, string.Format(ResourceManager.GetString("NOT_FOUND_ITEM"), (object)this.Destination)); var itemName = DateTime.Today.Year.ToString("0000") + "" + DateTime.Today.Month.ToString("00") + "" + DateTime.Today.Day.ToString("00") + "" + fields.ToList()[1].Value; Item obj = ItemManager.CreateItem(itemName, destination, template.ID); NameValueCollection nameValueCollection = StringUtil.ParseNameValueCollection(this.Mapping, '|', '='); obj.Editing.BeginEdit(); foreach (AdaptedControlResult adaptedControlResult in fields) { if (nameValueCollection[adaptedControlResult.FieldID] != null) { string index = nameValueCollection[adaptedControlResult.FieldID]; if (obj.Fields[index] != null) { string str = string.Join("|", new List<string>(FieldReflectionUtil.GetAdaptedListValue(new FieldItem(StaticSettings.ContextDatabase.GetItem(adaptedControlResult.FieldID)), adaptedControlResult.Value, false)).ToArray()); //Check to see if the file being uploaded is an image, if it is then format it correctly //if (str.Contains("sitecore://master/")) //{ //todo:this will not work when using a different template // if (template.OwnFields[3].Type == "Image") // { // string[] result = str.Split('{'); // string id = result[1].Split('}').First(); // str = "<image mediaid=\"{" + id + "}\" />"; // } //} obj.Fields[index].Value = str; if (index == Sitecore.FieldIDs.DisplayName.ToString()) obj.Name = Sitecore.Data.Items.ItemUtil.ProposeValidItemName(adaptedControlResult.Value); } else Log.Warn(string.Format("The Create Item action : the template does not contain field: {0}", (object)index), (object)this); } } obj.Editing.EndEdit(); }
/// <summary> Fill form data to name value collection </summary> /// <param name="formData">form data to process</param> /// <param name="formFields">form fields</param> /// <param name="ps">fields processor method</param> protected internal static void FillFormData(NameValueCollection formData, AdaptedResultList formFields, ProcessField ps) { foreach (AdaptedControlResult field in formFields) { string fieldName = GetFieldName(field); if (!string.IsNullOrEmpty(fieldName)) { if (ps != null) { formData.Add(ps(fieldName, field.Value)); } else { formData.Add(fieldName, field.Value); } } } }
public virtual void Execute(ID formid, AdaptedResultList fields, object[] data = null) { SecurityDisabler securityDisabler = (SecurityDisabler)null; if (!this.CheckSecurity) { securityDisabler = new SecurityDisabler(); } try { this.CreateItemByFields(formid, fields); } finally { if (securityDisabler != null) { securityDisabler.Dispose(); } } }
/// <summary> Submitts the new password for the associated sitecore membership account </summary> /// <param name="formid">The formid.</param> /// <param name="fields">The fields.</param> /// <param name="data">The data.</param> /// <exception cref="ValidatorException">The password information provided is incorrect.</exception> public void Execute(ID formid, AdaptedResultList fields, params object[] data) { NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); if (!string.IsNullOrEmpty(form["CreatePassword"])) { ICustomerManager <CustomerInfo> customerManager = Context.Entity.Resolve <ICustomerManager <CustomerInfo> >(); string customerId = customerManager.CurrentUser.NickName; MembershipUser membershipUser = Membership.GetUser(customerId); // Checks that the user information is correct for the user who want's to change password if (AuthenticationManager.Login(customerId, form["OldPassword"]) && !string.IsNullOrEmpty(customerId) && !string.IsNullOrEmpty(form["OldPassword"])) { // We can continue if the information is correct if (membershipUser != null) { string email = customerManager.CurrentUser.Email; if (!MainUtil.IsValidEmailAddress(email)) { email = membershipUser.Email; } if (membershipUser.ChangePassword(form["OldPassword"], form["CreatePassword"])) { var param = new { Recipient = email }; IMail mailProvider = Context.Entity.Resolve <IMail>(); mailProvider.SendMail(MailTemplateNamePasswordChanged, param, string.Empty); } } } else { throw new ValidatorException("The password information provided is incorrect."); } } }
/// <summary> /// The user submitts an email to reset the password /// for the user account. /// The current password is encrypted in the email /// in order to be able to change the password. /// </summary> /// <param name="formid"> The formid. </param> /// <param name="fields"> The fields. </param> /// <param name="data">The data.</param> public void Execute(ID formid, AdaptedResultList fields, params object[] data) { NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); MembershipUser membershipUser = Membership.GetUser(Sitecore.Context.Domain.Name + @"\" + form["UserName"]); if (membershipUser != null) { string newPassword = Membership.GeneratePassword(6, 0); string oldPwd = membershipUser.ResetPassword(); newPassword = newPassword.Replace("|", string.Empty); membershipUser.ChangePassword(oldPwd, newPassword); ICustomerManager <CustomerInfo> customerProvider = Context.Entity.Resolve <ICustomerManager <CustomerInfo> >(); CustomerInfo customerInfo = customerProvider.GetCustomerInfo(form["UserName"]); string email = customerInfo.Email; if (!Utils.MainUtil.IsValidEmailAddress(email)) { email = customerInfo.Email; } string key = form["UserName"] + "|" + newPassword; string encryptKey = Crypto.EncryptTripleDES(key, "5dfkjek5"); encryptKey = Uri.EscapeDataString(encryptKey); Item newPasswordLink = Utils.ItemUtil.GetNavigationLinkItem("New Password"); string url = Utils.ItemUtil.GetNavigationLinkPath(newPasswordLink) + "?key=" + encryptKey; var param = new { Recipient = email, URL = url }; IMail mailProvider = Context.Entity.Resolve <IMail>(); mailProvider.SendMail(MailTemplateNameResetYourPassword, param, string.Empty); } // No action is performed because of the security policies. }
// Methods public void Execute(ID formid, AdaptedResultList fields, params object[] data) { Assert.ArgumentNotNull(fields, "fields"); Assert.IsNotNullOrEmpty(this.ContactsLists, "Empty contact list."); Assert.IsNotNull(Tracker.Current, "Tracker.Current"); Assert.IsNotNull(Tracker.Current.Contact, "Tracker.Current.Contact"); List<string> list = (from x in this.ContactsLists.Split(new char[] { ',' }) select ID.Parse(x).ToString()).ToList<string>(); using (new SecurityDisabler()) { Sitecore.Analytics.Tracking.Contact contact = Tracker.Current.Contact; var c = new XdbContactId(contact.ContactId); var recipientRepository = new XdbRecipientRepository(); recipientRepository.UpdateRecipientEmail(c, fields.GetEntryByID(ID.Parse(this.EmailField)).Value); // new code ClientApi.UpdateSubscriptions(c, list.ToArray(), new string[] {}, Factory.Instance.GetManagerRoots().First().InnerItem.ID.ToString(), this.SendConfirmation); } }
/// <summary> /// Gets the value. /// </summary> /// <param name="field"> /// The field. /// </param> /// <param name="list"> /// The list. /// </param> /// <returns> /// The get value. /// </returns> protected string GetValue(XCrmField field, AdaptedResultList list) { if (field != null && list != null) { switch ((Core.Data.ValueFromType)field.UseValueType) { case Core.Data.ValueFromType.FromForm: AdaptedControlResult formField = list.GetEntryByID(field.FormValueFrom); if (formField != null) { return(formField.Value); } break; case Core.Data.ValueFromType.FromCrm: case Core.Data.ValueFromType.Manual: return(field.CrmValue); case Core.Data.ValueFromType.PreviousAction: dynamic contextCallWorkAround = this; if (contextCallWorkAround.Context != null && contextCallWorkAround.Context.Parameters.ContainsKey(field.CrmValue)) { var result = (FormsCrmEntity)contextCallWorkAround.Context.Parameters[field.CrmValue]; if (result != null) { field.EntityReference = result.Name; return(result.ID == Guid.Empty ? null : result.ID.ToString()); } } break; } } return(null); }
/// <summary> Submitts the new password for the associated sitecore membership account </summary> /// <param name="formid"> The formid. </param> /// <param name="fields"> The fields. </param> /// <exception cref="ValidatorException">The password information provided is incorrect.</exception> public void Submit(ID formid, AdaptedResultList fields) { NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); if (!string.IsNullOrEmpty(form["CreatePassword"])) { ICustomerManager<CustomerInfo> customerManager = Context.Entity.Resolve<ICustomerManager<CustomerInfo>>(); string customerId = customerManager.CurrentUser.NickName; MembershipUser membershipUser = Membership.GetUser(customerId); // Checks that the user information is correct for the user who want's to change password if (AuthenticationManager.Login(customerId, form["OldPassword"]) && !string.IsNullOrEmpty(customerId) && !string.IsNullOrEmpty(form["OldPassword"])) { // We can continue if the information is correct if (membershipUser != null) { string email = customerManager.CurrentUser.Email; if (!MainUtil.IsValidEmailAddress(email)) { email = membershipUser.Email; } if (membershipUser.ChangePassword(form["OldPassword"], form["CreatePassword"])) { var param = new { Recipient = email }; IMail mailProvider = Context.Entity.Resolve<IMail>(); mailProvider.SendMail(MailTemplateNamePasswordChanged, param, string.Empty); } } } else { throw new ValidatorException("The password information provided is incorrect."); } } }
/// <summary> /// The user submitts an email to reset the password /// for the user account. /// The current password is encrypted in the email /// in order to be able to change the password. /// </summary> /// <param name="formid"> The formid. </param> /// <param name="fields"> The fields. </param> public void Submit(ID formid, AdaptedResultList fields) { NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, null); MembershipUser membershipUser = Membership.GetUser(Sitecore.Context.Domain.Name + @"\" + form["UserName"]); if (membershipUser != null) { string newPassword = Membership.GeneratePassword(6, 0); string oldPwd = membershipUser.ResetPassword(); newPassword = newPassword.Replace("|", string.Empty); membershipUser.ChangePassword(oldPwd, newPassword); ICustomerManager<CustomerInfo> customerProvider = Context.Entity.Resolve<ICustomerManager<CustomerInfo>>(); CustomerInfo customerInfo = customerProvider.GetCustomerInfo(form["UserName"]); string email = customerInfo.Email; if (!Utils.MainUtil.IsValidEmailAddress(email)) { email = customerInfo.Email; } string key = form["UserName"] + "|" + newPassword; string encryptKey = Crypto.EncryptTripleDES(key, "5dfkjek5"); encryptKey = Uri.EscapeDataString(encryptKey); Item newPasswordLink = Utils.ItemUtil.GetNavigationLinkItem("New Password"); string url = Utils.ItemUtil.GetNavigationLinkPath(newPasswordLink) + "?key=" + encryptKey; var param = new { Recipient = email, URL = url }; IMail mailProvider = Context.Entity.Resolve<IMail>(); mailProvider.SendMail(MailTemplateNameResetYourPassword, param, string.Empty); } // No action is performed because of the security policies. }
public override void Execute(ID formId, AdaptedResultList adaptedFields, ActionCallContext actionCallContext = null, params object[] data) { if (!adaptedFields.IsTrueStatement(ExecuteWhen)) { return; } var lists = ContactsLists.Split(',').Select(x => ID.Parse(x).ToString()).ToArray(); using (new SecurityDisabler()) { Contact currentContact = _analyticsTracker.CurrentContact; if (currentContact.Identifiers.IdentificationLevel != ContactIdentificationLevel.Known) { var emailAddresses = currentContact.GetFacet <Sitecore.Analytics.Model.Entities.IContactEmailAddresses>("Emails"); if (emailAddresses.Entries.Contains("Preferred")) { var email = emailAddresses.Entries["Preferred"]; _analyticsTracker.Current.Session.Identify(email.SmtpAddress); } } // //var recipientId = new Sitecore.Modules.EmailCampaign.Xdb.XdbContactId(currentContact.ContactId); // var rootList = (Sitecore.Context.ContentDatabase ?? Sitecore.Context.Database).GetItem(RootListPath); //Assert.IsNotNull(rootList, "Empty root list."); // var managerRootId = (rootList[ManagerRootsFieldName] ?? string.Empty).Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries).FirstOrDefault(); // Assert.IsNotNullOrEmpty(managerRootId, "Empty manager root id."); // Log.Info($"AddContactToContactList [{currentContact.ContactId}, {ContactsLists}, {managerRootId}]", this); // ClientApi.UpdateSubscriptions(recipientId, lists, new string[] { }, managerRootId, false); } }
internal Infrastructure.Data.Form Create(ID formId, AdaptedResultList fields, ID sessionID, string data) { Assert.ArgumentNotNull(formId, "formId"); Assert.ArgumentNotNull(fields, "fields"); Infrastructure.Data.Form form = new Infrastructure.Data.Form { Id = Guid.NewGuid(), FormItemId = formId.Guid, SessionId = sessionID.ToGuid(), Data = data, StorageName = string.Empty, Timestamp = DateTime.Now }; foreach (AdaptedControlResult adaptedControlResult in fields) { Infrastructure.Data.Field field = _fieldFactory.Create(adaptedControlResult); form.Fields.Add(field); } return(form); }
internal Infrastructure.Data.Form Create(ID formId, AdaptedResultList fields, ID sessionID, string data) { Assert.ArgumentNotNull(formId, "formId"); Assert.ArgumentNotNull(fields, "fields"); Infrastructure.Data.Form form = new Infrastructure.Data.Form { Id = Guid.NewGuid(), FormItemId = formId.Guid, SessionId = sessionID.ToGuid(), Data = data, StorageName = string.Empty, Timestamp = DateTime.Now }; foreach (AdaptedControlResult adaptedControlResult in fields) { Infrastructure.Data.Field field = _fieldFactory.Create(adaptedControlResult); form.Fields.Add(field); } return form; }
/// <summary> /// The get value source. /// </summary> /// <param name="field"> /// The field. /// </param> /// <param name="list"> /// The list. /// </param> /// <returns> /// The get value source. /// </returns> private string GetValueSource(XCrmField field, AdaptedResultList list) { switch ((Core.Data.ValueFromType)field.UseValueType) { case Core.Data.ValueFromType.FromForm: AdaptedControlResult formField = list.GetEntryByID(field.FormValueFrom); if (formField != null) { return(formField.FieldName); } break; case Core.Data.ValueFromType.FromCrm: return("crm"); case Core.Data.ValueFromType.Manual: return("manual"); case Core.Data.ValueFromType.PreviousAction: FormItem form = this.CurrentForm; if (form != null) { IActionItem action = DependenciesManager.ActionExecutor.GetAcitonByUniqId(form, field.CrmValue, true); if (action != null) { return("previous action: {0}".FormatWith(action.DisplayName)); } } return("previous action: {0}".FormatWith(field.CrmValue)); } return(string.Empty); }
public virtual void Submit(ID formid, AdaptedResultList fields) { this.Execute(formid, fields, (object[])null); }
/// <summary> /// Submits the specified formid. /// </summary> /// <param name="formid">The formid.</param> /// <param name="fields">The fields.</param> public void Submit(ID formid, AdaptedResultList fields) { if (StaticSettings.MasterDatabase == null) { Log.Warn("'Create Item' action : master database is unavailable", this); } NameValueCollection form = new NameValueCollection(); ActionHelper.FillFormData(form, fields, this.ProcessField); // If username and password was given, create a user. if (string.IsNullOrEmpty(form["Email"]) || string.IsNullOrEmpty(form["Password"])) { return; } string name = form["Email"].Trim(); string password = form["Password"]; string email = form["Email"]; string fullNickName = Sitecore.Context.Domain.GetFullName(name); ICustomerManager<CustomerInfo> customerManager = Context.Entity.Resolve<ICustomerManager<CustomerInfo>>(); CustomerInfo customerInfo = customerManager.CreateCustomerAccount(fullNickName, password, email); if (customerInfo == null) { AnalyticsUtil.AuthentificationAccountCreationFailed(); return; } foreach (string key in form.AllKeys) { customerInfo[key] = form[key]; } customerInfo.BillingAddress.Name = form["Name"]; customerInfo.BillingAddress.Address = form["Address"]; customerInfo.BillingAddress.Zip = form["Zip"]; customerInfo.BillingAddress.City = form["City"]; customerInfo.BillingAddress.State = form["State"]; if (!string.IsNullOrEmpty(form["Country"])) { IEntityProvider<Country> countryProvider = Context.Entity.Resolve<IEntityProvider<Country>>(); customerInfo.BillingAddress.Country = countryProvider.Get(form["Country"]); } if (form["HideThisSection"] == "1") { customerInfo.ShippingAddress.Name = form["Name"]; customerInfo.ShippingAddress.Address = form["Address"]; customerInfo.ShippingAddress.Zip = form["Zip"]; customerInfo.ShippingAddress.City = form["City"]; customerInfo.ShippingAddress.State = form["State"]; if (!string.IsNullOrEmpty(form["ShippingCountry"])) { IEntityProvider<Country> countryProvider = Context.Entity.Resolve<IEntityProvider<Country>>(); customerInfo.ShippingAddress.Country = countryProvider.Get(form["ShippingCountry"]); } } else { EntityHelper entityHepler = Context.Entity.Resolve<EntityHelper>(); AddressInfo targetAddressInfo = customerInfo.ShippingAddress; entityHepler.CopyPropertiesValues(customerInfo.BillingAddress, ref targetAddressInfo); } customerManager.UpdateCustomerProfile(customerInfo); customerManager.CurrentUser = customerInfo; AnalyticsUtil.AuthentificationAccountCreated(); }
public void Submit(ID formid, AdaptedResultList fields) { Execute(formid, fields, null); }
/// <summary> /// Executes the specified formid. /// </summary> /// <param name="formid">The formid.</param> /// <param name="fields">The fields.</param> /// <param name="data">The data.</param> public override void Execute(ID formid, AdaptedResultList fields, object[] data) { AnalyticsUtil.AuthentificationClickedLoginButton(); base.Execute(formid, fields, data); }
/// <summary> /// Adds CustomerInfo, Shippingdetails and Billingdetails into the ShoppingCart instance /// Also updates the CustomerInfo session /// </summary> /// <param name="formid">The formid.</param> /// <param name="fields">The fields.</param> /// <param name="data">The data.</param> /// <exception cref="ValidatorException">Throws <c>ValidatorException</c> in a customer is already exists.</exception> public void Execute(ID formid, AdaptedResultList fields, params object[] data) { AnalyticsUtil.CheckoutNext(); NameValueCollection orderInfo = new NameValueCollection(); ActionHelper.FillFormData(orderInfo, fields, this.FillOrderInfo); bool isNewUser = false; ICustomerManager<CustomerInfo> customerManager = Context.Entity.Resolve<ICustomerManager<CustomerInfo>>(); CustomerInfo customerInfo; if (orderInfo["HideCreateUserSection"] == "1" && !string.IsNullOrEmpty(orderInfo["Password"]) && !Sitecore.Context.User.IsAuthenticated) { try { string fullNickName = Sitecore.Context.Domain.GetFullName(orderInfo["Email"]); customerInfo = customerManager.CreateCustomerAccount(fullNickName, orderInfo["Password"], orderInfo["Email"]); } catch (MembershipCreateUserException ex) { Log.Error("Unable to create a customer account.", ex, this); throw new ValidatorException(ex.Message, ex); } isNewUser = true; } else { customerInfo = customerManager.CurrentUser; } Assert.IsNotNull(customerInfo, "Cannot create user"); foreach (string key in orderInfo.AllKeys) { customerInfo[key] = orderInfo[key]; } customerInfo.BillingAddress.Name = orderInfo["Name"]; customerInfo.BillingAddress.Address = orderInfo["Address"]; customerInfo.BillingAddress.Zip = orderInfo["Zip"]; customerInfo.BillingAddress.City = orderInfo["City"]; customerInfo.BillingAddress.State = orderInfo["State"]; customerInfo.Email = orderInfo["Email"]; // Find country. if (!string.IsNullOrEmpty(orderInfo["Country"])) { IEntityProvider<Country> countryProvider = Context.Entity.Resolve<IEntityProvider<Country>>(); customerInfo.BillingAddress.Country = countryProvider.Get(orderInfo["Country"]); } // If shipping checkbox is checked if (orderInfo["HideThisSection"] == "1") { customerInfo.ShippingAddress.Name = orderInfo["ShippingName"]; customerInfo.ShippingAddress.Address = orderInfo["ShippingAddress"]; customerInfo.ShippingAddress.Zip = orderInfo["ShippingZip"]; customerInfo.ShippingAddress.City = orderInfo["ShippingCity"]; customerInfo.ShippingAddress.State = orderInfo["ShippingState"]; if (!string.IsNullOrEmpty(orderInfo["ShippingCountry"])) { IEntityProvider<Country> countryProvider = Context.Entity.Resolve<IEntityProvider<Country>>(); customerInfo.ShippingAddress.Country = countryProvider.Get(orderInfo["ShippingCountry"]); } } else { EntityHelper entityHepler = Context.Entity.Resolve<EntityHelper>(); AddressInfo targetAddressInfo = customerInfo.ShippingAddress; entityHepler.CopyPropertiesValues(customerInfo.BillingAddress, ref targetAddressInfo); } ShoppingCart shoppingCart = Context.Entity.GetInstance<ShoppingCart>(); shoppingCart.CustomerInfo = customerInfo; IEntityProvider<NotificationOption> notificationProvider = Context.Entity.Resolve<IEntityProvider<NotificationOption>>(); Assert.IsNotNull(notificationProvider, "Notification options provider is null"); shoppingCart.NotificationOption = notificationProvider.Get("Email"); shoppingCart.NotificationOptionValue = orderInfo["Email"]; if (isNewUser) { customerManager.UpdateCustomerProfile(customerInfo); } customerManager.CurrentUser = customerInfo; Context.Entity.SetInstance(shoppingCart); // Indicates that the form has been filled out and that it should be initialized if the user returnes to this page. ICheckOut checkOut = Context.Entity.GetInstance<ICheckOut>(); if (checkOut is CheckOut) { ((CheckOut)checkOut).HasOtherShippingAddressBeenChecked = orderInfo["HideThisSection"] == "1"; } Context.Entity.SetInstance(checkOut); ItemUtil.RedirectToNavigationLink(NavigationLinkNext, false); }
private AdaptedResultList ExciseFields(AdaptedResultList fields) { IWFFMFieldValuesExcisor excisor = WFFMFieldValuesExcisor.CreateNewWFFMFieldValuesExcisor(FieldsToExcise); return excisor.Excise(fields); }
public override void Execute(ID formId, AdaptedResultList fields, object[] data) { base.Execute(formId, ExciseFields(fields), data); }