Example #1
0
    protected void Page_Load(object sender, EventArgs e)
    {
        mNewsletter = EditedObject as NewsletterInfo;

        if (mNewsletter == null)
        {
            RedirectToAccessDenied(GetString("general.invalidparameters"));
        }

        if (!mNewsletter.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser))
        {
            RedirectToAccessDenied(mNewsletter.TypeInfo.ModuleName, "Read");
        }

        mBounceMonitoringEnabled = NewsletterHelper.MonitorBouncedEmails(CurrentSiteName);
        mOnlineMarketingEnabled  = NewsletterHelper.OnlineMarketingAvailable(CurrentSiteName);
        mTrackingEnabled         = NewsletterHelper.IsTrackingAvailable();
        mABTestEnabled           = NewsletterHelper.IsABTestingAvailable();

        ScriptHelper.RegisterDialogScript(this);

        string scriptBlock = string.Format(@"
            function RefreshPage() {{ document.location.replace(document.location); }}
            function NewItem(id) {{ modalDialog('{0}?parentobjectid=' + id, 'NewsletterNewIssue', screen.availWidth - 10, screen.availHeight - 80); }}
            function ShowOpenedBy(id) {{ modalDialog('{1}?objectid=' + id, 'NewsletterIssueOpenedBy', '900px', '700px');  return false; }}
            function ViewClickedLinks(id) {{ modalDialog('{2}?objectid=' + id, 'NewsletterTrackedLinks', '900px', '700px'); return false; }}",
                                           ResolveUrl(@"~\CMSModules\Newsletters\Tools\Newsletters\Newsletter_Issue_New.aspx"),
                                           ResolveUrl(@"~\CMSModules\Newsletters\Tools\Newsletters\Newsletter_Issue_OpenedBy.aspx"),
                                           ResolveUrl(@"~\CMSModules\Newsletters\Tools\Newsletters\Newsletter_Issue_TrackedLinks.aspx"));

        ScriptHelper.RegisterClientScriptBlock(this, GetType(), "Actions", scriptBlock, true);

        // Initialize unigrid
        UniGrid.WhereCondition       = String.Format("IssueNewsletterID={0} AND IssueVariantOfIssueID IS NULL", mNewsletter.NewsletterID);
        UniGrid.ZeroRowsText         = GetString("Newsletter_Issue_List.NoIssuesFound");
        UniGrid.OnAction            += uniGrid_OnAction;
        UniGrid.OnBeforeDataReload  += UniGrid_OnBeforeDataReload;
        UniGrid.OnExternalDataBound += UniGrid_OnExternalDataBound;

        // Initialize header actions
        InitHeaderActions();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        newsletterId = QueryHelper.GetInteger("newsletterid", 0);
        if (newsletterId == 0)
        {
            RequestHelper.EndResponse();
        }

        // Get newsletter object and check its existence
        mNewsletter  = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);
        EditedObject = mNewsletter;

        string siteName = CMSContext.CurrentSiteName;

        mBounceMonitoringEnabled = NewsletterHelper.MonitorBouncedEmails(siteName);
        mOnlineMarketingEnabled  = NewsletterHelper.OnlineMarketingAvailable(siteName);
        mTrackingEnabled         = NewsletterHelper.IsTrackingAvailable();
        mABTestEnabled           = NewsletterHelper.IsABTestingAvailable();

        ScriptHelper.RegisterDialogScript(this);

        string scriptBlock = string.Format(@"
            function RefreshPage() {{ document.location.replace(document.location); }}
            function NewItem(id) {{ modalDialog('{0}?newsletterid=' + id, 'NewsletterNewIssue', screen.availWidth - 10, screen.availHeight - 80); }}
            function ShowOpenedBy(id) {{ modalDialog('{1}?issueid=' + id, 'NewsletterIssueOpenedBy', '900px', '700px');  return false; }}
            function ViewClickedLinks(id) {{ modalDialog('{2}?issueid=' + id, 'NewsletterTrackedLinks', '900px', '700px'); return false; }}",
                                           ResolveUrl(@"~\CMSModules\Newsletters\Tools\Newsletters\Newsletter_Issue_New.aspx"),
                                           ResolveUrl(@"~\CMSModules\Newsletters\Tools\Newsletters\Newsletter_Issue_OpenedBy.aspx"),
                                           ResolveUrl(@"~\CMSModules\Newsletters\Tools\Newsletters\Newsletter_Issue_TrackedLinks.aspx"));

        ScriptHelper.RegisterClientScriptBlock(this, GetType(), "Actions", scriptBlock, true);

        // Initialize unigrid
        UniGrid.WhereCondition       = String.Format("IssueNewsletterID={0} AND IssueVariantOfIssueID IS NULL", newsletterId);
        UniGrid.ZeroRowsText         = GetString("Newsletter_Issue_List.NoIssuesFound");
        UniGrid.OnAction            += uniGrid_OnAction;
        UniGrid.OnBeforeDataReload  += UniGrid_OnBeforeDataReload;
        UniGrid.OnExternalDataBound += UniGrid_OnExternalDataBound;

        // Initialize header actions
        InitHeaderActions();
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        mNewsletter = EditedObject as NewsletterInfo;
        if (mNewsletter == null)
        {
            RedirectToAccessDenied(GetString("general.invalidparameters"));
        }

        if (!mNewsletter.CheckPermissions(PermissionsEnum.Read, CurrentSiteName, CurrentUser))
        {
            RedirectToAccessDenied(mNewsletter.TypeInfo.ModuleName, "ManageSubscribers");
        }

        ScriptHelper.RegisterDialogScript(this);

        CurrentMaster.DisplayActionsPanel = true;
        chkRequireOptIn.CheckedChanged   += chkRequireOptIn_CheckedChanged;

        string currentSiteName = SiteContext.CurrentSiteName;

        mBounceLimit         = NewsletterHelper.BouncedEmailsLimit(currentSiteName);
        mBounceInfoAvailable = NewsletterHelper.MonitorBouncedEmails(currentSiteName);

        // Check if newsletter enables double opt-in
        if (!mNewsletter.NewsletterEnableOptIn)
        {
            chkRequireOptIn.Visible = false;
        }

        if (!RequestHelper.IsPostBack())
        {
            chkSendConfirmation.Checked = false;
        }

        // Initialize unigrid
        UniGridSubscribers.WhereCondition       = "NewsletterID = " + mNewsletter.NewsletterID;
        UniGridSubscribers.OnAction            += UniGridSubscribers_OnAction;
        UniGridSubscribers.OnExternalDataBound += UniGridSubscribers_OnExternalDataBound;

        // Initialize selectors and mass actions
        SetupSelectors();
    }
    public override void ReloadData(bool forceReload)
    {
        if (StopProcessing && !forceReload)
        {
            return;
        }
        InitControls(forceReload);

        // Javascript for handling winner mailout time
        var scriptBlock = string.Format(@"function SelWinner(id) {{ modalDialog('{0}?objectid=' + id, 'NewsletterWinnerMailout', '700px', '425px'); return false; }}",
                                        ResolveUrl(@"~\CMSModules\Newsletters\Tools\Newsletters\Newsletter_Issue_WinnerMailout.aspx"));

        ScriptHelper.RegisterDialogScript(Page);
        ScriptHelper.RegisterClientScriptBlock(this, GetType(), "Actions", scriptBlock, true);
        ScriptHelper.RegisterTooltip(Page);

        // Register handlers
        grdElem.OnExternalDataBound   -= grdElem_OnExternalDataBound;
        grdElem.OnExternalDataBound   += grdElem_OnExternalDataBound;
        grdElem.GridView.RowDataBound -= GridView_RowDataBound;
        grdElem.GridView.RowDataBound += GridView_RowDataBound;

        // Get winner ID if any
        var abTestInfo = ABTestInfoProvider.GetABTestInfoForIssue(ParentIssueID);

        if (abTestInfo != null)
        {
            WinnerIssueID = abTestInfo.TestWinnerIssueID;
        }

        mBounceMonitoringEnabled = NewsletterHelper.MonitorBouncedEmails(SiteContext.CurrentSiteName);

        grdElem.OrderBy         = "IssueVariantName, IssueID";
        grdElem.WhereCondition  = GetWhereCondition(ParentIssueID, false);
        grdElem.ShowActionsMenu = false;
        grdElem.ShowObjectMenu  = false;
        if (!ShowSelectWinnerAction)
        {
            grdElem.GridActions = null;
        }
        grdElem.ReloadData();
    }
Example #5
0
    private void InitAbTestingTab()
    {
        if (Issue.IssueIsABTest && (Issue.IssueVariantOfIssueID <= 0))
        {
            // Parent issue of A/B tests cannot be modified in Email builder => redirect to the original variant
            string originalVariantUrl = EmailBuilderHelper.GetOriginalVariantIssueUrl(Issue, IsInAutomation);
            URLHelper.Redirect(originalVariantUrl);
        }

        if (!NewsletterHelper.IsABTestingAvailable())
        {
            lnkAbTesting.Visible    = false;
            plcAbTestingTab.Visible = false;
        }

        // Initialize A/B testing control
        abVariants.Issue   = Issue;
        abVariants.Enabled = EditEnabled;
        abVariants.Save   += RightPanelSave;
    }
