public SettingsKey GetKeyByName(string keyName)
        {
            var keyInfo = SettingsKeyInfoProvider.GetSettingsKeyInfo(keyName);

            if (keyInfo == null)
            {
                throw new ArgumentException($"'{keyName}' is not a valid key name");
            }

            var groupInfo          = SettingsCategoryInfoProvider.GetSettingsCategoryInfo(keyInfo.KeyCategoryID);
            var categoryInfo       = SettingsCategoryInfoProvider.GetSettingsCategoryInfo(groupInfo.CategoryParentID);
            var categoryParentInfo = SettingsCategoryInfoProvider.GetSettingsCategoryInfo(categoryInfo.CategoryParentID);

            var category = new Category(categoryInfo.CategoryDisplayName, categoryInfo.CategoryName, categoryParentInfo.CategoryName);
            var group    = new Group(groupInfo.CategoryDisplayName, category);

            var key = new SettingsKey
            {
                KeyDefaultValue        = keyInfo.KeyDefaultValue,
                KeyDescription         = keyInfo.KeyDescription,
                KeyDisplayName         = keyInfo.KeyDisplayName,
                KeyEditingControlPath  = keyInfo.KeyEditingControlPath,
                KeyExplanationText     = keyInfo.KeyExplanationText,
                KeyFormControlSettings = keyInfo.KeyFormControlSettings,
                KeyName       = keyInfo.KeyName,
                KeyType       = keyInfo.KeyType,
                KeyValidation = keyInfo.KeyValidation,
                Group         = group
            };

            return(key);
        }
Пример #2
0
    /// <summary>
    /// Handles the settings key action event.
    /// </summary>
    /// <param name="actionName">Name of item (button) that throws event</param>
    /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param>
    protected void grpEdit_OnKeyAction(string actionName, object actionArgument)
    {
        int             keyId = ValidationHelper.GetInteger(actionArgument, 0);
        SettingsKeyInfo ski   = SettingsKeyInfoProvider.GetSettingsKeyInfo(keyId);

        switch (actionName.ToLowerCSafe())
        {
        case ("edit"):
            // Redirect to key edit page
            if (ski != null)
            {
                URLHelper.Redirect(URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ModuleName.CMS, "Modules.Settings.EditSettingsKey", false), "keyname=" + ski.KeyName + "&moduleid=" + moduleId));
            }
            break;

        case ("delete"):
            try
            {
                SettingsKeyInfoProvider.DeleteSettingsKeyInfo(ski);
            }
            catch
            {
                ShowError(GetString("settingsedit.settingskey_edit.errordelete"));
            }
            break;

        case ("moveup"):
            SettingsKeyInfoProvider.MoveSettingsKeyUp(ski.KeyName);
            break;

        case ("movedown"):
            SettingsKeyInfoProvider.MoveSettingsKeyDown(ski.KeyName);
            break;
        }
    }
Пример #3
0
    /// <summary>
    /// Validates the form. If validation succeeds returns true, otherwise returns false.
    /// </summary>
    private bool Validate()
    {
        bool isValid = true;

        // Validate form fields
        string errMsg = new Validator().NotEmpty(txtKeyName.Text.Trim(), ResHelper.GetString("general.requirescodename"))
                        .NotEmpty(txtKeyDisplayName.Text.Trim(), ResHelper.GetString("general.requiresdisplayname"))
                        .IsIdentifier(txtKeyName.Text.Trim(), GetString("general.erroridentifierformat"))
                        .Result;

        // Validate default value format
        if (!string.IsNullOrEmpty(DefaultValue))
        {
            switch (drpKeyType.SelectedValue)
            {
            case "double":
                if (!ValidationHelper.IsDouble(DefaultValue))
                {
                    lblDefValueError.Text    = ResHelper.GetString("settings.validationdoubleerror");
                    lblDefValueError.Visible = true;
                    isValid = false;
                }
                break;

            case "int":
                if (!ValidationHelper.IsInteger(DefaultValue))
                {
                    lblDefValueError.Text    = ResHelper.GetString("settings.validationinterror");
                    lblDefValueError.Visible = true;
                    isValid = false;
                }
                break;
            }
        }

        // Check if the code name is used
        var key = SettingsKeyInfoProvider.GetSettingsKeyInfo(txtKeyName.Text.Trim());

        if ((key != null) && (key.KeyID != mSettingsKeyId))
        {
            errMsg = GetString("general.codenameexists");
        }

        if (!ucSettingsKeyControlSelector.IsValid())
        {
            errMsg = GetString("settingskeyedit.selectcustomcontrol");
        }

        // Set up error message
        if (!string.IsNullOrEmpty(errMsg))
        {
            ShowError(errMsg);
            isValid = false;
        }

        return(isValid);
    }
