Exemple #1
0
    private void AddRules(InfoDataSet <MacroRuleInfo> ds)
    {
        var resolver = MacroResolverStorage.GetRegisteredResolver(ResolverName);

        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            bool add = true;
            if (resolver != null)
            {
                // Check the required data, all specified data have to be present in the resolver
                string requiredData = ValidationHelper.GetString(dr["MacroRuleRequiredData"], "");
                if (!string.IsNullOrEmpty(requiredData))
                {
                    var required = requiredData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var req in required)
                    {
                        if (!resolver.IsDataItemAvailable(req))
                        {
                            add = false;
                            break;
                        }
                    }
                }
            }

            if (add)
            {
                var      ruleId = dr["MacroRuleID"].ToString();
                ListItem item   = new ListItem(dr["MacroRuleDisplayName"].ToString(), ruleId);
                lstRules.Items.Add(item);

                // Save the tooltip
                RulesTooltips[ruleId] = ResHelper.LocalizeString(ValidationHelper.GetString(dr["MacroRuleDescription"], ""));
            }
        }
    }
    protected void InitAttachmentAction()
    {
        EmailTemplateInfo emailTemplate = (EmailTemplateInfo)EditedObject;

        if ((emailTemplate != null) && (emailTemplate.TemplateID > 0))
        {
            int siteId = emailTemplate.TemplateSiteID;

            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(emailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, ObjectAttachmentsCategories.TEMPLATE,
                                                                              siteId > 0 ? "MetaFileSiteID=" + siteId : "MetaFileSiteID IS NULL", null, "MetafileID", -1);
            int attachCount = ds.Items.Count;

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

            // Register dialog scripts
            ScriptHelper.RegisterDialogScript(Page);

            // Prepare metafile dialog URL
            string metaFileDialogUrl = ResolveUrl(@"~/CMSModules/AdminControls/Controls/MetaFiles/MetaFileDialog.aspx");
            string query             = String.Format("?objectid={0}&objecttype={1}&siteid={2}", emailTemplate.TemplateID, EmailTemplateInfo.OBJECT_TYPE, siteId);
            metaFileDialogUrl += String.Format("{0}&category={1}&hash={2}", query, ObjectAttachmentsCategories.TEMPLATE, QueryHelper.GetHash(query));

            ObjectEditMenu menu = (ObjectEditMenu)ControlsHelper.GetChildControl(Page, typeof(ObjectEditMenu));
            if (menu != null)
            {
                menu.AddExtraAction(new HeaderAction()
                {
                    Text          = GetString("general.attachments") + ((attachCount > 0) ? string.Format(" ({0})", attachCount) : String.Empty),
                    OnClientClick = String.Format(@"if (modalDialog) {{modalDialog('{0}', 'Attachments', '700', '500');}}", metaFileDialogUrl) + " return false;",
                    Enabled       = menu.ShowCheckIn || !SynchronizationHelper.UseCheckinCheckout,
                    CssClass      = mAttachmentsActionClass
                });
            }
        }
    }
