Exemplo n.º 1
0
    /// <summary>
    /// Checks whether url parameters are valid.
    /// </summary>
    protected bool CheckHashCode()
    {
        // Get hashcode from querystring
        string hash = QueryHelper.GetString("hash", String.Empty);

        // Check whether url contains all reuired values
        if (QueryHelper.Contains("dashboardname") && !String.IsNullOrEmpty(hash))
        {
            // Try get custom hash values
            string hashValues = QueryHelper.GetString("hashvalues", String.Empty);

            string hashString = String.Empty;
            // Use default hash values
            if (String.IsNullOrEmpty(hashValues))
            {
                hashString = QueryHelper.GetString("dashboardname", String.Empty) + "|" + QueryHelper.GetString("templatename", String.Empty);
            }
            // Use custom hash values
            else
            {
                string[] values = hashValues.Split(';');
                foreach (string value in values)
                {
                    hashString += QueryHelper.GetString(value, String.Empty) + "|";
                }

                hashString = hashString.TrimEnd('|');
            }

            // Compare url hash with current hash
            return((CMSString.Compare(hash, ValidationHelper.GetHashString(hashString), false) == 0));
        }
        return(false);
    }
Exemplo n.º 2
0
    /// <summary>
    /// Sets data to database.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (!CheckPermissions("cms.widgets", PERMISSION_MODIFY))
        {
            return;
        }

        // Create new widget info if new widget
        if (WidgetInfo == null)
        {
            // Parent webpart must be set
            if ((WidgetWebpartId == 0) || (WidgetCategoryId == 0))
            {
                return;
            }

            WidgetInfo = new WidgetInfo();
            WidgetInfo.WidgetWebPartID  = WidgetWebpartId;
            WidgetInfo.WidgetCategoryID = WidgetCategoryId;
        }

        txtCodeName.Text    = TextHelper.LimitLength(txtCodeName.Text.Trim(), 100, "");
        txtDisplayName.Text = TextHelper.LimitLength(txtDisplayName.Text.Trim(), 100, "");

        // Perform validation
        string errorMessage = new Validator().NotEmpty(txtCodeName.Text, rfvCodeName.ErrorMessage).IsCodeName(txtCodeName.Text, GetString("general.invalidcodename"))
                              .NotEmpty(txtDisplayName.Text, rfvDisplayName.ErrorMessage).Result;

        if (errorMessage == "")
        {
            // If name changed, check if new name is unique
            if (CMSString.Compare(WidgetInfo.WidgetName, txtCodeName.Text, true) != 0)
            {
                WidgetInfo widget = WidgetInfoProvider.GetWidgetInfo(txtCodeName.Text);
                if (widget != null)
                {
                    ShowError(GetString("general.codenameexists"));
                    return;
                }
            }

            WidgetInfo.WidgetName                 = txtCodeName.Text;
            WidgetInfo.WidgetDisplayName          = txtDisplayName.Text;
            WidgetInfo.WidgetDescription          = txtDescription.Text;
            WidgetInfo.WidgetLayoutID             = ValidationHelper.GetInteger(ucLayouts.Value, 0);
            WidgetInfo.WidgetCategoryID           = ValidationHelper.GetInteger(categorySelector.Value, WidgetInfo.WidgetCategoryID);
            WidgetInfo.WidgetSkipInsertProperties = chkSkipInsertProperties.Checked;

            WidgetInfoProvider.SetWidgetInfo(WidgetInfo);

            ShowChangesSaved();

            // Raise save for frame reload
            RaiseOnSaved();
        }
        else
        {
            ShowError(errorMessage);
        }
    }
Exemplo n.º 3
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do not process
        }
        else
        {
            // Get list of cultures
            List <string[]> cultures = GetCultures();

            // Check whether exists more than one culture
            if ((cultures != null) && ((cultures.Count > 1) || (HideCurrentCulture && (cultures.Count > 0))))
            {
                // Set separator with dependence on layout
                mSeparator = DisplayLayout.ToLowerCSafe() == "vertical" ? "<br />" : " ";

                // Cultures literal
                ltlHyperlinks.Text = String.Empty;
                // Indicates whether separator can be added
                bool addSeparator = false;

                // Keep current culture
                string currentCulture = CultureHelper.GetPreferredCulture();

                // Loop thru all cultures
                foreach (string[] data in cultures)
                {
                    string url  = data[0];
                    string code = data[1];
                    string name = data[2];

                    // Add separator if it;s allowed
                    if (addSeparator)
                    {
                        ltlHyperlinks.Text += mSeparator;
                    }

                    // Display link if document culture for current document is not the same
                    if (CMSString.Compare(code, currentCulture, true) != 0)
                    {
                        ltlHyperlinks.Text += "<a href=\"" + HTMLHelper.EncodeForHtmlAttribute(url) + "\">" + HTMLHelper.HTMLEncode(name) + "</a>";
                    }
                    // For the same doc. cultures display plain text
                    else
                    {
                        ltlHyperlinks.Text += name;
                    }
                    // Add separator for next run
                    addSeparator = true;
                }
            }
            // Hide lang. selector if there is not more than one culture
            else
            {
                Visible = false;
            }
        }
    }
Exemplo n.º 4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterModule(Page, "CMS/ScrollPane", new { selector = "#language-menu" });

        CssRegistration.RegisterCssLink(Page, "~/CMSScripts/jquery/jquery-jscrollpane.css");

        string currentSiteName = (SiteID != 0) ? SiteInfoProvider.GetSiteName(SiteID) : SiteContext.CurrentSiteName;
        var    cultures        = CultureSiteInfoProvider.GetSiteCultures(currentSiteName).Items;

        if (cultures.Count > 1)
        {
            string      defaultCulture = CultureHelper.GetDefaultCultureCode(currentSiteName);
            CultureInfo ci             = CultureInfo.Provider.Get(SelectedCulture);

            imgLanguage.ImageUrl      = GetFlagIconUrl(SelectedCulture, "16x16");
            imgLanguage.AlternateText = imgLanguage.ToolTip = ResHelper.LocalizeString(ci.CultureName);
            lblLanguageName.Text      = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ci.CultureShortName));

            // Generate sub-menu only if more cultures to choose from
            StringBuilder sb = new StringBuilder();
            foreach (var culture in cultures)
            {
                string cultureCode = culture.CultureCode;
                string cultureName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(culture.CultureName));

                if (CMSString.Compare(cultureCode, defaultCulture, true) == 0)
                {
                    cultureName += " " + GetString("general.defaultchoice");
                }

                string flagUrl = GetFlagIconUrl(cultureCode, "16x16");

                var click = String.Format("ChangeLanguage({0}); return false;", ScriptHelper.GetString(cultureCode));

                sb.AppendFormat("<li><a href=\"#\" onclick=\"{0}\"><img src=\"{1}\" alt=\"\" class=\"language-flag\"><span class=\"language-name\">{2}</span></a></li>", click, flagUrl, cultureName);
            }

            ltlLanguages.Text = sb.ToString();

            // Split view button
            btnCompare.ToolTip = GetString("SplitMode.CompareLangVersions");
            btnCompare.Text    = GetString("SplitMode.Compare");
            if (PortalUIHelper.DisplaySplitMode)
            {
                btnCompare.AddCssClass("active");
            }
            else
            {
                btnCompare.RemoveCssClass("active");
            }
        }
        else
        {
            // Hide language menu for one assigned culture on site
            Visible = false;
        }
    }
Exemplo n.º 5
0
    /// <summary>
    /// Ensures the current page index with dependenco on request data du to different contol's life cycle.
    /// </summary>
    private void EnsurePageIndex()
    {
        if ((UIGridViewObject != null) && (UIGridViewObject.AllowPaging))
        {
            // Get current postback target
            string eventTarget = Request.Params[Page.postEventSourceID];

            // Handle paging manually because of lifecycle of the control
            if (CMSString.Compare(eventTarget, UIGridViewObject.UniqueID, true) == 0)
            {
                // Get the current page value
                string eventArg = ValidationHelper.GetString(Request.Params[Page.postEventArgumentID], String.Empty);

                string[] args = eventArg.Split('$');
                if ((args.Length == 2) && (CMSString.Compare(args[0], "page", true) == 0))
                {
                    string pageValue = args[1];
                    int    pageIndex = 0;
                    // Switch by page value  0,1.... first,last
                    switch (pageValue.ToLowerInvariant())
                    {
                    // Last item
                    case "last":
                        // Check whether page count is available
                        if (UIGridViewObject.PageCount > 0)
                        {
                            pageIndex = UIGridViewObject.PageCount - 1;
                        }
                        // if page count is not defined, try compute page count
                        else
                        {
                            DataSet ds = UIGridViewObject.DataSource as DataSet;
                            if (!DataHelper.DataSourceIsEmpty(ds))
                            {
                                pageIndex = ds.Tables[0].Rows.Count / UIGridViewObject.PageSize;
                            }
                        }
                        break;

                    case "next":
                        pageIndex = UIGridViewObject.PageIndex + 1;
                        break;

                    case "prev":
                        pageIndex = UIGridViewObject.PageIndex - 1;
                        break;

                    // Page number
                    default:
                        pageIndex = ValidationHelper.GetInteger(pageValue, 1) - 1;
                        break;
                    }

                    UIGridViewObject.PageIndex = pageIndex;
                }
            }
        }
    }