Пример #4
0
    /// <summary>
    /// Deletes settings key. Called when the "Delete key" button is pressed.
    /// Expects the CreateSettingsKey method to be run first.
    /// </summary>
    private bool DeleteSettingsKey()
    {
        // Get the settings key
        SettingsKeyInfo deleteKey = SettingsKeyInfoProvider.GetSettingsKeyInfo("MyNewKey", SiteContext.CurrentSiteID);

        // Delete the settings key
        SettingsKeyInfoProvider.DeleteSettingsKeyInfo(deleteKey);

        return(deleteKey != null);
    }
        /// <summary>
        /// Adds a StatusCodePages middleware to the pipeline. Specifies that the response body should be generated by
        /// re-executing the request pipeline using an alternate localized path. This path may contain a '{0}' placeholder
        /// of the culture and the '{1}' placeholder the status code.
        /// </summary>
        /// <param name="app">App builder.</param>
        /// <param name="localizedPathFormat">Format pattern with two placeholders: the culture and the status code.</param>
        /// <param name="queryFormat">Query format</param>
        /// <returns></returns>
        public static IApplicationBuilder UseLocalizedStatusCodePagesWithReExecute(
            this IApplicationBuilder app,
            string localizedPathFormat,
            string?queryFormat = default)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

            return(app.UseStatusCodePages(async context =>
            {
                var originalPath = context.HttpContext.Request.Path;
                var originalQueryString = context.HttpContext.Request.QueryString;

                // Store the original paths so the app can check it.
                context.HttpContext.Features.Set <IStatusCodeReExecuteFeature>(new StatusCodeReExecuteFeature()
                {
                    OriginalPathBase = context.HttpContext.Request.PathBase.Value,
                    OriginalPath = originalPath.Value,
                    OriginalQueryString = originalQueryString.HasValue ? originalQueryString.Value : null,
                });

                var firstSegment = Regex.Match(originalPath, @"/([^/]+)/");
                var segmentValue = firstSegment.Groups[1]?.Value;
                string?culture = default;

                if (firstSegment.Success && !string.IsNullOrWhiteSpace(segmentValue))
                {
                    var currentSiteName = SiteContext.CurrentSiteName;
                    var siteInfoIdentifier = new SiteInfoIdentifier(currentSiteName);
                    var defaultCulture = SettingsKeyInfoProvider.GetSettingsKeyInfo("CMSDefaultCultureCode", siteInfoIdentifier)?.KeyValue;

                    culture = CultureSiteInfoProvider.IsCultureOnSite(segmentValue, currentSiteName)
                        ? segmentValue
                        : defaultCulture?.ToLowerInvariant();
                }

                var cultureRouteValue = culture ?? "en-us";

                var newPath = new PathString(
                    string.Format(CultureInfo.InvariantCulture, localizedPathFormat, cultureRouteValue, context.HttpContext.Response.StatusCode));

                var formatedQueryString = queryFormat == null ? null :
                                          string.Format(CultureInfo.InvariantCulture, queryFormat, context.HttpContext.Response.StatusCode);

                var newQueryString = queryFormat == null ? QueryString.Empty : new QueryString(formatedQueryString);

                await ReExecuteRequest(context, originalPath, originalQueryString, newPath, newQueryString);
            }));
        }
