コード例 #1
0
    void Start()
    {
        //animator = GetComponent<Animator>();

        subscriber = new Subscriber();
        subscriber.Add("ui_move_speed", (float v) => { targetSpeed = v * maxSpeed; });
        subscriber.Add("ui_move_angle", (float v) => { targetAngle = v; });
        subscriber.Add("ui_change_yaw_pitch", (float y, float p) => {
            targetYaw  += y;
            targetPitch = Mathf.Clamp(targetPitch + p, pitchMin, pitchMax);
        });
        subscriber.Add("ui_mouse_scroll", (float scroll) => {
            cameraFollowDistance *= (scroll < 0?1.3f : 1 / 1.3f);
            cameraFollowDistance  = Mathf.Clamp(cameraFollowDistance, minCameraDistance, maxCameraDistance);
        });
        subscriber.Add("ui_use_skill", (int id) => {
            if (id == 0)
            {
                grassManager.AddDisturbance(transform.position, 3, 2);
            }
            else
            {
                grassManager.AddDisturbance(transform.position, 6, 2);
            }
        });
    }
コード例 #2
0
        /// <summary>
        /// Adds a user to a list
        /// </summary>
        /// <param name="email"></param>
        /// <param name="name"></param>
        /// <param name="resubscribe">Adds the user back into the list if they have already been unsubscribed before</param>
        /// <returns>Success Status</returns>
        public static bool Subscribe(out string message, string email, string name, string listID, bool resubscribe)
        {
            createsend_dotnet.CreateSendOptions.ApiKey = Constants.CampaignMonitorAPIKey;

            message = "";
            bool       isSuccess  = false;
            Subscriber subscriber = new Subscriber(listID);
            string     result     = "";

            try
            {
                string newSubscriberID = subscriber.Add(email, name, null, resubscribe);
                isSuccess = true;
            }
            catch (CreatesendException ex)
            {
                ErrorResult error = (ErrorResult)ex.Data["ErrorResult"];
                result = error.Code + " || " + error.Message;
            }
            catch (Exception ex)
            {
                result = "-1 || An internal error occured";
            }

            message = result;

            return(isSuccess);
        }
コード例 #3
0
        public ActionResult SubscribeTour(TourShow tourShow)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    foreach (var value in ModelState.Values.ToList())
                    {
                        foreach (var error in value.Errors)
                        {
                            ModelState.AddModelError(string.Empty, error.ErrorMessage);
                        }
                    }
                    tourShow.IsTripBooked = false;
                    return(PartialView("_Coming Soon", tourShow));
                }

                tourShow.IsTripBooked = true;
                if (tourShow.MailingListID != null)
                {
                    AuthenticationDetails auth          = new ApiKeyAuthenticationDetails(ConfigurationManager.AppSettings["CampaignMonitorAPI_key"]);
                    Subscriber            objSubscriber = new Subscriber(auth, tourShow.MailingListID);
                    string newSubscriberID = objSubscriber.Add(tourShow.EmailToSubscribe.ToString(), null, null, false);
                }

                return(PartialView("_Coming Soon", tourShow));
            }
            catch (Exception e)
            {
                Elmah.ErrorSignal.FromCurrentContext().Raise(e);
                return(PartialView("_Coming Soon"));
            }
        }
コード例 #4
0
 public void AddSubscriber(object system, Action <E> eventListener)
 {
                 #if UNITY_EDITOR
     Subscriber.Add(system);
                 #endif
     gameEvent += eventListener;
 }
コード例 #5
0
        private void SendSubscriberToList(string listId, string emailField, List <SubscriberCustomField> fields)
        {
            // send subscriber to campaign monitor list using CM API
            var name  = fields.Where(f => f.Key == "fullname").FirstOrDefault();
            var email = fields.Where(f => f.Key == emailField).FirstOrDefault();

            MetadataHelper mdh = new MetadataHelper(orgService, tracer);

            fields = SharedLogic.PrettifySchemaNames(mdh, fields);

            Subscriber subscriber = new Subscriber(authDetails, listId);

            subscriber.Add(email?.Value, name?.Value, fields, false, false);
        }
コード例 #6
0
        public ActionResult HandleNewsletterSubmit(USNNewsletterFormViewModel model)
        {
            System.Threading.Thread.Sleep(1000);

            string lsReturnValue = "";

            var currentNode = Umbraco.TypedContent(model.CurrentNodeID);
            var currentPage = Umbraco.TypedContent(model.ActualPageID);

            IPublishedContent homeNode = currentPage.AncestorOrSelf(1);
            var settingsFolder         = Umbraco.TypedContent(homeNode.GetProperty("websiteConfigurationNode").Value);
            var globalSettings         = settingsFolder.Children.Where(x => x.DocumentTypeAlias == "USNGlobalSettings").First();

            if (!ModelState.IsValid)
            {
                return(JavaScript(String.Format("$(NewsletterError{0}).show();$(NewsletterError{0}).html('<div class=\"info\"><p>{1}</p></div>');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Newsletter Form General Error"))));
            }
            try
            {
                AuthenticationDetails auth = new ApiKeyAuthenticationDetails(globalSettings.GetProperty("campaignMonitorAPIKey").Value.ToString());

                string subsciberListID = "";

                if (currentNode.GetProperty("campaignMonitorSubscriberListID").Value.ToString() != String.Empty)
                {
                    subsciberListID = currentNode.GetProperty("campaignMonitorSubscriberListID").Value.ToString();
                }
                else
                {
                    subsciberListID = globalSettings.GetProperty("defaultCampaignMonitorSubscriberListID").Value.ToString();
                }

                Subscriber loSubscriber = new Subscriber(auth, subsciberListID);

                List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();

                string lsSubscriberID = loSubscriber.Add(model.Email, model.FirstName + " " + model.LastName, customFields, false);

                lsReturnValue = String.Format("<div class=\"page_component alert alert-success alert-dismissible fade in\" role=\"alert\"><div class=\"info\">{0}</div></div>", currentNode.GetProperty("submissionMessage").Value.ToString());
                return(Content(lsReturnValue));
            }
            catch (Exception ex)
            {
                return(JavaScript(String.Format("$(NewsletterError{0}).show();$(NewsletterError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Newsletter Form Signup Error"), ex.Message)));
            }
        }