Exemplo n.º 6
0
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do not process
        }
        else
        {
            // Get list of cultures
            List <string[]> cultures = GetCultures();

            // Check whether exists more than one culture
            if ((cultures != null) && (cultures.Count > 1))
            {
                // Set separator with dependence on layout
                mSeparator = DisplayLayout.ToLowerCSafe() == "vertical" ? "<br />" : " ";

                // Cultures literal
                ltlHyperlinks.Text = String.Empty;
                // Indicates whether separator can be added
                bool addSeparator = false;
                // Keep current document culture
                string currentCulture = DocumentContext.CurrentDocument.DocumentCulture;

                // Loop thru all cultures
                foreach (string[] data in cultures)
                {
                    string url         = data[0];
                    string code        = data[1];
                    string name        = data[2];
                    string primaryCode = code.Split('-').FirstOrDefault();
                    // Add separator if it;s allowed
                    if (addSeparator)
                    {
                        ltlHyperlinks.Text += mSeparator;
                    }

                    // Display link if document culture for current document is not the same
                    if (CMSString.Compare(code, currentCulture, true) != 0)
                    {
                        ltlHyperlinks.Text += "<li class =\"LangueDisable\"><a href=\"" + URLHelper.ResolveUrl(url) + "\">" + HTMLHelper.HTMLEncode(primaryCode) + "</a></li>";
                    }
                    // For the same doc. cultures display plain text
                    else
                    {
                        ltlHyperlinks.Text += "<li class =\"LangueEnable\"><a>" + primaryCode + "</a></li>";
                    }
                    // Add separator for next run
                    addSeparator = true;
                }
            }
            // Hide lang. selector if there is not more than one culture
            else
            {
                Visible = false;
            }
        }
    }
    /// <summary>
    /// Sets the property value of the control, setting the value affects only local property value.
    /// </summary>
    /// <param name="propertyName">Property name to set</param>
    /// <param name="value">New property value</param>
    public override void SetValue(string propertyName, object value)
    {
        base.SetValue(propertyName, value);

        if (CMSString.Compare(propertyName, "isdashboard", true) == 0)
        {
            FillItemsCollection();
        }
    }
    /// <summary>
    /// Returns true if user control is valid.
    /// </summary>
    public override bool IsValid()
    {
        var postedFile = uploader.PostedFile;

        // Check allow empty
        if ((FieldInfo != null) && !FieldInfo.AllowEmpty && ((Form == null) || Form.CheckFieldEmptiness))
        {
            if (String.IsNullOrEmpty(uploader.CurrentFileName) && (postedFile == null))
            {
                // Empty error
                if ((ErrorMessage != null) && !ErrorMessage.EqualsCSafe(ResHelper.GetString("BasicForm.InvalidInput"), true))
                {
                    ValidationError = ErrorMessage;
                }
                else
                {
                    ValidationError += ResHelper.GetString("BasicForm.ErrorEmptyValue");
                }
                return(false);
            }
        }

        if ((postedFile != null) && (!String.IsNullOrEmpty(postedFile.FileName.Trim())))
        {
            // Test if file has allowed file-type
            string customExtension = ValidationHelper.GetString(GetValue("extensions"), String.Empty);
            string extensions      = null;

            if (CMSString.Compare(customExtension, "custom", true) == 0)
            {
                extensions = ValidationHelper.GetString(GetValue("allowed_extensions"), String.Empty);
            }

            // Only extensions that are also allowed in settings can be uploaded
            extensions = UploadHelper.RestrictExtensions(extensions, SiteContext.CurrentSiteName);

            string ext             = Path.GetExtension(postedFile.FileName);
            string validationError = string.Empty;

            if (extensions.EqualsCSafe(UploadHelper.NO_ALLOWED_EXTENSION))
            {
                validationError = ResHelper.GetString("uploader.noextensionallowed");
            }
            else if (!UploadHelper.IsExtensionAllowed(ext, extensions))
            {
                validationError = string.Format(ResHelper.GetString("BasicForm.ErrorWrongFileType"), HTMLHelper.HTMLEncode(ext.TrimStart('.')), extensions.Replace(";", ", "));
            }

            if (!string.IsNullOrEmpty(validationError))
            {
                ValidationError += validationError;
                return(false);
            }
        }

        return(true);
    }
    /// <summary>
    /// Reload data.
    /// </summary>
    /// <param name="setAutomatically">Indicates whether search options should be set automatically</param>
    public void ReloadSearch(bool setAutomatically)
    {
        ClassFields.ItemID = ItemID;
        ClassFields.ReloadData(setAutomatically, true);

        // Initialize properties
        List <IFormItem> itemList  = null;
        FormFieldInfo    formField = null;

        // Load DataClass
        dci = DataClassInfoProvider.GetDataClass(ItemID);

        if (dci != null)
        {
            // Load XML definition
            fi = FormHelper.GetFormInfo(dci.ClassName, true);

            if (CMSString.Compare(dci.ClassName, "cms.user", true) == 0)
            {
                plcImage.Visible = false;
                ClassFields.DisplaySetAutomatically = false;
                pnlIndent.Visible = true;

                document = DataClassInfoProvider.GetDataClass("cms.usersettings");
                if (document != null)
                {
                    FormInfo fiSettings = FormHelper.GetFormInfo(document.ClassName, true);
                    fi.CombineWithForm(fiSettings, true, String.Empty);
                }
            }

            // Get all fields
            itemList = fi.GetFormElements(true, true);
        }

        if (itemList != null)
        {
            if (itemList.Any())
            {
                pnlIndent.Visible = true;
            }

            // Store each field to array
            foreach (object item in itemList)
            {
                if (item is FormFieldInfo)
                {
                    formField = ((FormFieldInfo)(item));
                    object[] obj = { formField.Name, FormHelper.GetDataType(formField.DataType) };
                    attributes.Add(obj);
                }
            }
        }

        ReloadControls();
    }
Exemplo n.º 10
0
    /// <summary>
    /// Reload data.
    /// </summary>
    /// <param name="setAutomatically">Indicates whether search options should be set automatically</param>
    public void ReloadSearch(bool setAutomatically)
    {
        ClassFields.ItemID = ItemID;
        ClassFields.ReloadData(setAutomatically, true);

        // Initialize properties
        List <IDataDefinitionItem> itemList = null;

        if (ClassInfo != null)
        {
            // Load XML definition
            fi = FormHelper.GetFormInfo(ClassInfo.ClassName, true);

            if (CMSString.Compare(ClassInfo.ClassName, "cms.user", true) == 0)
            {
                plcImage.Visible = false;
                ClassFields.DisplaySetAutomatically = false;
                pnlIndent.Visible = true;

                document = DataClassInfoProvider.GetDataClassInfo("cms.usersettings");
                if (document != null)
                {
                    FormInfo fiSettings = FormHelper.GetFormInfo(document.ClassName, true);
                    fi.CombineWithForm(fiSettings, true, String.Empty);
                }
            }

            // Get all fields
            itemList = fi.GetFormElements(true, true);
        }

        if (itemList != null)
        {
            if (itemList.Any())
            {
                pnlIndent.Visible = true;
            }

            // Store each field to array
            foreach (var item in itemList)
            {
                var formField = item as FormFieldInfo;
                if (formField != null)
                {
                    object[] obj = { formField.Name, DataTypeManager.GetSystemType(TypeEnum.Field, formField.DataType) };
                    attributes.Add(obj);
                }
            }
        }

        if (AdvancedMode)
        {
            ReloadControls();
        }
    }
    /// <summary>
    /// Display collation dialog.
    /// </summary>
    public void DisplayCollationDialog()
    {
        string collation = DatabaseHelper.GetDatabaseCollation(ConnectionString);

        if (CMSString.Compare(collation, COLLATION_CASE_INSENSITIVE, true) != 0)
        {
            lblChangeCollation.ResourceString = string.Format(ResHelper.GetFileString("separationDB.collation"), collation);
            btnChangeCollation.ResourceString = string.Format(ResHelper.GetFileString("install.changecollation"), COLLATION_CASE_INSENSITIVE);
            plcChangeCollation.Visible        = true;
        }
    }
Exemplo n.º 12
0
    /// <summary>
    /// Returns true if user control is valid.
    /// </summary>
    public override bool IsValid()
    {
        // Check allow empty
        if ((FieldInfo != null) && !FieldInfo.AllowEmpty && ((Form == null) || Form.CheckFieldEmptiness))
        {
            if (String.IsNullOrEmpty(uploader.CurrentFileName) && (uploader.PostedFile == null))
            {
                // Error empty
                ValidationError += ResHelper.GetString("BasicForm.ErrorEmptyValue");
                return(false);
            }
        }

        // Test if file has allowed file-type
        if ((uploader.PostedFile != null) && (!String.IsNullOrEmpty(uploader.PostedFile.FileName.Trim())))
        {
            string customExtension = ValidationHelper.GetString(GetValue("extensions"), String.Empty);
            string extensions      = null;

            if (CMSString.Compare(customExtension, "custom", true) == 0)
            {
                extensions = ValidationHelper.GetString(GetValue("allowed_extensions"), String.Empty);
            }

            string ext = Path.GetExtension(uploader.PostedFile.FileName);
            if (!IsFileTypeAllowed(ext, extensions))
            {
                // Add global allowed file extensions from Settings
                if (extensions == null)
                {
                    extensions += ";" + SettingsKeyInfoProvider.GetStringValue(SiteContext.CurrentSiteName + ".CMSUploadExtensions");
                }
                extensions = (extensions.TrimStart(';')).TrimEnd(';').ToLowerCSafe();

                // Remove forbidden extensions
                var allowedExtensions = new List <string>(extensions.Split(';'));
                foreach (string extension in FORBIDDEN_EXTENSIONS.Split(';'))
                {
                    if (allowedExtensions.Contains(extension))
                    {
                        allowedExtensions.Remove(extension);
                    }
                }

                ValidationError += string.Format(ResHelper.GetString("BasicForm.ErrorWrongFileType"), ext.TrimStart('.'), string.Join(", ", allowedExtensions));
                return(false);
            }
        }
        return(true);
    }
Exemplo n.º 13
0
    void EditForm_OnItemValidation(object sender, ref string errorMessage)
    {
        Control ctrl = (Control)sender;

        if (CMSString.Compare(ctrl.ID, "fcScoreNotificationEmail", true) == 0 || CMSString.Compare(ctrl.ID, "fcScoreEmailAtScore", true) == 0)
        {
            var sendAtScoreControl = (TextBoxControl)fSendAtScore.EditingControl;
            var emailControl       = (FormEngineUserControl)fEmail.EditingControl;

            if (String.IsNullOrEmpty(sendAtScoreControl.Value.ToString()) != String.IsNullOrEmpty(emailControl.Value.ToString()))
            {
                errorMessage = GetString("om.score.requiredemailandscore");
            }
        }
    }
