Beispiel #1
0
 protected void wb_table3_22_012e(bool wbgen)
 {
     if (wbgen)
     {
         context.WriteHtmlText("</td>");
         context.WriteHtmlText("</tr>");
         context.WriteHtmlText("<tr>");
         context.WriteHtmlText("<td colspan=\"2\" >");
         if (!isFullAjaxMode( ))
         {
             /* WebComponent */
             GxWebStd.gx_hidden_field(context, "MPW0034" + "", StringUtil.RTrim(WebComp_Wcrecentlinks_Component));
             context.WriteHtmlText("<div");
             GxWebStd.ClassAttribute(context, "gxwebcomponent");
             context.WriteHtmlText(" id=\"" + "gxHTMLWrpMPW0034" + "" + "\"" + "");
             context.WriteHtmlText(">");
             if (StringUtil.Len(WebComp_Wcrecentlinks_Component) != 0)
             {
                 if (StringUtil.StrCmp(StringUtil.Lower(OldWcrecentlinks), StringUtil.Lower(WebComp_Wcrecentlinks_Component)) != 0)
                 {
                     context.httpAjaxContext.ajax_rspStartCmp("gxHTMLWrpMPW0034" + "");
                 }
                 WebComp_Wcrecentlinks.componentdraw();
                 if (StringUtil.StrCmp(StringUtil.Lower(OldWcrecentlinks), StringUtil.Lower(WebComp_Wcrecentlinks_Component)) != 0)
                 {
                     context.httpAjaxContext.ajax_rspEndCmp();
                 }
             }
             context.WriteHtmlText("</div>");
         }
         context.WriteHtmlText("</td>");
         context.WriteHtmlText("</tr>");
         context.WriteHtmlText("<tr>");
         context.WriteHtmlText("<td style=\"" + CSSHelper.Prettify("height:14px;width:100%") + "\">");
         if (context.isSpaRequest( ))
         {
             enableOutput();
         }
         if (context.isSpaRequest( ))
         {
             disableJsOutput();
         }
         /* Content placeholder */
         context.WriteHtmlText("<div");
         GxWebStd.ClassAttribute(context, "gx-content-placeholder");
         context.WriteHtmlText(">");
         if (!isFullAjaxMode( ))
         {
             getDataAreaObject().RenderHtmlContent();
         }
         context.WriteHtmlText("</div>");
         if (context.isSpaRequest( ))
         {
             disableOutput();
         }
         if (context.isSpaRequest( ))
         {
             enableJsOutput();
         }
         context.WriteHtmlText("</td>");
         context.WriteHtmlText("</tr>");
         context.WriteHtmlText("<tr>");
         context.WriteHtmlText("<td style=\"" + CSSHelper.Prettify("height:15px") + "\">");
         context.WriteHtmlText("</td>");
         context.WriteHtmlText("</tr>");
         context.WriteHtmlText("<tr>");
         context.WriteHtmlText("<td colspan=\"2\" >");
         wb_table4_42_012(true);
     }
     else
     {
         wb_table4_42_012(false);
     }
     return;
 }
    /// <summary>
    /// Initialize design.
    /// </summary>
    private void InitDesign()
    {
        // Register css styles for uploader
        CSSHelper.RegisterCSSBlock(Page, "dfu_" + containerDiv.ClientID, CreateCss(containerDiv.ClientID));

        bool isRTL = IsLiveSite ? CultureHelper.IsPreferredCultureRTL() : CultureHelper.IsUICultureRTL();

        // Prepare loading image
        imgLoading.Style.Add("float", isRTL ? "right" : "left");
        imgLoading.Attributes["title"] = GetString("tree.loading");

        // Loading css class
        lblProgress.CssClass = InnerLoadingElementClass;

        // Ensure nowrap on loading text
        pnlLoading.Style.Add("white-space", "nowrap;");
        pnlLoading.Style.Add("display", "none");

        // Decide between icon or text mode
        uploadIcon.Visible = ShowIconMode;
        btnUpload.Visible  = !ShowIconMode;

        // Disable everything properly
        if (!Enabled)
        {
            btnUpload.Enabled = false;
            uploadIcon.Attributes["class"] += " icon-disabled";
            pnlInnerDiv.CssClass           += " uploader-button-disabled";
        }

        uploaderFrame.Visible     = Enabled;
        mfuDirectUploader.Visible = Enabled;

        // Inner div html and design
        if (!String.IsNullOrEmpty(Text))
        {
            btnUpload.Text = Text;
        }
        if (!String.IsNullOrEmpty(InnerElementClass))
        {
            pnlInnerDiv.CssClass += " " + InnerElementClass;
        }

        // Container div styles
        containerDiv.Style.Add("position", "relative");
        if (DisplayInline)
        {
            containerDiv.Style.Add("float", isRTL ? "right" : "left");
        }

        if (!String.IsNullOrEmpty(ControlGroup))
        {
            containerDiv.Attributes.Add("class", ControlGroup);
        }

        string initScript = ScriptHelper.GetScript(String.Format("if (typeof(DFU) !== 'undefined') {{ DFU.initializeDesign({0}); }}", ScriptHelper.GetString(containerDiv.ClientID)));

        if (ControlsHelper.IsInAsyncPostback(Page))
        {
            ScriptHelper.RegisterStartupScript(this, typeof(string), "DFUInit_" + ClientID, initScript);
        }
        else
        {
            ltlScript.Text = initScript;
        }
    }
Beispiel #3
0
    protected override void OnInit(EventArgs e)
    {
        DocumentManager.OnValidateData += new EventHandler <DocumentManagerEventArgs>(DocumentManager_OnValidateData);
        DocumentManager.OnAfterAction  += new EventHandler <DocumentManagerEventArgs>(DocumentManager_OnAfterAction);

        // Set the region type manually for ASPX mode
        if (QueryHelper.Contains("regiontype"))
        {
            ucEditableText.RegionType = CMSEditableRegionTypeEnumFunctions.GetRegionTypeEnum(QueryHelper.GetString("regiontype", string.Empty));
            if (ucEditableText.RegionType == CMSEditableRegionTypeEnum.HtmlEditor)
            {
                // HtmlEditor needs toolbar location defined (due to toolbar positioning and editing area padding)
                ucEditableText.HtmlAreaToolbarLocation = "Out:CKToolbar";
            }
        }

        ucEditableText.ViewMode        = CheckPermissions();
        ucEditableText.DataControl     = CurrentWebPartInstance as ISimpleDataContainer;
        ucEditableText.CurrentPageInfo = CurrentPageInfo;
        ucEditableText.IsDialogEdit    = true;
        ucEditableText.SetupControl();

        string title = GetString("Content.EditTextTitle");

        if (!String.IsNullOrEmpty(PageTitleSuffix))
        {
            title += " - " + HTMLHelper.HTMLEncode(PageTitleSuffix);
        }
        SetTitle("CMSModules/CMS_PortalEngine/OnSiteEdit/EditText.png", title, null, null);

        base.OnInit(e);

        CSSHelper.RegisterCSSLink(Page, "Design", "OnSiteEdit.css");
        ScriptHelper.RegisterJQuery(this.Page);

        menuElem.ShowSaveAndClose = true;

        if (ucEditableText.RegionType == CMSEditableRegionTypeEnum.TextArea)
        {
            string resizeScript = @"
            var resizeTextAreaTimer;

            // DOM ready
            jQuery(document).ready( function() { ResizeEditableArea(200); });

            // Window resize
            jQuery(window).resize(function () { ResizeEditableArea(100); });

            function ResizeEditableArea(timeout) {
                clearTimeout(resizeTextAreaTimer);
                resizeTextAreaTimer = window.setTimeout(function () {
                    var textarea = jQuery('.EditableTextTextBox');
                    var editableTextContainer = jQuery('.EditableTextContainer');
                    var editableTextEdit = jQuery('.EditableTextEdit');
                    var borderMargin1 = textarea.outerHeight(true) - textarea.height();
                    var borderMargin2 = editableTextEdit.outerHeight(true) - editableTextEdit.height();
                    var borderMargin3 = editableTextContainer.outerHeight(true) - editableTextContainer.height();
                    var height = jQuery('.ModalDialogContent').height() - borderMargin1 - borderMargin2 - borderMargin3;
                    textarea.height(height);
            }, timeout); }";

            ScriptHelper.RegisterClientScriptBlock(this, typeof(Page), "ResizeEditableArea", ScriptHelper.GetScript(resizeScript));
        }

        CurrentDeviceInfo device = CMSContext.CurrentDevice;

        // Resize of HTML area is handled from editor itself
        if ((ucEditableText.RegionType == CMSEditableRegionTypeEnum.HtmlEditor) && !device.IsMobile)
        {
            // Hide editor area before its fully loaded
            pnlEditor.Style.Add("visibility", "hidden");
        }

        if (device.IsMobile)
        {
            // Do not use fixed positioning for mobile devices
            (CurrentMaster.HeaderContainer as CMSPanel).FixedPosition = false;
        }
    }