Exemple #3
0
    /// <summary>
    /// Initializes header actions.
    /// </summary>
    protected void InitHeaderActions()
    {
        bool isAuthorized = CurrentUser.IsAuthorizedPerResource("cms.form", "EditForm");

        int attachCount = 0;

        if (isAuthorized)
        {
            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(FormInfo.FormID, BizFormInfo.OBJECT_TYPE, ObjectAttachmentsCategories.LAYOUT, 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") });

            // Register dialog scripts
            ScriptHelper.RegisterDialogScript(Page);
        }

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

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

        // Init attachment button
        attachments = 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       = isAuthorized,
            Visible       = !layoutElem.IsEditedObjectLocked(),
            CssClass      = mAttachmentsActionClass
        };
        layoutElem.AddExtraHeaderAction(attachments);
    }
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        string prefferedCultureCode = CMSContext.PreferredCultureCode;
        string defaultSmallIconUrl  = GetImageUrl("CMSModules/CMS_DeviceProfiles/default_list.png");
        string defaultBigIconUrl    = GetImageUrl("CMSModules/CMS_DeviceProfiles/default.png");
        string defaultString        = GetString("general.default");

        InfoDataSet <CultureInfo> siteCultures = CultureInfoProvider.GetSiteCultures(CMSContext.CurrentSiteName);

        pi = CMSContext.CurrentPageInfo ?? OnSiteEditHelper.PageInfoForPageNotFound;

        // Cultures button
        MenuItem cultureItem = new MenuItem();

        cultureItem.CssClass     = "BigButton";
        cultureItem.ImageAlign   = ImageAlign.Top;
        cultureItem.ImagePath    = URLHelper.UnResolveUrl(UIHelper.GetFlagIconUrl(Page, prefferedCultureCode, "16x16"), URLHelper.ApplicationPath);
        cultureItem.Text         = GetString("general.cultures");
        cultureItem.Tooltip      = GetString("onsiteedit.languageselector");
        cultureItem.ImageAltText = GetString("general.cultures");

        // Add all cultures to the sub menu
        foreach (CultureInfo culture in siteCultures)
        {
            string iconUrl          = UIHelper.GetFlagIconUrl(Page, culture.CultureCode, "16x16");
            string cultureName      = culture.CultureName;
            string cultureCode      = culture.CultureCode;
            string cultureShortName = culture.CultureShortName;

            if (cultureCode != prefferedCultureCode)
            {
                SubMenuItem menuItem = new SubMenuItem()
                {
                    Text         = cultureName,
                    Tooltip      = cultureName,
                    ImagePath    = iconUrl,
                    ImageAltText = cultureName
                };

                // Build the web part image html
                bool translationExists = NodeCultures.ContainsKey(cultureCode);

                if (translationExists)
                {
                    // Assign click action which changes the document culture
                    menuItem.OnClientClick = "document.location.replace(" + ScriptHelper.GetString(URLHelper.UpdateParameterInUrl(URLHelper.CurrentURL, URLHelper.LanguageParameterName, cultureCode)) + ");";
                }
                else
                {
                    // Display the "Not translated" image
                    menuItem.RightImagePath    = GetImageUrl("/CMSModules/CMS_PortalEngine/OnSiteEdit/no_culture.png");
                    menuItem.RightImageAltText = GetString("onsitedit.culturenotavailable");

                    // Assign click action -> Create new document culture
                    menuItem.OnClientClick = "NewDocumentCulture(" + pi.NodeID + ",'" + cultureCode + "');";
                }

                cultureItem.SubItems.Add(menuItem);
            }
            else
            {
                // Current culture
                cultureItem.Text         = culture.CultureShortName;
                cultureItem.Tooltip      = cultureName;
                cultureItem.ImagePath    = iconUrl;
                cultureItem.ImageAltText = cultureName;
            }
        }

        btnCulture.Buttons.Add(cultureItem);
    }
    /// <summary>
    /// Loads device profile menu.
    /// </summary>
    private void LoadDevicesMenu()
    {
        string defaultSmallIconUrl = GetImageUrl("CMSModules/CMS_DeviceProfile/default_list.png");
        string defaultBigIconUrl   = GetImageUrl("CMSModules/CMS_DeviceProfile/default.png");

        if ((Page is PortalPage) || (Page is TemplatePage))
        {
            // Display grayscale icon in On-site editing
            defaultBigIconUrl   = GetImageUrl("CMSModules/CMS_DeviceProfile/default_grayscale.png");
            defaultSmallIconUrl = defaultBigIconUrl;
        }

        string deviceSmallIconUrl = GetImageUrl("CMSModules/CMS_DeviceProfile/list.png");
        string deviceBigIconUrl   = GetImageUrl("CMSModules/CMS_DeviceProfile/module.png");

        string defaultString = HTMLHelper.HTMLEncode(GetString("general.default"));

        MenuItem devMenuItem = new MenuItem
        {
            Text         = defaultString,
            Tooltip      = defaultString,
            ImagePath    = defaultBigIconUrl,
            ImageAltText = defaultString
        };

        SetStyles(devMenuItem);
        buttons.Buttons.Add(devMenuItem);

        // Load enabled profiles
        InfoDataSet <DeviceProfileInfo> ds = DeviceProfileInfoProvider.GetDeviceProfileInfos("ProfileEnabled = 1", "ProfileOrder");

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            // Create default item
            SubMenuItem defaultMenuItem = new SubMenuItem
            {
                Text          = defaultString,
                Tooltip       = defaultString,
                ImagePath     = defaultSmallIconUrl,
                ImageAltText  = defaultString,
                OnClientClick = String.Format("CMSUniMenu.ChangeButton(##BUTTON##, {0}, {1}); ChangeDevice('');", ScriptHelper.GetString(defaultString), ScriptHelper.GetString(ResolveUrl(defaultBigIconUrl)))
            };

            devMenuItem.SubItems.Add(defaultMenuItem);

            foreach (DeviceProfileInfo profileInfo in ds.Items)
            {
                string bigIconUrl   = null;
                string smallIconUrl = null;
                if (profileInfo.ProfileIconGuid == Guid.Empty)
                {
                    smallIconUrl = deviceSmallIconUrl;
                    bigIconUrl   = deviceBigIconUrl;
                }
                else
                {
                    string iconUrl = MetaFileURLProvider.GetMetaFileUrl(profileInfo.ProfileIconGuid, profileInfo.ProfileName);
                    smallIconUrl = URLHelper.UpdateParameterInUrl(iconUrl, "maxsidesize", "16");
                    bigIconUrl   = URLHelper.UpdateParameterInUrl(iconUrl, "maxsidesize", "24");
                }

                string      profileName = GetString(profileInfo.ProfileDisplayName);
                SubMenuItem menuItem    = new SubMenuItem
                {
                    Text          = HTMLHelper.HTMLEncode(profileName),
                    Tooltip       = HTMLHelper.HTMLEncode(profileName),
                    ImagePath     = smallIconUrl,
                    ImageAltText  = HTMLHelper.HTMLEncode(profileName),
                    OnClientClick = String.Format("CMSUniMenu.ChangeButton(##BUTTON##, {0}, {1}); ChangeDevice({2});", ScriptHelper.GetString(profileName), ScriptHelper.GetString(ResolveUrl(bigIconUrl)), ScriptHelper.GetString(profileInfo.ProfileName))
                };

                devMenuItem.SubItems.Add(menuItem);

                // Update main button if current device profile is equal currently processed profile
                if ((currentDevice != null) && (currentDevice.ProfileName.CompareToCSafe(profileInfo.ProfileName, true) == 0))
                {
                    devMenuItem.Text         = HTMLHelper.HTMLEncode(profileName);
                    devMenuItem.Tooltip      = HTMLHelper.HTMLEncode(profileName);
                    devMenuItem.ImagePath    = bigIconUrl;
                    devMenuItem.ImageAltText = HTMLHelper.HTMLEncode(profileName);
                }
            }
        }
    }