Example #6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        SiteInfo currentSite = CMSContext.CurrentSite;

        mBounceLimit         = NewsletterHelper.BouncedEmailsLimit(currentSite.SiteName);
        mBounceInfoAvailable = NewsletterHelper.MonitorBouncedEmails(currentSite.SiteName);

        // Add subscriber link
        string[,] actions = new string[1, 6];
        actions[0, 0]     = HeaderActions.TYPE_HYPERLINK;
        actions[0, 1]     = GetString("Subscriber_List.NewItemCaption");
        actions[0, 3]     = ResolveUrl("Subscriber_New.aspx");
        actions[0, 5]     = GetImageUrl("Objects/Newsletter_Subscriber/add.png");

        CurrentMaster.HeaderActions.Actions = actions;

        // Initialize unigrid
        UniGrid.OnAction            += uniGrid_OnAction;
        UniGrid.OnExternalDataBound += uniGrid_OnExternalDataBound;
        UniGrid.WhereCondition       = "SubscriberSiteID = " + currentSite.SiteID;
    }
        private void LoadSettings()
        {
            if (Request.Params.Get("token") != null)
            {
                authToken = Request.Params.Get("token");
            }

            timeOffset = SiteUtils.GetUserTimeOffset();
            timeZone   = SiteUtils.GetUserTimeZone();

            siteAvailableSubscriptions    = NewsletterHelper.GetAvailableNewslettersForCurrentUser(siteSettings.SiteGuid);
            IncludeDescriptionInList      = displaySettings.IncludeNewsletterDescriptionInList;
            pnlSubscribe.Visible          = displaySettings.ShowNewsLetters;
            lblNewsletterListHeading.Text = displaySettings.NewsletterListHeading.Coalesce(Resource.NewsletterPreferencesHeader);

            tokenUrl   = SiteRoot + "/Secure/OpenIdRpxHandler.aspx";
            rpxBaseUrl = "https://rpxnow.com";
            rpxApiKey  = siteSettings.RpxNowApiKey;

            if (WebConfigSettings.UseOpenIdRpxSettingsFromWebConfig)
            {
                if (WebConfigSettings.OpenIdRpxApiKey.Length > 0)
                {
                    rpxApiKey = WebConfigSettings.OpenIdRpxApiKey;
                }
            }


            regexEmail.ErrorMessage = Resource.RegisterEmailRegexMessage;

            returnUrlCookieName = "returnurl" + siteSettings.SiteId.ToString(CultureInfo.InvariantCulture);

            termsOfUse = siteSettings.RegistrationAgreement;
            if (termsOfUse.Length == 0)
            {
                termsOfUse = ResourceHelper.GetMessageTemplate("RegisterLicense.config");
            }

            AddClassToBody("rpxhandler");
        }