Exemplo n.º 14
0
    /// <summary>
    /// Sets the property value of the control, setting the value affects only local property value.
    /// </summary>
    /// <param name="propertyName">Property name to set</param>
    /// <param name="value">New property value</param>
    public override bool SetValue(string propertyName, object value)
    {
        // Allow change group display name
        if (CMSString.Compare(propertyName, "AllowChangeGroupDisplayName", true) == 0)
        {
            AllowChangeGroupDisplayName = ValidationHelper.GetBoolean(value, false);
        }

        // Allow change theme of group page
        if (CMSString.Compare(propertyName, "AllowSelectTheme", true) == 0)
        {
            AllowSelectTheme = ValidationHelper.GetBoolean(value, false);
        }

        // Call base method
        return(base.SetValue(propertyName, value));
    }
Exemplo n.º 15
0
    /// <summary>
    /// Control ID validation.
    /// </summary>
    protected void formElem_OnItemValidation(object sender, ref string errorMessage)
    {
        Control ctrl = (Control)sender;

        if (CMSString.Compare(ctrl.ID, "widgetcontrolid", true) == 0)
        {
            TextBox ctrlTextbox = (TextBox)ctrl;
            string  newId       = ctrlTextbox.Text;

            var pti = CMSPortalManager.GetTemplateInstanceForEditing(CurrentPageInfo);

            // Validate unique ID
            WebPartInstance existingPart = pti.GetWebPart(newId);
            if ((existingPart != null) && (existingPart != mWidgetInstance) && (existingPart.InstanceGUID != mWidgetInstance.InstanceGUID))
            {
                // Error - duplicated IDs
                errorMessage = GetString("Widgets.Properties.ErrorUniqueID");
            }
        }
    }
Exemplo n.º 16
0
    /// <summary>
    /// Returns true if user control is valid.
    /// </summary>
    public override bool IsValid()
    {
        // Check allow empty
        if ((FieldInfo != null) && !FieldInfo.AllowEmpty)
        {
            if (String.IsNullOrEmpty(uploader.CurrentFileName) && (uploader.PostedFile == null))
            {
                // Error empty
                ValidationError += ResHelper.GetString("BasicForm.ErrorEmptyValue");
                return(false);
            }
        }

        // Test if file has allowed file-type
        if ((uploader.PostedFile != null) && (!String.IsNullOrEmpty(uploader.PostedFile.FileName.Trim())))
        {
            string customExtension = ValidationHelper.GetString(GetValue("extensions"), "");
            string extensions      = null;

            if (CMSString.Compare(customExtension, "custom", true) == 0)
            {
                extensions = ValidationHelper.GetString(GetValue("allowed_extensions"), "");
            }

            string ext = Path.GetExtension(uploader.PostedFile.FileName);
            if (!IsFileTypeAllowed(ext, extensions))
            {
                // Add global allowed file extensions from Settings
                if (extensions == null)
                {
                    extensions += ";" + SettingsKeyProvider.GetStringValue(CMSContext.CurrentSiteName + ".CMSUploadExtensions");
                }
                extensions = (extensions.TrimStart(';')).TrimEnd(';');

                ValidationError += string.Format(ResHelper.GetString("BasicForm.ErrorWrongFileType"), ext.TrimStart('.'), extensions.Replace(";", ", "));
                return(false);
            }
        }
        return(true);
    }
Exemplo n.º 17
0
    /// <summary>
    /// Sets the property value of the control, setting the value affects only local property value.
    /// </summary>
    /// <param name="propertyName">Property name to set</param>
    /// <param name="value">New property value</param>
    public override bool SetValue(string propertyName, object value)
    {
        // Community group id
        if (CMSString.Compare(propertyName, "CommunityGroupID", true) == 0)
        {
            int groupId = ValidationHelper.GetInteger(value, 0);
            ucProjectList.CommunityGroupID = groupId;
            ucProjectNew.CommunityGroupID  = groupId;
            ucProjectEdit.CommunityGroupID = groupId;
        }
        // Is livesite
        else if (CMSString.Compare(propertyName, "IsLiveSite", true) == 0)
        {
            bool isLiveSite = ValidationHelper.GetBoolean(value, base.IsLiveSite);
            ucProjectEdit.IsLiveSite = isLiveSite;
            ucProjectList.IsLiveSite = isLiveSite;
            ucProjectNew.IsLiveSite  = isLiveSite;
        }

        // Call base method
        return(base.SetValue(propertyName, value));
    }
Exemplo n.º 18
0
    /// <summary>
    /// Redirects user to the installation page if connectionString not set.
    /// </summary>
    /// <param name="forceRedirect">If true, the redirect is forced</param>
    public static bool InstallRedirect(bool forceRedirect)
    {
        // Check if the connection string is initialized
        if (!SqlHelperClass.IsConnectionStringInitialized || forceRedirect)
        {
            // Redirect only it not installer
            string currentPath = "";

            if (HttpContext.Current != null)
            {
                currentPath = HttpContext.Current.Request.Path.ToLowerCSafe();
            }

            string relativePath = URLHelper.RemoveApplicationPath(currentPath);

            string currentFile = Path.GetFileName(relativePath);
            if (CMSString.Compare(currentFile, "install.aspx", true) == 0)
            {
                return(true);
            }

            string fileExtension = Path.GetExtension(currentFile);
            if ((CMSString.Compare(fileExtension, ".aspx", true) == 0) || currentFile == String.Empty || currentFile == "/")
            {
                if (!IsInstallerExcluded(relativePath))
                {
                    if (HttpContext.Current != null)
                    {
                        URLHelper.Redirect("~/cmsinstall/install.aspx");
                    }
                }
            }
            return(true);
        }
        else
        {
            return(false);
        }
    }
Exemplo n.º 19
0
    /// <summary>
    /// Checks whether current user can modify task.
    /// </summary>
    /// <param name="permissionType">Permission type</param>
    /// <param name="modulePermissionType">Module permission type</param>
    /// <param name="sender">Sender object</param>
    private void ucTaskEdit_OnCheckPermissionsExtended(string permissionType, string modulePermissionType, CMSAdminControl sender)
    {
        // Get task info for currently deleted task
        ProjectTaskInfo pti = ProjectTaskInfoProvider.GetProjectTaskInfo(ucTaskEdit.ItemID);

        // Check permission only for existing tasks and tasks assigned to some project
        if ((pti != null) && (pti.ProjectTaskProjectID > 0))
        {
            // Keep current user
            CurrentUserInfo cui = CMSContext.CurrentUser;

            // Check access to project permission for modify action
            if ((CMSString.Compare(permissionType, ProjectManagementPermissionType.MODIFY, true) == 0) && ProjectInfoProvider.IsAuthorizedPerProject(pti.ProjectTaskProjectID, ProjectManagementPermissionType.READ, cui))
            {
                // If user is owner or assignee => allow taks edit
                if ((pti.ProjectTaskOwnerID == cui.UserID) || (pti.ProjectTaskAssignedToUserID == cui.UserID))
                {
                    return;
                }
            }

            // Check whether user is allowed to modify task
            if (!ProjectInfoProvider.IsAuthorizedPerProject(pti.ProjectTaskProjectID, permissionType, cui))
            {
                // Set error message to the dialog
                ucTaskEdit.SetError(GetString("pm.project.permission"));
                // Stop edit control processing
                sender.StopProcessing = true;

                // Render dialog
                ucPopupDialog.Visible = true;
                // Show dialog
                ucPopupDialog.Show();
                // Update dialog panel
                pnlUpdateList.Update();
            }
        }
    }
Exemplo n.º 20
0
    /// <summary>
    /// Button OK clicked.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        if (dci != null)
        {
            string reportFields = null;
            bool   itemSelected = (chkListFields.SelectedIndex != -1);

            if (itemSelected)
            {
                foreach (ListItem item in chkListFields.Items)
                {
                    // Display only selected fields
                    if (item.Selected)
                    {
                        reportFields += item.Value + ";";
                    }
                }
            }

            if (!string.IsNullOrEmpty(reportFields))
            {
                // Remove ending ';'
                reportFields = reportFields.TrimEnd(';');
            }


            // Save report fields
            if (CMSString.Compare(dci.ClassShowColumns, reportFields, true) != 0)
            {
                dci.ClassShowColumns = reportFields;
                DataClassInfoProvider.SetDataClassInfo(dci);
            }

            // Close dialog window
            ScriptHelper.RegisterStartupScript(this, typeof(string), "CustomTable_SelectFields", "CloseAndRefresh();", true);
        }
    }