Exemple #6
0
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        string preferredCultureCode            = LocalizationContext.PreferredCultureCode;
        InfoDataSet <CultureInfo> siteCultures = CultureSiteInfoProvider.GetSiteCultures(SiteContext.CurrentSiteName);

        pi = DocumentContext.CurrentPageInfo ?? DocumentContext.CurrentCultureInvariantPageInfo ?? new PageInfo();

        // Cultures button
        MenuItem cultureItem = new MenuItem();

        cultureItem.CssClass     = "BigButton";
        cultureItem.ImageAlign   = ImageAlign.Top;
        cultureItem.ImagePath    = URLHelper.UnResolveUrl(UIHelper.GetFlagIconUrl(Page, preferredCultureCode, "16x16"), SystemContext.ApplicationPath);
        cultureItem.Text         = PortalHelper.LocalizeStringForUI("general.cultures");
        cultureItem.Tooltip      = PortalHelper.LocalizeStringForUI("onsiteedit.languageselector");
        cultureItem.ImageAltText = PortalHelper.LocalizeStringForUI("general.cultures");

        // Add all cultures to the sub menu
        foreach (CultureInfo culture in siteCultures)
        {
            string iconUrl     = UIHelper.GetFlagIconUrl(Page, culture.CultureCode, "16x16");
            string cultureName = culture.CultureName;
            string cultureCode = culture.CultureCode;

            if (cultureCode != preferredCultureCode)
            {
                SubMenuItem menuItem = new SubMenuItem
                {
                    Text         = cultureName,
                    Tooltip      = cultureName,
                    ImagePath    = iconUrl,
                    ImageAltText = cultureName
                };

                // Build the web part image html
                bool translationExists = NodeCultures.ContainsKey(cultureCode);

                if (translationExists)
                {
                    // Assign click action which changes the document culture
                    menuItem.OnClientClick = "document.location.replace(" + ScriptHelper.GetString(URLHelper.UpdateParameterInUrl(RequestContext.CurrentURL, URLHelper.LanguageParameterName, cultureCode)) + ");";
                }
                else
                {
                    // Display the "Not translated" image
                    menuItem.RightImageIconClass = "icon-ban-sign";
                    menuItem.RightImageAltText   = PortalHelper.LocalizeStringForUI("onsitedit.culturenotavailable");

                    // Assign click action -> Create new document culture
                    menuItem.OnClientClick = "NewDocumentCulture(" + pi.NodeID + ",'" + cultureCode + "');";
                }

                cultureItem.SubItems.Add(menuItem);
            }
            else
            {
                // Current culture
                cultureItem.Text         = culture.CultureShortName;
                cultureItem.Tooltip      = cultureName;
                cultureItem.ImagePath    = iconUrl;
                cultureItem.ImageAltText = cultureName;
            }
        }

        btnCulture.Buttons.Add(cultureItem);
    }
    /// <summary>
    /// Imports default metafiles which were changed in the new version.
    /// </summary>
    /// <param name="upgradeFolder">Folder where the generated metafiles.xml file is</param>
    private static void ImportMetaFiles(string upgradeFolder)
    {
        try
        {
            // To get the file use Phobos - Generate files button, Metafile settings.
            // Choose only those object types which had metafiles in previous version and these metafiles changed to the new version.
            String xmlPath = Path.Combine(upgradeFolder, "metafiles.xml");
            if (File.Exists(xmlPath))
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.Load(xmlPath);

                XmlNode metaFilesNode = xDoc.SelectSingleNode("MetaFiles");
                if (metaFilesNode == null)
                {
                    return;
                }

                String filesDirectory = Path.Combine(upgradeFolder, "Metafiles");

                using (new CMSActionContext {
                    LogEvents = false
                })
                {
                    foreach (XmlNode metaFile in metaFilesNode)
                    {
                        // Load metafiles information from XML
                        if (metaFile.Attributes == null)
                        {
                            continue;
                        }

                        String objType     = metaFile.Attributes["ObjectType"].Value;
                        String groupName   = metaFile.Attributes["GroupName"].Value;
                        String codeName    = metaFile.Attributes["CodeName"].Value;
                        String fileName    = metaFile.Attributes["FileName"].Value;
                        String extension   = metaFile.Attributes["Extension"].Value;
                        String fileGUID    = metaFile.Attributes["FileGUID"].Value;
                        String title       = (metaFile.Attributes["Title"] != null) ? metaFile.Attributes["Title"].Value : null;
                        String description = (metaFile.Attributes["Description"] != null) ? metaFile.Attributes["Description"].Value : null;

                        // Try to find correspondent info object
                        BaseInfo infoObject = ProviderHelper.GetInfoByName(objType, codeName);
                        if (infoObject == null)
                        {
                            continue;
                        }

                        int infoObjectId = infoObject.Generalized.ObjectID;

                        // Check if metafile exists
                        InfoDataSet <MetaFileInfo> metaFilesSet = MetaFileInfoProvider.GetMetaFilesWithoutBinary(infoObjectId, objType, groupName, "MetaFileGUID = '" + fileGUID + "'", null);
                        if (!DataHelper.DataSourceIsEmpty(metaFilesSet))
                        {
                            continue;
                        }

                        // Create new metafile if does not exists
                        String       mfFileName = String.Format("{0}.{1}", fileGUID, extension.TrimStart('.'));
                        MetaFileInfo mfInfo     = new MetaFileInfo(Path.Combine(filesDirectory, mfFileName), infoObjectId, objType, groupName);
                        mfInfo.MetaFileGUID = ValidationHelper.GetGuid(fileGUID, Guid.NewGuid());

                        // Set correct properties
                        mfInfo.MetaFileName = fileName;
                        if (title != null)
                        {
                            mfInfo.MetaFileTitle = title;
                        }
                        if (description != null)
                        {
                            mfInfo.MetaFileDescription = description;
                        }

                        // Save new meta file
                        MetaFileInfo.Provider.Set(mfInfo);
                    }

                    // Remove existing files after successful finish
                    String[] files = Directory.GetFiles(upgradeFolder);
                    foreach (String file in files)
                    {
                        File.Delete(file);
                    }
                }
            }
        }
        catch (Exception ex)
        {
            Service.Resolve <IEventLogService>().LogException(EventLogSource, "IMPORTMETAFILES", ex);
        }
    }
    protected void rptAdressItemCommand(object source, RepeaterCommandEventArgs e)
    {
        // Get AddressId from the row
        int AddressId = ValidationHelper.GetInteger(e.CommandArgument, 0);

        // Delete selected address
        if (e.CommandName.Equals("Remove"))
        {
            int idShoppingCart = 0;
            //   EventLogProvider ev = new EventLogProvider();
            // test du nombre d'adresse
            int idCustomer = ECommerceContext.CurrentCustomer.CustomerID;
            string where, orderby;
            where   = "AddressEnabled = 1 AND AddressCustomerID  = " + idCustomer;
            orderby = "AddressID";
            InfoDataSet <AddressInfo> listadresse = AddressInfoProvider.GetAddresses(where, orderby);
            if (listadresse.Tables[0].Rows.Count <= 1)
            {
                return;
            }

            else
            {
                // Delete AddressInfo object from database if address not used for order
                if ((OrderBillingAddress(AddressId) == 0) && (OrderShippingAddress(AddressId) == 0))
                {
                    SqlConnection con4  = new SqlConnection(ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString);
                    var           query = "Select ShoppingCartID from COM_ShoppingCart where ShoppingCartShippingAddressID = " + AddressId;
                    SqlCommand    cmd2  = new SqlCommand(query, con4);
                    //  ev.LogEvent("I", DateTime.Now, "ds billig&shipping=0", "code");
                    con4.Open();
                    try
                    {
                        idShoppingCart = (int)cmd2.ExecuteScalar();
                        //  ev.LogEvent("I", DateTime.Now, "dans try  " + idShoppingCart, "code");
                    }
                    catch (Exception ex)
                    {
                    }
                    con4.Close();
                    if (idShoppingCart != 0)
                    {
                        var        query2 = "Delete  from COM_ShoppingCartSKU WHERE ShoppingCartID = " + idShoppingCart;
                        SqlCommand cmd1   = new SqlCommand(query2, con4);
                        cmd1.ExecuteScalar();

                        var        stringQuery = "Delete  from COM_ShoppingCart WHERE ShoppingCartShippingAddressID = " + AddressId;
                        SqlCommand cmd3        = new SqlCommand(stringQuery, con4);
                        cmd3.ExecuteScalar();

                        con4.Dispose();
                    }
                    if (Session["newAddress"] != null)
                    {
                        int temp2 = Int32.Parse(Session["newAddress"].ToString());

                        if (temp2 != 0)
                        {
                            if (temp2 == AddressId)
                            {
                                Session["newAddress"] = null;
                            }
                        }
                    }
                    AddressInfoProvider.DeleteAddressInfo(AddressId);

                    //ev.LogEvent("I", DateTime.Now, "button delete enabled true", "code");
                    //
                    int id1 = ECommerceContext.CurrentCustomer.CustomerID;
                }
                // Disable AddressInfo object from database if address used for order
                else
                {
                    SqlConnection con3 = new SqlConnection(ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString);
                    // con3.Open();
                    //   ev.LogEvent("I", DateTime.Now, "iD = " + AddressId, "code");
                    var        query = "Select ShoppingCartID from COM_ShoppingCart where ShoppingCartShippingAddressID = " + AddressId;
                    SqlCommand cmd2  = new SqlCommand(query, con3);
                    //  ev.LogEvent("I", DateTime.Now, "test", "code");
                    con3.Open();
                    try
                    {
                        idShoppingCart = (int)cmd2.ExecuteScalar();
                        con3.Dispose();
                    }
                    catch (Exception ex)
                    {
                    }
                    con3.Close();

                    SqlConnection connect = new SqlConnection(ConfigurationManager.ConnectionStrings["CMSConnectionString"].ConnectionString);

                    //  ev.LogEvent("I", DateTime.Now, "idShoppingCart = " + idShoppingCart, "code");

                    if (idShoppingCart != 0)
                    {
                        connect.Open();
                        var        query2 = "Delete  from COM_ShoppingCartSKU WHERE ShoppingCartID = " + idShoppingCart;
                        SqlCommand cmd1   = new SqlCommand(query2, connect);
                        cmd1.ExecuteScalar();


                        var        stringQuery = "Delete  from COM_ShoppingCart WHERE ShoppingCartShippingAddressID = " + AddressId;
                        SqlCommand cmd3        = new SqlCommand(stringQuery, connect);
                        cmd3.ExecuteScalar();
                        connect.Close();
                        Response.Redirect("~/Special-Page/Mon-compte.aspx");
                    }
                    //    ev.LogEvent("I", DateTime.Now, "btn delet enabled false", "code");
                    AddressInfo  UpdateAdress = AddressInfoProvider.GetAddressInfo(AddressId);
                    CustomerInfo uc           = ECommerceContext.CurrentCustomer;
                    UpdateAdress.AddressEnabled    = false;
                    UpdateAdress.AddressCustomerID = mCustomerId;
                    AddressInfoProvider.SetAddressInfo(UpdateAdress);
                    AddressId = UpdateAdress.AddressID;
                }
            }
            ReloadDataAdress();
            // PnlInsertAdress.Visible = false;
        }

        // Update selected adress
        if (e.CommandName.Equals("Update"))
        {
            // lblErrorAdress
            var lblErrorAdress = e.Item.FindControl("lblErrorAdress") as Label;

            // chkShippingAddr
            var chkShippingAddr = e.Item.FindControl("chkShippingAddr") as CheckBox;

            // chkBillingAddr
            var chkBillingAddr = e.Item.FindControl("chkBillingAddr") as CheckBox;

            if (!chkBillingAddr.Checked && !chkShippingAddr.Checked)
            {
                lblErrorAdress.Text    = "V�rifier le type d'adresse";
                lblErrorAdress.Visible = true;
                return;
            }

            int         AddressID = Convert.ToInt32(e.CommandArgument);
            AddressInfo ai        = AddressInfoProvider.GetAddressInfo(AddressID);
            string      s         = ai.AddressZip;

            // txtnumero
            var txtnumero = e.Item.FindControl("txtnumero") as TextBox;
            if (txtnumero != null)
            {
                ai.SetValue("AddressNumber", txtnumero.Text);
            }

            // txtadresse1
            var txtadresse1 = e.Item.FindControl("txtadresse1") as TextBox;
            if (txtadresse1 != null)
            {
                ai.AddressLine1 = txtadresse1.Text;
            }

            // txtadresse2
            var txtadresse2 = e.Item.FindControl("txtadresse2") as TextBox;
            if (txtadresse2 != null)
            {
                ai.AddressLine2 = txtadresse2.Text;
            }

            // txtcp
            TextBox txtcp = e.Item.FindControl("txtcp") as TextBox;
            if (txtcp != null)
            {
                ai.AddressZip = txtcp.Text;
                // Response.Write("<script>alert('This is Alert " + txtcp.Text + " " + DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff tt") + "');</script>");
            }

            // txtville
            var txtville = e.Item.FindControl("txtville") as TextBox;
            if (txtville != null)
            {
                ai.AddressCity = txtville.Text;
            }

            // chkShippingAddr
            if (chkShippingAddr != null)
            {
                ai.AddressIsShipping = chkShippingAddr.Checked;
            }

            // chkBillingAddr
            if (chkBillingAddr != null)
            {
                ai.AddressIsBilling = chkBillingAddr.Checked;
            }

            CustomerInfo uc            = ECommerceContext.CurrentCustomer;
            string       mCustomerName = string.Format("{0} {1}", uc.CustomerFirstName, uc.CustomerLastName);
            // Set the properties
            ai.AddressName = string.Format("{0}, {4} {1} - {2} {3}", mCustomerName, ai.AddressLine1, ai.AddressZip, ai.AddressCity, ai.GetStringValue("AddressNumber", string.Empty));
            AddressInfoProvider.SetAddressInfo(ai);

            // Update page here
            ReloadDataAdress();
        }
    }
    private void AddRules(InfoDataSet<MacroRuleInfo> ds)
    {
        var resolver = MacroResolverStorage.GetRegisteredResolver(ResolverName);

        foreach (DataRow dr in ds.Tables[0].Rows)
        {
            bool add = true;
            if (resolver != null)
            {
                // Check the required data, all specified data have to be present in the resolver
                string requiredData = ValidationHelper.GetString(dr["MacroRuleRequiredData"], "");
                if (!string.IsNullOrEmpty(requiredData))
                {
                    var required = requiredData.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);

                    foreach (var req in required)
                    {
                        if (!resolver.IsDataItemAvailable(req))
                        {
                            add = false;
                            break;
                        }
                    }
                }
            }

            if (add)
            {
                var ruleId = dr["MacroRuleID"].ToString();
                ListItem item = new ListItem(dr["MacroRuleDisplayName"].ToString(), ruleId);
                lstRules.Items.Add(item);

                // Save the tooltip
                RulesTooltips[ruleId] = ResHelper.LocalizeString(ValidationHelper.GetString(dr["MacroRuleDescription"], ""));
            }
        }
    }
    /// <summary>
    /// Loads device profile menu.
    /// </summary>
    private void LoadDevicesMenu()
    {
        if (UseSmallButton)
        {
            plcSmallButton.Visible = true;
        }
        else
        {
            plcBigButton.Visible = true;
        }

        string        defaultString    = HTMLHelper.HTMLEncode(GetString("deviceselector.default", ResourceCulture));
        StringBuilder sbDeviceProfiles = new StringBuilder();
        MenuItem      devMenuItem      = null;

        if (!UseSmallButton)
        {
            devMenuItem = new MenuItem
            {
                Text    = defaultString,
                Tooltip = defaultString,
            };

            // Display icon in On-site editing
            if ((Page is PortalPage) || (Page is TemplatePage))
            {
                devMenuItem.IconClass = "icon-monitor-smartphone";
            }

            SetStyles(devMenuItem);
            buttons.Buttons.Add(devMenuItem);
        }

        // Load enabled profiles
        InfoDataSet <DeviceProfileInfo> ds = DeviceProfileInfoProvider.GetDeviceProfiles()
                                             .WhereEquals("ProfileEnabled", 1)
                                             .OrderBy("ProfileOrder")
                                             .TypedResult;

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            // Create default item
            SubMenuItem defaultMenuItem = new SubMenuItem
            {
                Text          = defaultString,
                Tooltip       = defaultString,
                OnClientClick = "ChangeDevice('');",
            };

            if (UseSmallButton)
            {
                // Insert the current device profile to the button
                btnProfilesSelector.Actions.Add(new CMSButtonAction()
                {
                    OnClientClick = String.Format("ChangeDevice({0}); return false;", ScriptHelper.GetString(defaultString)),
                    Text          = defaultString
                });
            }
            else
            {
                // Insert the current device profile to the context menu
                devMenuItem.SubItems.Add(defaultMenuItem);
            }

            // Load the profiles list
            foreach (DeviceProfileInfo profileInfo in ds.Items)
            {
                string          profileName  = GetString(profileInfo.ProfileDisplayName, ResourceCulture);
                CMSButtonAction deviceButton = null;

                if (UseSmallButton)
                {
                    deviceButton = new CMSButtonAction()
                    {
                        OnClientClick = String.Format("ChangeDevice({0}); return false;", ScriptHelper.GetString(profileInfo.ProfileName)),
                        Text          = profileName,
                        Name          = profileName
                    };

                    btnProfilesSelector.Actions.Add(deviceButton);
                }
                else
                {
                    SubMenuItem menuItem = new SubMenuItem
                    {
                        Text          = HTMLHelper.HTMLEncode(profileName),
                        Tooltip       = HTMLHelper.HTMLEncode(profileName),
                        OnClientClick = String.Format("ChangeDevice({0});", ScriptHelper.GetString(profileInfo.ProfileName))
                    };
                    devMenuItem.SubItems.Add(menuItem);
                }

                // Update main button if current device profile is equal currently processed profile
                if ((currentDevice != null) && (currentDevice.ProfileName.CompareToCSafe(profileInfo.ProfileName, true) == 0))
                {
                    if (UseSmallButton)
                    {
                        btnProfilesSelector.SelectedActionName = profileName;
                    }
                    else
                    {
                        devMenuItem.Text    = HTMLHelper.HTMLEncode(profileName);
                        devMenuItem.Tooltip = HTMLHelper.HTMLEncode(profileName);
                    }
                }
            }
        }
    }
    /// <summary>
    /// Gets and sets the donation values
    /// </summary>
    /// <param name="orderItems">All order items</param>
    /// <returns>List of all donations items</returns>
    protected PagedDataSource GetDonationValues(InfoDataSet<OrderItemInfo> orderItems)
    {
        List<DonationValues> lstValues = new List<DonationValues>();
        double totalRaisedRunning = 0;
        double totalOfflineRunning = 0;
        double totalOnlineRunning = 0;
        OrderStatusInfo OS = OrderStatusInfoProvider.GetOrderStatusInfo("Failed", CMSContext.CurrentSiteName);
        OrderStatusInfo OS2 = OrderStatusInfoProvider.GetOrderStatusInfo("OrderCreated", CMSContext.CurrentSiteName);
        foreach (OrderItemInfo item in orderItems)
        {
            OrderInfo order = OrderInfoProvider.GetOrderInfo(item.OrderItemOrderID);
            CustomerInfo customer = CustomerInfoProvider.GetCustomerInfo(order.OrderCustomerID);

            if (order.OrderStatusID == OS.StatusID) continue;
            if (order.OrderStatusID == OS2.StatusID) continue;

            string name = string.Empty;
            string comments = string.Empty;

            double giftAidAmount = 0;

            DateTime date = order.OrderDate;
            double amount = 0;

            PaymentOptionInfo poi = PaymentOptionInfoProvider.GetPaymentOptionInfo(order.OrderPaymentOptionID);

            if (poi.PaymentOptionDisplayName != "WorldPay")
            {
                totalOfflineRunning += order.OrderTotalPrice;
                amount = order.OrderTotalPrice;
            }
            else
            {
                totalOnlineRunning += order.OrderTotalPrice;
                amount = order.OrderTotalPrice;
            }

            string imagePath = ValidationHelper.GetString(order.GetValue("ImagePath"), "");
            if (imagePath == "") imagePath = "~/app_themes/websitedefault/images/avatar_default.jpg";

            //Comment
            bool allowComments = ValidationHelper.GetBoolean(order.GetValue("AllowUseOfComment"), false);
            bool allowCommentsAdmin = ValidationHelper.GetBoolean(order.GetValue("UseCommentOnSite"), false);
            if (allowComments && allowCommentsAdmin) comments = ValidationHelper.GetString(order.GetValue("CustomisedCommentUsedOnLive"), "");

            //Allow Name
            bool allowName = ValidationHelper.GetBoolean(order.GetValue("AllowUseOfName"), false);
            if (allowName)
            {
                name = "Donation by <strong>" + customer.GetValue("CusomterTitle") + order.GetValue("CustomerTitle") + " " + customer.CustomerFirstName + " " + customer.CustomerLastName + "</strong>";
            }
            else
            {
                name = "Donation by <strong> Anonymous </strong>";
            }

            //Allow Image
            bool allowImage = ValidationHelper.GetBoolean(order.GetValue("AllowUseOfImage"), false);
            if (!allowImage)
            {
                imagePath = "/App_themes/websitedefault/images/avatar_default.jpg";
            }

            //Giftaid
            bool giftAid = ValidationHelper.GetBoolean(order.GetValue("IsGiftAid"), false);
            if (giftAid) giftAidAmount = Math.Round((amount / 100) * 25, 2);

            DonationValues donation = new DonationValues(comments, name, date, amount, giftAidAmount, imagePath);

            lstValues.Add(donation);
            giftTotal += giftAidAmount;
            double total = amount;
            totalRaisedRunning += total;
        }
        onlineTotal = totalOnlineRunning;
        offlineTotal = totalOfflineRunning;
        totalRaised = totalRaisedRunning + totalOfflineRunning;
        donationCount = lstValues.Count;

        //convert to paged data sauce
        PagedDataSource pds = new PagedDataSource();
        pds.DataSource = lstValues;
        pds.AllowPaging = true;
        pds.PageSize = 5;

        //return lstValues;
        return pds;
    }