Example #8
0
    /// <summary>
    /// Initializes the variants drop-down list or hides it if the issue has no variants.
    /// </summary>
    private void InitVariantDropDownList()
    {
        if (!NewsletterHelper.IsABTestingAvailable())
        {
            return;
        }

        var variants = IssueHelper.GetIssueVariants(Issue)
                       .Select(v => new ListItem(v.IssueVariantName, v.IssueID.ToString())).ToList();

        if (variants.Any())
        {
            foreach (var variant in variants)
            {
                drpVariantsSelector.Items.Add(variant);
            }

            drpVariantsSelector.SelectedValue = Issue.IssueID.ToString();
            pnlTabs.AddCssClass("with-variants");
            plcVariantSelection.Visible = true;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        SiteInfo currentSite = SiteContext.CurrentSite;

        mBounceLimit         = NewsletterHelper.BouncedEmailsLimit(currentSite.SiteName);
        mBounceInfoAvailable = NewsletterHelper.MonitorBouncedEmails(currentSite.SiteName);

        // Initialize unigrid
        UniGrid.OnAction            += uniGrid_OnAction;
        UniGrid.OnExternalDataBound += uniGrid_OnExternalDataBound;
        UniGrid.WhereCondition       = "SubscriberSiteID = " + currentSite.SiteID;
        UniGrid.FilteredZeroRowsText = GetString("subscriber_list.nodata.filtered");

        if (LicenseContext.CurrentLicenseInfo.Edition == ProductEditionEnum.EnterpriseMarketingSolution)
        {
            UniGrid.ZeroRowsText = string.Format(GetString("subscriber_list.nodata.ems"), URLHelper.ResolveUrl(UIContextHelper.GetApplicationUrl(ModuleName.ONLINEMARKETING, "ContactsFrameset", "?tabname=Contacts")));
        }
        else
        {
            UniGrid.ZeroRowsText = GetString("subscriber_list.nodata.noems");
        }
    }
Example #10
0
    /// <summary>
    /// Create schedule task.
    /// </summary>
    private void CreateTask()
    {
        try
        {
            var editedObject   = TypedEditedObject;
            var newsletterGUID = editedObject.NewsletterGUID.ToString();
            var maxLength      = 200;

            TaskInfo task = new TaskInfo();
            task.TaskAssemblyName = "CMS.Newsletters";
            task.TaskClass        = "CMS.Newsletters.DynamicNewsletterSender";
            task.TaskDisplayName  = TextHelper.LimitLength(GetString("DynamicNewsletter.TaskName") + editedObject.NewsletterDisplayName, maxLength, CutTextEnum.End);
            task.TaskEnabled      = true;
            task.TaskInterval     = ScheduleInterval.ScheduleInterval;
            task.TaskLastResult   = string.Empty;
            task.TaskName         = ValidationHelper.GetCodeName("DynamicNewsletter." + editedObject.NewsletterName, "_", maxLength - newsletterGUID.Length) + newsletterGUID;
            task.TaskSiteID       = SiteContext.CurrentSiteID;
            task.TaskNextRunTime  = SchedulingHelper.GetNextTime(ScheduleInterval.TaskInterval);
            task.TaskData         = newsletterGUID;
            // Set task for processing in external service
            task.TaskAllowExternalService = true;
            task.TaskUseExternalService   = (SchedulingHelper.UseExternalService && NewsletterHelper.UseExternalServiceForDynamicNewsletters(SiteContext.CurrentSiteName));
            task.TaskType = ScheduledTaskTypeEnum.System;

            TaskInfoProvider.SetTaskInfo(task);

            editedObject.NewsletterDynamicScheduledTaskID = task.TaskID;
            NewsletterInfoProvider.SetNewsletterInfo(editedObject);

            Redirect();
        }
        catch (Exception ex)
        {
            ShowError(GetString(ex.Message));
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterDialogScript(this);

        CurrentMaster.DisplayActionsPanel = true;
        chkRequireOptIn.CheckedChanged   += chkRequireOptIn_CheckedChanged;

        string siteName = CMSContext.CurrentSiteName;

        mBounceLimit         = NewsletterHelper.BouncedEmailsLimit(siteName);
        mBounceInfoAvailable = NewsletterHelper.MonitorBouncedEmails(siteName);

        newsletterId = QueryHelper.GetInteger("newsletterid", 0);
        NewsletterInfo newsletter = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);

        EditedObject = newsletter;

        // Check if newsletter enables double opt-in
        if ((newsletter != null) && !newsletter.NewsletterEnableOptIn)
        {
            chkRequireOptIn.Visible = false;
        }

        if (!RequestHelper.IsPostBack())
        {
            chkSendConfirmation.Checked = false;
        }

        // Initialize unigrid
        UniGridSubscribers.WhereCondition       = "NewsletterID = " + newsletterId;
        UniGridSubscribers.OnAction            += UniGridSubscribers_OnAction;
        UniGridSubscribers.OnExternalDataBound += UniGridSubscribers_OnExternalDataBound;

        // Initialize selectors and mass actions
        SetupSelectors();
    }
Example #12
0
        void btnSubscribe_Click(object sender, EventArgs e)
        {
            Page.Validate(validationGroup);
            if (!Page.IsValid)
            {
                return;
            }

            if (siteAvailableSubscriptions == null)
            {
                siteAvailableSubscriptions = NewsletterHelper.GetAvailableNewslettersForCurrentUser(siteSettings.SiteGuid);
            }

            if ((siteAvailableSubscriptions != null) && (siteAvailableSubscriptions.Count == 0))
            {
                pnlSubscribe.Visible     = false;
                pnlNoNewsletters.Visible = true;
                return;
            }

            currentUser = SiteUtils.GetCurrentSiteUser();
            DoSubscribe();
            if (hdnJs.Value != "js")
            {
                // this means javascript was not enabled so this was a full postback not an ajax postback
                // to get out of postback we will redirect to a thank you page
                WebUtils.SetupRedirect(this, siteRoot + "/eletter/ThankYou.aspx");
                return;
            }
            else
            {
                pnlSubscribe.Visible = false;
                pnlThanks.Visible    = true;
                UpdatePanel1.Update();
            }
        }
Example #13
0
 protected void Page_Load(object sender, EventArgs e)
 {
     mBounceLimit = NewsletterHelper.BouncedEmailsLimit(SiteContext.CurrentSiteName);
 }
Example #14
0
 private void LoadMarketableRecipientsCount()
 {
     var newsletterMarketableRecipientsCount = NewsletterHelper.GetNewsletterMarketableRecipientsCount(mNewsletter);
     ltlTotalRecipientsCount.Text = ResHelper.GetStringFormat("emailmarketing.ui.recipientsheader", newsletterMarketableRecipientsCount);
 }
    /// <summary>
    /// Initializes header action control.
    /// </summary>
    /// <param name="issueId">Issue ID</param>
    private void InitHeaderActions(int issueId)
    {
        // Show info message and get current issue state
        bool editingEnabled;
        bool variantSliderEnabled;

        UpdateDialog(issueId, out editingEnabled, out variantSliderEnabled);
        editElem.Enabled = editingEnabled;

        bool isIssueVariant = ucVariantSlider.Variants.Count > 0;

        ucVariantSlider.Visible        = isIssueVariant;
        ucVariantSlider.EditingEnabled = editingEnabled && variantSliderEnabled;

        ScriptHelper.RegisterDialogScript(Page);

        CurrentMaster.HeaderActions.ActionsList.Clear();

        // Init save button
        CurrentMaster.HeaderActions.ActionsList.Add(new SaveAction
        {
            OnClientClick = "if (GetContent != null) {return GetContent();} else {return false;}",
            Enabled       = editingEnabled
        });

        // Ensure spell check action
        if (editingEnabled)
        {
            CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction
            {
                Text          = GetString("EditMenu.IconSpellCheck"),
                Tooltip       = GetString("EditMenu.SpellCheck"),
                OnClientClick = "var frame = GetFrame(); if ((frame != null) && (frame.contentWindow.SpellCheck_" + ClientID + " != null)) {frame.contentWindow.SpellCheck_" + ClientID + "();} return false;",
                ButtonStyle   = ButtonStyle.Default,
            });
        }

        // Init send draft button
        CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("newsletterissue_content.senddraft"),
            Tooltip       = GetString("newsletterissue_content.senddraft"),
            OnClientClick = string.Format(@"if (modalDialog) {{modalDialog('{0}?objectid={1}', 'SendDraft', '700', '300');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_SendDraft.aspx"), issueId) + " return false;",
            Enabled       = true,
            ButtonStyle   = ButtonStyle.Default,
        });

        // Init preview button
        CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("general.preview"),
            Tooltip       = GetString("general.preview"),
            OnClientClick = string.Format(@"if (modalDialog) {{modalDialog('{0}?objectid={1}', 'Preview', '90%', '90%');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_Preview.aspx"), issueId) + " return false;",
            ButtonStyle   = ButtonStyle.Default,
        });

        int attachCount = 0;
        // Get number of attachments
        InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(issueId,
                                                                          (isIssueVariant ? IssueInfo.OBJECT_TYPE_VARIANT : IssueInfo.OBJECT_TYPE), ObjectAttachmentsCategories.ISSUE, null, null, "MetafileID", -1);

        attachCount = ds.Items.Count;

        // Register attachments count update module
        ScriptHelper.RegisterModule(this, "CMS/AttachmentsCountUpdater", new { Selector = "." + mAttachmentsActionClass, Text = ResHelper.GetString("general.attachments") });


        // Prepare metafile dialog URL
        string metaFileDialogUrl = ResolveUrl(@"~/CMSModules/AdminControls/Controls/MetaFiles/MetaFileDialog.aspx");
        string query             = string.Format("?objectid={0}&objecttype={1}", issueId, (isIssueVariant? IssueInfo.OBJECT_TYPE_VARIANT : IssueInfo.OBJECT_TYPE));

        metaFileDialogUrl += string.Format("{0}&category={1}&hash={2}", query, ObjectAttachmentsCategories.ISSUE, QueryHelper.GetHash(query));

        // Init attachment button
        CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("general.attachments") + ((attachCount > 0) ? " (" + attachCount + ")" : string.Empty),
            Tooltip       = GetString("general.attachments"),
            OnClientClick = string.Format(@"if (modalDialog) {{modalDialog('{0}', 'Attachments', '700', '500');}}", metaFileDialogUrl) + " return false;",
            Enabled       = true,
            CssClass      = mAttachmentsActionClass,
            ButtonStyle   = ButtonStyle.Default,
        });

        // Init create A/B test button - online marketing, open email and click through tracking are required
        if (!isIssueVariant)
        {
            IssueInfo issue = (IssueInfo)EditedObject;
            if (editingEnabled && (issue.IssueStatus == IssueStatusEnum.Idle) && NewsletterHelper.IsABTestingAvailable())
            {
                // Check that trackings are enabled
                bool trackingsEnabled = (newsletter != null) && newsletter.NewsletterTrackOpenEmails && newsletter.NewsletterTrackClickedLinks;

                CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction
                {
                    Text          = GetString("newsletterissue_content.createabtest"),
                    Tooltip       = trackingsEnabled ? GetString("newsletterissue_content.createabtest") : GetString("newsletterissue_content.abtesttooltip"),
                    OnClientClick = trackingsEnabled ? "ShowVariantDialog_" + ucVariantDialog.ClientID + "('addvariant', ''); return false;" : "return false;",
                    Enabled       = trackingsEnabled,
                    ButtonStyle   = ButtonStyle.Default,
                });
                ucVariantDialog.IssueID       = issueId;
                ucVariantDialog.OnAddVariant += ucVariantSlider_OnVariantAdded;
            }
        }

        // Init masterpage
        CurrentMaster.HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;
        CurrentMaster.DisplayControlsPanel           = isIssueVariant;
        CurrentMaster.PanelContent.Attributes.Add("onmouseout", "if (RememberFocusedRegion) {RememberFocusedRegion();}");
    }
        private void CreateUser(
            string openId,
            string email,
            string loginName,
            string name)
        {
            SiteUser newUser = new SiteUser(siteSettings);

            newUser.Email = email;

            if (loginName.Length > 50)
            {
                loginName = loginName.Substring(0, 50);
            }

            int i = 1;

            while (SiteUser.LoginExistsInDB(
                       siteSettings.SiteId, loginName))
            {
                loginName += i.ToString();
                if (loginName.Length > 50)
                {
                    loginName = loginName.Remove(40, 1);
                }
                i++;
            }
            if ((name == null) || (name.Length == 0))
            {
                name = loginName;
            }
            newUser.LoginName = loginName;
            newUser.Name      = name;
            //newUser.Password = SiteUser.CreateRandomPassword(7);
            mojoMembershipProvider mojoMembership = (mojoMembershipProvider)Membership.Provider;

            newUser.Password         = mojoMembership.EncodePassword(siteSettings, newUser, SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars));
            newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            newUser.PasswordAnswer   = Resource.ManageUsersDefaultSecurityAnswer;
            newUser.OpenIdUri        = openId;
            newUser.Save();
            if (siteSettings.UseSecureRegistration)
            {
                newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());
            }

            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            // set default values first
            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                mojoProfilePropertyDefinition.SavePropertyDefault(
                    newUser, propertyDefinition);
            }

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                if ((propertyDefinition.RequiredForRegistration) || (propertyDefinition.ShowOnRegistration))
                {
                    mojoProfilePropertyDefinition.SaveProperty(
                        newUser,
                        pnlRequiredProfileProperties,
                        propertyDefinition,
                        timeOffset,
                        timeZone);
                }
            }

            // track user ip address
            UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());

            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Page.Request.UserHostName;
            userLocation.Save();

            UserRegisteredEventArgs u = new UserRegisteredEventArgs(newUser);

            OnUserRegistered(u);

            CacheHelper.ClearMembershipStatisticsCache();

            NewsletterHelper.ClaimExistingSubscriptions(newUser);

            DoUserLogin(newUser);
        }
        private SiteUser CreateUser(
            string openId,
            string email,
            string loginName,
            string name,
            bool emailIsVerified)
        {
            SiteUser newUser = new SiteUser(siteSettings);

            newUser.Email = email;

            if (loginName.Length > 50)
            {
                loginName = loginName.Substring(0, 50);
            }

            int i = 1;

            while (SiteUser.LoginExistsInDB(
                       siteSettings.SiteId, loginName))
            {
                loginName += i.ToString();
                if (loginName.Length > 50)
                {
                    loginName = loginName.Remove(40, 1);
                }
                i++;
            }
            if ((name == null) || (name.Length == 0))
            {
                name = loginName;
            }
            newUser.LoginName = loginName;
            newUser.Name      = name;
            //newUser.Password = SiteUser.CreateRandomPassword(7);
            CMembershipProvider CMembership = (CMembershipProvider)Membership.Provider;

            newUser.Password         = CMembership.EncodePassword(SiteUser.CreateRandomPassword(7), siteSettings);
            newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            newUser.PasswordAnswer   = Resource.ManageUsersDefaultSecurityAnswer;
            newUser.OpenIdUri        = openId;
            newUser.Save();
            if (siteSettings.UseSecureRegistration)
            {
                if (!emailIsVerified)
                {
                    newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());
                }
            }

            CProfileConfiguration profileConfig
                = CProfileConfiguration.GetConfig();

            // set default values first
            foreach (CProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                CProfilePropertyDefinition.SavePropertyDefault(
                    newUser, propertyDefinition);
            }

            foreach (CProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                if (propertyDefinition.RequiredForRegistration)
                {
                    CProfilePropertyDefinition.SaveProperty(
                        newUser,
                        pnlRequiredProfileProperties,
                        propertyDefinition,
                        timeOffset);
                }
            }

            // track user ip address
            UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());

            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Page.Request.UserHostName;
            userLocation.Save();

            UserRegisteredEventArgs u = new UserRegisteredEventArgs(newUser);

            OnUserRegistered(u);

            CacheHelper.TouchMembershipStatisticsCacheDependencyFile();

            // we'll map them next time they login
            //OpenIdRpxHelper rpxHelper = new OpenIdRpxHelper(rpxApiKey, rpxBaseUrl);
            //rpxHelper.Map(openId, newUser.UserGuid.ToString());

            NewsletterHelper.ClaimExistingSubscriptions(newUser);

            return(newUser);
        }