Пример #6
0
    /// <summary>
    /// Enables the setting for actual scope and by which button user has chosen.
    /// If scope is Both, and global button is pressed then global setting is set and site setting inherits, otherwise only site setting is set.
    /// If scope is Site, only for current site is setting set.
    /// If scope is Global, only global setting is set.
    /// If scope is CurrentSiteAndGlobal, current site's setting and global setting are set.
    /// If scope is AllSiteAndGlobal, all sites settings and global setting are set.
    /// </summary>
    /// <param name="isSite">Site button or global button.</param>
    /// <param name="key">Setting to enable.</param>
    private void EnableSettingByActualScope(string key, bool isSite)
    {
        // If scope is only global, then set only global setting
        if (KeyScope == DisabledModuleScope.Global)
        {
            SettingsKeyInfoProvider.SetGlobalValue(key, true);
            return;
        }

        // If setting is only global setting, set global setting
        var ski = SettingsKeyInfoProvider.GetSettingsKeyInfo(key);

        if (ski.KeyIsGlobal)
        {
            SettingsKeyInfoProvider.SetGlobalValue(key, true);
            return;
        }

        switch (KeyScope)
        {
        case DisabledModuleScope.Both:
            if (isSite)
            {
                SettingsKeyInfoProvider.SetValue(key, SiteName, true);
                break;
            }

            //If global button was pressed, set global setting, and inherit site setting
            SettingsKeyInfoProvider.SetGlobalValue(key, true);
            SettingsKeyInfoProvider.SetValue(key, SiteName, null);
            break;

        case DisabledModuleScope.Site:
            SettingsKeyInfoProvider.SetValue(key, SiteName, true);
            break;

        case DisabledModuleScope.CurrentSiteAndGlobal:
            SettingsKeyInfoProvider.SetGlobalValue(key, true);
            SettingsKeyInfoProvider.SetValue(key, SiteName, true);
            break;

        case DisabledModuleScope.AllSitesAndGlobal:
            SiteInfoProvider.GetSites().ForEachObject(site => SettingsKeyInfoProvider.SetValue(key, SiteName, true));
            SettingsKeyInfoProvider.SetGlobalValue(key, true);
            break;
        }
    }
Пример #7
0
    /// <summary>
    /// Gets and updates settings key. Called when the "Get and update key" button is pressed.
    /// Expects the CreateSettingsKey method to be run first.
    /// </summary>
    private bool GetAndUpdateSettingsKey()
    {
        // Get the settings key
        SettingsKeyInfo updateKey = SettingsKeyInfoProvider.GetSettingsKeyInfo("MyNewKey", SiteContext.CurrentSiteID);

        if (updateKey != null)
        {
            // Update the property
            updateKey.KeyDisplayName = updateKey.KeyDisplayName.ToLowerCSafe();

            // Update the settings key
            SettingsKeyInfoProvider.SetSettingsKeyInfo(updateKey);

            return(true);
        }

        return(false);
    }
Пример #8
0
    /// <summary>
    /// Shows or hides disabled module info, depends on SettingsEnabled property.
    /// </summary>
    private void DisplayErrorText()
    {
        // If module is disabled, then display disabled module info, otherwise hide
        if (ParentPanel != null)
        {
            ParentPanel.Visible = !SettingsEnabled;
        }
        Visible         = !SettingsEnabled;
        lblText.Visible = !SettingsEnabled;

        SetButtonVisibility();

        // If settings enabled, info text is hidden, there is no point in generating info text
        if (SettingsEnabled)
        {
            return;
        }

        // If InfoText is set ignore everything else
        if (!String.IsNullOrEmpty(InfoText))
        {
            lblText.Text += InfoText;
            return;
        }

        foreach (string key in SettingsList)
        {
            // If module disabled for given key, write text about given setting
            if (!IsSettingEnabledInActualScope(key))
            {
                string text = GenerateInfoText(SettingsKeyInfoProvider.GetSettingsKeyInfo(key));

                if (!String.IsNullOrEmpty(lblText.Text))
                {
                    lblText.Text += "<br />";
                }

                // Add new text to label
                lblText.Text += text;
            }
        }
    }