Beispiel #4
0
    /// <summary>
    /// Handles the Load event of the Page control.
    /// </summary>
    protected void Page_Load(object sender, EventArgs e)
    {
        // Do not process control by default
        StopProcessing = true;

        // Keep frequent objects
        CurrentUserInfo cui = MembershipContext.AuthenticatedUser;
        PageInfo        pi  = DocumentContext.CurrentPageInfo;

        if (pi == null)
        {
            IsPageNotFound = true;
            pi             = DocumentContext.CurrentCultureInvariantPageInfo ?? new PageInfo();
            checkChanges   = string.Empty;
        }

        ucUIToolbar.StopProcessing = true;

        // Get main UI element
        var element = UIElementInfoProvider.GetUIElementInfo(MODULE_NAME, ELEMENT_NAME);

        if (element == null)
        {
            return;
        }

        // Check whether user is authorized to edit page
        if ((pi != null) &&
            AuthenticationHelper.IsAuthenticated() &&
            cui.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Editor, SiteContext.CurrentSiteName) &&
            ((IsPageNotFound && pi.NodeID == 0) || cui.IsAuthorizedPerTreeNode(pi.NodeID, NodePermissionsEnum.Read) == AuthorizationResultEnum.Allowed) &&
            CMSPage.CheckUIElementAccessHierarchical(element, redirectToAccessDenied: false))
        {
            // Enable processing
            StopProcessing = false;

            // Check whether the preferred culture is RTL
            isRTL = CultureHelper.IsUICultureRTL();

            // Add link to CSS file
            CSSHelper.RegisterCSSLink(Page, "Design", "OnSiteEdit.css");
            CSSHelper.RegisterBootstrap(Page);

            // Filter UI element buttons
            ucUIToolbar.OnButtonFiltered += ucUIToolbar_OnButtonFiltered;
            ucUIToolbar.OnButtonCreated  += ucUIToolbar_OnButtonCreated;
            ucUIToolbar.OnGroupsCreated  += ucUIToolbar_OnGroupsCreated;
            ucUIToolbar.IsRTL             = isRTL;

            // Register edit script file
            RegisterEditScripts(pi);

            if (ViewMode.IsEditLive())
            {
                popupHandler.Visible           = true;
                IsLiveSite                     = false;
                MessagesPlaceHolder.IsLiveSite = false;
                MessagesPlaceHolder.Opacity    = 100;

                // Keep content of editable web parts when saving the document changes
                if (!IsPageNotFound)
                {
                    PortalManager.PreserveContent = true;
                }

                // Display warning in the Safe mode
                if (PortalHelper.SafeMode)
                {
                    string safeModeText        = GetString("onsiteedit.safemode") + "<br/><a href=\"" + RequestContext.RawURL.Replace("safemode=1", "safemode=0") + "\">" + GetString("general.close") + "</a> " + GetString("contentedit.safemode2");
                    string safeModeDescription = GetString("onsiteedit.safemode") + "<br/>" + GetString("general.seeeventlog");

                    // Display the warning message
                    ShowWarning(safeModeText, safeModeDescription, "");
                }

                ucUIToolbar.StopProcessing = false;

                // Ensure document redirection
                var redirectUrl = TreePathUtils.GetRedirectionUrl(pi);
                if (!String.IsNullOrEmpty(redirectUrl))
                {
                    redirectUrl = URLHelper.ResolveUrl(redirectUrl);
                    ShowInformation(GetString("onsiteedit.redirectinfo") + " <a href=\"" + redirectUrl + "\">" + redirectUrl + "</a>");
                }

                pnlUpdateProgress.Visible = true;
            }
            // Mode menu on live site
            else if (ViewMode.IsLiveSite())
            {
                // Hide the edit panel, show only slider button
                pnlToolbarSpace.Visible = false;
                pnlToolbar.Visible      = false;
                pnlSlider.Visible       = true;

                icon.CssClass = "cms-icon-80 icon-edit";
                icon.ToolTip  = GetString("onsitedit.editmode");

                lblSliderText.Text = GetString("onsiteedit.editmode");
                pnlButton.Attributes.Add("onclick", "OnSiteEdit_ChangeEditMode();");

                // Hide the OnSite edit button when displayed in CMSDesk
                pnlSlider.Style.Add("display", "none");
            }
        }
        // Hide control actions for unauthorized users
        else
        {
            plcEdit.Visible = false;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        DateTimePicker datePickerObject = PickerControl as DateTimePicker;

        if (datePickerObject == null)
        {
            return;
        }

        // Default settings
        int numberOfRows = 6;
        // Buttons NotAvaible,Done,Now
        bool showActionPanel = true;
        // Display OK button
        bool displayOK = true;
        // Text for N/A button
        string naText = ResHelper.GetString("general.notavailable");
        // Hides if date is selected
        bool hideOnDateSelection = false;
        // Display seconds
        bool displaySeconds = true;
        // Add icon - triggers datepicker show
        string shownOn = "button";

        LoadResources(datePickerObject);

        CultureInfo        culture = new CultureInfo(datePickerObject.CultureCode, true);
        DateTimeFormatInfo info    = culture.DateTimeFormat;

        // Register default css a js files
        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterScriptFile(Page, "~/CMSScripts/JQuery/jquery-ui-datetimepicker.js");
        ScriptHelper.RegisterScriptFile(Page, "~/CMSScripts/modalCalendar.js");
        CSSHelper.RegisterCSSLink(Page, "~/CMSAdminControls/ModalCalendar/Themes/Calendar_core.css");

        string datePattern = info.ShortDatePattern.Replace("yyyy", "yy").Replace("'", "");

        if (datePickerObject.EditTime)
        {
            datePattern += " " + (displaySeconds ? info.LongTimePattern : info.ShortTimePattern);
        }

        bool use24HourMode = !datePattern.Contains("tt");

        // Generate 'now' string with full year
        string format = info.ShortDatePattern;

        if (Regex.Matches(format, "y").Count == 2)
        {
            format = format.Replace("yy", "yyyy");
        }

        string now = CMSContext.DateTimeConvert(DateTime.Now, datePickerObject.TimeZone, datePickerObject.CustomTimeZone).ToString(format, culture);

        // Localized settings
        string todayText = datePickerObject.EditTime ? ResHelper.GetString("calendar.now") : ResHelper.GetString("Calendar.Today");
        string localize  = String.Format("monthNames:{0},monthNamesShort:{1},dayNames:{2},dayNamesMin:{3},firstDay:{4},", ArrayToString(info.MonthNames), ArrayToString(info.AbbreviatedMonthNames), ArrayToString(info.DayNames), ArrayToString(info.ShortestDayNames), ConvertFirstDayToNumber(info.FirstDayOfWeek));

        localize += String.Format("AMDesignator:'{0}',PMDesignator:'{1}',NAText:'{2}',closeText:'{3}',isRTL:{4},prevText:'{5}',nextText:'{6}',defaultDate:'{7}'", info.AMDesignator.Replace("'", "\\'"), info.PMDesignator.Replace("'", "\\'"), naText.Replace("'", "\\'"), ResHelper.GetString("general.ok").Replace("'", "\\'"), culture.TextInfo.IsRightToLeft.ToString().ToLower(), ResHelper.GetString("calendar.previous").Replace("'", "\\'"), ResHelper.GetString("calendar.next").Replace("'", "\\'"), now);

        string minDate = String.Empty;
        string maxDate = String.Empty;

        if (datePickerObject.UseCalendarLimit)
        {
            if (datePickerObject.MinDate != DateTimeHelper.ZERO_TIME)
            {
                minDate = "minDate: " + (datePickerObject.MinDate.Date - DateTime.Now.Date).Days.ToString() + ",";
            }

            if (datePickerObject.MaxDate != DateTimeHelper.ZERO_TIME)
            {
                maxDate = "maxDate: " + (datePickerObject.MaxDate.Date - DateTime.Now.Date).Days.ToString() + ",";
            }
        }

        // Other settings
        String buttons        = "[" + (displayOK ? "'ok'" : "") + "," + (datePickerObject.AllowEmptyValue ? "'na'" : "") + "," + (datePickerObject.DisplayNow ? "'now'" : "") + "]";
        String initParameters = minDate + maxDate + String.Format("numberOfRows:{0},showTimePanel:{1},use24HourMode:{2},showButtonPanel:{3},actionPanelButtons:{4},hideOnDateSelection:{5},displaySeconds:{6},", numberOfRows, datePickerObject.EditTime.ToString().ToLower(), use24HourMode.ToString().ToLower(), showActionPanel.ToString().ToLower(), buttons, hideOnDateSelection.ToString().ToLower(), displaySeconds.ToString().ToLower());

        initParameters += String.Format("IconID:'{0}',showOn:'{1}',dateFormat:'{2}',currentText:'{3}',timeZoneOffset:{4},selectOtherMonths:true,showOtherMonths:true,changeMonth:true,changeYear:true", datePickerObject.CalendarImageClientID, shownOn, datePattern, todayText.Replace("'", "\\'"), datePickerObject.TimeZoneOffset);
        // Init calendar
        string calendarInit = "$j(function() {$j('#" + datePickerObject.DateTimeTextBox.ClientID + "').datepicker({" + localize + "," + initParameters + "})});";

        ScriptHelper.RegisterClientScriptBlock(Page, GetType(), ClientID + "_RegisterDatePickerFunction", ScriptHelper.GetScript(calendarInit));

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "DTPickerModalSelectDate" + datePickerObject.DateTimeTextBox.ClientID, ScriptHelper.GetScript(
                                                   "function SelectModalDate_" + datePickerObject.DateTimeTextBox.ClientID + "(param, pickerId) { " + this.Page.ClientScript.GetCallbackEventReference(datePickerObject, "param", "SetDateModal", "pickerId") + " } \n"));
        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "DTPickerModalSetDate", ScriptHelper.GetScript("function SetDateModal(result, context) {$j('#'+context).datepicker('setDateNoTextBox',result); } \n"));
    }
Beispiel #6
0
    protected override void OnInit(EventArgs e)
    {
        DocumentManager.OnValidateData += DocumentManager_OnValidateData;
        DocumentManager.OnAfterAction  += DocumentManager_OnAfterAction;

        // Process ASPX template parameters
        if (QueryHelper.Contains("regiontype"))
        {
            ucEditableText.RegionType = CMSEditableRegionTypeEnumFunctions.GetRegionTypeEnum(QueryHelper.GetString("regiontype", string.Empty));
            if (ucEditableText.RegionType == CMSEditableRegionTypeEnum.HtmlEditor)
            {
                // HtmlEditor needs toolbar location defined (due to toolbar positioning and editing area padding)
                ucEditableText.HtmlAreaToolbarLocation = "Out:CKToolbar";
            }

            // Min/Max length
            ucEditableText.MaxLength = QueryHelper.GetInteger("maxl", ucEditableText.MaxLength);
            ucEditableText.MinLength = QueryHelper.GetInteger("minl", ucEditableText.MinLength);

            // Editor stylesheet
            ucEditableText.HTMLEditorCssStylesheet = QueryHelper.GetString("editorcss", ucEditableText.HTMLEditorCssStylesheet);

            // Word wrap
            ucEditableText.WordWrap = QueryHelper.GetBoolean("wordwrap", ucEditableText.WordWrap);

            // Upload image dimensions
            ucEditableText.ResizeToHeight      = QueryHelper.GetInteger("resizetoheight", ucEditableText.ResizeToHeight);
            ucEditableText.ResizeToWidth       = QueryHelper.GetInteger("resizetowidth", ucEditableText.ResizeToHeight);
            ucEditableText.ResizeToMaxSideSize = QueryHelper.GetInteger("resizetomaxsidesize", ucEditableText.ResizeToHeight);

            // Toolbar set
            ucEditableText.HtmlAreaToolbar = QueryHelper.GetString("toolbarset", ucEditableText.HtmlAreaToolbar);
        }

        ucEditableText.ViewMode        = CheckPermissions();
        ucEditableText.DataControl     = CurrentWebPartInstance;
        ucEditableText.CurrentPageInfo = CurrentPageInfo;
        ucEditableText.SetupControl();

        CurrentMaster.FooterContainer.Visible = false;
        CurrentMaster.PanelContent.RemoveCssClass("dialog-content");

        string title = GetString("Content.EditTextTitle");

        if (!String.IsNullOrEmpty(PageTitleSuffix))
        {
            title += " - " + HTMLHelper.HTMLEncode(PageTitleSuffix);
        }
        SetTitle(title);

        base.OnInit(e);

        CSSHelper.RegisterCSSLink(Page, "Design", "OnSiteEdit.css");
        ScriptHelper.RegisterJQuery(Page);

        menuElem.ShowSaveAndClose = true;

        String resize = @"function resizeEditor() {$cmsj('.cke_contents').height($cmsj(window).height()-$cmsj('.DialogsPageHeader').height() - $cmsj('.cke_top').height() - $cmsj('.cke_bottom').height() - 20) }
        $cmsj(window).resize(function() {resizeEditor()});";

        ScriptHelper.RegisterClientScriptBlock(this, typeof(Page), "resizeHeight", ScriptHelper.GetScript(resize));

        if (ucEditableText.RegionType == CMSEditableRegionTypeEnum.TextArea)
        {
            const string resizeScript = @"
            var resizeTextAreaTimer;

            // DOM ready
            $cmsj(document).ready( function() { ResizeEditableArea(200); });

            // Window resize
            $cmsj(window).resize(function () { ResizeEditableArea(100); });

            function ResizeEditableArea(timeout) {
                clearTimeout(resizeTextAreaTimer);
                resizeTextAreaTimer = window.setTimeout(function () {
                    var textarea = $cmsj('.EditableTextTextBox');
                    var editableTextContainer = $cmsj('.EditableTextContainer');
                    var editableTextEdit = $cmsj('.EditableTextEdit');
                    var borderMargin1 = textarea.outerHeight(true) - textarea.height();
                    var borderMargin2 = editableTextEdit.outerHeight(true) - editableTextEdit.height();
                    var borderMargin3 = editableTextContainer.outerHeight(true) - editableTextContainer.height();
                    var height = $cmsj('.ModalDialogContent').height() - borderMargin1 - borderMargin2 - borderMargin3;
                    textarea.height(height);
             }, timeout); }";


            ScriptHelper.RegisterClientScriptBlock(this, typeof(Page), "ResizeEditableArea", ScriptHelper.GetScript(resizeScript));
        }

        CurrentDeviceInfo device = DeviceContext.CurrentDevice;

        if (device.IsMobile)
        {
            // Do not use fixed positioning for mobile devices
            (CurrentMaster.HeaderContainer as CMSPanel).FixedPosition = false;
        }
    }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // If there is only one culture on site and hiding is enabled hide webpart
            if (HideIfOneCulture && !CultureInfoProvider.IsSiteMultilignual(CMSContext.CurrentSiteName))
            {
                Visible = false;
                return;
            }

            // 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))))
            {
                // Add CSS Stylesheet
                CSSHelper.RegisterCSSLink(Page, URLHelper.ResolveUrl("~/CMSWebparts/Localization/languageselectiondropdown_files/langselector.css"));

                string imgFlagIcon = String.Empty;

                StringBuilder result = new StringBuilder();
                result.Append("<ul class=\"langselector\">");

                // Set first item to the current language
                CultureInfo ci = CultureInfoProvider.GetCultureInfo(CultureHelper.GetPreferredCulture());
                if (ci != null)
                {
                    // Drop down imitating icon
                    string dropIcon = ResolveUrl("~/CMSWebparts/Localization/languageselectiondropdown_files/dd_arrow.gif");

                    // Current language
                    imgFlagIcon = GetImageUrl("Flags/16x16/" + HTMLHelper.HTMLEncode(ci.CultureCode) + ".png");

                    string currentCultureShortName = String.Empty;
                    if (ShowCultureNames)
                    {
                        currentCultureShortName = HTMLHelper.HTMLEncode(ci.CultureShortName);
                    }

                    result.AppendFormat("<li class=\"lifirst\" style=\"background-image:url('{0}'); background-repeat: no-repeat\"><a class=\"first\" style=\"background-image:url({1}); background-repeat: no-repeat\" href=\"{2}\">{3}</a>",
                                        dropIcon, imgFlagIcon, "#", currentCultureShortName);
                }

                result.Append("<ul>");

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

                    // Language icon
                    imgFlagIcon = GetImageUrl("Flags/16x16/" + HTMLHelper.HTMLEncode(code) + ".png");
                    if (!ShowCultureNames)
                    {
                        name = string.Empty;
                    }

                    result.AppendFormat("<li><a style=\"background-image:url({0}); background-repeat: no-repeat\" href=\"{1}\">{2}</a></li>\r\n",
                                        imgFlagIcon, HTMLHelper.HTMLEncode(URLHelper.ResolveUrl(url)), name);
                }

                result.Append("</ul></li></ul>");
                ltlLanguages.Text = result.ToString();
            }
            else if (HideIfOneCulture)
            {
                Visible = false;
            }
        }
    }
    protected override void OnPreRender(EventArgs e)
    {
        bool errorOccurred = !string.IsNullOrEmpty(lblError.Text);

        if (StopProcessing)
        {
            Visible = false;
        }
        else
        {
            // AllowSave property needs to be accessed to initialize the security properties in context of updated document instance - CM-815
            bool initSecurity = propertiesElem.AllowSave;

            // Render the styles link if live site mode
            if (PortalContext.ViewMode.IsLiveSite())
            {
                CSSHelper.RegisterDesignMode(Page);
            }

            pnlUpdate.Visible = !errorOccurred;

            btnLocalizeSaveClose.Visible = localizeElem.Visible && localizeElem.AllowSave;

            // Ensure correct dialog buttons
            if ((CurrentModal != null) && (((CurrentModal == mdlProperties) && (propertiesElem.Node != null)) || ((CurrentModal == mdlLocalize) && (localizeElem.Node != null))))
            {
                bool properties = (CurrentModal == mdlProperties);

                // Get workflow information
                WorkflowInfo wi = DocumentManager.Workflow;
                if (wi != null)
                {
                    if (!wi.WorkflowAutoPublishChanges)
                    {
                        if (!properties)
                        {
                            btnLocalizeSaveClose.Visible = false;
                        }
                    }
                }
            }
        }

        // Set up the captions
        btnClose1.ResourceString = btnLocalizeSaveClose.Visible ? "general.cancel" : "general.close";
        btnClose2.ResourceString = "general.close";

        if (Visible && pnlUpdate.Visible)
        {
            if (RequestHelper.IsPostBack() && (CurrentModal != null))
            {
                // Show popup after postback
                CurrentModal.Show();
            }
        }

        lblError.Visible = errorOccurred && (PortalContext.IsDesignMode(PortalContext.ViewMode));

        // Set viewstate
        pnlLocalizePopup.EnableViewState    = (CurrentDialog == pnlLocalizePopup);
        pnlCopyPopup.EnableViewState        = (CurrentDialog == pnlCopyPopup);
        pnlDeletePopup.EnableViewState      = (CurrentDialog == pnlDeletePopup);
        pnlPermissionsPopup.EnableViewState = (CurrentDialog == pnlPermissionsPopup);
        pnlVersionsPopup.EnableViewState    = (CurrentDialog == pnlVersionsPopup);
        pnlPropertiesPopup.EnableViewState  = (CurrentDialog == pnlPropertiesPopup);
    }
    /// <summary>
    /// Prepares the layout of the web part.
    /// </summary>
    protected override void PrepareLayout()
    {
        StartLayout();

        if (IsDesign)
        {
            Append("<table class=\"LayoutTable\" cellspacing=\"0\" style=\"width: 100%;\">");

            if (ViewModeIsDesign())
            {
                Append("<tr><td class=\"LayoutHeader\">");

                // Add header container
                AddHeaderContainer();

                Append("</td></tr>");
            }

            Append("<tr><td>");
        }

        // Content before zones
        Append(BeforeZones);

        string separator = Separator;
        string before    = BeforeZone;
        string after     = AfterZone;

        string zoneclass = ZoneCSSClass;
        string zonewidth = ZoneWidth;

        // Render the zones
        for (int i = 1; i <= Zones; i++)
        {
            if (i > 1)
            {
                Append(separator);
            }
            Append("<div");

            // Zone class
            if (!String.IsNullOrEmpty(zoneclass))
            {
                Append(" class=\"", zoneclass, "\"");
            }

            // Zone width
            if (!String.IsNullOrEmpty(zonewidth))
            {
                Append(" style=\"width: ", zonewidth, "\";");
            }

            Append(">", before);

            // Add the zone
            CMSWebPartZone zone = AddZone(ID + "_" + i, "[" + i + "]");

            Append(after, "</div>");
        }

        // Content after zones
        Append(AfterZones);

        if (IsDesign)
        {
            Append("</td></tr>");

            // Footer
            if (AllowDesignMode)
            {
                Append("<tr><td class=\"LayoutFooter cms-bootstrap\" colspan=\"2\"><div class=\"LayoutFooterContent\">");

                // Zone actions
                AppendRemoveAction(ResHelper.GetString("Layout.RemoveZone"), "Zones");
                Append("&nbsp;&nbsp;");
                AppendAddAction(ResHelper.GetString("Layout.AddZone"), "Zones");

                Append("</div></td></tr>");
            }

            Append("</table>");
        }

        // Register jQuery
        if (IncludeJQuery)
        {
            ScriptHelper.RegisterJQuery(Page);
        }

        // Register scripts
        string[] scripts = ScriptFiles.Split('\r', '\n');
        foreach (string script in scripts)
        {
            // Register the script file
            string sfile = script.Trim();
            if (!String.IsNullOrEmpty(sfile))
            {
                ScriptHelper.RegisterScriptFile(Page, sfile);
            }
        }

        // Add init script
        string resolvedInitScript = MacroResolver.Resolve(InitScript);

        if (!string.IsNullOrEmpty(resolvedInitScript))
        {
            ScriptHelper.RegisterStartupScript(this, typeof(string), ShortClientID + "_Init", ScriptHelper.GetScript(resolvedInitScript));
        }

        // Register CSS files
        string[] cssFiles = CSSFiles.Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
        Array.ForEach(cssFiles, cssFile => CSSHelper.RegisterCSSLink(Page, cssFile.Trim()));

        // Add inline CSS
        string inlinecss = MacroResolver.Resolve(InlineCSS);

        if (!string.IsNullOrEmpty(inlinecss))
        {
            // Add css to page header
            CSSHelper.RegisterCSSBlock(Page, "zonesWithEffectInlineCss_" + ClientID, inlinecss);
        }

        FinishLayout();
    }