コード例 #7
0
 public override WorkflowExecutionStatus Execute(Record record, RecordEventArgs e)
 {
     try
     {
         if (ValidateSettings().Any() || string.IsNullOrWhiteSpace(CampaignMonitorConfiguration.ApiKey) || string.IsNullOrWhiteSpace(CampaignMonitorConfiguration.ClientId))
         {
             return(WorkflowExecutionStatus.NotConfigured);
         }
         var listMapping     = JsonConvert.DeserializeObject <ListMappingModel>(ListMapping);
         var subscribeString = GetMapAsString(listMapping, record, "Subscribe");
         var subscribe       = !string.IsNullOrWhiteSpace(subscribeString) && subscribeString != "False";
         if (!subscribe)
         {
             return(WorkflowExecutionStatus.Completed);
         }
         var emailAddress = GetMapAsString(listMapping, record, "Email Address");
         if (string.IsNullOrWhiteSpace(emailAddress))
         {
             return(WorkflowExecutionStatus.Completed);
         }
         var name     = GetMapAsString(listMapping, record, "Name");
         var lastName = GetMapAsString(listMapping, record, "Lastname");
         if (!string.IsNullOrWhiteSpace(lastName))
         {
             name += " " + lastName;
         }
         var auth       = new ApiKeyAuthenticationDetails(CampaignMonitorConfiguration.ApiKey);
         var subscriber = new Subscriber(auth, listMapping.ListId);
         subscriber.Add(emailAddress, name, listMapping.Mappings.
                        Where(m => m.ListField.StartsWith("[")).Select(m => {
             return(new SubscriberCustomField
             {
                 Key = m.ListField,
                 Value = GetFieldValue(record, m)
             });
         }).ToList(), subscribe);
         return(WorkflowExecutionStatus.Completed);
     }
     catch (Exception ex)
     {
         LogHelper.Error <PushToMarketing>("Failed to send users record to marketing", ex);
         return(WorkflowExecutionStatus.Failed);
     }
 }
コード例 #8
0
        public string AddSubscriber(CampaignUser user, bool resubscribe = false)
        {
            Subscriber subscriber = new Subscriber(_auth, _listId);
            string     result     = string.Empty;

            try
            {
                string newSubscriberID = subscriber
                                         .Add(user.Email, user.Name, null, resubscribe, ConsentToTrack.Unchanged);
                result = newSubscriberID;
            }
            catch (CreatesendException ex)
            {
                ErrorResult error = (ErrorResult)ex.Data["ErrorResult"];
                throw new ApplicationException(error.Code + " " + error.Message);
            }
            catch (Exception ex)
            {
                throw new ApplicationException(ex.ToString());
            }
            return(result);
        }