Example #18
0
        private SiteUser CreateUser(
            string openId,
            string email,
            string loginName,
            string name,
            bool emailIsVerified)
        {
            SiteUser newUser = new SiteUser(siteSettings);

            newUser.Email = email;

            if (loginName.Length > 50)
            {
                loginName = loginName.Substring(0, 50);
            }

            int i = 1;

            while (SiteUser.LoginExistsInDB(
                       siteSettings.SiteId, loginName))
            {
                loginName += i.ToString();
                if (loginName.Length > 50)
                {
                    loginName = loginName.Remove(40, 1);
                }
                i++;
            }
            if ((name == null) || (name.Length == 0))
            {
                name = loginName;
            }
            newUser.LoginName = loginName;
            newUser.Name      = name;
            //newUser.Password = SiteUser.CreateRandomPassword(7);
            mojoMembershipProvider mojoMembership = (mojoMembershipProvider)Membership.Provider;

            newUser.Password         = mojoMembership.EncodePassword(siteSettings, newUser, SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars));
            newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            newUser.PasswordAnswer   = Resource.ManageUsersDefaultSecurityAnswer;
            newUser.OpenIdUri        = openId;
            newUser.Save();

            //test
            //emailIsVerified = false;

            if (siteSettings.UseSecureRegistration)
            {
                if (!emailIsVerified)
                {
                    newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());
                }
            }



            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            // set default values first
            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey)
                {
                    continue;
                }
                mojoProfilePropertyDefinition.SavePropertyDefault(
                    newUser, propertyDefinition);
            }

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey)
                {
                    continue;
                }
                if ((propertyDefinition.RequiredForRegistration) || (propertyDefinition.ShowOnRegistration))
                {
                    mojoProfilePropertyDefinition.SaveProperty(
                        newUser,
                        pnlRequiredProfileProperties,
                        propertyDefinition,
                        timeOffset,
                        timeZone);
                }
            }

            // track user ip address
            UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());

            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Page.Request.UserHostName;
            userLocation.Save();

            UserRegisteredEventArgs u = new UserRegisteredEventArgs(newUser);

            OnUserRegistered(u);

            CacheHelper.ClearMembershipStatisticsCache();

            // we'll map them next time they login
            //OpenIdRpxHelper rpxHelper = new OpenIdRpxHelper(rpxApiKey, rpxBaseUrl);
            //rpxHelper.Map(openId, newUser.UserGuid.ToString());

            DoSubscribe(newUser);

            NewsletterHelper.ClaimExistingSubscriptions(newUser);

            return(newUser);
        }
    /// <summary>
    /// Initializes header action control.
    /// </summary>
    private void InitHeaderActions()
    {
        bool isNew          = (IssueId == 0);
        bool isIssueVariant = !isNew && IssueInfoProvider.IsABTestIssue(IssueId);

        hdrActions.ActionsList.Clear();

        // Init save button
        hdrActions.ActionsList.Add(new SaveAction(this)
        {
            OnClientClick = "if (GetContent != null) {return GetContent();} else {return false;}"
        });

        // Ensure spell check action
        hdrActions.ActionsList.Add(new HeaderAction()
        {
            CssClass      = "MenuItemEdit",
            Text          = GetString("EditMenu.IconSpellCheck"),
            Tooltip       = GetString("EditMenu.SpellCheck"),
            OnClientClick = "var frame = GetFrame(); if ((frame != null) && (frame.contentWindow.SpellCheck_" + ClientID + " != null)) {frame.contentWindow.SpellCheck_" + ClientID + "();} return false;",
            ImageUrl      = GetImageUrl("CMSModules/CMS_Content/EditMenu/spellcheck.png"),
            SmallImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/16/spellcheck.png"),
        });

        // Init send draft button
        hdrActions.ActionsList.Add(new HeaderAction()
        {
            ControlType   = HeaderActionTypeEnum.LinkButton,
            Text          = GetString("newsletterissue_content.senddraft"),
            Tooltip       = GetString("newsletterissue_content.senddraft"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}?issueid={1}', 'SendDraft', '500', '300');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_SendDraft.aspx"), IssueId) + " return false;",
            ImageUrl      = (isNew) ? GetImageUrl("CMSModules/CMS_Newsletter/senddraft_disabled.png") : GetImageUrl("CMSModules/CMS_Newsletter/senddraft.png"),
            Enabled       = !isNew
        });

        // Init preview button
        hdrActions.ActionsList.Add(new HeaderAction()
        {
            ControlType   = HeaderActionTypeEnum.Hyperlink,
            Text          = GetString("general.preview"),
            Tooltip       = GetString("general.preview"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}?issueid={1}', 'Preview', '90%', '90%');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_Preview.aspx"), IssueId) + " return false;",
            ImageUrl      = (isNew) ? GetImageUrl("CMSModules/CMS_Newsletter/preview_disabled.png") : GetImageUrl("CMSModules/CMS_Newsletter/preview.png"),
            Enabled       = !isNew
        });

        int    attachCount       = 0;
        string metaFileDialogUrl = null;

        if (!isNew)
        {
            ScriptHelper.RegisterDialogScript(Page);

            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(IssueId,
                                                                              (isIssueVariant ? NewsletterObjectType.NEWSLETTERISSUEVARIANT : NewsletterObjectType.NEWSLETTERISSUE),
                                                                              MetaFileInfoProvider.OBJECT_CATEGORY_ISSUE, null, null, "MetafileID", -1);
            attachCount = ds.Items.Count;

            string script = @"function UpdateAttachmentCount(count) {
                                var counter = document.getElementById('attachmentCount');
                                if (counter != null) {
                                    if (count > 0) { counter.innerHTML = ' (' + count + ')'; }
                                    else { counter.innerHTML = ''; }
                                }
                            }";
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "UpdateAttachmentScript_" + this.ClientID, script, true);

            // Prepare metafile dialog URL
            metaFileDialogUrl = ResolveUrl(@"~/CMSModules/AdminControls/Controls/MetaFiles/MetaFileDialog.aspx");
            string query = string.Format("?objectid={0}&objecttype={1}", IssueId, (isIssueVariant ? NewsletterObjectType.NEWSLETTERISSUEVARIANT : NewsletterObjectType.NEWSLETTERISSUE));
            metaFileDialogUrl += string.Format("{0}&category={1}&hash={2}", query, MetaFileInfoProvider.OBJECT_CATEGORY_ISSUE, QueryHelper.GetHash(query));
        }

        // Init attachment button
        hdrActions.ActionsList.Add(new HeaderAction()
        {
            ControlType   = HeaderActionTypeEnum.LinkButton,
            Text          = GetString("general.attachments") + string.Format("<span id='attachmentCount'>{0}</span>", (attachCount > 0) ? " (" + attachCount.ToString() + ")" : string.Empty),
            Tooltip       = GetString("general.attachments"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}', 'Attachments', '700', '500');}}", metaFileDialogUrl) + " return false;",
            ImageUrl      = (isNew) ? GetImageUrl("Objects/CMS_MetaFile/attachment_disabled.png") : GetImageUrl("Objects/CMS_MetaFile/attachment.png"),
            Enabled       = !isNew
        });

        // Init create A/B test button - online marketing, open email and click through tracking are required
        if (isNew || !isIssueVariant)
        {
            if (NewsletterHelper.IsABTestingAvailable())
            {
                // Check that trackings are enabled
                NewsletterInfo news             = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);
                bool           trackingsEnabled = (news != null) && news.NewsletterTrackOpenEmails && news.NewsletterTrackClickedLinks;

                hdrActions.ActionsList.Add(new HeaderAction()
                {
                    ControlType   = HeaderActionTypeEnum.LinkButton,
                    Text          = GetString("newsletterissue_content.createabtest"),
                    Tooltip       = trackingsEnabled ? GetString("newsletterissue_content.createabtest") : GetString("newsletterissue_content.abtesttooltip"),
                    OnClientClick = (isNew || !trackingsEnabled) ? "return false;" : "ShowVariantDialog_" + ucVariantDialog.ClientID + "('addvariant', ''); return false;",
                    ImageUrl      = (isNew || !trackingsEnabled) ? GetImageUrl("CMSModules/CMS_Newsletter/abtest_disabled.png") : GetImageUrl("CMSModules/CMS_Newsletter/abtest.png"),
                    Enabled       = !isNew && trackingsEnabled
                });
                ucVariantDialog.IssueID       = IssueId;
                ucVariantDialog.OnAddVariant += new EventHandler(ucVariantSlider_OnVariantAdded);
            }
        }

        hdrActions.ActionPerformed += HeaderActions_ActionPerformed;
        hdrActions.ReloadData();
        pnlActions.Attributes.Add("onmouseover", "if (RememberFocusedRegion) {RememberFocusedRegion();}");
    }