Exemplo n.º 21
0
        /// <summary>
        /// Binds grid with properties.
        /// </summary>
        private void BindProperties()
        {
            // Clear rows
            grdUserProperties.Rows.Clear();

            // Create list of AD properties
            List <ComboBoxItemContainer> attributeList = new List <ComboBoxItemContainer>();

            switch (ImportProfile.BindingEditorMode)
            {
            case BindingEditorMode.Simple:
                foreach (string attr in ADSimpleUserProperties)
                {
                    string attrName = ResHelper.GetString("ADAttribute_" + attr);
                    if (attr != ADProvider.NoneAttribute)
                    {
                        attrName += " (" + attr + ")";
                    }
                    ComboBoxItemContainer container = new ComboBoxItemContainer(attrName, attr);
                    attributeList.Add(container);
                }
                break;

            case BindingEditorMode.Advanced:
                // Add 'none' item
                attributeList.Add(new ComboBoxItemContainer(ResHelper.GetString("ADAttribute_" + ADProvider.NoneAttribute), ADProvider.NoneAttribute));

                // Add non-culture-specific attributes
                attributeList.AddRange(ADProvider.GetUserAttributes().Select(attribute => new ComboBoxItemContainer(attribute, attribute)));
                break;
            }


            // Sort attributes alphabetically
            attributeList.Sort((c1, c2) => CMSString.Compare(c1.DisplayMember, c2.DisplayMember, StringComparison.OrdinalIgnoreCase));

            if (CMSUserProperties.Count == 0)
            {
                // Load user data class
                DataClassInfo dci = DataClassInfoProvider.GetDataClassInfo(UserInfo.OBJECT_TYPE);

                // Load columns from the user data class
                LoadColumns(dci);

                // Load user settings data class
                dci = DataClassInfoProvider.GetDataClassInfo(UserSettingsInfo.OBJECT_TYPE);

                // Load columns from the user settings data class
                LoadColumns(dci);

                // Sort properties by name
                CMSUserProperties.Sort();
            }

            // Create default preselection
            if (ImportProfile.UserProperties.Count == 0)
            {
                ImportProfile.UserProperties.Add("FirstName", "givenName");
                ImportProfile.UserProperties.Add("MiddleName", "middleName");
                ImportProfile.UserProperties.Add("LastName", "sn");
                ImportProfile.UserProperties.Add("Email", "mail");
            }

            foreach (string property in CMSUserProperties)
            {
                // Create new row
                DataGridViewRow dr = new DataGridViewRow();

                // Create cell with CMS property
                DataGridViewTextBoxCell cmsProp = new DataGridViewTextBoxCell();
                cmsProp.Value = property;

                // Create cell with AD attributes
                DataGridViewComboBoxCell adAttr = new DataGridViewComboBoxCell();

                // Bind combobox cell
                adAttr.DisplayMember = "DisplayMember";
                adAttr.ValueMember   = "ValueMember";
                adAttr.DataSource    = attributeList;

                // Preselect values based on import profile
                if (ImportProfile.UserProperties.ContainsKey(property))
                {
                    string val = ImportProfile.UserProperties[property];
                    if (!chkAllAttributes.Checked && !ADSimpleUserProperties.Contains(val))
                    {
                        // Add values selected in advanced mode
                        attributeList.Add(new ComboBoxItemContainer(val, val));
                    }

                    adAttr.Value = val;
                }
                else
                {
                    // Set empty mapping
                    adAttr.Value = ADProvider.NoneAttribute;
                }

                // Add both cells to datarow
                dr.Cells.Add(cmsProp);
                dr.Cells.Add(adAttr);

                // Set CMS property read-only
                cmsProp.ReadOnly = true;

                // Add row to DataGridView
                grdUserProperties.Rows.Add(dr);
            }
        }
Exemplo n.º 22
0
    /// <summary>
    /// Initializes controls for activity rule.
    /// </summary>
    private void InitActivityRuleControls(string selectedActivityType)
    {
        ucActivityType.OnSelectedIndexChanged += new EventHandler(ucActivityType_OnSelectedIndexChanged);

        // Init activity selector from  edited object if any
        string activityType = selectedActivityType;

        if ((EditForm.EditedObject != null) && !RequestHelper.IsPostBack())
        {
            ucActivityType.Value = ValidationHelper.GetString(EditForm.Data["RuleParameter"], PredefinedActivityType.ABUSE_REPORT);
            activityType         = ucActivityType.SelectedValue;
            PreviousActivityType = activityType;
        }

        // List of ignored columns
        string ignoredColumns = "|activitytype|activitysiteid|activityguid|activityactivecontactid|activityoriginalcontactid|pagevisitid|pagevisitactivityid|searchid|searchactivityid|";

        // List of activities with "ActivityValue"
        StringBuilder sb = new StringBuilder();

        sb.Append("|");
        sb.Append(PredefinedActivityType.PURCHASE);
        sb.Append("|");
        sb.Append(PredefinedActivityType.PURCHASEDPRODUCT);
        sb.Append("|");
        sb.Append(PredefinedActivityType.RATING);
        sb.Append("|");
        sb.Append(PredefinedActivityType.POLL_VOTING);
        sb.Append("|");
        sb.Append(PredefinedActivityType.PRODUCT_ADDED_TO_SHOPPINGCART);
        sb.Append("|");
        string showActivityValueFor = sb.ToString();

        // Get columns from OM_Activity (i.e. base table for all activities)
        ActivityTypeInfo ati = ActivityTypeInfoProvider.GetActivityTypeInfo(activityType);

        FormInfo fi = new FormInfo(null);

        // Get columns from additional table (if any) according to selected activity type (page visit, search)
        FormInfo additionalFieldsForm = null;
        bool     extraFieldsAtEnd     = true;

        switch (activityType)
        {
        case PredefinedActivityType.PAGE_VISIT:
        case PredefinedActivityType.LANDING_PAGE:
            // Page visits
            additionalFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.PAGEVISIT, false);
            break;

        case PredefinedActivityType.INTERNAL_SEARCH:
        case PredefinedActivityType.EXTERNAL_SEARCH:
            // Search
            additionalFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.SEARCH, false);
            extraFieldsAtEnd     = false;
            break;
        }

        // Get the activity form elements
        FormInfo filterFieldsForm = FormHelper.GetFormInfo(OnlineMarketingObjectType.ACTIVITY, true);
        var      elements         = filterFieldsForm.GetFormElements(true, false);

        FormCategoryInfo newCategory = null;

        string caption    = null;
        string captionKey = null;

        foreach (var elem in elements)
        {
            if (elem is FormCategoryInfo)
            {
                // Form category
                newCategory = (FormCategoryInfo)elem;
            }
            else if (elem is FormFieldInfo)
            {
                // Form field
                FormFieldInfo ffi = (FormFieldInfo)elem;

                // Skip ignored columns
                if (ignoredColumns.IndexOfCSafe("|" + ffi.Name.ToLowerCSafe() + "|") >= 0)
                {
                    continue;
                }

                string controlName = null;
                if (!ffi.PrimaryKey && (fi.GetFormField(ffi.Name) == null))
                {
                    // Set default filters
                    switch (ffi.DataType)
                    {
                    case FormFieldDataTypeEnum.Text:
                    case FormFieldDataTypeEnum.LongText:
                        controlName = "textfilter";
                        ffi.Settings["OperatorFieldName"] = ffi.Name + ".operator";
                        break;

                    case FormFieldDataTypeEnum.DateTime:
                        controlName = "datetimefilter";
                        ffi.Settings["SecondDateFieldName"] = ffi.Name + ".seconddatetime";
                        break;

                    case FormFieldDataTypeEnum.Integer:
                    case FormFieldDataTypeEnum.LongInteger:
                        controlName = "numberfilter";
                        ffi.Settings["OperatorFieldName"] = ffi.Name + ".operator";
                        break;

                    case FormFieldDataTypeEnum.GUID:
                        continue;
                    }

                    // For item ID and detail ID fields use control defined in activity type
                    if (CMSString.Compare(ffi.Name, "ActivityItemID", true) == 0)
                    {
                        if (ati.ActivityTypeMainFormControl == null)
                        {
                            continue;
                        }

                        if (ati.ActivityTypeMainFormControl != String.Empty)
                        {
                            // Check if user defined control exists
                            FormUserControlInfo fui = FormUserControlInfoProvider.GetFormUserControlInfo(ati.ActivityTypeMainFormControl);
                            if (fui != null)
                            {
                                controlName = ati.ActivityTypeMainFormControl;
                            }
                        }

                        // Set detailed caption
                        captionKey = "activityitem." + activityType;
                        caption    = GetString(captionKey);
                        if (!caption.EqualsCSafe(captionKey, true))
                        {
                            ffi.Caption = caption;
                        }
                    }
                    else if (CMSString.Compare(ffi.Name, "ActivityItemDetailID", true) == 0)
                    {
                        if (ati.ActivityTypeDetailFormControl == null)
                        {
                            continue;
                        }

                        if (ati.ActivityTypeDetailFormControl != String.Empty)
                        {
                            // Check if user defined control exists
                            FormUserControlInfo fui = FormUserControlInfoProvider.GetFormUserControlInfo(ati.ActivityTypeDetailFormControl);
                            if (fui != null)
                            {
                                controlName = ati.ActivityTypeDetailFormControl;
                            }
                        }

                        // Set detailed caption
                        captionKey = "activityitemdetail." + activityType;
                        caption    = GetString(captionKey);
                        if (!caption.EqualsCSafe(captionKey, true))
                        {
                            ffi.Caption = caption;
                        }
                    }
                    else if (CMSString.Compare(ffi.Name, "ActivityNodeID", true) == 0)
                    {
                        // Document selector for NodeID
                        controlName = "selectdocument";
                    }
                    else if (CMSString.Compare(ffi.Name, "ActivityCulture", true) == 0)
                    {
                        // Culture selector for culture
                        controlName = "sitecultureselector";
                    }
                    else if (CMSString.Compare(ffi.Name, "ActivityValue", true) == 0)
                    {
                        // Show activity value only for relevant activity types
                        if (!ati.ActivityTypeIsCustom && (showActivityValueFor.IndexOfCSafe("|" + activityType + "|", true) < 0))
                        {
                            continue;
                        }
                    }

                    if (controlName != null)
                    {
                        // SKU selector for product
                        ffi.Settings["controlname"] = controlName;
                        if (CMSString.Compare(controlName, "skuselector", true) == 0)
                        {
                            ffi.Settings["allowempty"] = true;
                        }
                    }

                    // Ensure the category
                    if (newCategory != null)
                    {
                        fi.AddFormCategory(newCategory);

                        newCategory = null;

                        // // Extra fields at the beginning
                        if (!extraFieldsAtEnd && (additionalFieldsForm != null))
                        {
                            AddExtraFields(ignoredColumns, fi, additionalFieldsForm);

                            additionalFieldsForm = null;
                        }
                    }

                    fi.AddFormField(ffi);
                }
            }
        }

        // Extra fields at end
        if (extraFieldsAtEnd && (additionalFieldsForm != null))
        {
            // Ensure the category for extra fields
            if (newCategory != null)
            {
                fi.AddFormCategory(newCategory);

                newCategory = null;
            }

            AddExtraFields(ignoredColumns, fi, additionalFieldsForm);
        }

        LoadForm(activityFormCondition, fi, activityType);
    }