Пример #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Get parameters
        mKeyName     = QueryHelper.GetString("keyname", "");
        mParentGroup = QueryHelper.GetString("parentgroup", null);

        skeEditKey.OnSaved += skeEditKey_OnSaved;

        // Set up editing mode
        if (!string.IsNullOrEmpty(mKeyName))
        {
            mEditedKey = SettingsKeyInfoProvider.GetSettingsKeyInfo(mKeyName, 0);

            // Set id of key
            if (mEditedKey != null)
            {
                skeEditKey.SettingsKeyID = mEditedKey.KeyID;
            }
        }
        // Set up creating mode
        else
        {
            if (mParentGroup != null)
            {
                SettingsCategoryInfo parentCat = SettingsCategoryInfoProvider.GetSettingsCategoryInfoByName(mParentGroup);
                if (parentCat != null)
                {
                    skeEditKey.SelectedGroupID = parentCat.CategoryID;
                }
            }
        }

        // Check if there is something right created to edit.
        if (ViewState["newId"] != null)
        {
            skeEditKey.SettingsKeyID = ValidationHelper.GetInteger(ViewState["newId"], 0);
        }

        skeEditKey.ModuleID = mModuleId;
    }
Пример #10
0
        private void EnableDataProtectionSamples(ISiteInfo site)
        {
            var dataProtectionSamplesEnabledSettingsKey = SettingsKeyInfoProvider.GetSettingsKeyInfo(DATA_PROTECTION_SETTINGS_KEY);

            if (dataProtectionSamplesEnabledSettingsKey?.KeyValue.ToBoolean(false) ?? false)
            {
                return;
            }

            var keyInfo = new SettingsKeyInfo
            {
                KeyName         = DATA_PROTECTION_SETTINGS_KEY,
                KeyDisplayName  = DATA_PROTECTION_SETTINGS_KEY,
                KeyType         = "boolean",
                KeyValue        = "True",
                KeyDefaultValue = "False",
                KeyIsGlobal     = true,
                KeyIsHidden     = true
            };

            SettingsKeyInfoProvider.SetSettingsKeyInfo(keyInfo);
            EnsureTask(site);
        }
        protected override void OnInit()
        {
            base.OnInit();

            ApplicationEvents.End.Execute += End_Execute;

            if (SettingsHelper.AppSettings[nameof(WebConfigKeys.CMSStorageProviderAssembly)] == "AzureStorageProvider")
            {
                var provider = new StorageProvider("AzureStorageProvider", "AzureStorageProvider", true);
                StorageHelper.MapStoragePath("/", provider);
            }


            if (SettingsKeyInfoProvider.GetSettingsKeyInfo(nameof(SettingsKeys.AzureStorageProviderEnableLogs)) == null)
            {
                var category = SettingsCategoryInfoProvider.GetSettingsCategoryInfoByName("CMS.Debug.General");
                // settings key does not exist
                var logEnabledKey = new SettingsKeyInfo
                {
                    KeyName         = nameof(SettingsKeys.AzureStorageProviderEnableLogs),
                    KeyDisplayName  = "Azure Storage Provider Enable Logs",
                    KeyDescription  = "Enables logs",
                    KeyType         = "boolean",
                    KeyCategoryID   = category.CategoryID,
                    KeyDefaultValue = "False",
                    KeyIsGlobal     = true,
                    KeyIsCustom     = false,
                    KeyIsHidden     = false
                };
                logEnabledKey.Insert();
            }

            if (ValidationHelper.GetBoolean(SettingsHelper.AppSettings[nameof(WebConfigKeys.AzureStorageProviderInitializeAtAppStart)], false))
            {
                BlobDirectoryCollection.Instance.GetOrCreate(string.Empty).Reinitialize();
            }
        }