Example #20
0
    /// <summary>
    /// Initializes header action control.
    /// </summary>
    /// <param name="issueId">Issue ID</param>
    private void InitHeaderActions(int issueId)
    {
        // Show info message and get current issue state
        bool editingEnabled       = false;
        bool variantSliderEnabled = false;

        UpdateDialog(issueId, out editingEnabled, out variantSliderEnabled);
        editElem.Enabled = editingEnabled;

        bool   isAuthorized   = CurrentUser.IsAuthorizedPerResource("CMS.Newsletter", "AuthorIssues");
        bool   isIssueVariant = ucVariantSlider.Variants.Count > 0;
        string script         = null;

        ucVariantSlider.Visible        = isIssueVariant;
        ucVariantSlider.EditingEnabled = editingEnabled && variantSliderEnabled;

        ScriptHelper.RegisterDialogScript(Page);

        CurrentMaster.HeaderActions.ActionsList.Clear();

        // Init save button
        CurrentMaster.HeaderActions.ActionsList.Add(new SaveAction(this)
        {
            OnClientClick = "if (GetContent != null) {return GetContent();} else {return false;}",
            SmallImageUrl = isAuthorized && editingEnabled ? GetImageUrl("CMSModules/CMS_Content/EditMenu/16/save.png") : GetImageUrl("CMSModules/CMS_Content/EditMenu/16/savedisabled.png"),
            Enabled       = isAuthorized && editingEnabled
        });

        // Ensure spell check action
        if (isAuthorized && editingEnabled)
        {
            CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction()
            {
                CssClass      = "MenuItemEdit",
                Text          = GetString("EditMenu.IconSpellCheck"),
                Tooltip       = GetString("EditMenu.SpellCheck"),
                OnClientClick = "var frame = GetFrame(); if ((frame != null) && (frame.contentWindow.SpellCheck_" + ClientID + " != null)) {frame.contentWindow.SpellCheck_" + ClientID + "();} return false;",
                ImageUrl      = GetImageUrl("CMSModules/CMS_Content/EditMenu/spellcheck.png"),
                SmallImageUrl = GetImageUrl("CMSModules/CMS_Content/EditMenu/16/spellcheck.png"),
            });
        }

        // Init send draft button
        CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction()
        {
            ControlType   = HeaderActionTypeEnum.LinkButton,
            Text          = GetString("newsletterissue_content.senddraft"),
            Tooltip       = GetString("newsletterissue_content.senddraft"),
            OnClientClick = string.Format(@"if (modalDialog) {{modalDialog('{0}?issueid={1}', 'SendDraft', '500', '300');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_SendDraft.aspx"), issueId) + " return false;",
            ImageUrl      = GetImageUrl("CMSModules/CMS_Newsletter/senddraft.png"),
            Enabled       = isAuthorized
        });

        // Init preview button
        CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction()
        {
            ControlType   = HeaderActionTypeEnum.Hyperlink,
            Text          = GetString("general.preview"),
            Tooltip       = GetString("general.preview"),
            OnClientClick = string.Format(@"if (modalDialog) {{modalDialog('{0}?issueid={1}', 'Preview', '90%', '90%');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_Preview.aspx"), issueId) + " return false;",
            ImageUrl      = GetImageUrl("CMSModules/CMS_Newsletter/preview.png")
        });

        int attachCount = 0;

        if (isAuthorized)
        {
            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(issueId,
                                                                              (isIssueVariant ? NewsletterObjectType.NEWSLETTERISSUEVARIANT : NewsletterObjectType.NEWSLETTERISSUE), MetaFileInfoProvider.OBJECT_CATEGORY_ISSUE, null, null, "MetafileID", -1);
            attachCount = ds.Items.Count;

            script = @"
function UpdateAttachmentCount(count) {
    var counter = document.getElementById('attachmentCount');
    if (counter != null) {
        if (count > 0) { counter.innerHTML = ' (' + count + ')'; }
        else { counter.innerHTML = ''; }
    }
}";
            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "UpdateAttachmentScript_" + ClientID, script, true);
        }

        // Prepare metafile dialog URL
        string metaFileDialogUrl = ResolveUrl(@"~/CMSModules/AdminControls/Controls/MetaFiles/MetaFileDialog.aspx");
        string query             = string.Format("?objectid={0}&objecttype={1}", issueId, (isIssueVariant? NewsletterObjectType.NEWSLETTERISSUEVARIANT : NewsletterObjectType.NEWSLETTERISSUE));

        metaFileDialogUrl += string.Format("{0}&category={1}&hash={2}", query, MetaFileInfoProvider.OBJECT_CATEGORY_ISSUE, QueryHelper.GetHash(query));

        // Init attachment button
        CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction()
        {
            ControlType   = HeaderActionTypeEnum.LinkButton,
            Text          = GetString("general.attachments") + string.Format("<span id='attachmentCount'>{0}</span>", (attachCount > 0) ? " (" + attachCount.ToString() + ")" : string.Empty),
            Tooltip       = GetString("general.attachments"),
            OnClientClick = string.Format(@"if (modalDialog) {{modalDialog('{0}', 'Attachments', '700', '500');}}", metaFileDialogUrl) + " return false;",
            ImageUrl      = GetImageUrl("Objects/CMS_MetaFile/attachment.png"),
            Enabled       = isAuthorized
        });

        // Init create A/B test button - online marketing, open email and click through tracking are required
        if (!isIssueVariant)
        {
            IssueInfo issue = (IssueInfo)EditedObject;
            if (editingEnabled && (issue.IssueStatus == IssueStatusEnum.Idle) && NewsletterHelper.IsABTestingAvailable())
            {
                // Check that trackings are enabled
                bool trackingsEnabled = (newsletter != null) && newsletter.NewsletterTrackOpenEmails && newsletter.NewsletterTrackClickedLinks;

                CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction()
                {
                    ControlType   = HeaderActionTypeEnum.LinkButton,
                    Text          = GetString("newsletterissue_content.createabtest"),
                    Tooltip       = trackingsEnabled ? GetString("newsletterissue_content.createabtest") : GetString("newsletterissue_content.abtesttooltip"),
                    OnClientClick = isAuthorized && trackingsEnabled ? "ShowVariantDialog_" + ucVariantDialog.ClientID + "('addvariant', ''); return false;" : "return false;",
                    ImageUrl      = isAuthorized && trackingsEnabled ? GetImageUrl("CMSModules/CMS_Newsletter/abtest.png") : GetImageUrl("CMSModules/CMS_Newsletter/abtest_disabled.png"),
                    Enabled       = isAuthorized && trackingsEnabled
                });
                ucVariantDialog.IssueID       = issueId;
                ucVariantDialog.OnAddVariant += new EventHandler(ucVariantSlider_OnVariantAdded);
            }
        }

        // Init fullscreen button
        string imageOff = ResolveUrl(GetImageUrl("CMSModules/CMS_Newsletter/fullscreenoff.png"));
        string imageOn  = ResolveUrl(GetImageUrl("CMSModules/CMS_Newsletter/fullscreenon.png"));

        // Create fullscreen toogle function
        script = string.Format(@"
function ToogleFullScreen(elem) {{
 if (window.maximized) {{
     window.maximized = false;
     $j(elem).find('img').attr('src','{0}');
     MaximizeAll(top.window);
 }} else {{
     window.maximized = true;
     $j(elem).find('img').attr('src','{1}');
     MinimizeAll(top.window);
 }}
}}", imageOff, imageOn);

        // Register fullscreen toogle function and necessary scripts
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ToogleFullScreen_" + ClientID, script, true);
        ScriptHelper.RegisterResizer(this);
        ScriptHelper.RegisterJQuery(this);

        CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction()
        {
            ControlType   = HeaderActionTypeEnum.LinkButton,
            Text          = GetString("general.fullscreen"),
            OnClientClick = "ToogleFullScreen(this);return false;",
            ImageUrl      = GetImageUrl("CMSModules/CMS_Newsletter/fullscreenoff.png"),
            CssClass      = !isIssueVariant ? "MenuItemEdit Right" : "MenuItemEdit RightABVariant"
        });

        // Init masterpage
        CurrentMaster.HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;
        CurrentMaster.DisplayControlsPanel           = isIssueVariant;
        CurrentMaster.PanelContent.Attributes.Add("onmouseout", "if (RememberFocusedRegion) {RememberFocusedRegion();}");
    }