コード例 #9
0
        public ActionResult HandleContactSubmit(USNContactFormViewModel model)
        {
            System.Threading.Thread.Sleep(1000);

            string returnValue = String.Empty;

            if (!ModelState.IsValid)
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('{1}');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Contact Form General Error"))));
            }

            //Need to get NodeID from hidden field. CurrentPage does not work with Ajax.BeginForm
            IPublishedContent contactFormNode = Umbraco.TypedContent(model.CurrentNodeID);

            IPublishedContent homeNode       = contactFormNode.Site();
            IPublishedContent globalSettings = homeNode.GetPropertyValue <IPublishedContent>("websiteConfigurationNode").Children.Where(x => x.IsDocumentType("USNGlobalSettings")).First();

            string mailTo      = contactFormNode.GetPropertyValue <string>("recipientEmailAddress");
            string websiteName = globalSettings.GetPropertyValue <string>("websiteName");
            string pageName    = contactFormNode.Parent.Parent.Name;

            string errorMessage = String.Empty;

            if (!SendContactFormMail(model, mailTo, websiteName, pageName, out errorMessage))
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Contact Form Mail Send Error"), errorMessage)));
            }

            try
            {
                if (model.NewsletterSignup && globalSettings.HasValue("newsletterAPIKey") &&
                    (globalSettings.HasValue("defaultNewsletterSubscriberListID") || contactFormNode.HasValue("newsletterSubscriberListID")))
                {
                    if (globalSettings.GetPropertyValue <string>("emailMarketingPlatform") == "Campaign Monitor")
                    {
                        AuthenticationDetails auth = new ApiKeyAuthenticationDetails(globalSettings.GetProperty("newsletterAPIKey").Value.ToString());

                        string subsciberListID = String.Empty;

                        if (contactFormNode.HasValue("newsletterSubscriberListID"))
                        {
                            subsciberListID = contactFormNode.GetPropertyValue <string>("newsletterSubscriberListID");
                        }
                        else
                        {
                            subsciberListID = globalSettings.GetPropertyValue <string>("defaultNewsletterSubscriberListID");
                        }

                        Subscriber loSubscriber = new Subscriber(auth, subsciberListID);

                        List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();

                        string subscriberID = loSubscriber.Add(model.Email, model.FirstName + " " + model.LastName, customFields, false);
                    }
                    else if (globalSettings.GetPropertyValue <string>("emailMarketingPlatform") == "MailChimp")
                    {
                        var mc = new MailChimpManager(globalSettings.GetPropertyValue <string>("newsletterAPIKey"));

                        string subsciberListID = String.Empty;

                        if (contactFormNode.HasValue("newsletterSubscriberListID"))
                        {
                            subsciberListID = contactFormNode.GetPropertyValue <string>("newsletterSubscriberListID");
                        }
                        else
                        {
                            subsciberListID = globalSettings.GetPropertyValue <string>("defaultNewsletterSubscriberListID");
                        }

                        var email = new EmailParameter()
                        {
                            Email = model.Email
                        };

                        var myMergeVars = new MergeVar();
                        myMergeVars.Add("FNAME", model.FirstName);
                        myMergeVars.Add("LNAME", model.LastName);

                        EmailParameter results = mc.Subscribe(subsciberListID, email, myMergeVars, "html", false, true, false, false);
                    }
                }
            }
            catch (Exception ex)
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Contact Form Signup Error"), ex.Message.Replace("'", "\""))));
            }

            returnValue = String.Format("<div class=\"spc alert alert-success alert-dismissible fade in\" role=\"alert\"><div class=\"info\">{0}</div></div>", contactFormNode.GetPropertyValue <string>("submissionMessage"));

            return(Content(returnValue));
        }
        public async Task <ActionResult> HandleNewsletterSubmit(USNNewsletterFormViewModel model)
        {
            System.Threading.Thread.Sleep(1000);

            string lsReturnValue = "";

            var currentNode = Umbraco.TypedContent(model.CurrentNodeID);
            var currentPage = Umbraco.TypedContent(model.ActualPageID);

            IPublishedContent homeNode = currentPage.AncestorOrSelf(1);
            var settingsFolder         = Umbraco.TypedContent(homeNode.GetProperty("websiteConfigurationNode").Value);
            var globalSettings         = settingsFolder.Children.Where(x => x.DocumentTypeAlias == "USNGlobalSettings").First();

            if (!ModelState.IsValid)
            {
                return(JavaScript(String.Format("$(NewsletterError{0}).show();$(NewsletterError{0}).html('<div class=\"info\"><p>{1}</p></div>');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Newsletter Form General Error"))));
            }
            try
            {
                if (globalSettings.GetProperty("emailMarketingPlatform").Value.ToString() == "Campaign Monitor")
                {
                    AuthenticationDetails auth = new ApiKeyAuthenticationDetails(globalSettings.GetProperty("newsletterAPIKey").Value.ToString());

                    string subsciberListID = String.Empty;

                    if (currentNode.GetProperty("newsletterSubscriberListID").Value.ToString() != String.Empty)
                    {
                        subsciberListID = currentNode.GetProperty("newsletterSubscriberListID").Value.ToString();
                    }
                    else
                    {
                        subsciberListID = globalSettings.GetProperty("defaultNewsletterSubscriberListID").Value.ToString();
                    }

                    Subscriber loSubscriber = new Subscriber(auth, subsciberListID);

                    List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();

                    string subscriberID = loSubscriber.Add(model.Email, model.FirstName + " " + model.LastName, customFields, false);
                }
                else if (globalSettings.GetProperty("emailMarketingPlatform").Value.ToString() == "MailChimp")
                {
                    var mc = new MailChimpManager(globalSettings.GetProperty("newsletterAPIKey").Value.ToString());

                    string subsciberListID = String.Empty;

                    if (currentNode.GetProperty("newsletterSubscriberListID").Value.ToString() != String.Empty)
                    {
                        subsciberListID = currentNode.GetProperty("newsletterSubscriberListID").Value.ToString();
                    }
                    else
                    {
                        subsciberListID = globalSettings.GetProperty("defaultNewsletterSubscriberListID").Value.ToString();
                    }


                    var email = new EmailParameter()
                    {
                        Email = model.Email
                    };

                    var myMergeVars = new MergeVar();
                    myMergeVars.Add("FNAME", model.FirstName);
                    myMergeVars.Add("LNAME", model.LastName);

                    EmailParameter results = mc.Subscribe(subsciberListID, email, myMergeVars, "html", false, true, false, false);
                }

                lsReturnValue = String.Format("<div class=\"spc alert alert-success alert-dismissible fade in\" role=\"alert\"><div class=\"info\">{0}</div></div>", currentNode.GetProperty("submissionMessage").Value.ToString());
                return(Content(lsReturnValue));
            }
            catch (Exception ex)
            {
                return(JavaScript(String.Format("$(NewsletterError{0}).show();$(NewsletterError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Newsletter Form Signup Error"), ex.Message)));
            }
        }