Exemplo n.º 23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!RequestHelper.IsPostBack())
        {
            string preferredCultureCode = CMSContext.PreferredCultureCode;
            string currentSiteName      = CMSContext.CurrentSiteName;
            string where = "CultureCode IN (SELECT DocumentCulture FROM View_CMS_Tree_Joined WHERE NodeID = " + Node.NodeID + ")";
            DataSet documentCultures = CultureInfoProvider.GetCultures(where, null, 0, "CultureCode");

            // Get site cultures
            DataSet siteCultures = CultureInfoProvider.GetSiteCultures(currentSiteName);
            if (!DataHelper.DataSourceIsEmpty(siteCultures) && !DataHelper.DataSourceIsEmpty(documentCultures))
            {
                string suffixNotTranslated = GetString("SplitMode.NotTranslated");

                foreach (DataRow row in siteCultures.Tables[0].Rows)
                {
                    string cultureCode = ValidationHelper.GetString(row["CultureCode"], null);
                    string cultureName = ResHelper.LocalizeString(ValidationHelper.GetString(row["CultureName"], null));

                    string suffix = string.Empty;

                    // Compare with preferred culture
                    if (CMSString.Compare(preferredCultureCode, cultureCode, true) == 0)
                    {
                        suffix = GetString("SplitMode.Current");
                    }
                    else
                    {
                        // Find culture
                        DataRow[] findRows = documentCultures.Tables[0].Select("CultureCode = '" + cultureCode + "'");
                        if (findRows.Length == 0)
                        {
                            suffix = suffixNotTranslated;
                        }
                    }

                    // Add new item
                    ListItem item = new ListItem(cultureName + " " + suffix, cultureCode);
                    drpCultures.Items.Add(item);
                }
            }

            drpCultures.SelectedValue = CMSContext.SplitModeCultureCode;
            drpCultures.Attributes.Add("onchange", "if (parent.CheckChanges('frame2')) { parent.FSP_ChangeCulture(this); }");
        }

        // Image URL and tooltip
        helpElem.IconUrl       = GetImageUrl("Design/Controls/SplitView/splitviewhelpicon.png");
        imgHorizontal.ImageUrl = UIHelper.GetImageUrl(Page, HorizontalImageUrl);
        imgVertical.ImageUrl   = UIHelper.GetImageUrl(Page, VerticalImageUrl);
        imgClose.ImageUrl      = UIHelper.GetImageUrl(Page, CloseImageUrl);
        imgHorizontal.ToolTip  = GetString("splitmode.horizontallayout");
        imgVertical.ToolTip    = GetString("splitmode.verticallayout");
        imgClose.ToolTip       = GetString("splitmode.closesplitmode");

        // Set css class
        switch (CMSContext.SplitMode)
        {
        case SplitModeEnum.Horizontal:
            divHorizontal.Attributes["class"] = buttonSelectedClass;
            divVertical.Attributes["class"]   = buttonClass;
            break;

        case SplitModeEnum.Vertical:
            divHorizontal.Attributes["class"] = buttonClass;
            divVertical.Attributes["class"]   = buttonSelectedClass;
            break;

        default:
            divHorizontal.Attributes["class"] = buttonClass;
            divVertical.Attributes["class"]   = buttonClass;
            break;
        }

        string checkedSyncUrl   = UIHelper.GetImageUrl(Page, mSyncCheckedImageUrl);
        string uncheckedSyncUrl = UIHelper.GetImageUrl(Page, mSyncUncheckedImageUrl);

        // Synchronize image
        string tooltip = GetString("splitmode.scrollbarsynchronization");

        imgSync.AlternateText = tooltip;
        imgSync.ToolTip       = tooltip;
        imgSync.ImageUrl      = CMSContext.SplitModeSyncScrollbars ? checkedSyncUrl : uncheckedSyncUrl;

        StringBuilder script = new StringBuilder();

        script.Append(@"
function FSP_Layout(vertical, frameName, cssClassName)
{
    if ((frameName != null) && parent.CheckChanges(frameName)) {
        if (cssClassName != null) {
            var element = document.getElementById('", pnlMain.ClientID, @"');
            if (element != null) {
                element.setAttribute(""class"", 'SplitToolbar ' + cssClassName);
                element.setAttribute(""className"", 'SplitToolbar ' + cssClassName);
            }
        }
        var divRight = document.getElementById('", divRight.ClientID, @"');
        if (vertical) {
            divRight.setAttribute(""class"", 'RightAlign');
            parent.FSP_VerticalLayout();
        }
        else {
            divRight.setAttribute(""class"", '');
            parent.FSP_HorizontalLayout();
        }
    }
}");

        script.Append(@"
function FSP_Close() { if (parent.CheckChanges()) { parent.FSP_CloseSplitMode(); } }"
                      );

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "toolbarScript_" + ClientID, ScriptHelper.GetScript(script.ToString()));

        // Register js events
        imgHorizontal.Attributes.Add("onclick", "javascript:FSP_Layout(false,'frame1Vertical','Horizontal');");
        imgHorizontal.AlternateText = GetString("SplitMode.Horizontal");
        imgVertical.Attributes.Add("onclick", "javascript:FSP_Layout('true','frame1','Vertical');");
        imgVertical.AlternateText = GetString("SplitMode.Vertical");
        imgClose.Attributes.Add("onclick", "javascript:FSP_Close();");
        imgSync.Attributes.Add("onclick", "javascript:parent.FSP_SynchronizeToolbar()");
        imgClose.Style.Add("cursor", "pointer");

        // Set layout
        if (CMSContext.SplitMode == SplitModeEnum.Horizontal)
        {
            pnlMain.CssClass             = "SplitToolbar Horizontal";
            divRight.Attributes["class"] = null;
        }
        else if (CMSContext.SplitMode == SplitModeEnum.Vertical)
        {
            pnlMain.CssClass = "SplitToolbar Vertical";
        }

        // Register Init script - FSP_ToolbarInit(selectorId, checkboxId)
        StringBuilder initScript = new StringBuilder();

        initScript.Append("parent.FSP_ToolbarInit('", drpCultures.ClientID, "','", imgSync.ClientID, "','", checkedSyncUrl, "','", uncheckedSyncUrl,
                          "','", divHorizontal.ClientID, "','", divVertical.ClientID, "');");

        // Register js scripts
        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterStartupScript(Page, typeof(string), "FSP_initToolbar", ScriptHelper.GetScript(initScript.ToString()));
    }
    /// <summary>
    /// Updates existing or creates new web part.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Validate the text box fields
        string errorMessage = new Validator().IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename")).Result;

        if (errorMessage != String.Empty)
        {
            ShowError(errorMessage);
            return;
        }

        WebPartInfo wi = WebPartInfoProvider.GetWebPartInfo(webPartId);

        if (wi != null)
        {
            string webpartPath = GetWebPartPhysicalPath(FileSystemSelector.Value.ToString());

            txtWebPartName.Text        = TextHelper.LimitLength(txtWebPartName.Text.Trim(), 100, "");
            txtWebPartDisplayName.Text = TextHelper.LimitLength(txtWebPartDisplayName.Text.Trim(), 100, "");

            // Perform validation
            errorMessage = new Validator().NotEmpty(txtWebPartName.Text, rfvWebPartName.ErrorMessage).IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename"))
                           .NotEmpty(txtWebPartDisplayName.Text, rfvWebPartDisplayName.ErrorMessage).Result;

            // Check file name
            if (wi.WebPartParentID <= 0)
            {
                if (!FileSystemSelector.IsValid())
                {
                    errorMessage += FileSystemSelector.ValidationError;
                }
            }

            if (errorMessage != String.Empty)
            {
                ShowError(errorMessage);
                return;
            }


            string oldDisplayName = wi.WebPartDisplayName;
            string oldCodeName    = wi.WebPartName;
            int    oldCategory    = wi.WebPartCategoryID;

            // Remove starting CMSwebparts folder
            string filename = FileSystemSelector.Value.ToString().Trim();
            if (filename.ToLowerCSafe().StartsWithCSafe("~/cmswebparts/"))
            {
                filename = filename.Substring("~/cmswebparts/".Length);
            }


            // If name changed, check if new name is unique
            if (CMSString.Compare(wi.WebPartName, txtWebPartName.Text, true) != 0)
            {
                WebPartInfo webpart = WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text);
                if (webpart != null)
                {
                    ShowError(GetString("Development.WebParts.WebPartNameAlreadyExist").Replace("%%name%%", txtWebPartName.Text));
                    return;
                }
            }

            wi.WebPartName                 = txtWebPartName.Text;
            wi.WebPartDisplayName          = txtWebPartDisplayName.Text;
            wi.WebPartDescription          = txtWebPartDescription.Text.Trim();
            wi.WebPartFileName             = filename;
            wi.WebPartType                 = ValidationHelper.GetInteger(drpWebPartType.SelectedValue, 0);
            wi.WebPartSkipInsertProperties = chkSkipInsertProperties.Checked;

            wi.WebPartLoadGeneration = drpGeneration.Value;
            wi.WebPartResourceID     = ValidationHelper.GetInteger(drpModule.Value, 0);

            FileSystemSelector.Value = wi.WebPartFileName;

            wi.WebPartCategoryID = ValidationHelper.GetInteger(categorySelector.Value, 0);

            WebPartInfoProvider.SetWebPartInfo(wi);

            // if DisplayName or Category was changed, then refresh web part tree and header
            if ((oldCodeName != wi.WebPartName) || (oldDisplayName != wi.WebPartDisplayName) || (oldCategory != wi.WebPartCategoryID))
            {
                ltlScript.Text += ScriptHelper.GetScript(
                    "parent.parent.frames['webparttree'].location.replace('WebPart_Tree.aspx?webpartid=" + wi.WebPartID + "'); \n" +
                    "parent.frames['webparteditheader'].location.replace(parent.frames['webparteditheader'].location.href); \n"
                    );
            }

            ShowChangesSaved();
        }
    }