Beispiel #10
0
    /// <summary>
    /// Prepares the layout of the web part.
    /// </summary>
    protected override void PrepareLayout()
    {
        StartLayout();

        string height = ValidationHelper.GetString(GetValue("Height"), "");

        // Prepare the data for equal heights script
        bool equal = EqualHeight;

        string groupClass = null;

        if (equal)
        {
            groupClass = "Cols_" + InstanceGUID.ToString().Replace("-", "");
        }

        if (IsDesign)
        {
            Append("<table class=\"LayoutTable\" cellspacing=\"0\" style=\"width: 100%;\">");

            if (ViewMode == ViewModeEnum.Design)
            {
                Append("<tr><td class=\"LayoutHeader\">");

                // Add header container
                AddHeaderContainer();

                Append("</td></tr>");
            }

            Append("<tr><td>");
        }

        // Prepare automatic width
        string autoWidth = null;
        int    cols      = LeftColumns + RightColumns;

        if (CenterColumn)
        {
            cols++;
        }
        if (cols > 0)
        {
            autoWidth = ((100 - cols) / cols) + "%";
        }

        // Encapsulating div
        if (IsDesign && AllowDesignMode)
        {
            Append("<div id=\"", ShortClientID, "_all\">");
        }
        else
        {
            Append("<div>");
        }

        // Left columns
        CreateColumns(LeftColumns, height, equal, groupClass, autoWidth, false);

        // Right columns
        CreateColumns(RightColumns, height, equal, groupClass, autoWidth, true);

        // Center column
        if (CenterColumn)
        {
            if (IsDesign && AllowDesignMode)
            {
                Append("<div style=\"overflow: auto;\" class=\"LayoutCenterColumn\">");
            }

            Append("<div");

            // Cell class
            string thisColumnClass = ValidationHelper.GetString(GetValue("CenterColumnCSSClass"), "");
            if (equal)
            {
                thisColumnClass = CSSHelper.JoinClasses(thisColumnClass, groupClass);
            }

            if (!String.IsNullOrEmpty(thisColumnClass))
            {
                Append(" class=\"");
                Append(thisColumnClass);
                Append("\"");
            }

            string style = "overflow: auto;";

            // Height
            if (!equal)
            {
                height = DataHelper.GetNotEmpty(GetValue("CenterColumnHeight"), height);
            }
            if (!String.IsNullOrEmpty(height))
            {
                style += " height: " + height + ";";
            }

            // Append style
            if (!String.IsNullOrEmpty(style))
            {
                Append(" style=\"");
                Append(style);
                Append("\"");
            }

            if (IsDesign)
            {
                Append(" id=\"", ShortClientID, "_col_c\"");
            }

            Append(">");

            // Add the zone
            AddZone(ID + "_center", "Center");

            Append("</div>");

            if (IsDesign)
            {
                // Vertical resizer for center column
                if (AllowDesignMode && !equal)
                {
                    Append("<div class=\"VerticalResizer\" onmousedown=\"" + GetVerticalResizerScript("col_c", "CenterColumnHeight") + " return false;\">&nbsp;</div>");
                }

                Append("</div>");
            }
        }

        // End of encapsulating div
        Append("<div style=\"clear: both;\"></div></div>");

        if (IsDesign)
        {
            Append("</td></tr>");

            // Footer with actions
            if (AllowDesignMode)
            {
                // Vertical resizer for all columns
                if (equal)
                {
                    Append("<tr><td class=\"VerticalResizer\" onmousedown=\"" + GetVerticalResizerScript("all", "Height", null, "SetAllHeight_" + groupClass) + " return false;\">&nbsp;</td></tr>");
                }

                Append("<tr><td class=\"LayoutFooter\"><div class=\"LayoutFooterContent\">");

                // Pane actions
                Append("<div class=\"LayoutLeftActions\">");
                if (LeftColumns > 0)
                {
                    AppendRemoveAction(ResHelper.GetString("Layout.RemoveLeftColumn"), "LeftColumns");
                    Append(" ");
                }
                AppendAddAction(ResHelper.GetString("Layout.AddLeftColumn"), "LeftColumns");
                Append("</div>");

                Append("<div class=\"LayoutRightActions\">");
                if (RightColumns > 0)
                {
                    AppendRemoveAction(ResHelper.GetString("Layout.RemoveRightColumn"), "RightColumns");
                    Append(" ");
                }
                AppendAddAction(ResHelper.GetString("Layout.AddRightColumn"), "RightColumns");
                Append("</div>");

                Append("</div></td></tr>");
            }

            Append("</table>");
        }

        FinishLayout();

        // Enforce equal height with a javascript
        if (equal)
        {
            PortalHelper.RegisterLayoutsScript(this.Page);
            ScriptHelper.RegisterScriptFile(Page, "jquery/jquery-equalheight.js");

            StringBuilder sb = new StringBuilder();

            sb.Append(
                @"
function SetAllHeight_", groupClass, @"(h) {
    SetAllHeight('", groupClass, @"', h);
}

InitEqualHeight('", groupClass, @"');
"
                );

            ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "EqualHeight_" + groupClass, ScriptHelper.GetScript(sb.ToString()));
        }
    }
Beispiel #11
0
    /// <summary>
    /// Creates the columns in the layout.
    /// </summary>
    /// <param name="cols">Number of columns</param>
    /// <param name="height">Height</param>
    /// <param name="equal">If true, the column heights should equal</param>
    /// <param name="groupClass">Group class</param>
    /// <param name="autoWidth">Automatic width</param>
    /// <param name="right">Right columns</param>
    protected void CreateColumns(int cols, string height, bool equal, string groupClass, string autoWidth, bool right)
    {
        for (int i = 1; i <= cols; i++)
        {
            string colMark = (right ? "r" : "l");

            // Set the width property
            string widthPropertyName  = colMark + "Column" + i + "Width";
            string heightPropertyName = colMark + "Column" + i + "Height";

            // Do not use automatic width in case of design mode
            if (IsDesign)
            {
                autoWidth = "";
            }

            string width = DataHelper.GetNotEmpty(GetValue(widthPropertyName), autoWidth);
            if (!equal)
            {
                height = DataHelper.GetNotEmpty(GetValue(heightPropertyName), height);
            }

            Append("<div");

            string colId = "col" + colMark + i;

            // Add alignment
            string fl = null;
            if (right)
            {
                fl = "float: right;";
            }
            else
            {
                fl = "float: left;";
            }

            string style = fl;

            if (IsDesign)
            {
                // Append style
                if (!String.IsNullOrEmpty(style))
                {
                    Append(" style=\"", style, "\"");
                }

                // Design mode classes
                if (AllowDesignMode)
                {
                    Append(" class=\"", (right ? "LayoutRightColumn" : "LayoutLeftColumn"), "\"");
                }

                Append("><table cellspacing=\"0\" cellpadding=\"0\" border=\"0\"><tr>");

                if (right)
                {
                    // Width resizer
                    if (AllowDesignMode)
                    {
                        Append("<td class=\"HorizontalResizer\" onmousedown=\"", GetHorizontalResizerScript(colId, widthPropertyName, true, null, null), " return false;\">&nbsp;</td>");
                    }
                }

                Append("<td style=\"vertical-align: top;\">");

                Append("<div");

                style = null;
            }

            // Column width
            if (!String.IsNullOrEmpty(width))
            {
                style += "width: " + width + ";";
            }

            // Height
            if (!String.IsNullOrEmpty(height))
            {
                style += "height: " + height + ";";
            }

            // Append style
            if (!String.IsNullOrEmpty(style))
            {
                Append(" style=\"", style, "\"");
            }

            // Cell class
            string thisColumnClass = ValidationHelper.GetString(GetValue(colMark + "Column" + i + "CSSClass"), "");
            if (equal)
            {
                thisColumnClass = CSSHelper.JoinClasses(thisColumnClass, groupClass);
            }

            if (!String.IsNullOrEmpty(thisColumnClass))
            {
                Append(" class=\"", thisColumnClass, "\"");
            }

            if (IsDesign)
            {
                Append(" id=\"", ShortClientID, "_", colId, "\"");
            }

            Append(">");

            // Add the zone
            AddZone(ID + "_" + colMark + i, "[" + colMark.ToUpperCSafe() + i + "]");

            Append("</div>");

            if (IsDesign)
            {
                // Right column
                Append("</td>");

                if (AllowDesignMode)
                {
                    if (right)
                    {
                        // Resizers
                        if (!equal)
                        {
                            Append("</tr><tr>");

                            Append("<td class=\"BothResizer\" onmousedown=\"", GetBothResizerScript(colId, widthPropertyName, heightPropertyName, true, null), " return false;\">&nbsp;</td>");
                            Append("<td class=\"VerticalResizer\" onmousedown=\"", GetVerticalResizerScript(colId, heightPropertyName), " return false;\">&nbsp;</td>");
                        }
                    }
                    else
                    {
                        // Resizers
                        Append("<td class=\"HorizontalResizer\" onmousedown=\"");
                        Append(GetHorizontalResizerScript(colId, widthPropertyName, false, null, null));
                        Append(" return false;\">&nbsp;</td>");

                        if (!equal)
                        {
                            Append("</tr><tr>");

                            Append("<td class=\"VerticalResizer\" onmousedown=\"", GetVerticalResizerScript(colId, heightPropertyName), " return false;\">&nbsp;</td>");
                            Append("<td class=\"BothResizer\" onmousedown=\"", GetBothResizerScript(colId, widthPropertyName, heightPropertyName), " return false;\">&nbsp;</td>");
                        }
                    }
                }

                Append("</tr></table>");

                Append("</div>");
            }
        }
    }