コード例 #11
0
        public ActionResult HandleNewsletterSubmit(USNNewsletterFormViewModel model)
        {
            System.Threading.Thread.Sleep(1000);

            var globalSettings = Umbraco.Content(model.GlobalSettingsID);

            string recaptchaReset = globalSettings.HasValue("googleReCAPTCHASiteKey") && globalSettings.HasValue("googleReCAPTCHASecretKey") ? "grecaptcha.reset();" : String.Empty;

            string lsReturnValue = String.Empty;

            if (!ModelState.IsValid)
            {
                return(JavaScript(String.Format("{0}$('#NE_{1}').show();$('#NE_{1}').html('<div class=\"info\"><p>{2}</p></div>');", recaptchaReset, model.UniqueID, HttpUtility.JavaScriptStringEncode(Umbraco.GetDictionaryValue("USN Form Required Field Error")))));
            }
            try
            {
                if (globalSettings.HasValue("googleReCAPTCHASiteKey") && globalSettings.HasValue("googleReCAPTCHASecretKey"))
                {
                    var    response  = Request["g-recaptcha-response"];
                    string secretKey = globalSettings.Value <string>("googleReCAPTCHASecretKey");
                    var    client    = new WebClient();
                    var    result    = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
                    var    obj       = JObject.Parse(result);
                    var    status    = (bool)obj.SelectToken("success");

                    if (!status)
                    {
                        return(JavaScript(String.Format("{0}$('#NE_{1}').show();$('#NE_{1}').html('{2}');", recaptchaReset, model.UniqueID, HttpUtility.JavaScriptStringEncode(Umbraco.GetDictionaryValue("USN Form reCAPTCHA Error")))));
                    }
                }

                string firstName = model.FirstName == "***" ? String.Empty : model.FirstName;
                string lastName  = model.LastName == "***" ? String.Empty : model.LastName;

                if (globalSettings.Value <string>("emailMarketingPlatform") == "newsletterCM")
                {
                    AuthenticationDetails auth = new ApiKeyAuthenticationDetails(globalSettings.Value <string>("newsletterAPIKey"));

                    string subsciberListID = String.Empty;

                    if (model.FormSubscriberListID.HasValue())
                    {
                        subsciberListID = model.FormSubscriberListID;
                    }
                    else
                    {
                        subsciberListID = globalSettings.Value <string>("defaultNewsletterSubscriberListID");
                    }

                    Subscriber loSubscriber = new Subscriber(auth, subsciberListID);

                    List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();

                    string subscriberID = loSubscriber.Add(model.Email, firstName + " " + lastName, customFields, false);
                }
                else if (globalSettings.Value <string>("emailMarketingPlatform") == "newsletterMC")
                {
                    var mc = new MailChimpManager(globalSettings.Value <string>("newsletterAPIKey"));

                    string subsciberListID = String.Empty;

                    if (model.FormSubscriberListID.HasValue())
                    {
                        subsciberListID = model.FormSubscriberListID;
                    }
                    else
                    {
                        subsciberListID = globalSettings.Value <string>("defaultNewsletterSubscriberListID");
                    }


                    var email = new EmailParameter()
                    {
                        Email = model.Email
                    };

                    var myMergeVars = new MergeVar();
                    myMergeVars.Add("FNAME", firstName);
                    myMergeVars.Add("LNAME", lastName);

                    EmailParameter results = mc.Subscribe(subsciberListID, email, myMergeVars, "html", false, true, false, false);
                }

                return(JavaScript(String.Format("$('#S_{0}').show();$('#Form_{0}').hide();", model.UniqueID)));
            }
            catch (Exception ex)
            {
                return(JavaScript(String.Format("{0}$('#NE_{1}').show();$('#NE_{1}').html('<div class=\"info\"><p>{2}</p><p>{3}</p></div>');", recaptchaReset, model.UniqueID, HttpUtility.JavaScriptStringEncode(Umbraco.GetDictionaryValue("USN Newsletter Form Signup Error")), HttpUtility.JavaScriptStringEncode(ex.Message))));
            }
        }