Example #21
0
        private void DoSubscribe(LetterInfo letter, string email)
        {
            if (email == "*****@*****.**")
            {
                return;
            }                                           //I've been seeing a lot of this from a bot

            LetterSubscriber s = subscriptions.Fetch(siteSettings.SiteGuid, letter.LetterInfoGuid, email);

            bool needToSendVerification = false;

            if (s == null)
            {
                s                = new LetterSubscriber();
                s.SiteGuid       = siteSettings.SiteGuid;
                s.EmailAddress   = email;
                s.LetterInfoGuid = letter.LetterInfoGuid;
                if (showFormatOptions)
                {
                    s.UseHtml = rbHtmlFormat.Checked;
                }
                else
                {
                    s.UseHtml = htmlIsDefault;
                }

                if ((currentUser != null) && (string.Equals(currentUser.Email, email, StringComparison.InvariantCultureIgnoreCase)))
                {
                    s.UserGuid   = currentUser.UserGuid;
                    s.IsVerified = true;
                }
                else
                {
                    // user is not authenticated but may still exist
                    // attach userguid but don't flag as verified
                    // because we don't know that the user who submited the form is the account owner
                    SiteUser siteUser = SiteUser.GetByEmail(siteSettings, email);
                    if (siteUser != null)
                    {
                        s.UserGuid = siteUser.UserGuid;
                    }
                }
                s.IpAddress = SiteUtils.GetIP4Address();
                subscriptions.Save(s);

                LetterInfo.UpdateSubscriberCount(s.LetterInfoGuid);

                if (WebConfigSettings.LogNewsletterSubscriptions)
                {
                    log.Info(s.EmailAddress + " just subscribed to newsletter " + letter.Title);
                }


                if (!s.IsVerified)
                {
                    needToSendVerification = true;
                }
            }
            else
            {
                // we found an existing subscription

                if (!s.IsVerified)
                {
                    // if the current authenticated user has the same email mark it as verified
                    if ((currentUser != null) && (string.Equals(currentUser.Email, email, StringComparison.InvariantCultureIgnoreCase)))
                    {
                        s.UserGuid = currentUser.UserGuid;
                        if (showFormatOptions)
                        {
                            s.UseHtml = rbHtmlFormat.Checked;
                        }
                        subscriptions.Save(s);
                        subscriptions.Verify(s.SubscribeGuid, true, Guid.Empty);
                    }
                    else if (s.BeginUtc < DateTime.UtcNow.AddDays(-WebConfigSettings.NewsletterReVerifcationAfterDays))
                    {
                        // if the user never verifed before and its been at least x days go ahead and send another chance to verify
                        needToSendVerification = true;
                        // TODO: maybe we should log this in case some spam script is using the same email over and over
                        // or maybe we should add a verification sent count on subscription
                    }
                }
            }

            //added 2012-05-16 to support intranet scenarios where verification is not required
            if (!WebConfigSettings.NewsletterRequireVerification)
            {
                if (!s.IsVerified)
                {
                    s.IsVerified = true;
                    subscriptions.Save(s);
                }
                needToSendVerification = false;
            }

            if (needToSendVerification)
            {
                NewsletterHelper.SendSubscriberVerificationEmail(
                    siteRoot,
                    email,
                    s.SubscribeGuid,
                    letter,
                    siteSettings);
            }
        }
Example #22
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Check 'configure' permission
        if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.newsletter", "configure"))
        {
            RedirectToCMSDeskAccessDenied("cms.newsletter", "configure");
        }

        // Validate base inputs (newsletter display name, code name, sender name, sender e-mail)
        string errorMessage = new Validator().NotEmpty(txtNewsletterDisplayName.Text.Trim(), GetString("general.requiresdisplayname")).NotEmpty(txtNewsletterName.Text.Trim(), GetString("Newsletter_Edit.ErrorEmptyName")).NotEmpty(txtNewsletterSenderName.Text.Trim(), GetString("Newsletter_Edit.ErrorEmptySenderName")).NotEmpty(txtNewsletterSenderEmail.Text.Trim(), GetString("Newsletter_Edit.ErrorEmptySenderEmail")).IsEmail(txtNewsletterSenderEmail.Text.Trim(), GetString("Newsletter_Edit.ErrorEmailFormat")).IsCodeName(txtNewsletterName.Text.Trim(), GetString("general.invalidcodename")).Result;

        if (String.IsNullOrEmpty(errorMessage))
        {
            if (String.IsNullOrEmpty((string)subscriptionTemplate.Value))
            {
                // No subscription template selected
                lblSubscriptionError.Visible = true;
                return;
            }

            if (String.IsNullOrEmpty((string)unsubscriptionTemplate.Value))
            {
                // No unsubscription template selected
                lblUnsubscriptionError.Visible = true;
                return;
            }

            if ((radTemplateBased.Checked) && (String.IsNullOrEmpty((string)issueTemplate.Value)))
            {
                // No issue template selected for template based newsletter
                lblIssueError.Visible = true;
                return;
            }

            if ((radDynamic.Checked) && (String.IsNullOrEmpty(txtNewsletterDynamicURL.Text.Trim())))
            {
                // Dynamic URL cannot be empty
                ShowError(GetString("menuitem_edit.errorpageurlempty"));
                return;
            }

            if ((radDynamic.Checked) && (chkSchedule.Checked) && (!ScheduleInterval.CheckOneDayMinimum()))
            {
                // Problem occurred while setting schedule interval for dynamic newsletter
                ShowError(GetString("Newsletter_Edit.NoDaySelected"));
                return;
            }

            if ((radDynamic.Checked) && (chkSchedule.Checked) && (SchedulingHelper.DecodeInterval(ScheduleInterval.ScheduleInterval).StartTime == DateTime.MinValue))
            {
                ShowError(GetString("Newsletter.IncorrectDate"));
                return;
            }

            // Newsletter code name must to be unique per site...
            NewsletterInfo newsletterObj = NewsletterInfoProvider.GetNewsletterInfo(txtNewsletterName.Text.Trim(), CMSContext.CurrentSiteID);

            // If newsletter code name is unique...
            if (newsletterObj == null)
            {
                // Create new item -> insert
                newsletterObj = new NewsletterInfo();

                newsletterObj.NewsletterDisplayName = txtNewsletterDisplayName.Text.Trim();
                newsletterObj.NewsletterName        = txtNewsletterName.Text.Trim();

                int selectedValue = ValidationHelper.GetInteger(subscriptionTemplate.Value, 0);
                if (selectedValue != 0)
                {
                    newsletterObj.NewsletterSubscriptionTemplateID = selectedValue;
                }
                else
                {
                    ShowError(GetString("Newsletter_Edit.NoSubscriptionTemplateSelected"));
                    return;
                }

                selectedValue = ValidationHelper.GetInteger(unsubscriptionTemplate.Value, 0);
                if (selectedValue != 0)
                {
                    newsletterObj.NewsletterUnsubscriptionTemplateID = selectedValue;
                }
                else
                {
                    ShowError(GetString("Newsletter_Edit.NoUnsubscriptionTemplateSelected"));
                    return;
                }
                newsletterObj.NewsletterSenderName  = txtNewsletterSenderName.Text.Trim();
                newsletterObj.NewsletterSenderEmail = txtNewsletterSenderEmail.Text.Trim();
                if (radDynamic.Checked)
                {
                    newsletterObj.NewsletterDynamicURL = txtNewsletterDynamicURL.Text.Trim();
                    newsletterObj.NewsletterType       = NewsletterType.Dynamic;
                }
                else
                {
                    selectedValue = ValidationHelper.GetInteger(issueTemplate.Value, 0);
                    if (selectedValue != 0)
                    {
                        newsletterObj.NewsletterTemplateID = selectedValue;
                    }
                    else
                    {
                        ShowError(GetString("Newsletter_Edit.NoEmailTemplateSelected"));
                        return;
                    }
                    newsletterObj.NewsletterType = NewsletterType.TemplateBased;
                }
                newsletterObj.NewsletterSiteID          = CMSContext.CurrentSiteID;
                newsletterObj.NewsletterGUID            = Guid.NewGuid();
                newsletterObj.NewsletterLogActivity     = true;
                newsletterObj.NewsletterEnableResending = true;

                try
                {
                    // Create new newsletter
                    NewsletterInfoProvider.SetNewsletterInfo(newsletterObj);

                    if (radDynamic.Checked)
                    {
                        if (chkSchedule.Checked)
                        {
                            // Create new task to schedule the dynamic newsletter
                            TaskInfo task = new TaskInfo();
                            task.TaskAssemblyName = "CMS.Newsletter";
                            task.TaskClass        = "CMS.Newsletter.DynamicNewsletterSender";
                            task.TaskDisplayName  = GetString("DynamicNewsletter.TaskName") + newsletterObj.NewsletterDisplayName;
                            task.TaskEnabled      = true;
                            task.TaskInterval     = ScheduleInterval.ScheduleInterval;
                            task.TaskLastResult   = string.Empty;
                            task.TaskName         = "DynamicNewsletter." + ValidationHelper.GetCodeName(newsletterObj.NewsletterName, "_");
                            task.TaskSiteID       = CMSContext.CurrentSiteID;
                            task.TaskNextRunTime  = SchedulingHelper.GetNextTime(task.TaskInterval, new DateTime(), new DateTime());
                            task.TaskData         = newsletterObj.NewsletterGUID.ToString();
                            // Set task for processing in external service
                            task.TaskAllowExternalService = true;
                            task.TaskUseExternalService   = (SchedulingHelper.UseExternalService && NewsletterHelper.UseExternalServiceForDynamicNewsletters(CMSContext.CurrentSiteName));
                            task.TaskType = ScheduledTaskTypeEnum.System;

                            TaskInfoProvider.SetTaskInfo(task);

                            newsletterObj.NewsletterDynamicScheduledTaskID = task.TaskID;
                            NewsletterInfoProvider.SetNewsletterInfo(newsletterObj);
                        }
                    }
                    URLHelper.Redirect("Newsletter_Frameset.aspx?newsletterid=" + ValidationHelper.GetString(newsletterObj.NewsletterID, null) + "&saved=1");
                }
                catch (Exception ex)
                {
                    ShowError(GetString(ex.Message));
                }
            }
            else
            {
                ShowError(GetString("Newsletter_Edit.NewsletterNameExists"));
            }
        }
        else
        {
            ShowError(errorMessage);
        }
    }
    /// <summary>
    /// Returns all e-mail addresses for specified newsletter.
    /// </summary>
    /// <param name="newsletterId">Newsletter</param>
    /// <param name="siteId">Site</param>
    private int GetEmailAddressCount(int newsletterId, int siteId)
    {
        // Get e-mail addresses for ordinary subscriber, user subriber and role subscriber
        string siteName       = SiteInfoProvider.GetSiteName(siteId);
        int    emailAddresses = NewsletterInfoProvider.GetEmailAddressCount(newsletterId, siteName);

        DataSet ContactID = SubscriberNewsletterInfoProvider.GetSubscriptions(
            String.Format("NewsletterID={0} AND (SubscriptionApproved=1 OR SubscriptionApproved IS NULL) AND (SubscriptionEnabled=1 OR SubscriptionEnabled IS NULL) AND SubscriberType='om.contactgroup'", newsletterId), null, 0, "DISTINCT(SubscriberRelatedID) AS SubscriberRelatedID");

        if (!DataHelper.DataSourceIsEmpty(ContactID))
        {
            int groupId = 0;
            foreach (DataRow dr in ContactID.Tables[0].Rows)
            {
                groupId = ValidationHelper.GetInteger(dr[0], 0);

                DataSet dsMembers = ModuleCommands.OnlineMarketingGetContactGroupMemberIDs(groupId, 0, 0,
                                                                                           NewsletterHelper.MonitorBouncedEmails(siteName),
                                                                                           NewsletterHelper.BouncedEmailsLimit(siteName), newsletterId);
                if (!DataHelper.DataSourceIsEmpty(dsMembers))
                {
                    emailAddresses += ValidationHelper.GetInteger(dsMembers.Tables[0].Rows.Count, 0);
                }
            }
        }

        return(emailAddresses);
    }