Exemple #12
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();}");
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        CurrentMaster.Title.TitleText  = GetString("newsletter_issue_subscribersclicks.title");
        CurrentMaster.Title.TitleImage = GetImageUrl("CMSModules/CMS_Newsletter/ViewParticipants.png");

        linkId = QueryHelper.GetInteger("linkid", 0);
        if (linkId == 0)
        {
            RequestHelper.EndResponse();
        }

        LinkInfo link = LinkInfoProvider.GetLinkInfo(linkId);

        EditedObject = link;

        IssueInfo issue = IssueInfoProvider.GetIssueInfo(link.LinkIssueID);

        EditedObject = issue;

        // Prevent accessing issues from sites other than current site
        if (issue.IssueSiteID != CMSContext.CurrentSiteID)
        {
            RedirectToResourceNotAvailableOnSite("Issue with ID " + link.LinkIssueID);
        }

        QueryDataParameters parameters = null;

        string where = string.Empty;

        // Link's issue is the main A/B test issue
        if (issue.IssueIsABTest && !issue.IssueIsVariant)
        {
            // Prepare base where condition
            where = "LinkID IN (" + link.LinkID.ToString();

            // Get A/B test and its winner issue ID
            ABTestInfo test = ABTestInfoProvider.GetABTestInfoForIssue(issue.IssueID);
            if (test != null)
            {
                // Get ID of the same link from winner issue
                InfoDataSet <LinkInfo> winnerLink = LinkInfoProvider.GetLinks(string.Format("LinkIssueID={0} AND LinkTarget=N'{1}' AND LinkDescription=N'{2}'", test.TestWinnerIssueID, link.LinkTarget, link.LinkDescription), null, 1, "LinkID");
                if (!DataHelper.DataSourceIsEmpty(winnerLink))
                {
                    string winnerLinkID = ValidationHelper.GetString(DataHelper.GetDataRowValue(winnerLink.Tables[0].Rows[0], "LinkID"), string.Empty);
                    if (!string.IsNullOrEmpty(winnerLinkID))
                    {
                        // Add link ID of winner issue link
                        where += "," + winnerLinkID;
                    }
                }
            }

            // Close where condition
            where += ")";
        }
        else
        {
            // Filter by Link ID (from querystring)
            parameters = new QueryDataParameters();
            parameters.Add("@LinkID", linkId);
        }

        UniGrid.QueryParameters       = parameters;
        UniGrid.WhereCondition        = SqlHelperClass.AddWhereCondition(fltOpenedBy.WhereCondition, where);
        UniGrid.Pager.DefaultPageSize = PAGESIZE;
        UniGrid.Pager.ShowPageSize    = false;
        UniGrid.FilterLimit           = 1;
        UniGrid.OnExternalDataBound  += UniGrid_OnExternalDataBound;
    }
    /// <summary>
    /// Handles the UniGrid's OnExternalDataBound event.
    /// </summary>
    /// <param name="sender">The sender</param>
    /// <param name="sourceName">Name of the source</param>
    /// <param name="parameter">The data row</param>
    /// <returns>Formatted value to be used in the UniGrid</returns>
    protected object UniGrid_OnExternalDataBound(object sender, string sourceName, object parameter)
    {
        switch (sourceName.ToLowerCSafe())
        {
        case "issuesubject":
            return(HTMLHelper.HTMLEncode(MacroResolver.RemoveSecurityParameters(parameter.ToString(), true, null)));

        case "issueopenedemails":
            return(GetOpenedEmails(parameter as DataRowView));

        case "issuestatus":
            IssueStatusEnum status = IssueStatusEnum.Idle;
            if ((parameter != DBNull.Value) && (parameter != null))
            {
                status = (IssueStatusEnum)parameter;
            }
            return(GetString(String.Format("newsletterissuestatus." + Convert.ToString(status))));

        case "edit":
            if (sender is ImageButton)
            {
                if (mNewsletter.NewsletterType.EqualsCSafe(NewsletterType.Dynamic) && !mNewsletter.NewsletterEnableResending)
                {
                    // Hide 'edit' action if newsletter is dynamic and resending is disabled
                    ImageButton imageButton = sender as ImageButton;
                    imageButton.Style.Add(HtmlTextWriterStyle.Display, "none");
                }
            }
            return(sender);

        case "viewclickedlinks":
            if (sender is ImageButton)
            {
                // Hide 'view clicked links' action if tracking is not available or if the issue has no tracked links
                ImageButton imageButton = sender as ImageButton;
                if (!mTrackingEnabled)
                {
                    imageButton.Style.Add(HtmlTextWriterStyle.Display, "none");
                }
                else
                {
                    GridViewRow gvr = parameter as GridViewRow;
                    if (gvr != null)
                    {
                        DataRowView drv = gvr.DataItem as DataRowView;
                        if (drv != null)
                        {
                            int issueId = ValidationHelper.GetInteger(drv["IssueID"], 0);
                            // Try to get one tracked link (only ID) of the issue
                            InfoDataSet <LinkInfo> links = LinkInfoProvider.GetLinks("LinkIssueID=" + issueId, null, 1, "LinkID");
                            if (DataHelper.DataSourceIsEmpty(links))
                            {
                                imageButton.Style.Add(HtmlTextWriterStyle.Display, "none");
                            }
                        }
                    }
                }
            }
            return(sender);

        default:
            return(parameter);
        }
    }
    /// <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();}");
    }
    protected override void OnInit(EventArgs e)
    {
        base.OnInit(e);

        mDsGateways = NotificationGatewayInfoProvider.GetGateways(null, null, 11, "GatewayID,GatewayDisplayName");

        GatewayCount = (!DataHelper.DataSourceIsEmpty(mDsGateways)) ? mDsGateways.Items.Count : 0;
    }
    /// <summary>
    /// Initializes header action control.
    /// </summary>
    /// <param name="templateId">Template ID</param>
    protected void InitHeaderActions(int templateId)
    {
        bool   isAuthorized = CurrentUser.IsAuthorizedPerResource("CMS.Newsletter", "ManageTemplates") && (EditedObject != null);
        string script       = null;

        // Init save button
        CurrentMaster.HeaderActions.ActionsList.Add(new SaveAction(this)
        {
            ImageUrl = !isAuthorized ? GetImageUrl("CMSModules/CMS_Content/EditMenu/savedisabled.png") : string.Empty,
            Enabled  = isAuthorized
        });

        // Init spellcheck button
        CurrentMaster.HeaderActions.ActionsList.Add(new HeaderAction()
        {
            ControlType   = HeaderActionTypeEnum.LinkButton,
            Text          = GetString("spellcheck.title"),
            Tooltip       = GetString("spellcheck.title"),
            OnClientClick = "checkSpelling(spellURL); return false;",
            ImageUrl      = GetImageUrl("CMSModules/CMS_Content/EditMenu/spellcheck.png")
        });

        int attachCount = 0;

        if (isAuthorized)
        {
            // Get number of attachments
            InfoDataSet <MetaFileInfo> ds = MetaFileInfoProvider.GetMetaFiles(templateId, NewsletterObjectType.NEWSLETTERTEMPLATE, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE, 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_" + this.ClientID, script, true);

            // Register dialog scripts
            ScriptHelper.RegisterDialogScript(Page);
        }

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

        metaFileDialogUrl += string.Format("{0}&category={1}&hash={2}", query, MetaFileInfoProvider.OBJECT_CATEGORY_TEMPLATE, 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      = isAuthorized ? GetImageUrl("Objects/CMS_MetaFile/attachment.png") : GetImageUrl("Objects/CMS_MetaFile/attachment_disabled.png"),
            Enabled       = isAuthorized
        });

        // 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      = "MenuItemEdit Right"
        });

        CurrentMaster.HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;
    }