Exemplo n.º 25
0
    protected void libraryMenuElem_OnReloadData(object sender, EventArgs e)
    {
        string[] parameters = (libraryMenuElem.Parameter ?? string.Empty).Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
        if (parameters.Length == 2)
        {
            // Parse identifier and document culture from library parameter
            int    nodeId      = ValidationHelper.GetInteger(parameters[0], 0);
            string cultureCode = ValidationHelper.GetString(parameters[1], string.Empty);
            DocumentManager.Mode = FormModeEnum.Update;
            DocumentManager.ClearNode();
            DocumentManager.DocumentID  = 0;
            DocumentManager.NodeID      = nodeId;
            DocumentManager.CultureCode = cultureCode;
            TreeNode node = DocumentManager.Node;

            bool contextMenuVisible    = false;
            bool localizeVisible       = false;
            bool editVisible           = false;
            bool uploadVisible         = false;
            bool copyVisible           = false;
            bool deleteVisible         = false;
            bool openVisible           = false;
            bool propertiesVisible     = false;
            bool permissionsVisible    = false;
            bool versionHistoryVisible = false;

            bool checkOutVisible         = false;
            bool checkInVisible          = false;
            bool undoCheckoutVisible     = false;
            bool submitToApprovalVisible = false;
            bool rejectVisible           = false;
            bool archiveVisible          = false;

            if ((node != null) && (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed))
            {
                // Get original node (in case of linked documents)
                TreeNode originalNode = TreeProvider.GetOriginalNode(node);

                string documentType           = ValidationHelper.GetString(node.GetValue("DocumentType"), string.Empty);
                string siteName               = CMSContext.CurrentSiteName;
                string currentDocumentCulture = CMSContext.CurrentDocumentCulture.CultureCode;

                if (CMSContext.CurrentSiteID != originalNode.NodeSiteID)
                {
                    SiteInfo si = SiteInfoProvider.GetSiteInfo(originalNode.NodeSiteID);
                    siteName = si.SiteName;
                }

                if (!DocumentManager.ProcessingAction)
                {
                    // Get permissions
                    const bool authorizedToRead              = true;
                    bool       authorizedToDelete            = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Delete) == AuthorizationResultEnum.Allowed);
                    bool       authorizedToModify            = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify) == AuthorizationResultEnum.Allowed);
                    bool       authorizedCultureToModify     = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.Modify, false) == AuthorizationResultEnum.Allowed) && TreeSecurityProvider.HasUserCultureAllowed(NodePermissionsEnum.Modify, currentDocumentCulture, CMSContext.CurrentUser, siteName);
                    bool       authorizedToModifyPermissions = (CMSContext.CurrentUser.IsAuthorizedPerDocument(node, NodePermissionsEnum.ModifyPermissions) == AuthorizationResultEnum.Allowed);
                    bool       authorizedToCreate            = CMSContext.CurrentUser.IsAuthorizedToCreateNewDocument(node.NodeParentID, node.NodeClassName);

                    // Hide menu when user has no 'Read' permissions on document
                    libraryMenuElem.Visible = authorizedToRead;

                    // First evaluation of control's visibility
                    bool differentCulture = (CMSString.Compare(node.DocumentCulture, currentDocumentCulture, true) != 0);
                    localizeVisible       = differentCulture && authorizedToCreate && authorizedCultureToModify;
                    uploadVisible         = authorizedToModify && DocumentManager.AllowSave;
                    copyVisible           = authorizedToCreate && authorizedToModify;
                    deleteVisible         = authorizedToDelete;
                    openVisible           = authorizedToRead;
                    propertiesVisible     = authorizedToModify;
                    permissionsVisible    = authorizedToModifyPermissions;
                    versionHistoryVisible = authorizedToModify;
                    editVisible           = authorizedToModify && CMSContext.IsWebDAVEnabled(CMSContext.CurrentSiteName) && RequestHelper.IsWindowsAuthentication() && WebDAVSettings.IsExtensionAllowedForEditMode(documentType, CMSContext.CurrentSiteName);

                    // Get next step info
                    List <WorkflowStepInfo> stps     = new List <WorkflowStepInfo>();
                    WorkflowInfo            workflow = DocumentManager.Workflow;
                    bool basicWorkflow = true;
                    if (workflow != null)
                    {
                        basicWorkflow = workflow.IsBasic;
                        stps          = WorkflowManager.GetNextStepInfo(node);
                    }
                    var appSteps  = stps.FindAll(s => !s.StepIsArchived);
                    var archSteps = stps.FindAll(s => s.StepIsArchived);

                    // Workflow actions
                    submitToApprovalVisible = DocumentManager.IsActionAllowed(DocumentComponentEvents.APPROVE) && (appSteps.Count > 0);
                    rejectVisible           = DocumentManager.IsActionAllowed(DocumentComponentEvents.REJECT);
                    archiveVisible          = DocumentManager.IsActionAllowed(DocumentComponentEvents.ARCHIVE) && ((archSteps.Count > 0) || basicWorkflow);
                    checkOutVisible         = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKOUT);
                    checkInVisible          = DocumentManager.IsActionAllowed(DocumentComponentEvents.CHECKIN);
                    undoCheckoutVisible     = DocumentManager.IsActionAllowed(DocumentComponentEvents.UNDO_CHECKOUT);

                    string parameterScript = "GetContextMenuParameter('" + libraryMenuElem.MenuID + "')";

                    // Initialize edit menu item
                    Guid attachmentGuid = ValidationHelper.GetGuid(node.GetValue("FileAttachment"), Guid.Empty);

                    // If attachment field doesn't allow empty value and the value is empty
                    if ((FieldInfo != null) && !FieldInfo.AllowEmpty && (attachmentGuid == Guid.Empty))
                    {
                        submitToApprovalVisible = false;
                        archiveVisible          = false;
                        checkInVisible          = false;
                    }

                    // Get attachment
                    AttachmentInfo ai = DocumentHelper.GetAttachment(attachmentGuid, TreeProvider, siteName, false);

                    Panel previousPanel = null;
                    Panel currentPanel  = pnlEdit;

                    if (editVisible)
                    {
                        if (ai != null)
                        {
                            // Load WebDAV edit control and initialize it
                            WebDAVEditControl editAttachment = Page.LoadUserControl("~/CMSModules/WebDAV/Controls/AttachmentWebDAVEditControl.ascx") as WebDAVEditControl;

                            if (editAttachment != null)
                            {
                                editAttachment.ID                  = "editAttachment";
                                editAttachment.NodeAliasPath       = node.NodeAliasPath;
                                editAttachment.NodeCultureCode     = node.DocumentCulture;
                                editAttachment.AttachmentFieldName = "FileAttachment";
                                editAttachment.FileName            = ai.AttachmentName;
                                editAttachment.IsLiveSite          = IsLiveSite;
                                editAttachment.UseImageButton      = true;
                                editAttachment.LabelText           = GetString("general.edit");
                                editAttachment.CssClass            = "Icon";
                                editAttachment.LabelCssClass       = "Name";
                                editAttachment.RefreshScript       = JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'WebDAVRefresh');";
                                // Set Group ID for live site
                                editAttachment.GroupID = IsLiveSite ? node.GetIntegerValue("NodeGroupID") : 0;
                                editAttachment.ReloadData(true);

                                pnlEditPadding.Controls.Add(editAttachment);
                                pnlEditPadding.CssClass = editAttachment.EnabledResult ? "ItemPadding" : "ItemPaddingDisabled";
                            }
                        }
                        else
                        {
                            editVisible = false;
                            openVisible = false;
                        }
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlUpload;

                    // Initialize upload menu item
                    if (authorizedToModify)
                    {
                        StringBuilder uploaderInnerHtml = new StringBuilder();
                        uploaderInnerHtml.Append("<img class=\"UploaderImage\" src=\"", GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Upload.png", IsLiveSite), "\" alt=\"", GetString("general.update"), "\" />");
                        uploaderInnerHtml.Append("<span class=\"UploaderText\">", GetString("general.update"), "</span>");

                        // Initialize direct file uploader
                        updateAttachment.InnerDivHtml             = uploaderInnerHtml.ToString();
                        updateAttachment.InnerDivClass            = "LibraryContextUploader";
                        updateAttachment.DocumentID               = node.DocumentID;
                        updateAttachment.ParentElemID             = ClientID;
                        updateAttachment.SourceType               = MediaSourceEnum.Attachment;
                        updateAttachment.AttachmentGUIDColumnName = "FileAttachment";
                        updateAttachment.IsLiveSite               = IsLiveSite;

                        // Set allowed extensions
                        if ((FieldInfo != null) && ValidationHelper.GetString(FieldInfo.Settings["extensions"], "") == "custom")
                        {
                            // Load allowed extensions
                            updateAttachment.AllowedExtensions = ValidationHelper.GetString(FieldInfo.Settings["allowed_extensions"], "");
                        }
                        else
                        {
                            // Use site settings
                            updateAttachment.AllowedExtensions = SettingsKeyProvider.GetStringValue(siteName + ".CMSUploadExtensions");
                        }

                        updateAttachment.ReloadData();
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlLocalize;

                    // Initialize localize menu item
                    if (localizeVisible)
                    {
                        lblLocalize.RefreshText();
                        imgLocalize.AlternateText = lblLocalize.Text;
                        imgLocalize.ImageUrl      = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Localize.png", IsLiveSite);
                        pnlLocalize.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Localize');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = null;
                    currentPanel  = pnlCopy;

                    // Initialize copy menu item
                    if (copyVisible)
                    {
                        lblCopy.RefreshText();
                        imgCopy.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Copy.png", IsLiveSite);
                        pnlCopy.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ",'Copy');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlDelete;

                    // Initialize delete menu item
                    if (deleteVisible)
                    {
                        lblDelete.RefreshText();
                        imgDelete.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Delete.png", IsLiveSite);
                        pnlDelete.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Delete');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlOpen;

                    // Initialize open menu item
                    if (openVisible)
                    {
                        lblOpen.RefreshText();
                        imgOpen.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Open.png", IsLiveSite);
                        if (ai != null)
                        {
                            // Get document URL
                            string attachmentUrl = CMSContext.ResolveUIUrl(AttachmentURLProvider.GetPermanentAttachmentUrl(node.NodeGUID, node.NodeAlias));
                            if (authorizedToModify)
                            {
                                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "latestfordocid", ValidationHelper.GetString(node.DocumentID, string.Empty));
                                attachmentUrl = URLHelper.AddParameterToUrl(attachmentUrl, "hash", ValidationHelper.GetHashString("d" + node.DocumentID));
                            }
                            attachmentUrl = URLHelper.UpdateParameterInUrl(attachmentUrl, "chset", Guid.NewGuid().ToString());

                            if (!string.IsNullOrEmpty(attachmentUrl))
                            {
                                pnlOpen.Attributes.Add("onclick", "location.href = " + ScriptHelper.GetString(attachmentUrl) + ";");
                            }
                        }
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = null;
                    currentPanel  = pnlProperties;

                    // Initialize properties menu item
                    lblProperties.RefreshText();
                    imgProperties.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Properties.png", IsLiveSite);
                    pnlProperties.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Properties');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = currentPanel;
                    currentPanel  = pnlPermissions;

                    // Initialize permissions menu item
                    lblPermissions.RefreshText();
                    imgPermissions.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Permissions.png", IsLiveSite);
                    pnlPermissions.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Permissions');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = currentPanel;
                    currentPanel  = pnlVersionHistory;

                    // Initialize version history menu item
                    lblVersionHistory.RefreshText();
                    imgVersionHistory.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/VersionHistory.png", IsLiveSite);
                    pnlVersionHistory.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'VersionHistory');");
                    SetupPanelClasses(currentPanel, previousPanel);

                    previousPanel = null;
                    currentPanel  = pnlCheckOut;

                    // Initialize checkout menu item
                    if (checkOutVisible)
                    {
                        lblCheckOut.RefreshText();
                        imgCheckOut.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckOut.png", IsLiveSite);
                        pnlCheckOut.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckOut');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlCheckIn;

                    // Initialize check in menu item
                    if (checkInVisible)
                    {
                        lblCheckIn.RefreshText();
                        imgCheckIn.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/CheckIn.png", IsLiveSite);
                        pnlCheckIn.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'CheckIn');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlUndoCheckout;

                    // Initialize undo checkout menu item
                    if (undoCheckoutVisible)
                    {
                        lblUndoCheckout.RefreshText();
                        imgUndoCheckout.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/UndoCheckout.png", IsLiveSite);
                        pnlUndoCheckout.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'UndoCheckout');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlSubmitToApproval;

                    // Initialize submit to approval / publish menu item
                    if (submitToApprovalVisible)
                    {
                        // Only one next step
                        if (appSteps.Count == 1)
                        {
                            if (appSteps[0].StepIsPublished)
                            {
                                // Set 'Publish' label
                                lblSubmitToApproval.ResourceString = "general.publish";
                                cmcApp.Parameter = "GetContextMenuParameter('libraryMenu_" + ClientID + "')" + string.Format(" + '|{0}'", DocumentComponentEvents.PUBLISH);
                            }
                            pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'SubmitToApproval');");
                        }
                        // Multiple steps - display dialog
                        else
                        {
                            pnlSubmitToApproval.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new string[] { "'" + DocumentComponentEvents.APPROVE + "'", node.DocumentID.ToString() }), null) + ";");
                            cmcApp.Enabled = false;
                        }

                        lblSubmitToApproval.RefreshText();
                        imgSubmitToApproval.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/SubmitToApproval.png", IsLiveSite);
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlReject;

                    // Initialize reject menu item
                    if (rejectVisible)
                    {
                        lblReject.RefreshText();
                        imgReject.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Reject.png", IsLiveSite);
                        pnlReject.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Reject');");
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    previousPanel = currentPanel;
                    currentPanel  = pnlArchive;

                    // Initialize archive menu item
                    if (archiveVisible)
                    {
                        // Only one archive step
                        if ((archSteps.Count == 1) || basicWorkflow)
                        {
                            pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'Archive');");
                        }
                        // Multiple archive steps - display dialog
                        else
                        {
                            pnlArchive.Attributes.Add("onclick", JavaScriptPrefix + "PerformAction(" + parameterScript + ", 'RefreshGridSimple');" + DocumentManager.GetJSFunction(ComponentEvents.COMMENT, string.Join("|", new string[] { "'" + DocumentComponentEvents.ARCHIVE + "'", node.DocumentID.ToString() }), null) + ";");
                            cmcArch.Enabled = false;
                        }

                        lblArchive.RefreshText();
                        imgArchive.ImageUrl = GetImageUrl("Design/Controls/ContextMenu/DocumentLibrary/Archive.png", IsLiveSite);
                        SetupPanelClasses(currentPanel, previousPanel);
                    }

                    // Set up visibility of menu items
                    pnlLocalize.Visible       = localizeVisible;
                    pnlUpload.Visible         = uploadVisible;
                    pnlDelete.Visible         = deleteVisible;
                    pnlCopy.Visible           = copyVisible;
                    pnlOpen.Visible           = openVisible;
                    pnlProperties.Visible     = propertiesVisible;
                    pnlPermissions.Visible    = permissionsVisible;
                    pnlVersionHistory.Visible = versionHistoryVisible;
                    pnlEdit.Visible           = editVisible;

                    pnlCheckOut.Visible         = checkOutVisible;
                    pnlCheckIn.Visible          = checkInVisible;
                    pnlUndoCheckout.Visible     = undoCheckoutVisible;
                    pnlSubmitToApproval.Visible = submitToApprovalVisible;
                    pnlReject.Visible           = rejectVisible;
                    pnlArchive.Visible          = archiveVisible;

                    // Set up visibility of whole menu
                    contextMenuVisible = true;
                }

                if (DocumentManager.ProcessingAction)
                {
                    // Setup 'No action available' menu item
                    pnlNoAction.Visible        = true;
                    lblNoAction.ResourceString = null;
                    lblNoAction.Text           = DocumentManager.GetDocumentInfo(true);
                    lblNoAction.RefreshText();
                }
                else
                {
                    // Set up visibility of separators
                    bool firstGroupVisible  = editVisible || uploadVisible || localizeVisible;
                    bool secondGroupVisible = copyVisible || deleteVisible || openVisible;
                    bool thirdGroupVisible  = propertiesVisible || permissionsVisible || versionHistoryVisible;
                    bool fourthGroupVisible = checkOutVisible || checkInVisible || undoCheckoutVisible || submitToApprovalVisible || rejectVisible || archiveVisible;

                    pnlSep1.Visible = firstGroupVisible && secondGroupVisible;
                    pnlSep2.Visible = secondGroupVisible && thirdGroupVisible;
                    pnlSep3.Visible = thirdGroupVisible && fourthGroupVisible;

                    // Setup 'No action available' menu item
                    pnlNoAction.Visible = !contextMenuVisible;
                    lblNoAction.RefreshText();
                }
            }
        }
    }