Beispiel #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Security test
        if (!CMSContext.CurrentUser.UserSiteManagerAdmin)
        {
            RedirectToAccessDenied(GetString("attach.actiondenied"));
        }

        // Add link to external stylesheet
        CSSHelper.RegisterCSSLink(this, "~/App_Themes/Default/CMSDesk.css");

        // Get current resolver
        resolver = CMSContext.CurrentResolver.CreateContextChild();

        DataSet ds  = null;
        DataSet cds = null;

        // Check init settings
        bool allWidgets  = QueryHelper.GetBoolean("allWidgets", false);
        bool allWebParts = QueryHelper.GetBoolean("allWebparts", false);

        // Get webpart (widget) from querystring - only if no allwidget or allwebparts set
        bool   isWebpartInQuery  = false;
        bool   isWidgetInQuery   = false;
        String webpartQueryParam = String.Empty;

        //If not show all widgets or webparts - check if any widget or webpart is present
        if ((!allWidgets) && (!allWebParts))
        {
            webpartQueryParam = QueryHelper.GetString("webpart", "");
            if (!string.IsNullOrEmpty(webpartQueryParam))
            {
                isWebpartInQuery = true;
            }
            else
            {
                webpartQueryParam = QueryHelper.GetString("widget", "");
                if (!string.IsNullOrEmpty(webpartQueryParam))
                {
                    isWidgetInQuery = true;
                }
            }
        }

        // Set development option if is required
        if (QueryHelper.GetString("details", "0") == "1")
        {
            development = true;
        }

        // Generate all webparts
        if (allWebParts)
        {
            // Get all webpart categories
            cds = WebPartCategoryInfoProvider.GetAllCategories();
        }
        // Generate all widgets
        else if (allWidgets)
        {
            // Get all widget categories
            cds = WidgetCategoryInfoProvider.GetWidgetCategories(String.Empty, String.Empty, 0, String.Empty);
        }
        // Generate single webpart
        else if (isWebpartInQuery)
        {
            // Split weparts
            string[] webparts = webpartQueryParam.Split(';');
            if (webparts.Length > 0)
            {
                string webpartWhere = SqlHelperClass.GetWhereCondition("WebpartName", webparts);
                ds = WebPartInfoProvider.GetWebParts(webpartWhere, null);

                // If any webparts found
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    StringBuilder categoryWhere = new StringBuilder("");
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        categoryWhere.Append(ValidationHelper.GetString(dr["WebpartCategoryID"], "NULL") + ",");
                    }

                    string ctWhere = "CategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")";
                    cds = WebPartCategoryInfoProvider.GetCategories(ctWhere, null);
                }
            }
        }
        // Generate single widget
        else if (isWidgetInQuery)
        {
            string[] widgets = webpartQueryParam.Split(';');
            if (widgets.Length > 0)
            {
                string widgetsWhere = SqlHelperClass.GetWhereCondition("WidgetName", widgets);
                ds = WidgetInfoProvider.GetWidgets(widgetsWhere, null, 0, String.Empty);
            }

            if (!DataHelper.DataSourceIsEmpty(ds))
            {
                StringBuilder categoryWhere = new StringBuilder("");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    categoryWhere.Append(ValidationHelper.GetString(dr["WidgetCategoryID"], "NULL") + ",");
                }

                string ctWhere = "WidgetCategoryID IN (" + categoryWhere.ToString().TrimEnd(',') + ")";
                cds = WidgetCategoryInfoProvider.GetWidgetCategories(ctWhere, null, 0, String.Empty);
            }
        }

        if (allWidgets || isWidgetInQuery)
        {
            documentationTitle = "Kentico CMS Widgets";
            Page.Header.Title  = "Widgets documentation";
        }

        if (!allWebParts && !allWidgets && !isWebpartInQuery && !isWidgetInQuery)
        {
            pnlContent.Visible = false;
            pnlInfo.Visible    = true;
        }

        // Check whether at least one category is present
        if (!DataHelper.DataSourceIsEmpty(cds))
        {
            string namePrefix = ((isWidgetInQuery) || (allWidgets)) ? "Widget" : String.Empty;

            // Loop through all web part categories
            foreach (DataRow cdr in cds.Tables[0].Rows)
            {
                // Get all webpart in the categories
                if (allWebParts)
                {
                    ds = WebPartInfoProvider.GetAllWebParts(Convert.ToInt32(cdr["CategoryId"]));
                }
                // Get all widgets in the category
                else if (allWidgets)
                {
                    int categoryID = Convert.ToInt32(cdr["WidgetCategoryId"]);
                    ds = WidgetInfoProvider.GetWidgets("WidgetCategoryID = " + categoryID.ToString(), null, 0, null);
                }

                // Check whether current category contains at least one webpart
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    // Generate category name code
                    menu += "<br /><strong>" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + "</strong><br /><br />";

                    // Loop through all web web parts in categories
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        // Init
                        isImagePresent         = false;
                        undocumentedProperties = 0;
                        documentation          = 0;

                        // Webpart (Widget) information
                        string itemDisplayName   = String.Empty;
                        string itemDescription   = String.Empty;
                        string itemDocumentation = String.Empty;
                        string itemType          = String.Empty;
                        int    itemID            = 0;

                        WebPartInfo wpi = null;
                        WidgetInfo  wi  = null;

                        // Set webpart info
                        if ((isWebpartInQuery) || (allWebParts))
                        {
                            wpi = new WebPartInfo(dr);
                            if (wpi != null)
                            {
                                itemDisplayName   = wpi.WebPartDisplayName;
                                itemDescription   = wpi.WebPartDescription;
                                itemDocumentation = wpi.WebPartDocumentation;
                                itemID            = wpi.WebPartID;
                                itemType          = PortalObjectType.WEBPART;

                                if (wpi.WebPartCategoryID != ValidationHelper.GetInteger(cdr["CategoryId"], 0))
                                {
                                    wpi = null;
                                }
                            }
                        }
                        // Set widget info
                        else if ((isWidgetInQuery) || (allWidgets))
                        {
                            wi = new WidgetInfo(dr);
                            if (wi != null)
                            {
                                itemDisplayName   = wi.WidgetDisplayName;
                                itemDescription   = wi.WidgetDescription;
                                itemDocumentation = wi.WidgetDocumentation;
                                itemType          = PortalObjectType.WIDGET;
                                itemID            = wi.WidgetID;

                                if (wi.WidgetCategoryID != ValidationHelper.GetInteger(cdr["WidgetCategoryId"], 0))
                                {
                                    wi = null;
                                }
                            }
                        }

                        // Check whether web part (widget) exists
                        if ((wpi != null) || (wi != null))
                        {
                            // Link GUID
                            Guid mguid = Guid.NewGuid();

                            // Whether description is present in webpart
                            bool isDescription = false;

                            // Image url
                            string wimgurl = GetItemImage(itemID, itemType);

                            // Set description text
                            string descriptionText = itemDescription;

                            // Parent webpart info
                            WebPartInfo pwpi = null;

                            // If webpart look for parent's description and documentation
                            if (wpi != null)
                            {
                                // Get parent description if webpart is inherited
                                if (wpi.WebPartParentID > 0)
                                {
                                    pwpi = WebPartInfoProvider.GetWebPartInfo(wpi.WebPartParentID);
                                    if (pwpi != null)
                                    {
                                        if ((descriptionText == null || descriptionText.Trim() == ""))
                                        {
                                            // Set description from parent
                                            descriptionText = pwpi.WebPartDescription;
                                        }

                                        // Set documentation text from parent if WebPart is inherited
                                        if ((wpi.WebPartDocumentation == null) || (wpi.WebPartDocumentation.Trim() == ""))
                                        {
                                            itemDocumentation = pwpi.WebPartDocumentation;
                                            if (!String.IsNullOrEmpty(itemDocumentation))
                                            {
                                                documentation = 2;
                                            }
                                        }
                                    }
                                }
                            }

                            // Set description as present
                            if (descriptionText.Trim().Length > 0)
                            {
                                isDescription = true;
                            }

                            // Generate HTML for menu and content
                            menu += "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<a href=\"#_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(itemDisplayName) + "</a>&nbsp;";

                            // Generate webpart header
                            content += "<table style=\"width:100%;\"><tr><td><h1><a name=\"_" + mguid.ToString() + "\">" + HTMLHelper.HTMLEncode(cdr[namePrefix + "CategoryDisplayName"].ToString()) + "&nbsp;>&nbsp;" + HTMLHelper.HTMLEncode(itemDisplayName) + "</a></h1></td><td style=\"text-align:right;\">&nbsp;<a href=\"#top\" class=\"noprint\">top</a></td></tr></table>";

                            // Generate WebPart content
                            content +=
                                @"<table style=""width: 100%; height: 200px; border: solid 1px #DDDDDD;"">
                                   <tr> 
                                     <td style=""width: 50%; text-align:center; border-right: solid 1px #DDDDDD; vertical-align: middle;margin-left: auto; margin-right:auto; text-align:center;"">
                                         <img src=""" + wimgurl + @""" alt=""imageTeaser"">
                                     </td>
                                     <td style=""width: 50%; vertical-align: center;text-align:center;"">"
                                + HTMLHelper.HTMLEncode(descriptionText) + @"
                                     </td>
                                   </tr>
                                </table>";

                            // Properties content
                            content += "<div class=\"DocumentationWebPartsProperties\">";

                            // Generate content
                            if (wpi != null)
                            {
                                GenerateDocContent(CreateFormInfo(wpi));
                            }
                            else if (wi != null)
                            {
                                GenerateDocContent(CreateFormInfo(wi));
                            }

                            // Close content area
                            content += "</div>";

                            // Generate documentation text content
                            content += "<br /><div style=\"border: solid 1px #dddddd;width: 100%;\">" +
                                       DataHelper.GetNotEmpty(HTMLHelper.ResolveUrls(itemDocumentation, null), "<strong>Additional documentation text is not provided.</strong>") +
                                       "</div>";

                            // Set page break tag for print
                            content += "<br /><p style=\"page-break-after: always;width:100%\">&nbsp;</p><hr class=\"noprint\" />";

                            // If development is required - highlight missing description, images and doc. text
                            if (development)
                            {
                                // Check image
                                if (!isImagePresent)
                                {
                                    menu += "<span style=\"color:Brown;\">image&nbsp;</span>";
                                }

                                // Check properties
                                if (undocumentedProperties > 0)
                                {
                                    menu += "<span style=\"color:Red;\">properties(" + undocumentedProperties + ")&nbsp;</span>";
                                }

                                // Check properties
                                if (!isDescription)
                                {
                                    menu += "<span style=\"color:#37627F;\">description&nbsp;</span>";
                                }

                                // Check documentation text
                                if (String.IsNullOrEmpty(itemDocumentation))
                                {
                                    documentation = 1;
                                }

                                switch (documentation)
                                {
                                // Display information about missing documentation
                                case 1:
                                    menu += "<span style=\"color:Green;\">documentation&nbsp;</span>";
                                    break;

                                // Display information about inherited documentation
                                case 2:
                                    menu += "<span style=\"color:Green;\">documentation (inherited)&nbsp;</span>";
                                    break;
                                }
                            }

                            menu += "<br />";
                        }
                    }
                }
            }
        }

        ltlContent.Text = menu + "<br /><p style=\"page-break-after: always;width:100%\">&nbsp;</p><hr class=\"noprint\" />" + content;
    }