Exemple #18
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();}");
    }
    /// <summary>
    /// Checks if any tasks are enabled.
    /// </summary>
    public bool EnabledTasks()
    {
        InfoDataSet <TaskInfo> tasks = TaskInfoProvider.GetTasks("(TaskNextRunTime IS NULL) AND (TaskInterval NOT LIKE '" + SchedulingHelper.PERIOD_ONCE + "%') AND (TaskEnabled = 1)", null, -1, "TaskID");

        return(((tasks != null) && (tasks.Items.Count > 0)) || SchedulingHelper.EnableScheduler);
    }
    /// <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();}");
    }
Exemple #21
0
    /// <summary>
    /// Sets the current combination as default
    /// </summary>
    protected void btnUseCombination_Click(object sender, EventArgs e)
    {
        if ((CMSContext.CurrentPageInfo != null))
        {
            // Keep current page template instance
            PageInfo pi = CMSContext.CurrentPageInfo;

            // Set the selected combination (from cookie by default)
            MVTestInfo mvTestInfo = MVTestInfoProvider.GetRunningTest(CMSContext.CurrentAliasPath, CMSContext.CurrentSiteID, CMSContext.CurrentDocumentCulture.CultureCode);

            // Get combination from cookies
            string combinationName = CookieHelper.GetValue(cookieTestName);

            // Get the page template id
            int templateId = GetPageTemplateId(pi);

            // Get combination info
            MVTCombinationInfo currentCombination = MVTCombinationInfoProvider.GetMVTCombinationInfo(templateId, combinationName);

            // Get default combination info
            MVTCombinationInfo defaultCombination = MVTCombinationInfoProvider.GetDefaultCombinationInfo(templateId);

            // Check whether default and current combination exists
            if ((currentCombination != null) && (defaultCombination != null))
            {
                // Do not save default combination
                if (currentCombination.MVTCombinationID != defaultCombination.MVTCombinationID)
                {
                    // Copy the combination custom name
                    defaultCombination.MVTCombinationCustomName = currentCombination.MVTCombinationCustomName;
                    defaultCombination.Update();

                    // Tree provider instance
                    TreeProvider tp = new TreeProvider(currentUser);

                    // Documents - use the Preview view mode to ensure that only chosen variant will be rendered (Design mode renders all web part/zone variants and does not combine the instance with the variants)
                    PageTemplateInstance instance = MVTestInfoProvider.CombineWithMVT(pi, pi.UsedPageTemplateInfo.TemplateInstance, currentCombination.MVTCombinationID, ViewModeEnum.Preview);
                    CMSPortalManager.SaveTemplateChanges(pi, instance, WidgetZoneTypeEnum.None, ViewModeEnum.Design, tp);

                    // Widgets - use the Preview view mode to ensure that only chosen variant will be rendered (Edit mode renders all widget variants and does not combine the instance with the variants)
                    instance = MVTestInfoProvider.CombineWithMVT(pi, pi.DocumentTemplateInstance, currentCombination.MVTCombinationID, ViewModeEnum.Preview);
                    CMSPortalManager.SaveTemplateChanges(pi, instance, WidgetZoneTypeEnum.Editor, ViewModeEnum.Edit, tp);
                }

                // Remove all variants
                InfoDataSet <MVTVariantInfo> variants = MVTVariantInfoProvider.GetMVTVariants("MVTVariantPageTemplateID = " + templateId, null);
                if (!DataHelper.DataSourceIsEmpty(variants))
                {
                    foreach (MVTVariantInfo info in variants)
                    {
                        MVTVariantInfoProvider.DeleteMVTVariantInfo(info);
                    }
                }

                // Clear cached template info
                pi.UsedPageTemplateInfo.Update();

                // Redirect to the same page to update the current view
                URLHelper.Redirect(URLHelper.CurrentURL);
            }
        }
    }