Пример #12
0
    /// <summary>
    /// Displays info label, if any module is disabled
    /// </summary>
    private bool DisplayErrorText()
    {
        GlobalObjects = ";" + GlobalObjects + ";";
        SiteObjects   = ";" + SiteObjects + ";";

        bool keyDisabled    = false;
        bool isAnyKeySite   = false;
        bool settingChecked = false;
        bool showSite       = false;
        bool showGlobal     = false;

        // Check config keys - stronger
        if (!String.IsNullOrEmpty(ConfigKeys))
        {
            var keys = ConfigKeys.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string key in keys)
            {
                if (!ValidationHelper.GetBoolean(SettingsHelper.AppSettings[key], false))
                {
                    if (!AtLeastOne)
                    {
                        settingChecked = false;
                        break;
                    }
                }
                else
                {
                    settingChecked = true;
                }
            }
        }

        // Check settings
        if (!settingChecked && !String.IsNullOrEmpty(SettingsKeys))
        {
            int i = 0;

            var keys = SettingsKeys.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (string key in keys)
            {
                String objectKey    = ";" + key + ";";
                bool   globalObject = GlobalObjects.Contains(objectKey);
                bool   siteObject   = SiteObjects.Contains(objectKey);
                String siteKeyName  = SiteName + "." + key;
                String keyName      = (SiteOrGlobal || globalObject || KeyScope == DisabledModuleScope.Global) ? key : siteKeyName;

                // If module disabled
                if (!SettingsKeyInfoProvider.GetBoolValue(keyName) || (siteObject && !SettingsKeyInfoProvider.GetBoolValue(siteKeyName)))
                {
                    // For site or global settings check site setting separately
                    if (SiteOrGlobal && SettingsKeyInfoProvider.GetBoolValue(siteKeyName))
                    {
                        settingChecked = true;
                        i++;
                        continue;
                    }

                    // If at least one is checked, info error is set later
                    if (!AtLeastOne)
                    {
                        // If setting is global - hide site button
                        var ski = SettingsKeyInfoProvider.GetSettingsKeyInfo(key);
                        if ((ski != null) && (!ski.KeyIsGlobal))
                        {
                            isAnyKeySite = true;
                        }

                        // Get text (either from collection of text or from single text property)
                        String text = (InfoTexts.Count != 0 && InfoTexts.Count > i) ? InfoTexts[i] : InfoText;

                        if (String.IsNullOrEmpty(text) && (ski != null))
                        {
                            text = GenerateInfoText(ski);
                        }

                        if (lblText.Text != "")
                        {
                            lblText.Text += " ";
                        }

                        // Add new text to label
                        lblText.Text += text;

                        // Add this key to collection of disabled keys

                        // Make this info label visible
                        keyDisabled = !String.IsNullOrEmpty(text);

                        if (!siteObject && !globalObject)
                        {
                            showSite   = (KeyScope != DisabledModuleScope.Global);
                            showGlobal = (KeyScope != DisabledModuleScope.Site);
                        }
                        else
                        {
                            showSite   |= siteObject;
                            showGlobal |= globalObject;
                        }
                    }
                }
                else
                {
                    settingChecked = true;
                }

                i++;
            }
        }

        // If atleastone is set, check if any setting is checked. If no, display warning message
        if (AtLeastOne && !settingChecked)
        {
            keyDisabled  = true;
            lblText.Text = InfoText;
        }

        // If parent panel is set, show(hide) it
        if (ParentPanel != null)
        {
            ParentPanel.Visible = keyDisabled;
        }

        // Show/hide this control if module disabled
        Visible = keyDisabled;

        // Show site button only if any key is site
        btnSite.Visible = isAnyKeySite;

        // Set result to property
        SettingsEnabled = !keyDisabled;

        btnSite.Visible   &= showSite;
        btnGlobal.Visible &= showGlobal;

        return(!keyDisabled);
    }