コード例 #12
0
        internal void SyncContact(Entity target, Entity postImage, Entity preImage, bool isUpdate)
        {
            if (target == null || postImage == null)
            {
                tracer.Trace("Invalid target or postImage entity.");
                return;
            }

            if (campaignMonitorConfig == null)
            {
                tracer.Trace("Missing or invalid campaign monitor configuration.");
                return;
            }

            string emailField = SharedLogic.GetPrimaryEmailField(campaignMonitorConfig.SubscriberEmail);

            if (string.IsNullOrWhiteSpace(emailField) ||
                !postImage.Contains(emailField) || string.IsNullOrWhiteSpace(postImage[emailField].ToString()))
            {
                tracer.Trace("The email field to sync is missing or contains invalid data.");
                return;
            }

            if (campaignMonitorConfig.SyncViewId != Guid.Empty)
            {
                tracer.Trace("Testing the contact against the filter.");

                // Retrieve the view specified in the campmon_syncviewid field of the configuration record.
                var filterQuery = SharedLogic.GetConfigFilterQuery(orgService, campaignMonitorConfig.SyncViewId);

                // Modify the sync view fetch query to include a filter condition for the current contact id.Execute the modified query and check if the contact is returned.If it is, exit the plugin.
                if (!TestContactFitsFilter(filterQuery, target.Id))
                {
                    tracer.Trace("Contact does not fit the filter.");
                    return;
                }
            }
            else
            {
                if (target.Contains("statecode") && (target["statecode"] as OptionSetValue).Value == 1)
                {
                    tracer.Trace("Contact was not synced: no view is selected and this contact is deactivated.");
                    return;
                }
            }

            tracer.Trace("Contact fits the filter, or no filter is selected.");

            /*
             *  Create a campmon_message record with the following data:
             *      • campmon_sdkmessage = Plugin message (create or update)
             *      • campmon_data = JSON serialized sync data
             */
            var syncMessage = new Entity("campmon_message");
            var fields      = SharedLogic.ContactAttributesToSubscriberFields(orgService, tracer, target, campaignMonitorConfig.SyncFields.ToList());

            // Check that the plugin target has modified attributes that are included in the campmon_syncfields data. If there are not any sync fields in the target, exit the plugin.
            if (fields.Count <= 0)
            {
                tracer.Trace("There are no fields in the target that match the current fields being synced with Campaign Monitor.");
                return;
            }

            if (isUpdate && !target.Attributes.Contains(emailField))
            {
                fields.Add(new SubscriberCustomField {
                    Key = emailField, Value = postImage[emailField].ToString()
                });
            }
            else if (isUpdate && target.Attributes.Contains(emailField) && preImage[emailField].ToString() != postImage[emailField].ToString())
            {
                // if it contains primary email and isUpdate, then the primary email was changed and we need to do something to handle that
                var auth       = Authenticator.GetAuthentication(campaignMonitorConfig, orgService);
                var subscriber = new Subscriber(auth, campaignMonitorConfig.ListId);
                try
                {
                    subscriber.Update(preImage[emailField].ToString(), postImage[emailField].ToString(), postImage["fullname"].ToString(), null, false);
                }
                catch (CreatesendException csEx)
                {
                    if (csEx.Error.Code == "203")
                    {
                        subscriber.Add(postImage[emailField].ToString(), postImage["fullname"].ToString(), null, false);
                    }
                }
                catch (Exception ex)
                {
                    tracer.Trace("Exception type: {0}", ex.GetType().Name);
                    throw;
                }
            }

            if (isUpdate && !target.Attributes.Contains("fullname"))
            {
                fields.Add(new SubscriberCustomField {
                    Key = "fullname", Value = postImage["fullname"].ToString()
                });
            }

            var syncData = JsonConvert.SerializeObject(fields);

            syncMessage["campmon_name"]  = isUpdate ? "update" : "create";
            syncMessage["campmon_data"]  = syncData;
            syncMessage["campmon_email"] = emailField;
            orgService.Create(syncMessage);
        }
コード例 #13
0
        public ActionResult HandleContactSubmit(USNContactFormViewModel model)
        {
            System.Threading.Thread.Sleep(1000);

            string returnValue = "";

            if (!ModelState.IsValid)
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('{1}');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Contact Form General Error"))));
            }

            //Need to get NodeID from hidden field. CurrentPage does not work with Ajax.BeginForm
            var currentNode = Umbraco.TypedContent(model.CurrentNodeID);

            IPublishedContent homeNode = currentNode.AncestorOrSelf(1);
            var settingsFolder         = Umbraco.TypedContent(homeNode.GetProperty("websiteConfigurationNode").Value);
            var globalSettings         = settingsFolder.Children.Where(x => x.DocumentTypeAlias == "USNGlobalSettings").First();

            string mailTo      = currentNode.GetProperty("recipientEmailAddress").Value.ToString();
            string websiteName = globalSettings.GetProperty("websiteName").Value.ToString();
            string pageName    = currentNode.Parent.Parent.Name;

            string errorMessage = "";

            if (!SendContactFormMail(model, mailTo, websiteName, pageName, out errorMessage))
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Contact Form Mail Send Error"), errorMessage)));
            }

            try
            {
                if (model.NewsletterSignup && globalSettings.HasValue("campaignMonitorAPIKey") &&
                    (globalSettings.HasValue("defaultCampaignMonitorSubscriberListID") || currentNode.HasValue("campaignMonitorSubscriberListID")))
                {
                    string subsciberListID = "";

                    if (currentNode.GetProperty("campaignMonitorSubscriberListID").Value.ToString() != String.Empty)
                    {
                        subsciberListID = currentNode.GetProperty("campaignMonitorSubscriberListID").Value.ToString();
                    }
                    else
                    {
                        subsciberListID = globalSettings.GetProperty("defaultCampaignMonitorSubscriberListID").Value.ToString();
                    }

                    AuthenticationDetails auth = new ApiKeyAuthenticationDetails(globalSettings.GetProperty("campaignMonitorAPIKey").Value.ToString());

                    Subscriber loSubscriber = new Subscriber(auth, subsciberListID);

                    List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();

                    string lsSubscriberID = loSubscriber.Add(model.Email, model.FirstName + " " + model.LastName, customFields, false);
                }
            }
            catch (Exception ex)
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, umbraco.library.GetDictionaryItem("USN Contact Form Signup Error"), ex.Message)));
            }

            returnValue = String.Format("<div class=\"page_component alert alert-success alert-dismissible fade in\" role=\"alert\"><div class=\"info\">{0}</div></div>", currentNode.GetProperty("submissionMessage").Value.ToString());

            return(Content(returnValue));
        }