Beispiel #13
0
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (this.Behavior == "hover")
        {
            StringBuilder sb = new StringBuilder();
            // If jQuery not loaded
            sb.AppendFormat(@"
if (typeof jQuery == 'undefined') {{ 
    var jQueryCore=document.createElement('script');
    jQueryCore.setAttribute('type','text/javascript'); 
    jQueryCore.setAttribute('src', '{0}');
    setTimeout('document.body.appendChild(jQueryCore)',100); 
    setTimeout('loadTooltip()',200);
}}", ScriptHelper.GetScriptUrl("~/CMSScripts/jquery/jquery-core.js"));

            // If jQuery tooltip plugin not loaded
            sb.AppendFormat(@"
var jQueryTooltips=document.createElement('script'); 
function loadTooltip() {{ 
    if (typeof jQuery == 'undefined') {{ setTimeout('loadTooltip()',200); return;}} 
    if (typeof jQuery.fn.tooltip == 'undefined') {{ 
        jQueryTooltips.setAttribute('type','text/javascript'); 
        jQueryTooltips.setAttribute('src', '{0}'); 
        setTimeout('document.body.appendChild(jQueryTooltips)',100); 
    }}
}}", ScriptHelper.GetScriptUrl("~/CMSScripts/jquery/jquery-tooltips.js"));


            string rtlDefinition = null;
            if (((this.IsLiveSite) && (CultureHelper.IsPreferredCultureRTL())) || (CultureHelper.IsUICultureRTL()))
            {
                rtlDefinition = "positionLeft: true,left: -15,";
            }

            sb.AppendFormat(@"
function hover(imgID, width, height, sizeInUrl) {{ 
    if ((typeof jQuery == 'undefined')||(typeof jQuery.fn.tooltip == 'undefined')) {{
        var imgIDForTimeOut = imgID.replace(/\\/gi,""\\\\"").replace(/'/gi,""\\'"");
        setTimeout(""loadTooltip();hover('""+imgIDForTimeOut+""',""+width+"",""+height+"",""+sizeInUrl+"")"",100); return;
    }}
    jQuery('img[id='+imgID+']').tooltip({{
        delay: 0,
        track: true,
        showBody: "" - "",
        showBody: "" - "", 
        extraClass: ""ImageExtraClass"",
        showURL: false, 
        {0}
        bodyHandler: function() {{
            var hidden = jQuery(""#"" + imgID + ""_src"");
            var source = this.src;
            if (hidden[0] != null) {{
                source = hidden[0].value;
            }}
            var hoverDiv = jQuery(""<div/>"");
            var hoverImg = jQuery(""<img/>"").attr(""class"", ""ImageTooltip"").attr(""src"", source);
            hoverImg.css({{'width' : width, 'height' : height}});
            hoverDiv.append(hoverImg);
            return hoverDiv;
        }}
    }});
}}", rtlDefinition);

            ScriptHelper.RegisterStartupScript(this.Page, typeof(Page), "JQueryImagePreview", ScriptHelper.GetScript(sb.ToString()));
        }

        ImageParameters imgParams = new ImageParameters();

        if (!String.IsNullOrEmpty(this.URL))
        {
            imgParams.Url = ResolveUrl(this.URL);
        }
        imgParams.Align           = this.Align;
        imgParams.Alt             = this.Alt;
        imgParams.Behavior        = this.Behavior;
        imgParams.BorderColor     = this.BorderColor;
        imgParams.BorderWidth     = this.BorderWidth;
        imgParams.Class           = this.Class;
        imgParams.Extension       = this.Extension;
        imgParams.Height          = this.Height;
        imgParams.HSpace          = this.HSpace;
        imgParams.Id              = (String.IsNullOrEmpty(this.ImageID) ? Guid.NewGuid().ToString() : this.ImageID);
        imgParams.Link            = this.Link;
        imgParams.MouseOverHeight = this.MouseOverHeight;
        imgParams.MouseOverWidth  = this.MouseOverWidth;
        imgParams.SizeToURL       = this.SizeToURL;
        imgParams.Style           = this.Style;
        imgParams.Target          = this.Target;
        imgParams.Tooltip         = this.Tooltip;
        imgParams.VSpace          = this.VSpace;
        imgParams.Width           = this.Width;

        if (this.ShowFileIcons && (this.Extension != null))
        {
            imgParams.Width  = 0;
            imgParams.Height = 0;
            imgParams.Url    = GetFileIconUrl(this.Extension, "List");
        }

        this.ltlImage.Text = MediaHelper.GetImage(imgParams);

        // Dynamic JQuery hover effect
        if (this.Behavior == "hover")
        {
            string imgId = HTMLHelper.HTMLEncode(HttpUtility.UrlDecode(imgParams.Id));
            string url   = HttpUtility.HtmlDecode(this.URL);
            if (this.SizeToURL)
            {
                if (MouseOverWidth > 0)
                {
                    url = URLHelper.UpdateParameterInUrl(url, "width", this.MouseOverWidth.ToString());
                }
                if (MouseOverHeight > 0)
                {
                    url = URLHelper.UpdateParameterInUrl(url, "height", this.MouseOverHeight.ToString());
                }
                url = URLHelper.RemoveParameterFromUrl(url, "maxsidesize");
            }
            this.ltlImage.Text += "<input type=\"hidden\" id=\"" + imgId + "_src\" value=\"" + ResolveUrl(url) + "\" />";

            ScriptHelper.RegisterStartupScript(this.Page, typeof(Page), "ImageHover_" + imgId, ScriptHelper.GetScript("hover(" + ScriptHelper.GetString(ScriptHelper.EscapeJQueryCharacters(imgId)) + ", " + MouseOverWidth + ", " + MouseOverHeight + ", " + (SizeToURL ? "true" : "false") + ");"));
            if (!RequestStockHelper.Contains("DialogsImageHoverStyle"))
            {
                RequestStockHelper.Add("DialogsImageHoverStyle", true);
                CSSHelper.RegisterCSSBlock(this.Page, "#tooltip {position: absolute;z-index:5000;}");
            }
        }
    }
Beispiel #14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterModule(Page, "CMS.Content/LanguageMenu", new { selector = "#language-menu" });

        CSSHelper.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             = CultureInfoProvider.GetCultureInfo(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
            if (DisplayCompare)
            {
                btnCompare.ToolTip = GetString("SplitMode.CompareLangVersions");
                btnCompare.Text    = GetString("SplitMode.Compare");
                if (UIContext.DisplaySplitMode)
                {
                    btnCompare.AddCssClass("active");
                }
                else
                {
                    btnCompare.RemoveCssClass("active");
                }
            }
        }
        else
        {
            // Hide language menu for one assigned culture on site
            Visible = false;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Set control properties
        editor.AutoDetectLanguage = false;
        editor.DefaultLanguage    = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;

        string toolbarSet = editor.ToolbarSet;

        if (Form != null)
        {
            editor.DialogParameters = Form.DialogParameters;
        }

        // Get editor area toolbar
        toolbarSet             = DataHelper.GetNotEmpty(GetValue("toolbarset"), (Form != null) ? Form.HtmlAreaToolbar : "");
        editor.ToolbarSet      = toolbarSet;
        editor.ToolbarLocation = DataHelper.GetNotEmpty(GetValue("toolbarlocation"), (Form != null) ? Form.HtmlAreaToolbarLocation : "");

        // Set form dimensions
        UnitType widthUnitType  = GetUnitType(GetValue("widthunittype"));
        UnitType heightUnitType = GetUnitType(GetValue("heightunittype"));

        editor.Width  = new Unit(ValidationHelper.GetInteger(GetValue("width"), 700), widthUnitType);
        editor.Height = new Unit(ValidationHelper.GetInteger(GetValue("height"), 300), heightUnitType);

        // Get editor area starting path
        String startingPath = ValidationHelper.GetString(GetValue("startingpath"), "");

        editor.StartingPath = startingPath;

        // Set current context resolver
        editor.ResolverName = ResolverName;

        // Get editor area css file
        string mCssStylesheet = ValidationHelper.GetString(GetValue("cssstylesheet"), "");

        if (!String.IsNullOrEmpty(mCssStylesheet))
        {
            editor.EditorAreaCSS = CSSHelper.GetStylesheetUrl(mCssStylesheet);
        }
        else if (toolbarSet.EqualsCSafe("Wireframe", true))
        {
            // Special case for wireframe editor
            editor.EditorAreaCSS = "~/CMSAdminControls/CKeditor/skins/kentico/wireframe.css";
        }
        else if (CMSContext.CurrentSite != null)
        {
            editor.EditorAreaCSS = FormHelper.GetHtmlEditorAreaCss(CMSContext.CurrentSiteName);
        }

        // Set live site info
        editor.IsLiveSite = IsLiveSite;

        // Set direction
        if (CultureHelper.IsPreferredCultureRTL())
        {
            editor.ContentsLangDirection = LanguageDirection.RightToLeft;
        }
        else
        {
            editor.ContentsLangDirection = LanguageDirection.LeftToRight;
        }

        // Get dialog configuration
        DialogConfiguration mediaConfig = GetDialogConfiguration(FieldInfo);

        if (mediaConfig != null)
        {
            // Override starting path from main configuration
            if (!String.IsNullOrEmpty(startingPath))
            {
                mediaConfig.ContentStartingPath = startingPath;
                mediaConfig.LibStartingPath     = startingPath;
            }

            // Set configuration for 'Insert image or media' dialog
            editor.MediaDialogConfig = mediaConfig;
            // Set configuration for 'Insert link' dialog
            editor.LinkDialogConfig = mediaConfig.Clone();
            // Set configuration for 'Quickly insert image' dialog
            editor.QuickInsertConfig = mediaConfig.Clone();
        }

        // Set CSS settings
        if (!String.IsNullOrEmpty(ControlStyle))
        {
            editor.Attributes.Add("style", ControlStyle);
            ControlStyle = null;
        }
        if (!String.IsNullOrEmpty(CssClass))
        {
            editor.CssClass = CssClass;
            CssClass        = null;
        }

        CheckRegularExpression = true;
        CheckFieldEmptiness    = true;
    }
Beispiel #16
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Validate query string
        if (!QueryHelper.ValidateHash("hash"))
        {
            // Do nothing
        }
        else
        {
            // Get information on current source type
            string sourceType = QueryHelper.GetString("source", "attachments");
            SourceType = CMSDialogHelper.GetMediaSource(sourceType);

            // Ensure additional styles
            CurrentMaster.HeadElements.Visible = true;
            CurrentMaster.HeadElements.Text   += CSSHelper.GetStyle("*{direction:ltr !important;}body{background:transparent !important;}input,input:focus,input:hover,input:active{border:none;border-color:transparent;outline:none;}");

            // Get uploader control based on the current source type
            string uploaderPath = "";
            if (SourceType == MediaSourceEnum.MediaLibraries)
            {
                // If media library module is running
                if (ModuleEntry.IsModuleRegistered(ModuleEntry.MEDIALIBRARY) && ModuleEntry.IsModuleLoaded(ModuleEntry.MEDIALIBRARY))
                {
                    uploaderPath = "~/CMSModules/MediaLibrary/Controls/Dialogs/DirectFileUploader/DirectMediaFileUploaderControl.ascx";
                }
            }
            else
            {
                uploaderPath = "~/CMSModules/Content/Controls/Attachments/DirectFileUploader/DirectFileUploaderControl.ascx";
            }

            // Load direct file uploader
            if (uploaderPath != "")
            {
                DirectFileUploader fileUploaderElem = LoadControl(uploaderPath) as DirectFileUploader;
                if (fileUploaderElem != null)
                {
                    // Insert uploader to parent container
                    pnlUploaderElem.Controls.Add(fileUploaderElem);

                    // Initialize uploader control properties by query string values
                    fileUploaderElem.AttachmentGUID           = QueryHelper.GetGuid("attachmentguid", Guid.Empty);
                    fileUploaderElem.AttachmentGroupGUID      = QueryHelper.GetGuid("attachmentgroupguid", Guid.Empty);
                    fileUploaderElem.AttachmentGUIDColumnName = QueryHelper.GetString("attachmentguidcolumnname", null);
                    fileUploaderElem.FormGUID         = QueryHelper.GetGuid("formguid", Guid.Empty);
                    fileUploaderElem.DocumentID       = QueryHelper.GetInteger("documentid", 0);
                    fileUploaderElem.NodeParentNodeID = QueryHelper.GetInteger("parentid", 0);
                    fileUploaderElem.NodeClassName    = QueryHelper.GetString("classname", "");
                    fileUploaderElem.InsertMode       = QueryHelper.GetBoolean("insertmode", false);
                    fileUploaderElem.OnlyImages       = QueryHelper.GetBoolean("onlyimages", false);
                    fileUploaderElem.ParentElemID     = QueryHelper.GetString("parentelemid", String.Empty);
                    fileUploaderElem.CheckPermissions = QueryHelper.GetBoolean("checkperm", true);
                    fileUploaderElem.IsLiveSite       = QueryHelper.GetBoolean("islive", true);
                    fileUploaderElem.RaiseOnClick     = QueryHelper.GetBoolean("click", false);
                    fileUploaderElem.NodeSiteName     = QueryHelper.GetString("sitename", null);
                    fileUploaderElem.SourceType       = SourceType;
                    fileUploaderElem.NodeGroupID      = QueryHelper.GetInteger("nodegroupid", 0);

                    // Metafile upload
                    fileUploaderElem.SiteID     = QueryHelper.GetInteger("siteid", 0);
                    fileUploaderElem.Category   = QueryHelper.GetString("category", String.Empty);
                    fileUploaderElem.ObjectID   = QueryHelper.GetInteger("objectid", 0);
                    fileUploaderElem.ObjectType = QueryHelper.GetString("objecttype", String.Empty);

                    // Library info initialization
                    fileUploaderElem.LibraryID          = QueryHelper.GetInteger("libraryid", 0);
                    fileUploaderElem.MediaFileID        = QueryHelper.GetInteger("mediafileid", 0);
                    fileUploaderElem.MediaFileName      = QueryHelper.GetString("filename", null);
                    fileUploaderElem.IsMediaThumbnail   = QueryHelper.GetBoolean("ismediathumbnail", false);
                    fileUploaderElem.LibraryFolderPath  = QueryHelper.GetString("path", "");
                    fileUploaderElem.IncludeNewItemInfo = QueryHelper.GetBoolean("includeinfo", false);

                    string siteName = CMSContext.CurrentSiteName;
                    string allowed  = QueryHelper.GetString("allowedextensions", null);
                    if (allowed == null)
                    {
                        if (fileUploaderElem.SourceType == MediaSourceEnum.MediaLibraries)
                        {
                            allowed = SettingsKeyProvider.GetStringValue(siteName + ".CMSMediaFileAllowedExtensions");
                        }
                        else
                        {
                            allowed = SettingsKeyProvider.GetStringValue(siteName + ".CMSUploadExtensions");
                        }
                    }
                    fileUploaderElem.AllowedExtensions = allowed;

                    // Auto resize width
                    int autoResizeWidth = QueryHelper.GetInteger("autoresize_width", -1);
                    if (autoResizeWidth == -1)
                    {
                        autoResizeWidth = SettingsKeyProvider.GetIntValue(siteName + ".CMSAutoResizeImageWidth");
                    }
                    fileUploaderElem.ResizeToWidth = autoResizeWidth;

                    // Auto resize height
                    int autoResizeHeight = QueryHelper.GetInteger("autoresize_height", -1);
                    if (autoResizeHeight == -1)
                    {
                        autoResizeHeight = SettingsKeyProvider.GetIntValue(siteName + ".CMSAutoResizeImageHeight");
                    }
                    fileUploaderElem.ResizeToHeight = autoResizeHeight;

                    // Auto resize max side size
                    int autoResizeMaxSideSize = QueryHelper.GetInteger("autoresize_maxsidesize", -1);
                    if (autoResizeMaxSideSize == -1)
                    {
                        autoResizeMaxSideSize = SettingsKeyProvider.GetIntValue(siteName + ".CMSAutoResizeImageMaxSideSize");
                    }
                    fileUploaderElem.ResizeToMaxSideSize = autoResizeMaxSideSize;

                    fileUploaderElem.AfterSaveJavascript = QueryHelper.GetString("aftersave", String.Empty);
                    fileUploaderElem.TargetFolderPath    = QueryHelper.GetString("targetfolder", String.Empty);
                    fileUploaderElem.TargetFileName      = QueryHelper.GetString("targetfilename", String.Empty);
                }
            }
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        RangeDateTimePicker datePickerObject = PickerControl as RangeDateTimePicker;

        if (datePickerObject == null)
        {
            return;
        }

        // Default settings
        int numberOfRows = 6;
        // Buttons NotAvaible,Done,Now
        bool showActionPanel = false;
        // Hides if date is selected
        bool hideOnDateSelection = false;
        // Display seconds
        bool displaySeconds = true;
        // Add icon - triggers datepicker show
        string shownOn = "button";
        // If true display time
        bool displayTime = datePickerObject.EditTime && !datePickerObject.DisableDaySelect && !datePickerObject.DisableMonthSelect;

        string minDate = String.Empty;
        string maxDate = String.Empty;

        if (datePickerObject.UseCalendarLimit)
        {
            if (datePickerObject.MinDate != DateTimeHelper.ZERO_TIME)
            {
                minDate = "minDate: " + (datePickerObject.MinDate.Date - DateTime.Now.Date).Days.ToString() + ",";
            }

            if (datePickerObject.MaxDate != DateTimeHelper.ZERO_TIME)
            {
                maxDate = "maxDate: " + (datePickerObject.MaxDate.Date - DateTime.Now.Date).Days.ToString() + ",";
            }
        }

        LoadResources(datePickerObject);

        int stepMonth = datePickerObject.DisableMonthSelect ? 12 : 1;

        CultureInfo        culture = new CultureInfo(datePickerObject.CultureCode, true);
        DateTimeFormatInfo info    = culture.DateTimeFormat;

        // Register default css a js files
        ScriptHelper.RegisterJQuery(Page);
        ScriptHelper.RegisterScriptFile(Page, "~/CMSScripts/JQuery/jquery-ui-datetimepicker.js");
        ScriptHelper.RegisterScriptFile(Page, "~/CMSScripts/modalCalendar.js");
        CSSHelper.RegisterCSSLink(Page, "~/CMSAdminControls/ModalCalendar/Themes/Calendar_core.css");

        string datePattern = info.ShortDatePattern.Replace("yyyy", "yy").Replace("'", "");

        if (displayTime)
        {
            datePattern += " " + (displaySeconds ? info.LongTimePattern : info.ShortTimePattern);
        }

        bool use24HourMode = !datePattern.Contains("tt");

        // Generate 'now' string with full year
        string format = info.ShortDatePattern;

        if (Regex.Matches(format, "y").Count == 2)
        {
            format = format.Replace("yy", "yyyy");
        }

        string now = CMSContext.DateTimeConvert(DateTime.Now, datePickerObject.TimeZone, datePickerObject.CustomTimeZone).ToString(format, culture);

        // Localized settings
        string localize = String.Format("monthNames:{0},monthNamesShort:{1},dayNames:{2},dayNamesMin:{3},firstDay:{4},", ArrayToString(info.MonthNames), ArrayToString(info.AbbreviatedMonthNames), ArrayToString(info.DayNames), ArrayToString(info.ShortestDayNames), ConvertFirstDayToNumber(info.FirstDayOfWeek));

        localize += String.Format("AMDesignator:'{0}',PMDesignator:'{1}',closeText:'{2}',isRTL:{3},prevText:'{4}',nextText:'{5}',defaultDate:'{6}'", info.AMDesignator.Replace("'", "\\'"), info.PMDesignator.Replace("'", "\\'"), ResHelper.GetString("general.ok").Replace("'", "\\'"), culture.TextInfo.IsRightToLeft.ToString().ToLower(), ResHelper.GetString("calendar.previous").Replace("'", "\\'"), ResHelper.GetString("calendar.next").Replace("'", "\\'"), now);

        // Classic settings
        String initParameters = String.Format("numberOfRows:{0},showTimePanel:{1},use24HourMode:{2},showButtonPanel:{3},hideOnDateSelection:{4},displaySeconds:{5},", numberOfRows, displayTime.ToString().ToLower(), use24HourMode.ToString().ToLower(), showActionPanel.ToString().ToLower(), hideOnDateSelection.ToString().ToLower(), displaySeconds.ToString().ToLower());

        initParameters += String.Format("IconID:'{0}',showOn:'{1}',dateFormat:'{2}',disableDaySelect:{3},disableMonthSelect:{4},stepMonths:{5},changeMonth:{6},timeZoneOffset:{7},selectOtherMonths:true,showOtherMonths:true,changeYear:true", datePickerObject.CalendarImageClientID, shownOn, datePattern, datePickerObject.DisableDaySelect.ToString().ToLower(), datePickerObject.DisableMonthSelect.ToString().ToLower(), stepMonth, (!datePickerObject.DisableMonthSelect).ToString().ToLower(), datePickerObject.TimeZoneOffset);

        // Init first calendar
        string calendarInit = "$j(function() {$j('#" + dateFrom.ClientID + "').datepicker({" + minDate + maxDate + localize + "," + initParameters + ",defaultTimeValue:" + (datePickerObject.UseDynamicDefaultTime ? 1 : 0) + "});";

        // Init second calendar
        calendarInit += "$j('#" + dateTo.ClientID + "').datepicker({" + minDate + maxDate + localize + "," + initParameters + ",defaultTimeValue:" + (datePickerObject.UseDynamicDefaultTime ? 2 : 0) + "})});";

        ScriptHelper.RegisterClientScriptBlock(Page, GetType(), ClientID + "_RegisterDatePickerFunction", ScriptHelper.GetScript(calendarInit));

        // Button OK
        btnOK.OnClientClick  = "$j('#" + datePickerObject.DateTimeTextBox.ClientID + "').val ($j('#" + dateFrom.ClientID + "').datepicker ('getFormattedDate'));";
        btnOK.OnClientClick += "$j('#" + datePickerObject.AlternateDateTimeTextBox.ClientID + "').val ($j('#" + dateTo.ClientID + "').datepicker ('getFormattedDate'));";
        btnOK.OnClientClick += "$j('#" + rangeCalendar.ClientID + "').hide();";

        if (datePickerObject.DisplayNAButton)
        {
            btnNA.OnClientClick = "$j('#" + rangeCalendar.ClientID + "').hide(); $j('#" + datePickerObject.DateTimeTextBox.ClientID + "').val('');$j('#" + datePickerObject.AlternateDateTimeTextBox.ClientID + "').val('');return false;";
            btnNA.Visible       = true;
        }

        if (!datePickerObject.PostbackOnOK)
        {
            btnOK.OnClientClick += "return false;";
        }

        // Icon
        string clickScript = " if( $j('#" + rangeCalendar.ClientID + @"').is(':hidden')) { 
            $j('#" + dateFrom.ClientID + "').datepicker('setDate',$j('#" + datePickerObject.DateTimeTextBox.ClientID + @"').val());     
            $j('#" + dateTo.ClientID + "').datepicker('setDate',$j('#" + datePickerObject.AlternateDateTimeTextBox.ClientID + @"').val());                           
            var offset = localizeRangeCalendar($j('#" + rangeCalendar.ClientID + "'),$j('#" + datePickerObject.DateTimeTextBox.ClientID + "')," + CultureHelper.IsUICultureRTL().ToString().ToLower() + ",true);" +
                             "$j('#" + rangeCalendar.ClientID + "').css({left:offset.left+'px',top:offset.top+'px'});$j('#" + rangeCalendar.ClientID + "').show();}return false;";

        // Add image on click
        String script = "$j(\"#" + datePickerObject.CalendarImageClientID + "\").click(function() {" + clickScript + "});";

        ScriptHelper.RegisterStartupScript(this, typeof(string), ClientID + "CalendarImageInitScript", ScriptHelper.GetScript(script));

        datePickerObject.DateTimeTextBox.Attributes["OnClick"]          = clickScript;
        datePickerObject.AlternateDateTimeTextBox.Attributes["OnClick"] = clickScript;

        // Script for hiding calendar when clicked somewhere else
        ltlScript.Text = ScriptHelper.GetScript(@"$j(document).mousedown(function(event) { 
                var target = $j(event.target);    
                if ((target.closest('#" + rangeCalendar.ClientID + "').length == 0) && (target.parents('#" + rangeCalendar.ClientID + @"').length == 0) 
                 && (target.closest('#" + datePickerObject.CalendarImageClientID + "').length == 0) && (target.closest('#" + datePickerObject.DateTimeTextBox.ClientID + @"').length == 0) && (target.closest('#" + datePickerObject.AlternateDateTimeTextBox.ClientID + @"').length == 0))
                        $j('#" + rangeCalendar.ClientID + @"').hide(); 
                });");
    }
Beispiel #18
0
    private string BuildStartupScript()
    {
        bool       enBBCode = IsSupport || (ChatHelper.EnableBBCodeSetting && EnableBBCode);
        WebControl input    = enBBCode ? ucBBEditor.TextArea : txtMessage;

        if (enBBCode)
        {
            txtMessage.Visible = false;
        }
        else
        {
            ucBBEditor.Visible = false;
        }

        JavaScriptSerializer sr = new JavaScriptSerializer();
        string json             = sr.Serialize(
            new
        {
            roomID                        = RoomID,
            inputClientID                 = GetString(input),
            buttonClientID                = GetString(btnSendMessage),
            groupID                       = GroupID,
            chbWhisperClientID            = GetString(chbWhisper),
            drpRecipientClientID          = GetString(drpRecipient),
            pnlRecipientContainerClientID = GetString(pnlRecipientContainer),
            noneLabel                     = ResHelper.GetString("chat.everyone"),
            enableBBCode                  = enBBCode,
            bbCodeClientID                = GetString(ucBBEditor),
            btnCannedResponses            = GetString(btnCannedResponses),
            pnlContent                    = GetString(pnlWebpartContent),
            envelopeID                    = "#envelope_" + ClientID,
            informDialogID                = GetString(pnlChatMessageSendInfoDialog),
            btnInformDialogClose          = GetString(btnChatMessageSendInformDialogClose)
        }
            );
        string startupScript = String.Format("InitChatSenderWebpart({0});", json);

        // If this webpart is for support person -> generate "Canned responses"
        if ((ChatOnlineUserHelper.GetLoggedInChatUser() != null) && (IsSupport == true))
        {
            // Get canned responses from database
            IEnumerable <ChatSupportCannedResponseInfo> cannedResponses = ChatSupportCannedResponseInfoProvider.GetCannedResponses(ChatOnlineUserHelper.GetLoggedInChatUser().ChatUserID, SiteContext.CurrentSiteID);

            if (cannedResponses.Any())
            {
                plcCannedResponses.Visible = true;

                // Register necessary files
                ScriptHelper.RegisterScriptFile(Page, "~/CMSWebParts/Chat/ChatMessageSend_files/CannedResponses.js");
                CSSHelper.RegisterCSSLink(Page, "~/App_Themes/Design/Chat/ChatIntelliSense.css");

                // Creates canned responses in format expected in javascript
                var cannedResponseToSerialize = from cr in cannedResponses
                                                let resolvedText = MacroResolver.Resolve(cr.ChatSupportCannedResponseText)
                                                                   select new
                {
                    label   = "#" + HTMLHelper.HTMLEncode(cr.ChatSupportCannedResponseTagName),
                    tooltip = HTMLHelper.HTMLEncode(TextHelper.LimitLength(resolvedText, mTooltipLength)),
                    value   = resolvedText
                };

                // Serialize canned responses to JS Array expected by javascript
                string cannedResponsesJSArray = "";
                try
                {
                    cannedResponsesJSArray = sr.Serialize(cannedResponseToSerialize);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("Chat", "JSON serialization of canned responses", ex);
                }
                startupScript += string.Format("var CannedResponses = {0};", cannedResponsesJSArray);

                startupScript += string.Format("InitCannedResponses({0}, {1});", ScriptHelper.GetString("#" + input.ClientID), ScriptHelper.GetString("#" + btnCannedResponses.ClientID));
            }
        }

        return(startupScript);
    }
Beispiel #19
0
    /// <summary>
    /// Handles the PreRender event of the Page control.
    /// </summary>
    protected void Page_PreRender(object sender, EventArgs e)
    {
        if (stopProcessing)
        {
            Visible = false;
            return;
        }

        // Check permissions
        if (!CheckPermissions("Manage"))
        {
            // Hide add/remove variant buttons when the Manage permission is not allowed
            plcRemoveVariant.Visible = false;
            plcAddVariant.Visible    = false;
        }

        // Hide buttons in the template edit in the site manager
        if (DocumentContext.CurrentDocument == null)
        {
            plcRemoveVariant.Visible = false;
            plcAddVariant.Visible    = false;
            plcVariantList.Visible   = false;
        }

        // Get the sum of all variants
        int totalVariants = 0;

        switch (SliderMode)
        {
        case VariantTypeEnum.Zone:
            // Zone
            if ((WebPartZoneControl != null) &&
                (WebPartZoneControl.HasVariants) &&
                (WebPartZoneControl.ZoneInstance != null) &&
                (WebPartZoneControl.ZoneInstance.ZoneInstanceVariants != null))
            {
                totalVariants = WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.Count;
            }
            break;

        case VariantTypeEnum.WebPart:
        case VariantTypeEnum.Widget:
            // Web part
            // Widget
            if ((WebPartControl != null) &&
                (WebPartControl.HasVariants) &&
                (WebPartControl.PartInstance != null) &&
                (WebPartControl.PartInstance.PartInstanceVariants != null))
            {
                totalVariants = WebPartControl.PartInstance.PartInstanceVariants.Count;
            }
            break;
        }

        // Increase by 1 to include the original webpart
        totalVariants++;

        // Reset the slider state (correct variant for the current combination is chosen by javascript in window.onload)
        txtSlider.Text = "1";
        if (isRTL)
        {
            // Reverse position index when in RTL
            txtSlider.Text = totalVariants.ToString();
        }

        // Change the slider CSS class if used for widgets
        if ((WebPartControl != null) &&
            WebPartControl.IsWidget)
        {
            pnlVariations.CssClass = "WidgetVariantSlider";
        }

        // Setup the variant slider extender
        sliderExtender.Minimum        = 1;
        sliderExtender.Maximum        = totalVariants;
        sliderExtender.Steps          = totalVariants;
        sliderExtender.HandleImageUrl = GetImageUrl("Design/Controls/VariantSlider/slider.png");

        if (isRTL)
        {
            // RTL culture - set the javascript variable
            ScriptHelper.RegisterStartupScript(Page, typeof(string), "VariantSliderRTL", ScriptHelper.GetScript("variantSliderIsRTL = true;"));
        }

        // Change the arrows design for MVT
        if ((VariantMode == VariantModeEnum.MVT) || !PortalContext.ContentPersonalizationEnabled)
        {
            //pnlLeft.CssClass = "SliderLeftMVT";
            //pnlRight.CssClass = "SliderRightMVT";
        }

        CSSHelper.RegisterBootstrap(Page);

        sliderExtender.HandleCssClass = "slider-horizontal-handle";
        sliderExtender.RailCssClass   = "slider-horizontal-rail";
        lblTotal.Text = totalVariants.ToString();

        txtSlider.Attributes.Add("onchange", "$cmsj('#" + hdnSliderPosition.ClientID + "').change();");
        txtSlider.Style.Add("display", "none");

        // Prepare the parameters
        string zoneId = string.Empty;

        PageInfo pi = PagePlaceholder.PageInfo;

        string aliasPath  = pi.NodeAliasPath;
        string templateId = pi.GetUsedPageTemplateId().ToString();

        string webPartName        = string.Empty;
        string instanceGuidString = string.Empty;

        switch (SliderMode)
        {
        case VariantTypeEnum.Zone:
            // Zone
            zoneId = WebPartZoneControl.ZoneInstance.ZoneID;
            break;

        case VariantTypeEnum.WebPart:
        case VariantTypeEnum.Widget:
            // Web part
            zoneId             = WebPartControl.PartInstance.ParentZone.ZoneID;
            instanceGuidString = WebPartControl.InstanceGUID.ToString();
            webPartName        = WebPartControl.PartInstance.ControlID;
            break;
        }

        // Setup tooltips
        pnlLeft.ToolTip          = ResHelper.GetString("variantslider.btnleft", UICulture);
        pnlRight.ToolTip         = ResHelper.GetString("variantslider.btnright", UICulture);
        imgRemoveVariant.ToolTip = ResHelper.GetString("variantslider.btnremove", UICulture);
        imgVariantList.ToolTip   = ResHelper.GetString("variantslider.btnlist", UICulture);

        // Setup default behaviour - no action executed
        imgRemoveVariantDisabled.Attributes.Add("onclick", "return false;");
        imgVariantList.Attributes.Add("onclick", "return false;");

        // Cancel propagation of the double-click event (skips opening the web part properties dialog)
        pnlVariations.Attributes.Add("ondblclick", "CancelEventPropagation(event)");

        // Hidden field used for changing the slider position. The position of the slider is stored also here because of the usage of the slider arrows.
        hdnSliderPosition.Style.Add("display", "none");
        hdnSliderPosition.Attributes.Add("onchange", "OnHiddenChanged(this, document.getElementById('" + lblPart.ClientID + "'), '" + uniqueCode + "', '" + sliderExtender.BehaviorID + @"' );");

        String zoneIdPar    = (WebPartControl != null) ? "GetActualZoneId('wp_" + WebPartControl.InstanceGUID.ToString("N") + "')" : "'" + zoneId + "'";
        string dialogParams = zoneIdPar + ", '" + webPartName + "', '" + aliasPath + "', '" + instanceGuidString + "', " + templateId + ", '" + VariantTypeFunctions.GetVariantTypeString(SliderMode) + "'";

        // Allow edit actions
        if (totalVariants == 1)
        {
            if (SliderMode == VariantTypeEnum.Widget)
            {
                plcRemoveVariant.Visible = false;
                plcVariantList.Visible   = false;
                plcSliderPanel.Visible   = false;
                var  cui       = MembershipContext.AuthenticatedUser;
                bool manageMVT = cui.IsAuthorizedPerResource("cms.mvtest", "manage") && cui.IsAuthorizedPerResource("cms.mvtest", "read");
                bool manageCP  = cui.IsAuthorizedPerResource("cms.contentpersonalization", "manage") && cui.IsAuthorizedPerResource("cms.contentpersonalization", "read");

                if (PortalContext.MVTVariantsEnabled && PortalContext.ContentPersonalizationEnabled && manageMVT && manageCP)
                {
                    pnlAddVariantWrapper.Attributes.Add("onclick", "OpenMenuAddWidgetVariant(this, '" + WebPartControl.ShortClientID + "'); return false;");
                    imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnadd", UICulture);

                    // Script for opening a new variant dialog window and activating widget border to prevent to widget border from hiding
                    // when the user moves his mouse to the 'add widget' context menu.
                    string script = @"
function OpenMenuAddWidgetVariant(menuPositionEl, targetId) {
    currentContextMenuId = targetId;
    ContextMenu('addWidgetVariantMenu', menuPositionEl, webPartLocation[targetId + '_container'], true);
    AutoPostitionContextMenu('addWidgetVariantMenu');
}";
                    ScriptHelper.RegisterStartupScript(this, typeof(string), "OpenMenuAddWidgetVariantScript", ScriptHelper.GetScript(script));
                }
                else
                {
                    if (PortalContext.MVTVariantsEnabled && manageMVT)
                    {
                        imgAddVariant.Attributes.Add("onclick", "AddMVTVariant(" + dialogParams + "); return false;");
                        imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnaddmvt", UICulture);
                    }
                    else if (PortalContext.ContentPersonalizationEnabled && manageCP)
                    {
                        imgAddVariant.Attributes.Add("onclick", "AddPersonalizationVariant(" + dialogParams + "); return false;");
                        imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnaddpesronalization", UICulture);
                    }
                }
            }
        }
        else
        {
            if (VariantMode == VariantModeEnum.MVT)
            {
                imgAddVariant.Attributes.Add("onclick", "AddMVTVariant(" + dialogParams + "); return false;");
                imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnaddmvt", UICulture);
            }
            else
            {
                imgAddVariant.Attributes.Add("onclick", "AddPersonalizationVariant(" + dialogParams + "); return false;");
                imgAddVariant.ToolTip = ResHelper.GetString("variantslider.btnaddpesronalization", UICulture);
            }
        }

        if ((totalVariants > 1) || (SliderMode == VariantTypeEnum.Widget))
        {
            // Register only for full postback or first page load
            if (!RequestHelper.IsAsyncPostback())
            {
                if ((VariantMode == VariantModeEnum.MVT))
                {
                    // Activate the variant list button fot MVT
                    imgVariantList.Attributes.Add("onclick", "ListMVTVariants(" + dialogParams + ", '" + uniqueCode + "'); return false;");
                }
                else if (VariantMode == VariantModeEnum.ContentPersonalization)
                {
                    // Activate the variant list button for Content personalization
                    imgVariantList.Attributes.Add("onclick", "ListPersonalizationVariants(" + dialogParams + ", '" + uniqueCode + "'); return false;");
                }

                // Assign the onclick event for he Remove variant button
                imgRemoveVariant.Attributes.Add("onclick", "RemoveVariantPostBack_" + uniqueCode + @"(); return false");

                // Register Remove variant script
                string removeVariantScript = @"
                function RemoveVariantPostBack_" + uniqueCode + @"() {
                    if (confirm(" + ScriptHelper.GetLocalizedString("variantslider.removeconfirm") + @")) {" +
                                             DocumentManager.GetAllowSubmitScript() + @"
                        var postBackCode = '" + uniqueCode + ":remove:' + GetCurrentVariantId('" + uniqueCode + @"');
                        SetVariant('" + uniqueCode + @"', 0);"
                                             + ControlsHelper.GetPostBackEventReference(this, "#").Replace("'#'", "postBackCode") + @";
                    }
                }";

                ScriptHelper.RegisterStartupScript(Page, typeof(string), "removeVariantScript_" + uniqueCode, ScriptHelper.GetScript(removeVariantScript));

                int step = 1;
                if (isRTL)
                {
                    // Reverse step direction
                    step = -1;
                }
                // Assign the onclick events for the slider arrows
                pnlLeft.Attributes.Add("onclick", "OnSliderChanged(event, '" + hdnSliderPosition.ClientID + "', " + totalVariants + ", " + step * (-1) + ");");
                pnlRight.Attributes.Add("onclick", "OnSliderChanged(event, '" + hdnSliderPosition.ClientID + "', " + totalVariants + ", " + step + ");");

                // Get all variants GUIDs
                List <string> variantIDsArray        = new List <string>();
                List <string> variantControlIDsArray = new List <string>();
                List <string> divIDsArray            = new List <string>();

                switch (SliderMode)
                {
                case VariantTypeEnum.Zone:
                    // Zone
                    if ((WebPartZoneControl != null) &&
                        (WebPartZoneControl.ZoneInstance != null) &&
                        (WebPartZoneControl.ZoneInstance.ZoneInstanceVariants != null))
                    {
                        // Fill the variant IDs array
                        variantIDsArray = WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.Select(zone => zone.VariantID.ToString()).ToList <string>();
                        // First item is the original zone (variantid=0)
                        variantIDsArray.Insert(0, "0");

                        // Fill the variant control IDs array
                        variantControlIDsArray = WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.Select(zone => "\"" + (!string.IsNullOrEmpty(ValidationHelper.GetString(zone.Properties["zonetitle"], string.Empty)) ? HTMLHelper.HTMLEncode(zone.Properties["zonetitle"].ToString()) : zone.ZoneID) + "\"").ToList <string>();
                        // First item is the original web part/widget
                        variantControlIDsArray.Insert(0, "\"" + (!string.IsNullOrEmpty(WebPartZoneControl.ZoneTitle) ? HTMLHelper.HTMLEncode(WebPartZoneControl.ZoneTitle) : WebPartZoneControl.ZoneInstance.ZoneID) + "\"");

                        // Fill the DIV tag IDs array
                        divIDsArray = WebPartZoneControl.ZoneInstance.ZoneInstanceVariants.Select(zone => "\"Variant_" + VariantModeFunctions.GetVariantModeString(zone.VariantMode) + "_" + zone.VariantID.ToString() + "\"").ToList <string>();
                        // First item is the original web part
                        divIDsArray.Insert(0, "\"" + uniqueCode + "\"");
                    }
                    break;

                case VariantTypeEnum.WebPart:
                case VariantTypeEnum.Widget:
                    // Web part or widget
                    if ((WebPartControl != null) &&
                        (WebPartControl.PartInstance != null) &&
                        (WebPartControl.PartInstance.PartInstanceVariants != null))
                    {
                        // Fill the variant IDs array
                        variantIDsArray = WebPartControl.PartInstance.PartInstanceVariants.Select(webpart => webpart.VariantID.ToString()).ToList <string>();
                        // First item is the original web part/widget (variantid=0)
                        variantIDsArray.Insert(0, "0");

                        // Fill the variant control IDs array
                        variantControlIDsArray = WebPartControl.PartInstance.PartInstanceVariants.Select(webpart => "\"" + (!string.IsNullOrEmpty(ValidationHelper.GetString(webpart.Properties["webparttitle"], string.Empty)) ? HTMLHelper.HTMLEncode(webpart.Properties["webparttitle"].ToString()) : webpart.ControlID) + "\"").ToList <string>();
                        // First item is the original web part/widget
                        variantControlIDsArray.Insert(0, "\"" + (!string.IsNullOrEmpty(ValidationHelper.GetString(WebPartControl.PartInstance.Properties["webparttitle"], string.Empty)) ? HTMLHelper.HTMLEncode(WebPartControl.PartInstance.Properties["webparttitle"].ToString()) : WebPartControl.PartInstance.ControlID) + "\"");

                        // Fill the DIV tag IDs array
                        divIDsArray = WebPartControl.PartInstance.PartInstanceVariants.Select(webpart => "\"Variant_" + VariantModeFunctions.GetVariantModeString(webpart.VariantMode) + "_" + webpart.VariantID + "\"").ToList <string>();
                        // First item is the original web part/widget
                        divIDsArray.Insert(0, "\"" + uniqueCode + "\"");
                    }
                    break;
                }

                // Create a javascript arrays:
                // Fill the following javascript array: itemCodesArray.push([variantIDs], [divIDs], actualSliderPosition, totalVariants, variantSliderId, sliderElement, hiddenElem_SliderPosition, zoneId, webPartInstanceGuid)
                StringBuilder sb = new StringBuilder();
                sb.Append("itemIDs = [");
                sb.Append(String.Join(",", variantIDsArray.ToArray()));
                sb.Append("]; divIDs = [");
                sb.Append(String.Join(",", divIDsArray.ToArray()));
                sb.Append("]; itemControlIDs = [");
                sb.Append(String.Join(",", variantControlIDsArray.ToArray()));
                sb.Append("];");
                sb.Append("itemCodes = [itemIDs, divIDs, itemControlIDs, 1, "); // 0, 1, 2, 3 (see the details in the 'variants.js' file)
                sb.Append(totalVariants);                                       // 4
                sb.Append(", \"");
                sb.Append(pnlVariations.ClientID);                              // 5
                sb.Append("\", \"");
                sb.Append(sliderExtender.ClientID);                             // 6
                sb.Append("_handleImage\", \"");
                sb.Append(hdnSliderPosition.ClientID);                          // 7
                sb.Append("\", \"");
                if (SliderMode == VariantTypeEnum.Zone)                         // 8
                {
                    sb.Append(WebPartZoneControl.TitleLabel.ClientID);
                }
                else
                {
                    // Display label only for web parts (editor widgets have title hidden)
                    if (WebPartControl.TitleLabel != null)
                    {
                        sb.Append(WebPartControl.TitleLabel.ClientID);
                    }
                }
                sb.Append("\", \"");
                sb.Append(zoneId);                      // 9
                sb.Append("\", \"");
                if (SliderMode != VariantTypeEnum.Zone) // 10
                {
                    sb.Append(instanceGuidString);
                }
                sb.Append("\", \"");
                sb.Append(VariantModeFunctions.GetVariantModeString(VariantMode)); // 11
                sb.Append("\", \"");
                sb.Append(pnlVariations.ClientID);                                 // 12
                sb.Append("\"]; itemCodesAssociativeArray[\"");
                sb.Append(uniqueCode);
                sb.Append("\"] = itemCodes;");

                ScriptHelper.RegisterStartupScript(Page, typeof(string), sliderExtender.ClientID + "_InitScript", sb.ToString(), true);
            }
        }
        else
        {
            Visible = false;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Set control properties
        editor.AutoDetectLanguage = false;
        editor.DefaultLanguage    = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
        string toolbarSet = editor.ToolbarSet;

        if (this.Form != null)
        {
            editor.DialogParameters = this.Form.DialogParameters;
            // Get editor area toolbar
            toolbarSet             = DataHelper.GetNotEmpty(this.GetValue("toolbarset"), this.Form.HtmlAreaToolbar);
            editor.ToolbarSet      = toolbarSet;
            editor.ToolbarLocation = DataHelper.GetNotEmpty(this.GetValue("toolbarlocation"), this.Form.HtmlAreaToolbarLocation);

            // Set form dimensions
            editor.Width  = new Unit(ValidationHelper.GetInteger(this.GetValue("width"), 700));
            editor.Height = new Unit(ValidationHelper.GetInteger(this.GetValue("height"), 300));

            // Get editor area starting path
            editor.StartingPath = ValidationHelper.GetString(this.GetValue("startingpath"), "");

            // Get editor area css file
            string mCssStylesheet = ValidationHelper.GetString(this.GetValue("cssstylesheet"), "");
            if (!String.IsNullOrEmpty(mCssStylesheet))
            {
                editor.EditorAreaCSS = CSSHelper.GetStylesheetUrl(mCssStylesheet);
            }
            else if (toolbarSet.Equals("Wireframe", StringComparison.InvariantCultureIgnoreCase))
            {
                // Special case for wireframe editor
                editor.EditorAreaCSS = CSSHelper.GetCSSUrl("~/CMSAdminControls/CKeditor/skins/kentico/wireframe.css");
            }
            else if (CMSContext.CurrentSite != null)
            {
                editor.EditorAreaCSS = FormHelper.GetHtmlEditorAreaCss(CMSContext.CurrentSiteName);
            }
        }

        // Set live site info
        editor.IsLiveSite = this.IsLiveSite;

        // Set direction
        if (CultureHelper.IsPreferredCultureRTL())
        {
            editor.ContentsLangDirection = LanguageDirection.RightToLeft;
        }
        else
        {
            editor.ContentsLangDirection = LanguageDirection.LeftToRight;
        }

        // Get dialog configuration
        DialogConfiguration mediaConfig = GetDialogConfiguration(this.FieldInfo);

        if (mediaConfig != null)
        {
            // Set configuration for 'Insert image or media' dialog
            editor.MediaDialogConfig = mediaConfig;
            // Set configuration for 'Insert link' dialog
            editor.LinkDialogConfig = mediaConfig.Clone();
            // Set configuration for 'Quickly insert image' dialog
            editor.QuickInsertConfig = mediaConfig.Clone();
        }

        // Set CSS settings
        if (!String.IsNullOrEmpty(this.ControlStyle))
        {
            editor.Attributes.Add("style", this.ControlStyle);
            this.ControlStyle = null;
        }
        if (!String.IsNullOrEmpty(this.CssClass))
        {
            editor.CssClass = this.CssClass;
            this.CssClass   = null;
        }

        this.CheckRegularExpression = true;
        this.CheckFieldEmptiness    = true;
    }
Beispiel #21
0
    protected void ApplySettings()
    {
        EnsureChildControls();

        if (!StopProcessing)
        {
            // Create controls by actual page mode
            switch (ViewMode)
            {
            case ViewModeEnum.Edit:
            case ViewModeEnum.EditDisabled:
            {
                // Display the region control based on the region type
                switch (RegionType)
                {
                case CMSEditableRegionTypeEnum.HtmlEditor:
                    // HTML Editor
                    if (IsDialogEdit)
                    {
                        Editor.ToolbarLocation = "out:CKToolbar";
                        Editor.Title           = Title;

                        // Maximize editor to fill entire dialog
                        Editor.RemoveButtons.Add("Maximize");

                        if (!DeviceContext.CurrentDevice.IsMobile)
                        {
                            // Desktop browsers
                            Editor.Config["on"] = "{ 'instanceReady' : function(e) { e.editor.execCommand( 'maximize' ); } }";
                        }
                    }

                    // Set toolbar location
                    if (HtmlAreaToolbarLocation != "")
                    {
                        // Show the toolbar
                        if (HtmlAreaToolbarLocation.ToLowerCSafe() == "out:cktoolbar")
                        {
                            mShowToolbar = true;
                        }

                        Editor.ToolbarLocation = HtmlAreaToolbarLocation;
                    }

                    // Set the visual appearance
                    if (HtmlAreaToolbar != "")
                    {
                        Editor.ToolbarSet = HtmlAreaToolbar;
                    }

                    // Get editor area css file
                    if (HTMLEditorCssStylesheet != "")
                    {
                        Editor.EditorAreaCSS = CSSHelper.GetStylesheetUrl(HTMLEditorCssStylesheet);
                    }
                    else if (SiteContext.CurrentSite != null)
                    {
                        Editor.EditorAreaCSS = CssStylesheetInfoProvider.GetHtmlEditorAreaCss(SiteContext.CurrentSiteName);
                    }

                    // Set "Insert image or media" dialog configuration
                    Editor.MediaDialogConfig.ResizeToHeight      = ResizeToHeight;
                    Editor.MediaDialogConfig.ResizeToWidth       = ResizeToWidth;
                    Editor.MediaDialogConfig.ResizeToMaxSideSize = ResizeToMaxSideSize;

                    // Set "Insert link" dialog configuration
                    Editor.LinkDialogConfig.ResizeToHeight      = ResizeToHeight;
                    Editor.LinkDialogConfig.ResizeToWidth       = ResizeToWidth;
                    Editor.LinkDialogConfig.ResizeToMaxSideSize = ResizeToMaxSideSize;

                    // Set "Quickly insert image" configuration
                    Editor.QuickInsertConfig.ResizeToHeight      = ResizeToHeight;
                    Editor.QuickInsertConfig.ResizeToWidth       = ResizeToWidth;
                    Editor.QuickInsertConfig.ResizeToMaxSideSize = ResizeToMaxSideSize;

                    break;

                case CMSEditableRegionTypeEnum.TextArea:
                case CMSEditableRegionTypeEnum.TextBox:
                    // TextBox
                    if (RegionType == CMSEditableRegionTypeEnum.TextArea)
                    {
                        txtValue.TextMode = TextBoxMode.MultiLine;
                    }
                    else
                    {
                        txtValue.TextMode = TextBoxMode.SingleLine;
                    }

                    if (DialogWidth > 0)
                    {
                        txtValue.Width = new Unit(DialogWidth - 8);
                    }
                    else
                    {
                        // Default width is 100%
                        txtValue.Width = new Unit(100, UnitType.Percentage);
                    }

                    if (DialogHeight > 0)
                    {
                        txtValue.Height = new Unit(DialogHeight);
                    }

                    txtValue.Wrap = WordWrap;

                    break;
                }
            }
            break;
            }
        }
    }
Beispiel #22
0
    protected void Page_Load(object sender, EventArgs e)
    {
        previewState = GetPreviewStateFromCookies(MASTERPAGE);

        // Keep current user
        user = MembershipContext.AuthenticatedUser;

        // Get document node
        tree = new TreeProvider(user);
        node = UIContext.EditedObject as TreeNode;

        // Register the dialog script
        ScriptHelper.RegisterDialogScript(Page);

        // Register save changes
        ScriptHelper.RegisterSaveChanges(Page);

        // Save changes support
        bool   confirmChanges = SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSConfirmChanges");
        string script         = string.Empty;

        if (confirmChanges)
        {
            script  = "CMSContentManager.confirmLeave=" + ScriptHelper.GetString(ResHelper.GetString("Content.ConfirmLeave", user.PreferredUICultureCode), true, false) + "; \n";
            script += "CMSContentManager.confirmLeaveShort=" + ScriptHelper.GetString(ResHelper.GetString("Content.ConfirmLeaveShort", user.PreferredUICultureCode), true, false) + "; \n";
        }
        else
        {
            script += "CMSContentManager.confirmChanges = false;";
        }

        ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "saveChangesScript", script, true);

        try
        {
            if (node != null)
            {
                DocumentContext.CurrentPageInfo = PageInfoProvider.GetPageInfo(SiteContext.CurrentSiteName, node.NodeAliasPath, node.DocumentCulture, null, false);

                // Title
                string title = DocumentContext.CurrentTitle;
                if (!string.IsNullOrEmpty(title))
                {
                    title = "<title>" + title + "</title>";
                }

                // Body class
                string bodyCss = DocumentContext.CurrentBodyClass;
                // Remove bootstrap default class
                bodyCss = bodyCss.Replace(" cms-bootstrap", String.Empty);

                if (bodyCss != null && bodyCss.Trim() != "")
                {
                    bodyCss = "class=\"" + bodyCss + "\"";
                }
                else
                {
                    bodyCss = "";
                }

                // Metadata
                string meta = "<meta http-equiv=\"pragma\" content=\"no-cache\" />";

                string description = DocumentContext.CurrentDescription;
                if (description != "")
                {
                    meta += "<meta name=\"description\" content=\"" + description + "\" />";
                }

                string keywords = DocumentContext.CurrentKeyWords;
                if (keywords != "")
                {
                    meta += "<meta name=\"keywords\"  content=\"" + keywords + "\" />";
                }

                // Site style sheet
                string cssSiteSheet = "";

                int stylesheetId = DocumentContext.CurrentPageInfo.DocumentStylesheetID;

                CssStylesheetInfo cssInfo = CssStylesheetInfoProvider.GetCssStylesheetInfo((stylesheetId > 0) ? stylesheetId : SiteContext.CurrentSite.SiteDefaultStylesheetID);

                if (cssInfo != null)
                {
                    cssSiteSheet = CSSHelper.GetCSSFileLink(CSSHelper.GetStylesheetUrl(cssInfo.StylesheetName));
                }

                // Theme CSS files
                string themeCssFiles = "";
                if (cssInfo != null)
                {
                    try
                    {
                        string directory = URLHelper.GetPhysicalPath(string.Format("~/App_Themes/{0}/", cssInfo.StylesheetName));
                        if (Directory.Exists(directory))
                        {
                            foreach (string file in Directory.GetFiles(directory, "*.css"))
                            {
                                themeCssFiles += CSSHelper.GetCSSFileLink(CSSHelper.GetPhysicalCSSUrl(cssInfo.StylesheetName, Path.GetFileName(file)));
                            }
                        }
                    }
                    catch
                    {
                    }
                }

                // Add values to page
                mHead = FormatHTML(HighlightHTML(title + meta + cssSiteSheet + themeCssFiles), 2);
                mBody = bodyCss;
            }
        }
        catch
        {
            ShowError(GetString("MasterPage.PageEditErr"));
        }

        LoadData();

        // Add save action
        SaveAction save = new SaveAction(Page);

        save.CommandArgument = ComponentEvents.SAVE_DATA;
        save.CommandName     = ComponentEvents.SAVE_DATA;

        headerActions.ActionsList.Add(save);

        if (pti != null)
        {
            // Disable buttons for no-template
            bool actionsEnabled = (pti.PageTemplateId > 0);

            // Edit layout
            HeaderAction action = new HeaderAction
            {
                Text          = GetString("content.ui.pagelayout"),
                Tooltip       = GetString("pageplaceholder.editlayouttooltip"),
                OnClientClick = "EditLayout();return false;",
                Enabled       = actionsEnabled
            };
            headerActions.ActionsList.Add(action);

            string elemUrl = UIContextHelper.GetElementDialogUrl("cms.design", "PageTemplate.EditPageTemplate", pti.PageTemplateId);

            // Edit page properties action
            action = new HeaderAction
            {
                Text          = GetString("PageProperties.EditTemplateProperties"),
                Tooltip       = GetString("PageProperties.EditTemplateProperties"),
                OnClientClick = "modalDialog('" + elemUrl + "', 'TemplateSelection', 900, 680, false);return false;",
                Enabled       = actionsEnabled
            };

            CMSPagePlaceholder.RegisterEditLayoutScript(this, pti.PageTemplateId, node.NodeAliasPath, null);
            headerActions.ActionsList.Add(action);

            // Preview
            HeaderAction preview = new HeaderAction
            {
                Text          = GetString("general.preview"),
                OnClientClick = "performToolbarAction('split');return false;",
                Visible       = ((previewState == 0) && !UIContext.DisplaySplitMode),
                Tooltip       = GetString("preview.tooltip")
            };
            headerActions.ActionsList.Add(preview);

            headerActions.ActionPerformed += headerActions_ActionPerformed;
        }

        RegisterInitScripts(pnlBody.ClientID, pnlMenu.ClientID, false);
    }