Пример #13
0
    /// <summary>
    /// Updates settings key for all sites (or only global if the IsGlobal checkbox is checked).
    /// </summary>
    /// <returns>CodeName of the SettingsKey objects.</returns>
    private int UpdateKey()
    {
        // Try to get the key
        var keyObj = (mSettingsKeyId > 0) ? SettingsKeyInfoProvider.GetSettingsKeyInfo(mSettingsKeyId) : null;

        if (keyObj == null)
        {
            // Create new
            keyObj = new SettingsKeyInfo();
        }

        var oldKeyCategoryID = keyObj.KeyCategoryID;

        // Set values
        keyObj.KeyName         = txtKeyName.Text.Trim();
        keyObj.KeyDisplayName  = txtKeyDisplayName.Text.Trim();
        keyObj.KeyDescription  = txtKeyDescription.Text.Trim();
        keyObj.KeyType         = drpKeyType.SelectedValue;
        keyObj.KeyCategoryID   = mSelectedGroupId >= 0 ? mSelectedGroupId : drpCategory.SelectedCategory;
        keyObj.KeyIsGlobal     = chkKeyIsGlobal.Checked;
        keyObj.KeyIsHidden     = chkKeyIsHidden.Checked;
        keyObj.KeyValidation   = (string.IsNullOrEmpty(txtKeyValidation.Text.Trim()) ? null : txtKeyValidation.Text.Trim());
        keyObj.KeyDefaultValue = (string.IsNullOrEmpty(DefaultValue) ? null : DefaultValue);

        var path = ValidationHelper.GetString(ucSettingsKeyControlSelector.ControlPath, string.Empty);

        keyObj.KeyEditingControlPath = (string.IsNullOrEmpty(path.Trim()) ? null : path.Trim());

        // Update form control settings
        if (ucSettingsKeyControlSelector.IsFormControlSelected)
        {
            var formFieldInfo = new FormFieldInfo();
            ucControlSettings.SaveData();

            formFieldInfo.SettingsMacroTable = ucControlSettings.MacroTable;

            if ((ucControlSettings.FormData != null) && (ucControlSettings.FormData.ItemArray.Length > 0))
            {
                foreach (DataColumn column in ucControlSettings.FormData.Table.Columns)
                {
                    formFieldInfo.Settings[column.ColumnName] = ucControlSettings.FormData.Table.Rows[0][column.Caption];
                }
            }

            var settings = FormHelper.GetFormControlSettingsXml(formFieldInfo);
            keyObj.KeyFormControlSettings = settings;
        }
        else
        {
            keyObj.KeyFormControlSettings = null;
        }

        if (drpGeneration.Value >= 0)
        {
            keyObj.KeyLoadGeneration = drpGeneration.Value;
        }

        if (keyObj.KeyID == 0)
        {
            keyObj.KeyValue = DefaultValue;
        }

        if (chkKeyIsGlobal.Checked)
        {
            keyObj.SiteID = 0;
        }

        // If category changed set new order or if new set on the end of key list
        if (keyObj.KeyCategoryID != oldKeyCategoryID)
        {
            var keys = SettingsKeyInfoProvider.GetSettingsKeys(keyObj.KeyCategoryID)
                       .OrderByDescending("KeyOrder")
                       .Column("KeyOrder");

            keyObj.KeyOrder = keys.GetScalarResult(0) + 1;
        }

        SettingsKeyInfoProvider.SetSettingsKeyInfo(keyObj);

        // Update property
        mSettingsKeyObj = keyObj;

        return(keyObj.KeyID);
    }