コード例 #14
0
        public ActionResult AuthorizeNetSimGift(FormCollection post)
        {
            _logger.Info("keys: {0}", string.Join(", ", post.AllKeys));
            var orderId = Convert.ToInt32(post["GiftOrderId"]);
            var userId  = Convert.ToInt32(post["UserId"]);
            var order   = _giftCardOrderService.FindOrder(orderId, userId);

            _logger.Info("Authorizing SIM...");

            //the URL to redirect to- this MUST be absolute
            var successUrl  = Url.RouteUrl("giftconfirmation", new { orderId = order.Id }, SecureProtocol);
            var failureUrl  = Url.RouteUrl("billing-giftdetails", new { orderId = order.Id }, SecureProtocol);
            var redirectUrl = successUrl;

            var response = new SIMResponse(post);

            _logger.Info("Approved: {0}", response.Approved);
            _logger.Info("Code: {0}", response.ResponseCode);
            _logger.Info("Message: {0}", response.Message);
            _logger.Info("Authorization Code: {0}", response.AuthorizationCode);
            _logger.Info("Card Number: {0}", response.CardNumber);
            _logger.Info("Card Type: {0}", response.CardType);
            _logger.Info("Invoice Number: {0}", response.InvoiceNumber);
            _logger.Info("MD5 Hash: {0}", response.MD5Hash);
            _logger.Info("Transaction ID: {0}", response.TransactionID);

            //first order of business - validate that it was Authorize.Net that posted this using the
            //MD5 hash that was passed back to us
            var isValid = response.Validate(AuthorizeNetConfig.Md5HashValue, AuthorizeNetConfig.ApiLogin);

            _logger.Info("Valid: {0}", isValid);
            if (isValid && response.Approved)
            {
                _giftorderConfirmationMailer.SendGiftOrderConfirmationEmail(order);
                _giftCardOrderService.CompleteOrder(order, response.TransactionID);


                //Campaign Monitor -Adding subscriber to Gift card recipients List

                AuthenticationDetails auth          = new ApiKeyAuthenticationDetails(ConfigurationManager.AppSettings["CampaignMonitorAPI_key"]);
                Subscriber            objSubscriber = new Subscriber(auth, ConfigurationManager.AppSettings["CampaignMonitorListID"]);

                for (int i = 0; i < order.GiftOrderDetail.Count; i++)
                {
                    List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();
                    customFields.Add(new SubscriberCustomField()
                    {
                        Key = "Amount", Value = order.GiftOrderDetail[i].Amount.ToString()
                    });
                    customFields.Add(new SubscriberCustomField()
                    {
                        Key = "Your Name", Value = order.GiftOrderDetail[i].YourName.ToString()
                    });
                    customFields.Add(new SubscriberCustomField()
                    {
                        Key = "Gift Code", Value = order.GiftOrderDetail[i].RecipientGiftCode.ToString()
                    });
                    customFields.Add(new SubscriberCustomField()
                    {
                        Key = "Message", Value = order.GiftOrderDetail[i].Message.ToString()
                    });

                    string newSubscriberID = objSubscriber.Add(order.GiftOrderDetail[i].RecipientEmail.ToString(), null, customFields, false);
                }
            }
            else
            {
                _giftCardOrderService.FailOrder(order, response.Message);
                redirectUrl = failureUrl;
            }

            return(Content(AuthorizeNet.Helpers.CheckoutFormBuilders.Redirecter(redirectUrl)));
        }