Example #24
0
    /// <summary>
    /// Initializes header action control.
    /// </summary>
    private void InitHeaderActions()
    {
        bool isNew          = (IssueId == 0);
        var  issue          = IssueInfoProvider.GetIssueInfo(IssueId);
        bool isIssueVariant = !isNew && (issue != null) && issue.IssueIsABTest;

        hdrActions.ActionsList.Clear();

        // Init save button
        hdrActions.ActionsList.Add(new SaveAction(this)
        {
            OnClientClick = "if (GetContent != null) {return GetContent();} else {return false;}"
        });

        // Ensure spell check action
        hdrActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("EditMenu.IconSpellCheck"),
            Tooltip       = GetString("EditMenu.SpellCheck"),
            OnClientClick = "var frame = GetFrame(); if ((frame != null) && (frame.contentWindow.SpellCheck_" + ClientID + " != null)) {frame.contentWindow.SpellCheck_" + ClientID + "();} return false;"
        });

        // Init send draft button
        hdrActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("newsletterissue_content.senddraft"),
            Tooltip       = (isNew) ? GetString("newsletterissue_new.issueunsaved") : GetString("newsletterissue_content.senddraft"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}?objectid={1}', 'SendDraft', '700', '300');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_SendDraft.aspx"), IssueId) + " return false;",
            Enabled       = !isNew
        });

        // Init preview button
        hdrActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("general.preview"),
            Tooltip       = (isNew) ? GetString("newsletterissue_new.issueunsaved") : GetString("general.preview"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}?objectid={1}', 'Preview', '90%', '90%');}}", ResolveUrl(@"~/CMSModules/Newsletters/Tools/Newsletters/Newsletter_Issue_Preview.aspx"), IssueId) + " return false;",
            Enabled       = !isNew
        });

        int    attachCount       = 0;
        string metaFileDialogUrl = null;

        if (!isNew)
        {
            ScriptHelper.RegisterDialogScript(Page);

            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(IssueId,
                                                                              (isIssueVariant ? IssueInfo.OBJECT_TYPE_VARIANT : IssueInfo.OBJECT_TYPE),
                                                                              ObjectAttachmentsCategories.ISSUE, null, null, "MetafileID", -1);
            attachCount = ds.Items.Count;

            // Register attachments count update module
            ScriptHelper.RegisterModule(this, "CMS/AttachmentsCountUpdater", new { Selector = "." + mAttachmentsActionClass, Text = ResHelper.GetString("general.attachments") });

            // Prepare metafile dialog URL
            metaFileDialogUrl = ResolveUrl(@"~/CMSModules/AdminControls/Controls/MetaFiles/MetaFileDialog.aspx");
            string query = string.Format("?objectid={0}&objecttype={1}", IssueId, (isIssueVariant ? IssueInfo.OBJECT_TYPE_VARIANT : IssueInfo.OBJECT_TYPE));
            metaFileDialogUrl += string.Format("{0}&category={1}&hash={2}", query, ObjectAttachmentsCategories.ISSUE, QueryHelper.GetHash(query));
        }

        // Init attachment button
        hdrActions.ActionsList.Add(new HeaderAction
        {
            Text          = GetString("general.attachments") + ((attachCount > 0) ? " (" + attachCount + ")" : string.Empty),
            Tooltip       = (isNew) ? GetString("newsletterissue_new.issueunsaved") : GetString("general.attachments"),
            OnClientClick = (isNew) ? "return false;" : string.Format(@"if (modalDialog) {{modalDialog('{0}', 'Attachments', '700', '500');}}", metaFileDialogUrl) + " return false;",
            Enabled       = !isNew,
            CssClass      = mAttachmentsActionClass
        });

        // Init create A/B test button - online marketing, open email and click through tracking are required
        if (isNew || !isIssueVariant)
        {
            if (NewsletterHelper.IsABTestingAvailable())
            {
                // Check that trackings are enabled
                NewsletterInfo news             = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);
                bool           trackingsEnabled = (news != null) && news.NewsletterTrackOpenEmails && news.NewsletterTrackClickedLinks;

                hdrActions.ActionsList.Add(new HeaderAction
                {
                    Text          = GetString("newsletterissue_content.createabtest"),
                    Tooltip       = (isNew) ? GetString("newsletterissue_new.issueunsaved") : (trackingsEnabled ? GetString("newsletterissue_content.createabtest") : GetString("newsletterissue_content.abtesttooltip")),
                    OnClientClick = (isNew || !trackingsEnabled) ? "return false;" : "ShowVariantDialog_" + ucVariantDialog.ClientID + "('addvariant', ''); return false;",
                    Enabled       = !isNew && trackingsEnabled
                });
                ucVariantDialog.IssueID       = IssueId;
                ucVariantDialog.OnAddVariant += ucVariantSlider_OnVariantAdded;
            }
        }

        hdrActions.ActionPerformed += HeaderActions_ActionPerformed;
        hdrActions.ReloadData();
        pnlActions.Attributes.Add("onmouseover", "if (RememberFocusedRegion) {RememberFocusedRegion();}");
    }
Example #25
0
    /// <summary>
    /// Reloads control data.
    /// </summary>
    /// <param name="forceReload">Indicates if force reload should be used</param>
    public override void ReloadData(bool forceReload)
    {
        if (StopProcessing && !forceReload)
        {
            return;
        }

        if (ForceReloadNeeded)
        {
            forceReload       = true;
            ForceReloadNeeded = false;
        }

        int parentIssueId = 0;

        parentIssue = IssueInfoProvider.GetOriginalIssue(IssueID);
        if (parentIssue != null)
        {
            parentIssueId = parentIssue.IssueID;
        }

        // Get A/B test configuration
        abTest = ABTestInfoProvider.GetABTestInfoForIssue(parentIssueId);
        if (abTest == null)
        {
            // Ensure A/B test object with default settings
            abTest = new ABTestInfo()
            {
                TestIssueID = parentIssueId, TestSizePercentage = 50, TestWinnerOption = ABTestWinnerSelectionEnum.OpenRate, TestSelectWinnerAfter = 60
            };
            ABTestInfoProvider.SetABTestInfo(abTest);
        }

        CurrentState = GetCurrentState(parentIssue);
        InitControls(CurrentState, forceReload);

        ucMailout.ParentIssueID = parentIssueId;
        ucMailout.ReloadData(forceReload);

        InfoMessage = GetInfoMessage(CurrentState, parentIssue, (abTest != null ? abTest.TestWinnerOption : ABTestWinnerSelectionEnum.OpenRate), GetPlannedMailoutTime(ucMailout.HighestMailoutTime));

        // Init test group slider
        List <IssueABVariantItem> variants = IssueHelper.GetIssueVariants(parentIssue, null);

        ucGroupSlider.Variants = variants;
        bool allVariantsSent = true;

        if (variants != null)
        {
            allVariantsSent = variants.TrueForAll(delegate(IssueABVariantItem item) { return(item.IssueStatus == IssueStatusEnum.Finished); });
        }
        if ((parentIssue.IssueStatus == IssueStatusEnum.Finished) || allVariantsSent)
        {
            // Issue was sent long time ago => get number of subscribers from issue properties instead of current number of subscribers
            int perVariantEmails = 1;
            if (abTest != null)
            {
                perVariantEmails = abTest.TestNumberPerVariantEmails;
            }
            ucGroupSlider.NumberOfTestSubscribers = ucGroupSlider.Variants.Count * perVariantEmails;

            if (parentIssue.IssueStatus == IssueStatusEnum.Finished)
            {
                // Issue was sent => get number of subscribers from number of sent issues
                ucGroupSlider.NumberOfSubscribers = parentIssue.IssueSentEmails;
            }
            else
            {
                // Only variants was sent => get current number of subscribers
                ucGroupSlider.NumberOfSubscribers = NewsletterHelper.GetEmailAddressCount(parentIssue.IssueNewsletterID, parentIssue.IssueSiteID);
            }
        }
        else
        {
            ucGroupSlider.NumberOfSubscribers = NewsletterHelper.GetEmailAddressCount(parentIssue.IssueNewsletterID, parentIssue.IssueSiteID);
        }

        if (forceReload || !ucGroupSlider.Enabled)
        {
            ucGroupSlider.CurrentSize = (abTest != null ? abTest.TestSizePercentage : 10);
        }
        ucGroupSlider.ReloadData(forceReload);
        ucWO_OnChange(this, EventArgs.Empty);
    }