Exemplo n.º 26
0
    /// <summary>
    /// Saves the given DataRow data to the web part properties.
    /// </summary>
    /// <param name="form">Form to save</param>
    /// <param name="pti">Page template instance</param>
    private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti)
    {
        if (form.Visible && (widgetInstance != null))
        {
            // Keep the old ID to check the change of the ID
            string oldId = widgetInstance.ControlID.ToLowerCSafe();

            DataRow dr = form.DataRow;

            // Load default values for new widget
            if (IsNewWidget)
            {
                form.FormInformation.LoadDefaultValues(dr, wi.WidgetDefaultValues);
            }

            foreach (DataColumn column in dr.Table.Columns)
            {
                widgetInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()];
                widgetInstance.SetValue(column.ColumnName, dr[column]);

                // If name changed, move the content
                if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0)
                {
                    try
                    {
                        string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe();

                        // Name changed
                        if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0))
                        {
                            mWidgetIdChanged = true;
                            WidgetId         = newId;

                            // Move the document content if present
                            string currentContent = pi.EditableWebParts[oldId];
                            if (currentContent != null)
                            {
                                TreeNode node = DocumentHelper.GetDocument(pi.DocumentID, tree);

                                // Move the content in the page info
                                pi.EditableWebParts[oldId] = null;
                                pi.EditableWebParts[newId] = currentContent;

                                // Update the document
                                node.SetValue("DocumentContent", pi.GetContentXml());
                                DocumentHelper.UpdateDocument(node, tree);
                            }

                            // Change the underlying zone names if layout web part
                            if ((wpi != null) && ((WebPartTypeEnum)wpi.WebPartType == WebPartTypeEnum.Layout))
                            {
                                string prefix = oldId + "_";

                                foreach (WebPartZoneInstance zone in pti.WebPartZones)
                                {
                                    if (zone.ZoneID.StartsWithCSafe(prefix, true))
                                    {
                                        // Change the zone prefix to the new one
                                        zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider ev = new EventLogProvider();
                        ev.LogEvent("Content", "CHANGEWIDGET", ex);
                    }
                }
            }
        }
    }