コード例 #15
0
        //[ProductionRequireHttps]
        public ActionResult Billing(Britespokes.Services.GiftCards.BillingDetails billingDetails)
        {
            //decimal GiftAmount = 0;
            //int OrderDetailId = 0;

            var order = _giftCardOrderService.FindOrder(billingDetails.GiftOrderId, UserContext.UserId);

            if (!billingDetails.AcceptedTermsAndConditions)
            {
                ModelState.AddModelError("AcceptedTermsAndConditions", "you must accept the terms and conditions to purchase a tour");
            }
            if (order.OrderStatus != _giftCardOrderService.StatusPending())
            {
                ModelState.AddModelError("", "This order is no longer pending");
            }
            if (UserContext.IsGuest && string.IsNullOrEmpty(billingDetails.Password))
            {
                ModelState.AddModelError("Password", "required");
            }

            if (string.CompareOrdinal(billingDetails.Password, billingDetails.ConfirmPassword) != 0)
            {
                ModelState.AddModelError("ConfirmPassword", "doesn't match");
            }


            if (ModelState.IsValid)
            {
                if (UserContext.IsGuest)
                {
                    var user = _userService.Find(UserContext.UserId);
                    _registrationService.PromoteGuest(user, billingDetails.Email, billingDetails.Password);
                    _userMailer.SendWelcomeEmail(UserContext.Organization, user);
                }
                _giftCardOrderService.UpdateBillingDetails(billingDetails);

                //Campaign Monitor -Adding subscriber to Gift card recipients List

                AuthenticationDetails auth          = new ApiKeyAuthenticationDetails(ConfigurationManager.AppSettings["CampaignMonitorAPI_key"]);
                Subscriber            objSubscriber = new Subscriber(auth, ConfigurationManager.AppSettings["CampaignMonitorListID"]);

                for (int i = 0; i < order.GiftOrderDetail.Count; i++)
                {
                    List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();
                    customFields.Add(new SubscriberCustomField()
                    {
                        Key = "Amount", Value = order.GiftOrderDetail[i].Amount == null? "":order.GiftOrderDetail[i].Amount.ToString()
                    });
                    customFields.Add(new SubscriberCustomField()
                    {
                        Key = "Your Name", Value = order.GiftOrderDetail[i].YourName == null ? "" : order.GiftOrderDetail[i].YourName.ToString()
                    });
                    customFields.Add(new SubscriberCustomField()
                    {
                        Key = "Gift Code", Value = order.GiftOrderDetail[i].RecipientGiftCode == null ? "" : order.GiftOrderDetail[i].RecipientGiftCode.ToString()
                    });
                    customFields.Add(new SubscriberCustomField()
                    {
                        Key = "Message", Value = order.GiftOrderDetail[i].Message == null ? "" : order.GiftOrderDetail[i].Message.ToString()
                    });

                    string newSubscriberID = objSubscriber.Add(order.GiftOrderDetail[i].RecipientEmail.ToString(), null, customFields, false);
                }

                return(Json(new { BillingDetails = billingDetails, Errors = new object[0] }));
            }

            billingDetails.BillingOverview = _giftCardOrderService.BuildBillingOverview(order);
            billingDetails.PaymentRequest  = new PaymentRequest(order.Total, AuthorizeNetConfig.ApiLogin, AuthorizeNetConfig.TransactionKey, AuthorizeNetConfig.TestMode);
            return(Json(new { BillingDetails = billingDetails, Errors = ModelStateErrorsForJson() }));
        }