Example #26
0
    /// <summary>
    /// Saves configuration changes.
    /// </summary>
    protected void SaveData()
    {
        // Check "configure" permission
        if (!CMSContext.CurrentUser.IsAuthorizedPerResource("cms.newsletter", "configure"))
        {
            RedirectToCMSDeskAccessDenied("cms.newsletter", "configure");
        }

        string scheduledInterval = null;

        if (isDynamic && chkSchedule.Checked)
        {
            // Get scheduled interval for dynamic newsletter
            scheduledInterval = schedulerInterval.ScheduleInterval;
        }

        string errorMessage = ValidateNewsletterValues();

        if (!string.IsNullOrEmpty(errorMessage))
        {
            ShowError(errorMessage);
            return;
        }

        NewsletterInfo newsletterObj = NewsletterInfoProvider.GetNewsletterInfo(txtNewsletterName.Text.Trim(), CMSContext.CurrentSiteID);

        // Newsletter's code name must be unique
        if (newsletterObj != null && newsletterObj.NewsletterID != newsletterId)
        {
            ShowError(GetString("Newsletter_Edit.NewsletterNameExists"));
            return;
        }

        if (newsletterObj == null)
        {
            newsletterObj = NewsletterInfoProvider.GetNewsletterInfo(newsletterId);
        }

        SetNewsletterValues(newsletterObj);

        // Check if subscription template was selected
        int subscriptionTemplateValue = ValidationHelper.GetInteger(subscriptionTemplate.Value, 0);

        if (subscriptionTemplateValue == 0)
        {
            ShowError(GetString("Newsletter_Edit.NoSubscriptionTemplateSelected"));
            return;
        }
        newsletterObj.NewsletterSubscriptionTemplateID = subscriptionTemplateValue;

        // Check if double opt-in template was selected
        int optInTemplateValue = ValidationHelper.GetInteger(optInSelector.Value, 0);

        if (newsletterObj.NewsletterEnableOptIn && optInTemplateValue == 0)
        {
            ShowError(GetString("Newsletter_Edit.NoOptInTemplateSelected"));
            return;
        }
        newsletterObj.NewsletterOptInTemplateID = optInTemplateValue;

        // Check if unsubscription template was selected
        int unsubscriptionTemplateValue = ValidationHelper.GetInteger(unsubscriptionTemplate.Value, 0);

        if (unsubscriptionTemplateValue == 0)
        {
            ShowError(GetString("Newsletter_Edit.NoUnsubscriptionTemplateSelected"));
            return;
        }
        newsletterObj.NewsletterUnsubscriptionTemplateID = unsubscriptionTemplateValue;

        // ID of scheduled task which should be deleted
        int deleteScheduledTaskId = 0;

        if (isDynamic)
        {
            newsletterObj.NewsletterType           = NewsletterType.Dynamic;
            newsletterObj.NewsletterDynamicSubject = radFollowing.Checked ? txtSubject.Text : string.Empty;

            if ((String.IsNullOrEmpty(txtNewsletterDynamicURL.Text.Trim())))
            {
                // Dynamic URL cannot be empty
                ShowError(GetString("menuitem_edit.errorpageurlempty"));
                return;
            }

            newsletterObj.NewsletterDynamicURL = txtNewsletterDynamicURL.Text.Trim();

            if (chkSchedule.Checked)
            {
                // Set info for scheduled task
                TaskInfo task = GetDynamicNewsletterTask(newsletterObj);

                if (!schedulerInterval.CheckOneDayMinimum())
                {
                    // If problem occurred while setting schedule interval
                    ShowError(GetString("Newsletter_Edit.NoDaySelected"));
                    return;
                }

                if (!IsValidDate(SchedulingHelper.DecodeInterval(scheduledInterval).StartTime))
                {
                    ShowError(GetString("Newsletter.IncorrectDate"));
                    return;
                }

                task.TaskInterval = scheduledInterval;

                task.TaskNextRunTime = SchedulingHelper.GetNextTime(task.TaskInterval, new DateTime(), new DateTime());
                task.TaskDisplayName = GetString("DynamicNewsletter.TaskName") + newsletterObj.NewsletterDisplayName;
                task.TaskName        = "DynamicNewsletter_" + newsletterObj.NewsletterName;
                // Set task for processing in external service
                task.TaskAllowExternalService = true;
                task.TaskUseExternalService   = (SchedulingHelper.UseExternalService && NewsletterHelper.UseExternalServiceForDynamicNewsletters(CMSContext.CurrentSiteName));
                TaskInfoProvider.SetTaskInfo(task);
                newsletterObj.NewsletterDynamicScheduledTaskID = task.TaskID;
            }
            else
            {
                if (newsletterObj.NewsletterDynamicScheduledTaskID > 0)
                {
                    // Store task ID for deletion
                    deleteScheduledTaskId = newsletterObj.NewsletterDynamicScheduledTaskID;
                }
                newsletterObj.NewsletterDynamicScheduledTaskID = 0;
                schedulerInterval.Visible = false;
            }
        }
        else
        {
            newsletterObj.NewsletterType = NewsletterType.TemplateBased;

            // Check if issue template was selected
            int issueTemplateValue = ValidationHelper.GetInteger(issueTemplate.Value, 0);
            if (issueTemplateValue == 0)
            {
                ShowError(GetString("Newsletter_Edit.NoEmailTemplateSelected"));
                return;
            }
            newsletterObj.NewsletterTemplateID = issueTemplateValue;
        }

        // Save changes to DB
        NewsletterInfoProvider.SetNewsletterInfo(newsletterObj);
        if (deleteScheduledTaskId > 0)
        {
            // Delete scheduled task if schedule mail-outs were unchecked
            TaskInfoProvider.DeleteTaskInfo(deleteScheduledTaskId);
        }

        ShowChangesSaved();

        // Refresh header with display name
        ScriptHelper.RefreshTabHeader(Page, GetString("Newsletter_Header.Configuration"));
    }
        private void CreateUser(string windowsLiveId)
        {
            SiteUser newUser = new SiteUser(siteSettings);

            newUser.WindowsLiveId = windowsLiveId;
            newUser.Name          = SecurityHelper.RemoveMarkup(txtUserName.Text);
            newUser.LoginName     = newUser.Name;
            newUser.Email         = txtEmail.Text;
            mojoMembershipProvider mojoMembership = (mojoMembershipProvider)Membership.Provider;

            newUser.Password = mojoMembership.EncodePassword(siteSettings, newUser, SiteUser.CreateRandomPassword(7, WebConfigSettings.PasswordGeneratorChars));
            //newUser.Password = SiteUser.CreateRandomPassword(7);
            newUser.PasswordQuestion = Resource.ManageUsersDefaultSecurityQuestion;
            newUser.PasswordAnswer   = Resource.ManageUsersDefaultSecurityAnswer;
            newUser.Save();
            if (siteSettings.UseSecureRegistration)
            {
                newUser.SetRegistrationConfirmationGuid(Guid.NewGuid());
            }

            mojoProfileConfiguration profileConfig
                = mojoProfileConfiguration.GetConfig();

            // set default values first
            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
#if !MONO
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey)
                {
                    continue;
                }
#endif
                mojoProfilePropertyDefinition.SavePropertyDefault(
                    newUser, propertyDefinition);
            }

            foreach (mojoProfilePropertyDefinition propertyDefinition in profileConfig.PropertyDefinitions)
            {
#if !MONO
                // we are using the new TimeZoneInfo list but it doesn't work under Mono
                // this makes us skip the TimeOffsetHours setting from mojoProfile.config which is not used under windows
                if (propertyDefinition.Name == mojoProfilePropertyDefinition.TimeOffsetHoursKey)
                {
                    continue;
                }
#endif
                if ((propertyDefinition.RequiredForRegistration) || (propertyDefinition.ShowOnRegistration))
                {
                    mojoProfilePropertyDefinition.SaveProperty(
                        newUser,
                        pnlRequiredProfileProperties,
                        propertyDefinition,
                        timeOffset,
                        timeZone);
                }
            }

            // track user ip address
            UserLocation userLocation = new UserLocation(newUser.UserGuid, SiteUtils.GetIP4Address());
            userLocation.SiteGuid = siteSettings.SiteGuid;
            userLocation.Hostname = Page.Request.UserHostName;
            userLocation.Save();

            UserRegisteredEventArgs u = new UserRegisteredEventArgs(newUser);
            OnUserRegistered(u);

            CacheHelper.ClearMembershipStatisticsCache();

            NewsletterHelper.ClaimExistingSubscriptions(newUser);

            DoUserLogin(newUser);
        }