Exemplo n.º 27
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!RequestHelper.IsPostBack())
        {
            string preferredCultureCode = LocalizationContext.PreferredCultureCode;
            string currentSiteName      = SiteContext.CurrentSiteName;
            var    documentCultures     = Node.GetTranslatedCultures();

            // Get site cultures
            DataSet siteCultures = CultureSiteInfoProvider.GetSiteCultures(currentSiteName);
            if (!DataHelper.DataSourceIsEmpty(siteCultures) && (documentCultures.Count > 0))
            {
                string suffixNotTranslated = GetString("SplitMode.NotTranslated");

                foreach (DataRow row in siteCultures.Tables[0].Rows)
                {
                    string cultureCode = ValidationHelper.GetString(row["CultureCode"], null);
                    string cultureName = ResHelper.LocalizeString(ValidationHelper.GetString(row["CultureName"], null));

                    string suffix = string.Empty;

                    // Compare with preferred culture
                    if (CMSString.Compare(preferredCultureCode, cultureCode, true) == 0)
                    {
                        suffix = GetString("SplitMode.Current");
                    }
                    else if (!documentCultures.Contains(cultureCode))
                    {
                        suffix = suffixNotTranslated;
                    }

                    // Add new item
                    var item = new ListItem(cultureName + " " + suffix, cultureCode);
                    drpCultures.Items.Add(item);
                }
            }

            drpCultures.SelectedValue = PortalUIHelper.SplitModeCultureCode;
            drpCultures.Attributes.Add("onchange", "if (parent.CheckChanges('frame2')) { parent.FSP_ChangeCulture(this); }");
        }

        buttons.Actions.Add(new CMSButtonGroupAction {
            Name = "close", UseIconButton = true, OnClientClick = "FSP_Close();return false;", IconCssClass = "icon-l-list-titles", ToolTip = GetString("splitmode.closelayout")
        });
        buttons.Actions.Add(new CMSButtonGroupAction {
            Name = "vertical", UseIconButton = true, OnClientClick = "FSP_Layout('true','frame1','Vertical');return false;", IconCssClass = "icon-l-cols-2 js-split-vertical", ToolTip = GetString("splitmode.verticallayout")
        });
        buttons.Actions.Add(new CMSButtonGroupAction {
            Name = "horizontal", UseIconButton = true, OnClientClick = "FSP_Layout(false,'frame1Vertical','Horizontal');;return false;", IconCssClass = "icon-l-rows-2 js-split-horizontal", ToolTip = GetString("splitmode.horizontallayout")
        });

        // Set css class
        switch (PortalUIHelper.SplitMode)
        {
        case SplitModeEnum.Horizontal:
            buttons.SelectedActionName = "horizontal";
            break;

        case SplitModeEnum.Vertical:
            buttons.SelectedActionName = "vertical";
            break;

        default:
            buttons.SelectedActionName = "close";
            break;
        }

        // Synchronize image
        chckScroll.Checked = PortalUIHelper.SplitModeSyncScrollbars;

        StringBuilder script = new StringBuilder();

        script.Append(
            @"
function FSP_Layout(vertical, frameName, cssClassName)
{
    if ((frameName != null) && parent.CheckChanges(frameName)) {
        if (cssClassName != null) {
            var element = document.getElementById('", pnlMain.ClientID, @"');
            if (element != null) {
                element.setAttribute(""class"", 'SplitToolbar ' + cssClassName);
                element.setAttribute(""className"", 'SplitToolbar ' + cssClassName);
            }
        }
        var divRight = document.getElementById('", divRight.ClientID, @"');
        if (vertical) {
            divRight.setAttribute(""class"", 'RightAlign');
            parent.FSP_VerticalLayout();
        }
        else {
            divRight.setAttribute(""class"", '');
            parent.FSP_HorizontalLayout();
        }
    }
}

function FSP_Close() { 
    if (parent.CheckChanges()) { 
        parent.FSP_CloseSplitMode(); 
    }
}
");

        ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "toolbarScript_" + ClientID, ScriptHelper.GetScript(script.ToString()));

        chckScroll.Attributes.Add("onchange", "javascript:parent.FSP_SynchronizeToolbar()");

        // Set layout
        if (PortalUIHelper.SplitMode == SplitModeEnum.Horizontal)
        {
            pnlMain.CssClass             = "SplitToolbar Horizontal";
            divRight.Attributes["class"] = null;
        }
        else if (PortalUIHelper.SplitMode == SplitModeEnum.Vertical)
        {
            pnlMain.CssClass = "SplitToolbar Vertical";
        }

        // Register Init script - FSP_ToolbarInit(selectorId, checkboxId)
        StringBuilder initScript = new StringBuilder();

        initScript.Append("parent.FSP_ToolbarInit('", drpCultures.ClientID, "','", chckScroll.ClientID, "');");

        // Register js scripts
        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterStartupScript(Page, typeof(string), "FSP_initToolbar", ScriptHelper.GetScript(initScript.ToString()));
    }
Exemplo n.º 28
0
    /// <summary>
    /// Saves the given DataRow data to the web part properties.
    /// </summary>
    /// <param name="form">Form to save</param>
    /// <param name="pti">Page template instance</param>
    /// <param name="isLayoutWidget">Indicates whether the edited widget is a layout widget</param>
    private void SaveFormToWidget(BasicForm form, PageTemplateInstance pti, bool isLayoutWidget)
    {
        if (form.Visible && (mWidgetInstance != null))
        {
            // Keep the old ID to check the change of the ID
            string oldId = mWidgetInstance.ControlID.ToLowerCSafe();

            DataRow dr = form.DataRow;

            foreach (DataColumn column in dr.Table.Columns)
            {
                mWidgetInstance.MacroTable[column.ColumnName.ToLowerCSafe()] = form.MacroTable[column.ColumnName.ToLowerCSafe()];
                mWidgetInstance.SetValue(column.ColumnName, dr[column]);

                // If name changed, move the content
                // (This can happen when a user overrides the WidgetControlID property to be visible in the widget properties dialog)
                if (CMSString.Compare(column.ColumnName, "widgetcontrolid", true) == 0)
                {
                    try
                    {
                        string newId = ValidationHelper.GetString(dr[column], "").ToLowerCSafe();

                        // Name changed
                        if (!String.IsNullOrEmpty(newId) && (CMSString.Compare(newId, oldId, false) != 0))
                        {
                            WidgetIdChanged = true;
                            WidgetId        = newId;

                            // Move the document content if present
                            string currentContent = CurrentPageInfo.EditableWebParts[oldId];
                            if (currentContent != null)
                            {
                                TreeNode node = DocumentHelper.GetDocument(CurrentPageInfo.DocumentID, mTreeProvider);

                                // Move the content in the page info
                                CurrentPageInfo.EditableWebParts[oldId] = null;
                                CurrentPageInfo.EditableWebParts[newId] = currentContent;

                                // Update the document
                                node.SetValue("DocumentContent", CurrentPageInfo.GetContentXml());
                                DocumentHelper.UpdateDocument(node, mTreeProvider);
                            }

                            // Change the underlying zone names if layout widget
                            if (isLayoutWidget)
                            {
                                string prefix = oldId + "_";

                                foreach (WebPartZoneInstance zone in pti.WebPartZones)
                                {
                                    if (zone.ZoneID.StartsWithCSafe(prefix, true))
                                    {
                                        // Change the zone prefix to the new one
                                        zone.ZoneID = String.Format("{0}_{1}", newId, zone.ZoneID.Substring(prefix.Length));
                                    }
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        EventLogProvider.LogException("Content", "CHANGEWIDGET", ex);
                    }
                }
            }
        }
    }
    /// <summary>
    /// Displays the given report
    /// </summary>
    private void DisplayReport(bool reloadInnerReport)
    {
        // If report was already displayed .. return
        if (reportDisplayed)
        {
            return;
        }

        ucGraphType.ProcessChartSelectors(false);

        // Prepare report parameters
        DataTable dtp = new DataTable();

        dtp.Columns.Add("FromDate", typeof(DateTime));
        dtp.Columns.Add("ToDate", typeof(DateTime));
        dtp.Columns.Add("CampaignName", typeof(string));

        object[] parameters = new object[3];

        parameters[0] = ucGraphType.From;
        parameters[1] = ucGraphType.To;
        parameters[2] = "";

        // Get report name from query
        string reportName = ucGraphType.GetReportName(QueryHelper.GetString("reportCodeName", String.Empty));

        if (CMSString.Compare(Convert.ToString(ucSelectCampaign.Value), "-1", true) != 0)
        {
            parameters[2] = ucSelectCampaign.Value;
        }
        else
        {
            reportName = "all" + reportName;
        }

        dtp.Rows.Add(parameters);
        dtp.AcceptChanges();

        ucDisplayReport.ReportName = reportName;

        // Set display report
        if (!ucDisplayReport.IsReportLoaded())
        {
            ShowError(String.Format(GetString("Analytics_Report.ReportDoesnotExist"), reportName));
        }
        else
        {
            ucDisplayReport.LoadFormParameters   = false;
            ucDisplayReport.DisplayFilter        = false;
            ucDisplayReport.ReportParameters     = dtp.Rows[0];
            ucDisplayReport.GraphImageWidth      = 100;
            ucDisplayReport.IgnoreWasInit        = true;
            ucDisplayReport.UseExternalReload    = true;
            ucDisplayReport.UseProgressIndicator = true;
            if (reloadInnerReport)
            {
                ucDisplayReport.ReloadData(true);
            }
        }

        if (reloadInnerReport)
        {
            // Mark as report displayed
            reportDisplayed = true;
        }
    }
Exemplo n.º 30
0
    /// <summary>
    /// Handles btnOK's OnClick event - Save culture info.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Validate the input
        string result = new Validator().NotEmpty(txtCultureName.Text.Trim(), rfvCultureName.ErrorMessage).NotEmpty(txtCultureCode.Text.Trim(), rfvCultureCode.ErrorMessage).Result;

        if (txtCultureCode.Text.Trim().Length > 10)
        {
            result = GetString("Culture.MaxLengthError");
        }

        // Validate the culture code
        try
        {
            // Check if global culture exists
            if (new CultureInfo(txtCultureCode.Text.Trim()) == null)
            {
                result = GetString("Culture.ErrorNoGlobalCulture");
            }
        }
        catch
        {
            result = GetString("Culture.ErrorNoGlobalCulture");
        }

        txtCultureAlias.Text = URLHelper.GetSafeUrlPart(txtCultureAlias.Text.Trim(), String.Empty);
        string cultureAlias = txtCultureAlias.Text.Trim();

        // Check whether culture alias is unique
        if (!String.IsNullOrEmpty(cultureAlias))
        {
            CMS.SiteProvider.CultureInfo ci = CultureInfoProvider.GetCultureInfoForCulture(cultureAlias);
            if ((ci != null) || (CMSString.Compare(cultureAlias, txtCultureCode.Text.Trim(), true) == 0))
            {
                result = GetString("Culture.AliasNotUnique");
            }
        }

        if (result == "")
        {
            // Check if culture already exists
            CMS.SiteProvider.CultureInfo ci = CultureInfoProvider.GetCultureInfoForCulture(txtCultureCode.Text.Trim());
            if (ci == null)
            {
                // Save culture info
                ci                  = new CMS.SiteProvider.CultureInfo();
                ci.CultureName      = txtCultureName.Text.Trim();
                ci.CultureCode      = txtCultureCode.Text.Trim();
                ci.CultureShortName = txtCultureShortName.Text.Trim();
                ci.CultureAlias     = cultureAlias;
                CultureInfoProvider.SetCultureInfo(ci);

                URLHelper.Redirect("Culture_Edit_Frameset.aspx?cultureID=" + ci.CultureID + "&saved=1");
            }
            else
            {
                ShowError(GetString("Culture_New.CultureExists"));
            }
        }
        else
        {
            ShowError(result);
        }
    }