コード例 #16
0
        public ActionResult HandleContactSubmit(USNContactFormViewModel model)
        {
            System.Threading.Thread.Sleep(1000);

            string returnValue = String.Empty;

            if (!ModelState.IsValid)
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('{1}');", model.CurrentNodeID, HttpUtility.JavaScriptStringEncode(umbraco.library.GetDictionaryItem("USN Contact Form General Error")))));
            }

            //Need to get NodeID from hidden field. CurrentPage does not work with Ajax.BeginForm
            var contactFormNode = Umbraco.TypedContent(model.CurrentNodeID);
            var globalSettings  = Umbraco.TypedContent(model.GlobalSettingsID);

            if (globalSettings.HasValue("googleReCAPTCHASiteKey") && globalSettings.HasValue("googleReCAPTCHASecretKey"))
            {
                var    response  = Request["g-recaptcha-response"];
                string secretKey = globalSettings.GetPropertyValue <string>("googleReCAPTCHASecretKey");
                var    client    = new WebClient();
                var    result    = client.DownloadString(string.Format("https://www.google.com/recaptcha/api/siteverify?secret={0}&response={1}", secretKey, response));
                var    obj       = JObject.Parse(result);
                var    status    = (bool)obj.SelectToken("success");

                if (!status)
                {
                    return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('{1}');", model.CurrentNodeID, HttpUtility.JavaScriptStringEncode(umbraco.library.GetDictionaryItem("USN Form reCAPTCHA Error")))));
                }
            }

            string mailTo      = contactFormNode.GetPropertyValue <string>("contactRecipientEmailAddress");
            string websiteName = globalSettings.GetPropertyValue <string>("websiteName");
            string pageName    = contactFormNode.Parent.Parent.Name;

            string errorMessage = String.Empty;

            if (!SendContactFormMail(model, mailTo, websiteName, pageName, out errorMessage))
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, HttpUtility.JavaScriptStringEncode(umbraco.library.GetDictionaryItem("USN Contact Form Mail Send Error")), HttpUtility.JavaScriptStringEncode(errorMessage))));
            }

            try
            {
                if (model.NewsletterSignup && globalSettings.HasValue("newsletterAPIKey") &&
                    (globalSettings.HasValue("defaultNewsletterSubscriberListID") || contactFormNode.HasValue("contactSubscriberListID")))
                {
                    if (globalSettings.GetPropertyValue <USNOptions>("emailMarketingPlatform") == USNOptions.Newsletter_CM)
                    {
                        AuthenticationDetails auth = new ApiKeyAuthenticationDetails(globalSettings.GetPropertyValue <string>("newsletterAPIKey"));

                        string subsciberListID = String.Empty;

                        if (contactFormNode.HasValue("newsletterSubscriberListID"))
                        {
                            subsciberListID = contactFormNode.GetPropertyValue <string>("contactSubscriberListID");
                        }
                        else
                        {
                            subsciberListID = globalSettings.GetPropertyValue <string>("defaultNewsletterSubscriberListID");
                        }

                        Subscriber loSubscriber = new Subscriber(auth, subsciberListID);

                        List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();

                        string subscriberID = loSubscriber.Add(model.Email, model.FirstName + " " + model.LastName, customFields, false);
                    }
                    else if (globalSettings.GetPropertyValue <USNOptions>("emailMarketingPlatform") == USNOptions.Newsletter_Mailchimp)
                    {
                        var mc = new MailChimpManager(globalSettings.GetPropertyValue <string>("newsletterAPIKey"));

                        string subsciberListID = String.Empty;

                        if (contactFormNode.HasValue("contactSubscriberListID"))
                        {
                            subsciberListID = contactFormNode.GetPropertyValue <string>("contactSubscriberListID");
                        }
                        else
                        {
                            subsciberListID = globalSettings.GetPropertyValue <string>("defaultNewsletterSubscriberListID");
                        }

                        var email = new EmailParameter()
                        {
                            Email = model.Email
                        };

                        var myMergeVars = new MergeVar();
                        myMergeVars.Add("FNAME", model.FirstName);
                        myMergeVars.Add("LNAME", model.LastName);

                        EmailParameter results = mc.Subscribe(subsciberListID, email, myMergeVars, "html", false, true, false, false);
                    }
                }
            }
            catch (Exception ex)
            {
                return(JavaScript(String.Format("$(ContactError{0}).show();$(ContactError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, HttpUtility.JavaScriptStringEncode(umbraco.library.GetDictionaryItem("USN Contact Form Signup Error")), HttpUtility.JavaScriptStringEncode(ex.Message))));
            }

            returnValue = String.Format("<div class=\"spc alert alert-success alert-dismissible fade in\" role=\"alert\"><div class=\"info\">{0}</div></div>", contactFormNode.GetPropertyValue <string>("contactSubmissionMessage"));

            return(Content(returnValue));
        }
コード例 #17
0
 public void OnEnable()
 {
     subscriber = new Subscriber();
     subscriber.Add <int>("ui_use_skill", DoSkill);
 }
コード例 #18
0
        public ActionResult HandleNewsletterSubmit(USNNewsletterFormViewModel model)
        {
            System.Threading.Thread.Sleep(1000);

            string lsReturnValue = String.Empty;

            var currentNode    = Umbraco.TypedContent(model.CurrentNodeID);
            var globalSettings = Umbraco.TypedContent(model.GlobalSettingsID);

            if (!ModelState.IsValid)
            {
                return(JavaScript(String.Format("$(NewsletterError{0}).show();$(NewsletterError{0}).html('<div class=\"info\"><p>{1}</p></div>');", model.CurrentNodeID, HttpUtility.JavaScriptStringEncode(umbraco.library.GetDictionaryItem("USN Newsletter Form General Error")))));
            }
            try
            {
                if (globalSettings.GetPropertyValue <string>("emailMarketingPlatform") == "Campaign Monitor")
                {
                    AuthenticationDetails auth = new ApiKeyAuthenticationDetails(globalSettings.GetPropertyValue <string>("newsletterAPIKey"));

                    string subsciberListID = String.Empty;

                    if (currentNode.GetPropertyValue <string>("newsletterSubscriberListID") != String.Empty)
                    {
                        subsciberListID = currentNode.GetPropertyValue <string>("newsletterSubscriberListID");
                    }
                    else
                    {
                        subsciberListID = globalSettings.GetPropertyValue <string>("defaultNewsletterSubscriberListID");
                    }

                    Subscriber loSubscriber = new Subscriber(auth, subsciberListID);

                    List <SubscriberCustomField> customFields = new List <SubscriberCustomField>();

                    string subscriberID = loSubscriber.Add(model.Email, model.FirstName + " " + model.LastName, customFields, false);
                }
                else if (globalSettings.GetPropertyValue <string>("emailMarketingPlatform") == "MailChimp")
                {
                    var mc = new MailChimpManager(globalSettings.GetPropertyValue <string>("newsletterAPIKey"));

                    string subsciberListID = String.Empty;

                    if (currentNode.HasValue("newsletterSubscriberListID"))
                    {
                        subsciberListID = currentNode.GetPropertyValue <string>("newsletterSubscriberListID");
                    }
                    else
                    {
                        subsciberListID = globalSettings.GetPropertyValue <string>("defaultNewsletterSubscriberListID");
                    }


                    var email = new EmailParameter()
                    {
                        Email = model.Email
                    };

                    var myMergeVars = new MergeVar();
                    myMergeVars.Add("FNAME", model.FirstName);
                    myMergeVars.Add("LNAME", model.LastName);

                    EmailParameter results = mc.Subscribe(subsciberListID, email, myMergeVars, "html", false, true, false, false);
                }

                lsReturnValue = String.Format("<div class=\"spc alert alert-success alert-dismissible fade in\" role=\"alert\"><div class=\"info\">{0}</div></div>", currentNode.GetPropertyValue <string>("submissionMessage"));
                return(Content(lsReturnValue));
            }
            catch (Exception ex)
            {
                return(JavaScript(String.Format("$(NewsletterError{0}).show();$(NewsletterError{0}).html('<div class=\"info\"><p>{1}</p><p>{2}</p></div>');", model.CurrentNodeID, HttpUtility.JavaScriptStringEncode(umbraco.library.GetDictionaryItem("USN Newsletter Form Signup Error")), HttpUtility.JavaScriptStringEncode(ex.Message))));
            }
        }