/// <summary> /// Registers script files for on-site editing /// </summary> /// <param name="pi">Current page info</param> private void RegisterEditScripts(PageInfo pi) { ScriptHelper.RegisterJQueryCookie(Page); StringBuilder script = new StringBuilder(); // Edit toolbar scripts if (ViewMode.IsEditLive()) { // Dialog scripts ScriptHelper.RegisterDialogScript(Page); // General url settings UIPageURLSettings settings = new UIPageURLSettings(); settings.AllowSplitview = false; settings.NodeID = pi.NodeID; settings.Culture = pi.DocumentCulture; settings.AdditionalQuery = "dialog=1"; // Edit document settings.Mode = "editform"; settings.Action = null; string editUrl = DocumentUIHelper.GetDocumentPageUrl(settings); settings.Mode = string.Empty; // Toolbar - Edit button script editUrl = URLHelper.RemoveParameterFromUrl(editUrl, "mode"); string scriptEdit = GetModalDialogScript(editUrl, "editpage"); // Delete document settings.Action = "delete"; string deleteUrl = DocumentUIHelper.GetDocumentPageUrl(settings); // Toolbar - Delete button script string scriptDelete = GetModalDialogScript(deleteUrl, "deletepage"); // User contributions - Delete item script string scriptDeleteItem = GetModalDialogScript(AddItemUrlParameters(deleteUrl), "deletepage"); // New document settings.Action = "new"; settings.AdditionalQuery += "&reloadnewpage=1"; string newUrl = DocumentUIHelper.GetDocumentPageUrl(settings); newUrl = AddNewItemUrlParameters(newUrl); // Include culture code newUrl = URLHelper.AddParameterToUrl(newUrl, "parentculture", preferredCultureCode); // Toolbar - New button script string scriptNew = GetModalDialogScript(newUrl, "newpage"); const string CONTENT_CMSDESK_FOLDER = "~/CMSModules/Content/CMSDesk/"; // Toolbar - Properties button script string scriptProperties = GetModalDialogScript(ResolveUrl(CONTENT_CMSDESK_FOLDER + "Properties/Properties_Frameset.aspx?mode=editlive&documentid=" + pi.DocumentID), "propertiespage"); // Display items from current level by default int nodeId = pi.NodeParentID; // If current level is root display first level if (nodeId == 0) { isRootDocument = true; nodeId = pi.NodeID; } // In page not found mode display first level if (nodeId == 0) { TreeProvider tp = new TreeProvider(); TreeNode tn = tp.SelectSingleNode(SiteContext.CurrentSiteName, "/", TreeProvider.ALL_CULTURES); if (tn != null) { nodeId = tn.NodeID; } } // Listing string listItemUrl = ResolveUrl(CONTENT_CMSDESK_FOLDER + "View/listing.aspx?dialog=1&wopenernodeid=" + pi.NodeID + "&nodeid=##id##"); string scriptListItem = GetModalDialogScript(listItemUrl.Replace("##id##", nodeId.ToString()), "listingpage"); // New culture string newCultureUrl = ResolveUrl(CONTENT_CMSDESK_FOLDER + "New/NewCultureVersion.aspx?nodeid=##id##&culture=##cult##&dialog=1"); script.Append(@" var OEIsRTL = ", (isRTL ? "true" : "false"), @"; var OECurrentNodeId = ", (DocumentContext.CurrentPageInfo != null) ? DocumentContext.CurrentPageInfo.NodeID : 0, @"; var OEIsMobile = ", (DeviceContext.CurrentDevice.IsMobile() ? "true" : "false"), @"; var OEHdnPostbackValue = null; function NewDocument(parentId, classId, targetWindow) { OEClearZIndex(OEActiveWebPart); if (targetWindow == null) { ", scriptNew, @"; } else { targetWindow.location.href = '", newUrl, @"'; } } function EditDocument(nodeId, targetWindow) { OEClearZIndex(OEActiveWebPart); // Edit item button in repeaters and datalists var arg = 'editurl;' + nodeId; ", Page.ClientScript.GetCallbackEventReference(this, "arg", "OECallbackHandler", null), @"; } function SaveDocumentWidgets() { if (!CMSContentManager.contentModified()) { return false; } if (window.CMSContentManager) { CMSContentManager.allowSubmit = true; } ", ControlsHelper.GetPostBackEventReference(this, "savedocument"), @"; } function OECallbackHandler(arg, context) { ", GetModalDialogScript("arg", "editpage", false), @" } function DeleteDocument(nodeId) { OEClearZIndex(OEActiveWebPart); ", scriptDeleteItem, @" } function OnSiteToolbarAction(name) { ", checkChanges, @" switch(name) { case 'edit': ", scriptEdit, @" break; case 'properties': ", scriptProperties, @" break; case 'new': var parentId = OECurrentNodeId; var classId = 0; ", scriptNew, @" break; case 'delete': ", scriptDelete, @" break; case 'list': ", scriptListItem, @" break; default: alert('Required action is not implemented.'); } } function SelectNode(nodeId, parentNodeId) { var liu = '", listItemUrl, @"'; return liu.replace(/##id##/g, nodeId); } function NewDocumentCulture(nodeId, culture) { ", checkChanges, @" var liu = '", newCultureUrl, @"'; liu = liu.replace(/##id##/g, nodeId); liu = liu.replace(/##cult##/g, culture); ", GetModalDialogScript("liu", "newculture", false), @" } function OEEnsureHdnPostbackValue() { if (OEHdnPostbackValue == null) { OEHdnPostbackValue = document.getElementById('", hdnPostbackValue.ClientID, @"'); } } // Changes the device profile function ChangeDevice(device) { ", checkChanges, @" OEEnsureHdnPostbackValue(); OEHdnPostbackValue.value = device; ", ControlsHelper.GetPostBackEventReference(this, "changedeviceprofile"), @" } "); ScriptHelper.RegisterJQueryDialog(Page); // Register OnSiteEdit script file ScriptHelper.RegisterScriptFile(Page, "DesignMode/OnSiteEdit.js"); ScriptHelper.RegisterScriptFile(Page, "~/CMSScripts/jquery/jquery-url.js"); } // Slider buttons scripts else if (ViewMode.IsLiveSite()) { plcRfrWOpnrScript.Visible = false; script.Append(@" function OESlideSideToolbar() { // Hide the slider button in administration if (parent != this) { return; } var toolbarEl = document.getElementById('", pnlSlider.ClientID, @"'); toolbarEl.style.display = ""block""; // Show slider button toolbarEl.style.top = ""0px""; } // Display slider button $cmsj(document).ready(function() { OESlideSideToolbar(); }); "); } script.Append(" function OnSiteEdit_ChangeEditMode(){", ControlsHelper.GetPostBackEventReference(this, "changeviewmode"), "} "); ControlsHelper.RegisterClientScriptBlock(this, Page, typeof(string), "OnSiteEditActions", ScriptHelper.GetScript(script.ToString())); }
/// <summary> /// Setup controls. /// </summary> private void SetupControls() { Action act = reportSubscriptions.GridActions.Actions[1] as Action; if (act != null) { ScriptHelper.RegisterDialogScript(Page); String subscriptionUrl = IsLiveSite ? "~/CMSModules/Reporting/LiveDialogs/EditSubscription.aspx?subscriptionId={0}&mode=liveedit" : "~/CMSModules/Reporting/Dialogs/EditSubscription.aspx?subscriptionId={0}&mode=edit"; act.OnClick = String.Format("modalDialog('{0}','Subscription',{1},{2});return false;", ResolveUrl(subscriptionUrl), ReportHelper.SUBSCRIPTION_WINDOW_WIDTH + 70, ReportHelper.SUBSCRIPTION_WINDOW_HEIGHT + 100); } ScriptHelper.RegisterClientScriptBlock(Page, typeof(String), "RefreshScript", ScriptHelper.GetScript("function refreshCurrentPage() {" + ControlsHelper.GetPostBackEventReference(btnPostback, String.Empty) + "}")); reportSubscriptions.WhereCondition = "(ReportSubscriptionUserID = " + UserID + ") AND (ReportSubscriptionSiteID = " + SiteID + ")"; reportSubscriptions.IsLiveSite = IsLiveSite; reportSubscriptions.ZeroRowsText = GetString("reports.userhasnosubscriptions"); reportSubscriptions.OnAction += new OnActionEventHandler(reportSubscriptions_OnAction); reportSubscriptions.Pager.DefaultPageSize = 10; }
/// <summary> /// Generates row with textboxes for new values /// </summary> private void GenerateNewRow() { // New Item tab TableRow trNew = new TableRow(); // Actions TableCell tnew = new TableCell(); tnew.CssClass = "unigrid-actions"; var imgNew = new CMSGridActionButton(); imgNew.OnClientClick = String.Format("addNewRow('{0}'); return false;", ClientID); imgNew.IconCssClass = "icon-plus"; imgNew.IconStyle = GridIconStyle.Allow; imgNew.ToolTip = GetString("xmleditor.createitem"); imgNew.ID = "add"; var imgOK = new CMSGridActionButton(); imgOK.IconCssClass = "icon-check-circle"; imgOK.IconStyle = GridIconStyle.Allow; imgOK.ID = "newok"; imgOK.ToolTip = GetString("xmleditor.additem"); var imgDelete = new CMSGridActionButton(); imgDelete.OnClientClick = String.Format("if (confirm('" + GetString("xmleditor.confirmcancel") + "')) cancelNewRow('{0}'); return false;", ClientID); imgDelete.IconCssClass = "icon-bin"; imgDelete.IconStyle = GridIconStyle.Critical; imgDelete.ID = "newcancel"; imgDelete.ToolTip = GetString("xmleditor.cancelnewitem"); tnew.Controls.Add(imgNew); tnew.Controls.Add(imgOK); tnew.Controls.Add(imgDelete); // Textboxes CMSTextBox txtNewName = new CMSTextBox(); txtNewName.ID = "utk_newkey"; CMSTextBox txtNewValue = new CMSTextBox(); txtNewValue.ID = "utv_newvalue"; txtNewValue.Width = Unit.Pixel(490); TableCell tcnew = new TableCell(); tcnew.Controls.Add(txtNewName); TableCell tcvnew = new TableCell(); tcvnew.Controls.Add(txtNewValue); trNew.Cells.Add(tnew); trNew.Cells.Add(tcnew); trNew.Cells.Add(tcvnew); tblData.Rows.Add(trNew); imgOK.OnClientClick = "if (validateCustomProperties($cmsj('#" + txtNewName.ClientID + "').val(),null))" + ControlsHelper.GetPostBackEventReference(tblData, "add") + " ;return false"; // Prevent load styles from control state imgDelete.AddCssClass("hidden"); imgOK.AddCssClass("hidden"); txtNewName.AddCssClass("hidden"); txtNewValue.AddCssClass("hidden"); txtNewValue.Text = String.Empty; txtNewName.Text = String.Empty; if (!isNewValid && RequestHelper.IsPostBack()) { txtNewName.Text = Request.Form[UniqueID + "$utk_newkey"]; txtNewValue.Text = Request.Form[UniqueID + "$utv_newvalue"]; txtNewValue.CssClass = String.Empty; txtNewName.CssClass = String.Empty; imgOK.RemoveCssClass("hidden"); imgDelete.RemoveCssClass("hidden"); imgNew.AddCssClass("hidden"); RegisterEnableScript(false); } }
private void HyperLink_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e) { ControlsHelper.OpenUrl(e.Uri.AbsoluteUri); }
protected void Page_Load(object sender, EventArgs e) { rightHeaderActions.ActionPerformed += RightHeaderActions_ActionPerformed; // Show info that scheduler is disabled if (!SchedulingHelper.EnableScheduler) { ShowWarning(GetString("scheduledtask.disabled")); } listElem.SiteID = SiteID; string editUrl = UIContextHelper.GetElementUrl("CMS.ScheduledTasks", GetElementName("EditTask"), true); editUrl = URLHelper.AddParameterToUrl(editUrl, "siteid", SiteID.ToString()); listElem.EditURL = editUrl; // New task action HeaderActions.AddAction(new HeaderAction { Text = GetString("Task_List.NewItemCaption"), RedirectUrl = String.Format(listElem.EditURL, 0) }); // Refresh action HeaderActions.AddAction(new HeaderAction { Text = GetString("General.Refresh"), OnClientClick = "RefreshGrid();" }); if (SiteInfo != null) { bool usesTimer = SchedulingHelper.UseAutomaticScheduler || !SchedulingHelper.RunSchedulerWithinRequest; if (usesTimer) { // Restart timer action rightHeaderActions.AddAction(new HeaderAction { Text = GetString("Task_List.Restart"), EventName = TASKS_RESTART_TIMER }); } // Run execution ASAP action rightHeaderActions.AddAction(new HeaderAction { Text = GetString("Task_List.RunNow"), EventName = TASKS_RUN, Enabled = SchedulingHelper.EnableScheduler && (!usesTimer || SchedulingTimer.TimerExists(SiteInfo.SiteName)), ButtonStyle = ButtonStyle.Default }); } // Reset action to the right rightHeaderActions.AddAction(new HeaderAction { Text = GetString("tasks.resetexecutions"), OnClientClick = "if (!confirm(" + ScriptHelper.GetLocalizedString("tasks.resetall") + ")) return false;", EventName = TASKS_RESET, ButtonStyle = ButtonStyle.Default }); // Force action buttons to cause full postback so that tasks can be properly executed in global.asax ControlsHelper.RegisterPostbackControl(listElem); ControlsHelper.RegisterPostbackControl(rightHeaderActions); if (ControlsHelper.CausedPostBack(btnRefresh)) { // Update content after refresh pnlUpdate.Update(); } else if (QueryHelper.GetBoolean("reseted", false)) { // Show reset confirmation after reset button action ShowConfirmation(GetString("task.executions.reseted")); } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (SubmissionInfo == null) { return; } CreateButtons(); HandleAsyncProgress(); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "ShowUploadSuccess", "function ShowUploadSuccess() { " + ControlsHelper.GetPostBackEventReference(btnShowMessage) + " }", true); }
/// <summary> /// Initializes the validation scripts /// </summary> /// <param name="url">URL of the page</param> private void InitializeScripts(string url) { ScriptHelper.RegisterScriptFile(Page, "Validation.js"); ScriptHelper.RegisterJQuery(Page); // Disable minification on URL if (txtCodeText.Language == LanguageEnum.CSS) { url = DocumentValidationHelper.DisableMinificationOnUrl(url); } RegisterModalPageScripts(); string script = @" function ResizeCodeArea() { var height = $cmsj(""#divContent"").height(); $cmsj(""#" + txtCodeText.ClientID + @""").parent().css(""height"", height - 20 + ""px""); $cmsj("".js-code-mirror-scroll"").css(""height"", height - 52 + ""px""); } $cmsj(window).resize(function(){ResizeCodeArea()}); $cmsj(document).ready(function(){setTimeout(""ResizeCodeArea()"",300);" + ((!RequestHelper.IsPostBack() && !String.IsNullOrEmpty(url)) ? "LoadHTMLToElement('" + hdnHTML.ClientID + "','" + url + "');" + ControlsHelper.GetPostBackEventReference(this, null) + ";" : "") + @"});$cmsj(""#divContent"").css(""overflow"", ""hidden""); "; ScriptManager managaer = ScriptManager.GetCurrent(Page); managaer.RegisterAsyncPostBackControl(this); // Register script for resizing and scroll bar remove ScriptHelper.RegisterStartupScript(this, typeof(string), "AreaResizeAndScrollBarRemover", ScriptHelper.GetScript(script)); }
void AboutViGEmLinkLabel_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { ControlsHelper.OpenUrl(((Control)sender).Text); }
/// <summary> /// OnInit event. /// </summary> protected override void OnInit(EventArgs e) { SiteID = QueryHelper.GetInteger("siteid", 0); if (File.Exists(HttpContext.Current.Request.MapPath(ResolveUrl(pathToGroupselector)))) { Control ctrl = LoadUserControl(pathToGroupselector); if (ctrl != null) { selectInGroups = ctrl as FormEngineUserControl; ctrl.ID = "selGroups"; ctrl = LoadUserControl(pathToGroupselector); selectNotInGroups = ctrl as FormEngineUserControl; ctrl.ID = "selNoGroups"; plcGroups.Visible = true; plcSelectInGroups.Controls.Add(selectInGroups); plcSelectNotInGroups.Controls.Add(selectNotInGroups); selectNotInGroups.SetValue("UseFriendlyMode", true); selectInGroups.IsLiveSite = false; selectInGroups.SetValue("UseFriendlyMode", true); selectNotInGroups.IsLiveSite = false; } } if (LicenseHelper.CheckFeature(RequestContext.CurrentDomain, FeatureEnum.LeadScoring) && ResourceSiteInfoProvider.IsResourceOnSite("CMS.Scoring", SiteContext.CurrentSiteName) && SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOnlineMarketing")) { Control ctrl = LoadUserControl(pathToScoreSelector); if (ctrl != null) { ctrl.ID = "selectScore"; scoreSelector = ctrl as FormEngineUserControl; if (scoreSelector != null) { plcUpdateContent.Controls.Add(scoreSelector); scoreSelector.SetValue("AllowAll", false); scoreSelector.SetValue("AllowEmpty", true); } } } else { plcScore.Visible = false; lblScore.AssociatedControlID = null; } if (CurrentMode == "online" && DisplayContacts) { if (DisplayScore && (scoreSelector != null)) { plcScore.Visible = true; } } // Initialize advanced filter dropdownlists if (!RequestHelper.IsPostBack()) { InitAllAnyDropDown(drpTypeSelectInRoles); InitAllAnyDropDown(drpTypeSelectNotInRoles); InitAllAnyDropDown(drpTypeSelectInGroups); InitAllAnyDropDown(drpTypeSelectNotInGroups); // Init lock account reason DDL drpLockReason.Items.Add(new ListItem(GetString("General.selectall"), "")); ControlsHelper.FillListControlWithEnum <UserAccountLockEnum>(drpLockReason, "userlist.account"); } base.OnInit(e); plcDisplayAnonymous.Visible = ContactManagementPermission && SessionManager.StoreOnlineUsersInDatabase && EnableDisplayingGuests; if (!RequestHelper.IsPostBack()) { chkDisplayAnonymous.Checked = DisplayGuestsByDefault; } siteSelector.DropDownSingleSelect.AutoPostBack = true; }
protected void Page_Load(object sender, EventArgs e) { if (WorkflowStepID <= 0) { StopProcessing = true; return; } EditedObject = WorkflowStep; if (SourcePointGuid != null) { ShowInformation(GetString("workflowsteppoint.securityInfo")); } else if (WorkflowStep.StepAllowBranch) { ShowInformation(GetString("workflowstep.securityInfo")); } if (Workflow.IsAutomation) { headRoles.ResourceString = "processstep.rolessecurity"; headUsers.ResourceString = "processstep.userssecurity"; } else { headRoles.ResourceString = (SourcePointGuid == null) ? "workflowstep.rolessecurity" : "workflowsteppoint.rolessecurity"; headUsers.ResourceString = (SourcePointGuid == null) ? "workflowstep.userssecurity" : "workflowsteppoint.userssecurity"; } // Set site selector siteSelector.AllowGlobal = true; siteSelector.DropDownSingleSelect.AutoPostBack = true; siteSelector.AllowAll = false; siteSelector.OnlyRunningSites = false; siteSelector.UniSelector.OnSelectionChanged += UniSelector_OnSelectionChanged; usRoles.OnSelectionChanged += usRoles_OnSelectionChanged; usUsers.OnSelectionChanged += usUsers_OnSelectionChanged; usRoles.ObjectType = RoleInfo.OBJECT_TYPE; usUsers.ObjectType = UserInfo.OBJECT_TYPE; rbRoleType.SelectedIndexChanged += rbRoleType_SelectedIndexChanged; rbUserType.SelectedIndexChanged += rbUserType_SelectedIndexChanged; if (!RequestHelper.IsPostBack()) { siteId = SiteID; siteSelector.Value = siteId; string resPrefix = (SourcePointGuid == null) ? "workflowstep" : "workflowsteppoint"; ControlsHelper.FillListControlWithEnum <WorkflowStepSecurityEnum>(rbRoleType, resPrefix + ".security"); ControlsHelper.FillListControlWithEnum <WorkflowStepSecurityEnum>(rbUserType, resPrefix + ".usersecurity"); rbRoleType.SelectedValue = ((int)RolesSecurity).ToString(); rbUserType.SelectedValue = ((int)UsersSecurity).ToString(); } else { // Make sure the current site is always selected int selectedId = ValidationHelper.GetInteger(siteSelector.Value, 0); if (selectedId == 0) { selectedId = SiteID; siteSelector.Value = SiteID; } siteId = selectedId; } // If global role selected - set siteID to 0 if (siteSelector.GlobalRecordValue == siteId.ToString()) { siteId = 0; } string siteIDWhere = (siteId == 0) ? "SiteID IS NULL" : "SiteID = " + siteId; usRoles.WhereCondition = siteIDWhere + " AND RoleGroupID IS NULL"; usUsers.WhereCondition = "(UserIsHidden = 0 OR UserIsHidden IS NULL)"; // Get the active roles for this site string where = String.Format("[StepID] = {0} AND [StepSourcePointGuid] {1}", WorkflowStepID, (SourcePointGuid == null ? "IS NULL" : String.Format("= '{0}'", SourcePointGuid.ToString()))); var roles = WorkflowStepRoleInfoProvider.GetWorkflowStepRoles(where, null, 0, "RoleID").Select <WorkflowStepRoleInfo, string>(r => r.RoleID.ToString()); currentRoles = string.Join(";", roles.ToArray()); // Get the active users for this site var users = WorkflowStepUserInfoProvider.GetWorkflowStepUsers(where, null, 0, "UserID").Select <WorkflowStepUserInfo, string>(u => u.UserID.ToString()); currentUsers = string.Join(";", users.ToArray()); // Init lists when security type changes if (!RequestHelper.IsPostBack() || ControlsHelper.GetPostBackControlID(Page).StartsWithCSafe(rbRoleType.UniqueID) || ControlsHelper.GetPostBackControlID(Page).StartsWithCSafe(rbUserType.UniqueID)) { usRoles.Value = currentRoles; usUsers.Value = currentUsers; } }
/// <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", "$j('#" + 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; } }
/// <summary> /// Register required javascript functions /// </summary> private void InitScript() { StringBuilder sbScript = new StringBuilder(); sbScript.Append("function RefreshRelatedContent_", ClientID, "(){if(window.RefreshContent != null) { window.RefreshContent(); }\n"); if (RegisterReloadHeaderScript) { sbScript.Append("if(parent.frames[0] && parent.frames[0].ReloadAndSetTab) {parent.frames[0].ReloadAndSetTab(escape('selecttab|##versioningtab##'));}\n"); } sbScript.Append("}\n"); sbScript.Append("function RefreshVersions_", ClientID, "(){var button = document.getElementById('", btnRefresh.ClientID, "'); if(button){button.click();}}"); sbScript.Append("function ContextVersionAction_", gridHistory.ClientID, @"(action, versionId) { document.getElementById('", hdnValue.ClientID, @"').value = action + ';' + versionId;", ControlsHelper.GetPostBackEventReference(btnHidden), ";}"); // Register required js to reload related content ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ReloadContent_" + ClientID, ScriptHelper.GetScript(sbScript.ToString())); }
/// <summary> /// Gets the page javascripts. /// </summary> private string GetPageScripts() { // Generate toolbar scripts StringBuilder sb = new StringBuilder(); sb.Append( @"var wptIsMinimizedCookie = '", CookieName.WebPartToolbarMinimized, @"'; var wptIsRTL = ", (uiCultureRTL ? "true" : "false"), @"; var wpLoadingMoreString = " + ScriptHelper.GetLocalizedString("general.loading") + @"; function wptSetupSearch() { $cmsj('#", txtSearch.ClientID, @"') .keypress(function (e) { window.clearTimeout(wptFilterWebPartsTimer); return wptProceedSpecialKeys(this, e); }) .keyup(function (e) { var ret = wptProceedSpecialKeys(this, e); wptFilterWebParts(this); return ret; }); } function wptFilterWebParts(txtBoxElem) { window.clearTimeout(wptFilterWebPartsTimer); wptFilterWebPartsTimer = window.setTimeout(function () { var searchText = txtBoxElem.value.toLowerCase(); UpdateRefreshPageUrlParam('", SEARCH_TEXT_CODE, @"', searchText.replace(/ /g,'", SPACE_REPLACEMENT, @"')); wptFilter(searchText); wptInit(true); wptReloadScrollPanel(true); }, 200); } function wptFilterAfterPostBack(){ wptFilter(document.getElementById('", txtSearch.ClientID, @"').value); wptReloadScrollPanel(true); } function wptReloadScrollPanel(forceReload) { scrollPanelInit('", scrollPanel.ClientID, @"', forceReload); } function wptCategoryChanged() { $cmsj('#" + txtSearch.ClientID + @"').val(''); // Remove all tooltip temporary nodes $cmsj('.WPTTT').remove(); ", ControlsHelper.GetPostBackEventReference(hdnUpdater, CATEGORY_CHANGED_CODE), @"; } "); if (QueryHelper.Contains(SEARCH_TEXT_CODE)) { // Filter the web parts if the search text is set sb.Append("$cmsj(document).ready(function () { wptFilterWebParts(document.getElementById('", txtSearch.ClientID, @"')); })"); } return(sb.ToString()); }
/// <summary> /// Handles the PreRender event of the Page control. /// </summary> protected void Page_PreRender(object sender, EventArgs e) { if (QueryHelper.Contains(SEARCH_TEXT_CODE)) { // Get the search text from the current url txtSearch.Text = HttpUtility.UrlDecode(URLHelper.GetUrlParameter(RequestContext.CurrentURL, SEARCH_TEXT_CODE).Replace(SPACE_REPLACEMENT, " ")); // Hide the scrollPanel when the search filter will be applied (skip this when changing displayed category) if (Request.Form[Page.postEventArgumentID] != CATEGORY_CHANGED_CODE) { scrollPanel.Style.Add("display", "none"); } } // Add the javascript file and scripts into the page ScriptHelper.RegisterJQueryCookie(Page); ScriptHelper.RegisterScriptFile(Page, "DesignMode/WebPartToolbar.js"); ScriptHelper.RegisterScriptFile(Page, "~/CMSScripts/jquery/jquery-url.js"); ScriptHelper.RegisterStartupScript(this, typeof(string), "wptPageScripts", ScriptHelper.GetScript(GetPageScripts() + @" wptSetupSearch(); var WPTImgBaseSrc = '""" + ResolveUrl("~/CMSPages/GetMetaFile.aspx?maxsidesize=64&fileguid=") + @"'; ")); // Adjust the page to accommodate the web part toolbar scrollPanel.Layout = RepeatDirection.Vertical; scrollPanel.IsRTL = uiCultureRTL; // Set the selected category if (!RequestHelper.IsPostBack()) { if (SelectedCategory == CATEGORY_ALL) { // Select the "All web parts" category by index (value for the "All" category is not known) categorySelector.DropDownListControl.SelectedIndex = 1; } else { categorySelector.DropDownListControl.SelectedValue = SelectedCategory; } } else { SelectedCategory = categorySelector.DropDownListControl.SelectedValue; // Refresh scroll panel ScriptHelper.RegisterClientScriptBlock(pnlU, typeof(string), "wptRefreshScrollPanel", "$cmsj(document).ready(function () { wptInit(true); wptReloadScrollPanel(true); wptLoadWebpartImages(); });", true); } // Load the web part items according to the selected category and the search text condition LoadWebParts(false); // Register script for web part lazy load if (limitItems) { const string appearScript = @" $cmsj(document).ready( function () { $cmsj('.AppearElement').appear( function () { $cmsj(this).html(wpLoadingMoreString); DoToolbarPostBack(); }); });"; string postBackScript = @" function DoToolbarPostBack(){ " + ControlsHelper.GetPostBackEventReference(btnLoadMore, "") + @" };"; ScriptHelper.RegisterStartupScript(Page, typeof(string), "DoToolbarPostback", ScriptHelper.GetScript(appearScript + postBackScript)); } bool isMinimized = ValidationHelper.GetBoolean(CookieHelper.GetValue(CookieName.WebPartToolbarMinimized), false); if (isMinimized) { // Renew the cookie CookieHelper.SetValue(CookieName.WebPartToolbarMinimized, "true", "/", DateTime.Now.AddDays(31), false); // Hide the expanded web part toolbar pnlMaximized.Style.Add("display", "none"); } else { // Register the OnLoad javascript for the expanded bar ltrScript.Text = ScriptHelper.GetScript("function pageLoad(sender, args) { wptInit(true); }"); // Hide the minimized toolbar pnlMinimized.Style.Add("display", "none"); } ScriptHelper.RegisterJQueryAppear(Page); }
void CheckAll() { lock (IssueListLock) { if (IssueList == null) { IssueList = new List <WarningItem>(); IssueList.Add(new ExeFileIssue()); IssueList.Add(new DirectXIssue()); IssueList.Add(new LeakDetectorIssue()); IssueList.Add(new MdkIssue()); IssueList.Add(new ArchitectureIssue()); IssueList.Add(new GdbFileIssue()); IssueList.Add(new IniFileIssue()); IssueList.Add(new DllFileIssue()); foreach (var item in IssueList) { item.FixApplied += Item_FixApplied; } } } bool clearRest = false; foreach (var issue in IssueList) { if (clearRest) { issue.Severity = IssueSeverity.None; } else { issue.Check(); } if (issue.Severity == IssueSeverity.Critical) { clearRest = true; } UpdateWarning(issue); } ControlsHelper.BeginInvoke(() => { var update2 = MainForm.Current.update2Enabled; if (Warnings.Count > 0) { // If not visible and must not ignored then... if (!Visible && !IgnoreAll) { StartPosition = FormStartPosition.CenterParent; var result = ShowDialog(MainForm.Current); // If ignore button was used then... if (IgnoreAll) { // If critical issues remaining then... if (Warnings.Any(x => x.Severity == IssueSeverity.Critical)) { // Close application. MainForm.Current.Close(); } // Update 2 haven't ran yet then.. else if (!update2.HasValue) { MainForm.Current.update2Enabled = true; } } } } else { if (Visible) { DialogResult = DialogResult.OK; } if (!update2.HasValue) { MainForm.Current.update2Enabled = true; } } }); }
protected void Page_Load(object sender, EventArgs e) { // Attach events btnAutoIndent.Click += btnAutoIndent_Click; btnDelete.Click += btnDelete_Click; btnIndent.Click += btnIndent_Click; btnUnindent.Click += btnUnindent_Click; btnChangeOperator.Click += btnChangeOperator_Click; btnChangeParameter.Click += btnChangeParameter_Click; btnMove.Click += btnMove_Click; btnCancel.Click += btnCancel_Click; btnSetParameter.Click += btnSetParameter_Click; btnViewCode.Click += btnViewCode_Click; btnAddClause.Click += btnAddClause_Click; btnClearAll.Click += btnClearAll_Click; txtFilter.TextChanged += btnFilter_Click; btnFilter.Text = GetString("general.filter"); btnSetParameter.Text = GetString("macros.macrorule.setparameter"); btnCodeOK.Text = GetString("general.ok"); btnCancel.Text = GetString("general.cancel"); btnIndent.ScreenReaderDescription = btnIndent.ToolTip = GetString("macros.macrorule.indent"); btnUnindent.ScreenReaderDescription = btnUnindent.ToolTip = GetString("macros.macrorule.unindent"); btnAutoIndent.ScreenReaderDescription = btnAutoIndent.ToolTip = GetString("macros.macrorule.autoindent"); btnDelete.ScreenReaderDescription = btnDelete.ToolTip = GetString("general.delete"); btnClearAll.ScreenReaderDescription = btnClearAll.ToolTip = GetString("macro.macrorule.clearall"); btnViewCode.ScreenReaderDescription = btnViewCode.ToolTip = GetString("macros.macrorule.viewcode"); btnIndent.OnClientClick = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; }"; btnUnindent.OnClientClick = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; }"; btnDelete.OnClientClick = "if (isNothingSelected()) { alert(" + ScriptHelper.GetString(GetString("macros.macrorule.nothingselected")) + "); return false; } else { if (!confirm('" + GetString("macros.macrorule.deleteconfirmation") + "')) { return false; }}"; btnAutoIndent.OnClientClick = "if (!confirm(" + ScriptHelper.GetString(GetString("macros.macrorule.deleteautoindent")) + ")) { return false; }"; btnClearAll.OnClientClick = "if (!confirm(" + ScriptHelper.GetString(GetString("macros.macrorule.clearall.confirmation")) + ")) { return false; }"; lstRules.Attributes.Add("ondblclick", ControlsHelper.GetPostBackEventReference(btnAddClause, null)); pnlViewCode.Visible = false; // Basic form formElem.SubmitButton.Visible = false; formElem.SiteName = SiteContext.CurrentSiteName; titleElem.TitleText = GetString("macros.macrorule.changeparameter"); btnAddaClause.ToolTip = GetString("macros.macrorule.addclause"); btnAddaClause.Click += btnAddClause_Click; // Drop cue Panel pnlCue = new Panel(); pnlCue.ID = "pnlCue"; pnlCue.CssClass = "MacroRuleCue"; pnlCondtion.Controls.Add(pnlCue); pnlCue.Controls.Add(new LiteralControl(" ")); pnlCue.Style.Add("display", "none"); // Create drag and drop extender extDragDrop = new DragAndDropExtender(); extDragDrop.ID = "extDragDrop"; extDragDrop.TargetControlID = pnlCondtion.ID; extDragDrop.DragItemClass = "MacroRule"; extDragDrop.DragItemHandleClass = "MacroRuleHandle"; extDragDrop.DropCueID = pnlCue.ID; extDragDrop.OnClientDrop = "OnDropRule"; pnlCondtion.Controls.Add(extDragDrop); // Load the rule set if (!RequestHelper.IsPostBack()) { if (ShowGlobalRules || !string.IsNullOrEmpty(RuleCategoryNames)) { string where = (ShowGlobalRules ? "MacroRuleResourceName IS NULL OR MacroRuleResourceName = ''" : ""); // Append rules module name condition if (!string.IsNullOrEmpty(RuleCategoryNames)) { bool appendComma = false; StringBuilder sb = new StringBuilder(); string[] names = RuleCategoryNames.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (string n in names) { string name = "'" + SqlHelper.GetSafeQueryString(n.Trim(), false) + "'"; if (appendComma) { sb.Append(","); } sb.Append(name); appendComma = true; } where = SqlHelper.AddWhereCondition(where, "MacroRuleResourceName IN (" + sb.ToString() + ")", "OR"); } // Append require context condition switch (DisplayRuleType) { case 1: where = SqlHelper.AddWhereCondition(where, "MacroRuleRequiresContext = 0", "AND"); break; case 2: where = SqlHelper.AddWhereCondition(where, "MacroRuleRequiresContext = 1", "AND"); break; } // Select only enabled rules where = SqlHelper.AddWhereCondition(where, "MacroRuleEnabled = 1"); DataSet ds = MacroRuleInfoProvider.GetMacroRules(where, "MacroRuleDisplayName", 0, "MacroRuleID, MacroRuleDisplayName, MacroRuleDescription, MacroRuleRequiredData"); if (!DataHelper.DataSourceIsEmpty(ds)) { MacroResolver resolver = MacroResolverStorage.GetRegisteredResolver(ResolverName); foreach (DataRow dr in ds.Tables[0].Rows) { bool add = true; if (resolver != null) { // Check the required data, all specified data have to be present in the resolver string requiredData = ValidationHelper.GetString(dr["MacroRuleRequiredData"], ""); if (!string.IsNullOrEmpty(requiredData)) { string[] required = requiredData.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries); foreach (var req in required) { if (!resolver.IsDataItemAvailable(req)) { add = false; break; } } } } if (add) { var ruleId = dr["MacroRuleID"].ToString(); ListItem item = new ListItem(dr["MacroRuleDisplayName"].ToString(), ruleId); lstRules.Items.Add(item); // Save the tooltip RulesTooltips[ruleId] = ResHelper.LocalizeString(ValidationHelper.GetString(dr["MacroRuleDescription"], "")); } } } if (lstRules.Items.Count > 0) { lstRules.SelectedIndex = 0; } } } // Make sure that one user click somewhere else than to any rule, selection will disappear pnlCondtion.Attributes["onclick"] = "if (!doNotDeselect && !isCTRL) { $cmsj('.RuleSelected').removeClass('RuleSelected'); document.getElementById('" + hdnSelected.ClientID + "').value = ';'; }; doNotDeselect = false;"; LoadFormDefinition(false); // Set the default button for parameter edit dialog so that ENTER key works to submit the parameter value pnlParameterPopup.DefaultButton = btnSetParameter.ID; // Ensure correct edit dialog show/hide (because of form controls which cause postback) btnSetParameter.OnClientClick = "HideParamEdit();"; btnCancel.OnClientClick = "HideParamEdit();"; if (ShowParameterEdit) { mdlDialog.Show(); } if (!string.IsNullOrEmpty(hdnScroll.Value)) { // Preserve scroll position ScriptHelper.RegisterStartupScript(this.Page, typeof(string), "MacroRulesScroll", "setTimeout('setScrollPosition()', 100);", true); } // Add tooltips to the rules in the list foreach (ListItem item in lstRules.Items) { if (RulesTooltips.ContainsKey(item.Value)) { item.Attributes.Add("title", RulesTooltips[item.Value]); } } }
protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (StopProcessing || String.IsNullOrEmpty(ServiceUrl)) { // Do nothing StopProcessing = true; } else if (!RequestHelper.IsPostBack()) { // This message is hidden by javascript as soon as possible ShowWarning(ResHelper.GetString("webservices.checker.initialmessage")); // Request javascript proxy directly to avoid logon screen redirection string url = URLHelper.GetAbsoluteUrl(ServiceUrl.EndsWithCSafe("/js") ? ServiceUrl : ServiceUrl.TrimEnd('/') + "/js"); // Prepare the script StringBuilder actionScript = new StringBuilder(); actionScript.Append(@" function CheckService(){ var xmlHttp = new XMLHttpRequest(); xmlHttp.open('GET', ", ScriptHelper.GetString(url), @", false); xmlHttp.send(); return xmlHttp.status; } function CheckFailed(label, message, status){ if (", (OnCheckFailed != null).ToString().ToLowerCSafe(), @") { ", ControlsHelper.GetPostBackEventReference(this, "##PARAM##").Replace("'##PARAM##'", "status"), @"; } else if ((label != null) && (label.length > 0)) { label.empty(); label.append(message); label.show(); } } function PerformServiceCheck(){ var label = $cmsj('#", MessagesPlaceHolder.ClientID, ClientIDSeparator, MessagesPlaceHolder.WarningLabel.ID, @"'); label.hide(); var status = CheckService(); switch (status) { case 404: CheckFailed(label, ", ScriptHelper.GetString(NotFoundText), @", status); break; case 401: CheckFailed(label, ", ScriptHelper.GetString(NotAuthorizedText), @", status); break; case 403: CheckFailed(label, ", ScriptHelper.GetString(DisabledText), @", status); break; case 500: CheckFailed(label, ", ScriptHelper.GetString(ServerErrorText), @", status); break; default: if (", MessagesPlaceHolder.UseRelativePlaceHolder.ToString().ToLowerCSafe(), @") { label.parent().hide(); } } }"); ScriptHelper.RegisterJQuery(Page); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "WebServiceChecker_" + ClientID, ScriptHelper.GetScript(actionScript.ToString())); ScriptHelper.RegisterStartupScript(Page, typeof(string), "PerformServiceCheck_" + ClientID, "PerformServiceCheck();", true); } }
/// <summary> /// Registers needed JS methods for operating the designer. /// </summary> private void RegisterScriptMethods() { StringBuilder sb = new StringBuilder(); sb.Append(@" var doNotDeselect = false; function SelectRule(path, currentElem) { doNotDeselect = true; if (currentElem == null) { return; } var hidden = document.getElementById('", hdnSelected.ClientID, @"'); if (hidden != null) { if (!isCTRL) { // Deselect all rules when CTRL is not pressed $cmsj('.RuleSelected').removeClass('RuleSelected'); hidden.value = ''; } var orig = hidden.value; var newText = hidden.value.replace(';' + path + ';', ';'); if (orig.length != newText.length) { // If the rule was present it means it was selected, so deselect the item currentElem.removeClass('RuleSelected'); } else { // If the rule was not selected before, select it and add to the list of selected currentElem.addClass('RuleSelected'); if (newText == '') { newText = ';' + path + ';'; } else { newText += path + ';'; } } hidden.value = newText; } } function setScrollPosition() { var hdnScroll = document.getElementById('", hdnScroll.ClientID, @"'); var scrollDiv = document.getElementById('scrollDiv'); if ((hdnScroll != null) && (scrollDiv != null)) { if (hdnScroll.value != '') { scrollDiv.scrollTop = hdnScroll.value; } } } function isNothingSelected() { // If nothing is selected, do not allow to use buttons such as delete, indent, unindent var newText = document.getElementById('", hdnSelected.ClientID, @"').value; return (newText == '') || (newText == ';') || (newText == ';;'); } "); sb.Append( @" var isCTRL = false; $cmsj(document).keyup(function(event) { if (event.which == 17) { isCTRL = false; } }).keydown(function(event) { if (event.which == 17) { isCTRL = true; } }); "); sb.Append(string.Format( @"var targetPosition = new Array(); function OnDropRule(source, target) {{ var item = target.get_droppedItem(); var targetPos = target.get_position(); var hidden = document.getElementById('{0}') if (hidden != null) {{ hidden.value = item.id + ';' + targetPosition[targetPos]; {1}; }} }}", hdnParam.ClientID, ControlsHelper.GetPostBackEventReference(btnMove, null))); sb.Append( @" if (window.recursiveDragAndDrop) { window.recursiveDragAndDrop = true; } if (window.lastDragAndDropBehavior) { lastDragAndDropBehavior._initializeDraggableItems(); }"); sb.Append( @" function ActivateBorder(elementId, className) { var e = document.getElementById(elementId); if (e != null) { e.className = e.className.replace(className, className + 'Active'); } } function DeactivateBorder(elementId, className) { var e = document.getElementById(elementId); if (e != null) { e.className = e.className.replace(className + 'Active', className); } } "); sb.Append( @"function ChangeOperator(path, operator) { document.getElementById('", hdnOpSelected.ClientID, @"').value = path; document.getElementById('", hdnParam.ClientID, @"').value = operator; ", ControlsHelper.GetPostBackEventReference(btnChangeOperator, null), @" }"); sb.Append( @"function ChangeParamValue(path, parameter) { document.getElementById('", hdnParamSelected.ClientID, @"').value = path; document.getElementById('", hdnParam.ClientID, @"').value = parameter; ", ControlsHelper.GetPostBackEventReference(btnChangeParameter, null), @" }"); sb.Append( @"function InitDesignerAreaSize() { $cmsj('#", pnlCondtion.ClientID, @"').height(document.body.clientHeight - 295); $cmsj('#", lstRules.ClientID, @"').height(document.body.clientHeight - 287); $cmsj('.add-clause button').css('margin-top', (document.body.clientHeight - 164) / 2); } $cmsj(window).resize(InitDesignerAreaSize); $cmsj(document).ready(InitDesignerAreaSize); "); sb.Append( @"function HideParamEdit() { document.getElementById('" + hdnParamEditShown.ClientID + @"').value = '0'; } "); sb.Append( @"$cmsj('#scrollDiv').scroll(function() { document.getElementById('" + hdnScroll.ClientID + @"').value = document.getElementById('scrollDiv').scrollTop; });"); ScriptHelper.RegisterJQuery(this.Page); ScriptHelper.RegisterClientScriptBlock(this.Page, typeof(string), "MacroRuleDesigner", ScriptHelper.GetScript(sb.ToString())); }
protected void Page_Load(object sender, EventArgs e) { ucSelectString.Scope = ReportInfo.OBJECT_TYPE; pnlConnectionString.Visible = MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("cms.reporting", "SetConnectionString"); Title = "Report General"; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ReloadPage", ScriptHelper.GetScript("function ReloadPage() { \n" + Page.ClientScript.GetPostBackEventReference(btnHdnReload, null) + "}")); reportId = QueryHelper.GetInteger("reportId", 0); // control initializations rfvReportDisplayName.ErrorMessage = GetString("Report_New.EmptyDisplayName"); rfvReportName.ErrorMessage = GetString("Report_New.EmptyCodeName"); lblReportDisplayName.Text = GetString("Report_New.DisplayNameLabel"); lblReportName.Text = GetString("Report_New.NameLabel"); lblReportCategory.Text = GetString("Report_General.CategoryLabel"); lblLayout.Text = GetString("Report_General.LayoutLabel"); lblGraphs.Text = GetString("Report_General.GraphsLabel") + ":"; lblHtmlGraphs.Text = GetString("Report_General.HtmlGraphsLabel") + ":"; lblTables.Text = GetString("Report_General.TablesLabel") + ":"; lblValues.Text = GetString("Report_General.TablesValues") + ":"; lblReportAccess.Text = GetString("Report_General.ReportAccessLabel"); actionsElem.ActionsList.Add(new SaveAction()); actionsElem.ActionPerformed += actionsElem_ActionPerformed; AttachmentTitle.TitleText = GetString("general.attachments"); attachmentList.AllowPasteAttachments = true; attachmentList.ObjectID = reportId; attachmentList.ObjectType = ReportInfo.OBJECT_TYPE; attachmentList.Category = ObjectAttachmentsCategories.LAYOUT; // Get report info ri = ReportInfoProvider.GetReportInfo(reportId); if (ri == null) { URLHelper.SeeOther(AdministrationUrlHelper.GetInformationUrl("editedobject.notexists")); } if (!RequestHelper.IsPostBack()) { LoadData(); } htmlTemplateBody.AutoDetectLanguage = false; htmlTemplateBody.DefaultLanguage = Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName; htmlTemplateBody.EditorAreaCSS = ""; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ReportingHTML", ScriptHelper.GetScript(" var reporting_htmlTemplateBody = '" + htmlTemplateBody.ClientID + "'")); // initialize item list controls ilGraphs.Report = ri; ilTables.Report = ri; ilValues.Report = ri; ilHtmlGraphs.Report = ri; ilGraphs.EditUrl = "ReportGraph_Edit.aspx"; ilTables.EditUrl = "ReportTable_Edit.aspx"; ilValues.EditUrl = "ReportValue_Edit.aspx"; ilHtmlGraphs.EditUrl = "ReportHtmlGraph_Edit.aspx"; ilGraphs.ItemType = ReportItemType.Graph; ilTables.ItemType = ReportItemType.Table; ilValues.ItemType = ReportItemType.Value; ilHtmlGraphs.ItemType = ReportItemType.HtmlGraph; // Refresh script string script = "function RefreshWOpener(w) { if (w.refreshPageOnClose){ " + ControlsHelper.GetPostBackEventReference(this, "arg") + " }}"; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ReportingRefresh", ScriptHelper.GetScript(script)); }
protected void Page_Load(object sender, EventArgs e) { // Register JQuery ScriptHelper.RegisterJQuery(Page); SelectSite.StopProcessing = !DisplaySiteSelector; plcSelectSite.Visible = DisplaySiteSelector; bool hasSelected = SelectedCategory != null; // Ensure correct object type for clonning if (hasSelected) { gridSubCategories.ObjectType = SelectedCategory.CategoryIsPersonal ? PredefinedObjectType.USERCATEGORY : PredefinedObjectType.CATEGORY; } // Check if selection is valid CheckSelection(); // Stop processing grids, when no category selected gridDocuments.UniGrid.StopProcessing = !hasSelected; gridDocuments.UniGrid.FilterForm.StopProcessing = !hasSelected; gridDocuments.UniGrid.Visible = hasSelected; gridSubCategories.StopProcessing = !hasSelected; gridSubCategories.FilterForm.StopProcessing = !hasSelected; gridSubCategories.Visible = hasSelected; // Left from category edit forms is jQuery tab catEdit.MessagesPlaceHolder.OffsetX = 253; catNew.MessagesPlaceHolder.OffsetX = 253; if (!StopProcessing) { if (!URLHelper.IsPostback()) { // Start in mode of creating new category when requested if (StartInCreatingMode) { SwitchToNew(); } else { SwitchToInfo(); } } // Use images according to culture if (CultureHelper.IsUICultureRTL()) { treeElemG.LineImagesFolder = GetImageUrl("RTL/Design/Controls/Tree", false, false); treeElemP.LineImagesFolder = GetImageUrl("RTL/Design/Controls/Tree", false, false); } else { treeElemG.LineImagesFolder = GetImageUrl("Design/Controls/Tree", false, false); treeElemP.LineImagesFolder = GetImageUrl("Design/Controls/Tree", false, false); } treeElemG.StopProcessing = !DisplaySiteCategories; treeElemP.StopProcessing = !DisplayPersonalCategories; // Prepare node templates treeElemP.SelectedNodeTemplate = treeElemG.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME####NODEID##\" class=\"ContentTreeItem ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME####NODEID##'); if (NodeSelected) { NodeSelected(##NODEID##, ##PARENTID##); return false;}\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>"; treeElemP.NodeTemplate = treeElemG.NodeTemplate = "<span id=\"node_##NODECODENAME####NODEID##\" class=\"ContentTreeItem\" onclick=\"SelectNode('##NODECODENAME####NODEID##'); if (NodeSelected) { NodeSelected(##NODEID##, ##PARENTID##); return false;}\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>"; // Init tree provider objects treeElemG.ProviderObject = CreateTreeProvider(SiteID, 0); treeElemP.ProviderObject = CreateTreeProvider(0, UserID); // Expand first level by default treeElemP.ExpandPath = treeElemG.ExpandPath = "/"; catNew.CategoryID = 0; catNew.AllowCreateOnlyGlobal = SiteID == 0; catNew.SiteID = SiteID; CategoryInfo categoryObj = SelectedCategory; if (categoryObj != null) { catEdit.UserID = categoryObj.CategoryUserID; catEdit.Category = categoryObj; catNew.UserID = categoryObj.CategoryUserID; catNew.ParentCategory = categoryObj; gridDocuments.SiteName = filterDocuments.SelectedSite; PreselectCategory(categoryObj, false); } else { catNew.UserID = CustomCategoriesRootSelected ? UserID : 0; catNew.SiteID = CustomCategoriesRootSelected ? 0 : SiteID; catNew.ParentCategoryID = 0; } // Create root node for global and site categories string rootIcon = ""; string rootName = "<span class=\"TreeRoot\">" + GetString("categories.rootcategory") + "</span>"; string rootText = treeElemG.ReplaceMacros(treeElemG.NodeTemplate, 0, 6, rootName, rootIcon, 0, null, null); rootText = rootText.Replace("##NODECUSTOMNAME##", rootName); rootText = rootText.Replace("##NODECODENAME##", "CategoriesRoot"); rootText = rootText.Replace("##PARENTID##", CATEGORIES_ROOT_PARENT_ID.ToString()); treeElemG.SetRoot(rootText, "NULL", GetImageUrl("Objects/CMS_Category/list.png"), null, null); // Create root node for personal categories rootName = "<span class=\"TreeRoot\">" + GetString("categories.rootpersonalcategory") + "</span>"; rootText = ""; rootText = treeElemP.ReplaceMacros(treeElemP.NodeTemplate, 0, 6, rootName, rootIcon, 0, null, null); rootText = rootText.Replace("##NODECUSTOMNAME##", rootName); rootText = rootText.Replace("##NODECODENAME##", "PersonalCategoriesRoot"); rootText = rootText.Replace("##PARENTID##", PERSONAL_CATEGORIES_ROOT_PARENT_ID.ToString()); treeElemP.SetRoot(rootText, "NULL", GetImageUrl("Objects/CMS_Category/list.png"), null, null); // Prepare post abck reerence for selecting nodes and confirmation message string postBackRef = ControlsHelper.GetPostBackEventReference(hdnButton, ""); string script = "var menuHiddenId = '" + hidSelectedElem.ClientID + "';"; script += "function deleteConfirm() {"; script += "return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + ");"; script += "}"; script += "function RaiseHiddenPostBack(){" + postBackRef + ";}"; ltlScript.Text = ScriptHelper.GetScript(script); } }
void UpdateIgnoreButton() { var enabled = MainDataGrid.SelectedItems.Count > 0; ControlsHelper.SetEnabled(IgnoreButton, enabled); }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { // Do nothing } else { if (SettingsKeyProvider.GetBoolValue(CMSContext.CurrentSiteName + ".CMSEnableWindowsLiveID")) { string siteName = CMSContext.CurrentSiteName; if (!string.IsNullOrEmpty(siteName)) { // Get LiveID settings string appId = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationID"); string secret = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationSecret"); if (!WindowsLiveLogin.UseServerSideAuthorization) { // Add windows live ID script ScriptHelper.RegisterClientScriptInclude(Page, typeof(string), "WLScript", "https://js.live.net/v5.0/wl.js"); // Add login functions String loginLiveIDClientScript = @" function signUserIn() { var scopesArr = ['wl.signin']; WL.login({ scope: scopesArr }); } function refreshLiveID(param) { " + ControlsHelper.GetPostBackEventReference(btnHidden, "#").Replace("'#'", "param") + @" } "; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ClientInitLiveIDScript", ScriptHelper.GetScript(loginLiveIDClientScript)); } // Check valid Windows LiveID parameters if ((appId == string.Empty) || (secret == string.Empty)) { lblError.Visible = true; lblError.Text = GetString("liveid.incorrectsettings"); return; } WindowsLiveLogin wll = new WindowsLiveLogin(appId, secret); // If user is already authenticated if (CMSContext.CurrentUser.IsAuthenticated()) { // If signout should be visible and user has LiveID registered if ((ShowSignOut) && (!String.IsNullOrEmpty(CMSContext.CurrentUser.UserSettings.WindowsLiveID))) { // Get data from auth cookie string[] userData = AuthenticationHelper.GetUserDataFromAuthCookie(); // Check if user has truly logged in by LiveID if ((userData != null) && (Array.IndexOf(userData, "liveidlogin") >= 0)) { string navUrl = wll.GetLogoutUrl(); // If text is set use text/button link if (!string.IsNullOrEmpty(SignOutText)) { // Button link if (ShowAsButton) { btnSignOut.CommandArgument = navUrl; btnSignOut.Text = SignOutText; btnSignOut.Visible = true; } // Text link else { btnSignOutLink.CommandArgument = navUrl; btnSignOutLink.Text = SignOutText; btnSignOutLink.Visible = true; } } // Image link else { btnSignOutImage.CommandArgument = navUrl; btnSignOutImage.ImageUrl = ResolveUrl(SignOutImageURL); btnSignOutImage.Visible = true; btnSignOut.Text = GetString("webparts_membership_signoutbutton.signout"); } } } else { Visible = false; } } // Sign In else { // Create return URL string returnUrl = QueryHelper.GetText("returnurl", ""); returnUrl = (returnUrl == String.Empty) ? URLHelper.CurrentURL : returnUrl; // Create parameters for LiveID request URL String[] parameters = new String[3]; parameters[0] = returnUrl; parameters[1] = TrackConversionName; parameters[2] = ConversionValue.ToString(); SessionHelper.SetValue("LiveIDInformtion", parameters); returnUrl = wll.GetLoginUrl(); // Get App ID appId = SettingsKeyProvider.GetStringValue(siteName + ".CMSApplicationID"); // Create full LiveID request URL string navUrl = "https://oauth.live.com/authorize?&client_id=" + appId + "&redirect=true&scope=wl.signin&response_type=code&redirect_uri=" + HttpUtility.UrlEncode(returnUrl); // If text is set use text/button link if (!string.IsNullOrEmpty(SignInText)) { // Button link if (ShowAsButton) { AssignButtonControl(navUrl, returnUrl, appId); btnSignIn.Text = SignInText; } // Text link else { AssignHyperlinkControl(navUrl, returnUrl, appId); lnkSignIn.Text = SignInText; } } // Image link else { AssignHyperlinkControl(navUrl, returnUrl, appId); lnkSignIn.ImageUrl = ResolveUrl(SignInImageURL); lnkSignIn.Text = GetString("webparts_membership_signoutbutton.signin"); } } } } else { // Error label is displayed in Design mode when Windows Live ID is disabled if (CMSContext.ViewMode == ViewModeEnum.Design) { StringBuilder parameter = new StringBuilder(); parameter.Append(GetString("header.sitemanager") + " -> "); parameter.Append(GetString("settingscategory.cmssettings") + " -> "); parameter.Append(GetString("settingscategory.cmsmembership") + " -> "); parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> "); parameter.Append(GetString("settingscategory.cmswindowsliveid")); if (CMSContext.CurrentUser.UserSiteManagerAdmin) { // Make it link for SiteManager Admin parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl("~/CMSSiteManager/default.aspx?section=settings") + "\" target=\"_top\">"); parameter.Append("</a>"); } lblError.Text = String.Format(GetString("mem.liveid.disabled"), parameter.ToString()); lblError.Visible = true; } else { Visible = false; } } } }
protected override void OnPreRender(EventArgs e) { if (SiteInfo != null) { if (SchedulingHelper.UseAutomaticScheduler || !SchedulingHelper.RunSchedulerWithinRequest) { lblLastRun.Visible = true; string siteName = SiteInfo.SiteName.ToLowerCSafe(); if (SchedulingTimer.TimerExists(siteName)) { DateTime lastRun = ValidationHelper.GetDateTime(SchedulingTimer.LastRuns[siteName], DateTimeHelper.ZERO_TIME); if (lastRun != DateTimeHelper.ZERO_TIME) { lblLastRun.Text = GetString("Task_List.LastRun") + " " + lastRun; } else { lblLastRun.Text = GetString("Task_List.Running"); } } else { lblLastRun.Text = GetString("Task_List.NoRun"); } } else { lblLastRun.Visible = false; } } ScriptHelper.RegisterStartupScript(Page, typeof(string), "SchedulerRefreshScript", "function RefreshGrid() { " + ControlsHelper.GetPostBackEventReference(btnRefresh) + "; }", true); base.OnPreRender(e); }
/// <summary> /// Loads the control content. /// </summary> /// <param name="content">Content to load</param> /// <param name="forceReload">If true, the content is forced to reload</param> public void LoadContent(string content, bool forceReload) { if (StopProcessing) { return; } ApplySettings(); bool contentIsEmpty = String.IsNullOrEmpty(content); content = contentIsEmpty ? DefaultText : content; // Resolve URLs content = HTMLHelper.ResolveUrls(content, null); switch (ViewMode) { case ViewModeEnum.Edit: case ViewModeEnum.EditDisabled: switch (RegionType) { case CMSEditableRegionTypeEnum.HtmlEditor: // HTML editor if ((Editor != null) && (forceReload || !RequestHelper.IsPostBack() || (ViewMode == ViewModeEnum.EditDisabled) || contentIsEmpty)) { Editor.ResolvedValue = content; } break; case CMSEditableRegionTypeEnum.TextArea: case CMSEditableRegionTypeEnum.TextBox: content = (EncodeText) ? HTMLHelper.HTMLDecode(content) : content; // TextBox if ((forceReload || !RequestHelper.IsPostBack() || contentIsEmpty) && (txtValue != null)) { txtValue.Text = content; } break; } break; default: // Check authorization bool isAuthorized = true; if ((PageManager != null) && (CheckPermissions)) { isAuthorized = PageManager.IsAuthorized; } // Only published if ((PortalContext.ViewMode != ViewModeEnum.LiveSite) || !SelectOnlyPublished || ((CurrentPageInfo != null) && CurrentPageInfo.IsPublished)) { if (isAuthorized) { if (ltlContent == null) { ltlContent = (Literal)FindControl("ltlContent"); } if (ltlContent != null) { ltlContent.Text = content; // Resolve inline controls if (ResolveDynamicControls) { ControlsHelper.ResolveDynamicControls(this); } } } } break; } }
private string GetPostBackEventReference(string actionName) { return(ControlsHelper.GetPostBackEventReference(this, String.Format("{0};{1}", actionName, CommentID))); }
protected void Page_Load(object sender, EventArgs e) { // Register JQuery ScriptHelper.RegisterJQuery(Page); SelectSite.StopProcessing = !DisplaySiteSelector; plcSelectSite.Visible = DisplaySiteSelector; bool hasSelected = SelectedCategory != null; // Ensure correct object type for cloning if (hasSelected) { gridSubCategories.ObjectType = SelectedCategory.CategoryIsPersonal ? CategoryInfo.OBJECT_TYPE_USERCATEGORY : CategoryInfo.OBJECT_TYPE; } // Check if selection is valid CheckSelection(); // Stop processing grids, when no category selected gridDocuments.UniGrid.StopProcessing = !hasSelected; gridDocuments.UniGrid.FilterForm.StopProcessing = !hasSelected; gridDocuments.UniGrid.Visible = hasSelected; gridSubCategories.StopProcessing = !hasSelected; gridSubCategories.FilterForm.StopProcessing = !hasSelected; gridSubCategories.Visible = hasSelected; if (!StopProcessing) { if (!RequestHelper.IsPostBack()) { // Start in mode of creating new category when requested if (StartInCreatingMode) { SwitchToNew(); } else { SwitchToInfo(); } } // Use images according to culture var imageUrl = (CultureHelper.IsUICultureRTL()) ? GetImageUrl("RTL/Design/Controls/Tree") : GetImageUrl("Design/Controls/Tree"); treeElemG.LineImagesFolder = imageUrl; treeElemP.LineImagesFolder = imageUrl; treeElemG.StopProcessing = !DisplaySiteCategories; treeElemP.StopProcessing = !DisplayPersonalCategories; // Prepare node templates treeElemP.SelectedNodeTemplate = treeElemG.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME####NODEID##\" class=\"ContentTreeItem ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME####NODEID##'); if (NodeSelected) { NodeSelected(##NODEID##, ##PARENTID##); return false;}\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>"; treeElemP.NodeTemplate = treeElemG.NodeTemplate = "<span id=\"node_##NODECODENAME####NODEID##\" class=\"ContentTreeItem\" onclick=\"SelectNode('##NODECODENAME####NODEID##'); if (NodeSelected) { NodeSelected(##NODEID##, ##PARENTID##); return false;}\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>"; // Init tree provider objects treeElemG.ProviderObject = CreateTreeProvider(SiteID, 0); treeElemP.ProviderObject = CreateTreeProvider(0, UserID); // Expand first level by default treeElemP.ExpandPath = treeElemG.ExpandPath = "/"; if (SelectedCategory != null) { catEdit.UserID = SelectedCategory.CategoryUserID; catEdit.Category = SelectedCategory; catNew.UserID = SelectedCategory.CategoryUserID; catNew.ParentCategoryID = SelectedCategory.CategoryID; catNew.SiteID = SiteID; catNew.AllowCreateOnlyGlobal = SiteID == 0; gridDocuments.SiteName = filterDocuments.SelectedSite; PreselectCategory(SelectedCategory, false); } else { catNew.UserID = CustomCategoriesRootSelected ? UserID : 0; catNew.SiteID = CustomCategoriesRootSelected ? 0 : SiteID; catNew.ParentCategoryID = 0; catNew.AllowCreateOnlyGlobal = SiteID == 0; } // Create root node for global and site categories string rootName = "<span class=\"TreeRoot\">" + GetString("categories.rootcategory") + "</span>"; string rootText = treeElemG.ReplaceMacros(treeElemG.NodeTemplate, 0, 6, rootName, "", 0, null, null); rootText = rootText.Replace("##NODECUSTOMNAME##", rootName); rootText = rootText.Replace("##NODECODENAME##", "CategoriesRoot"); rootText = rootText.Replace("##PARENTID##", CATEGORIES_ROOT_PARENT_ID.ToString()); treeElemG.SetRoot(rootText, "NULL", null, null, null); // Create root node for personal categories rootName = "<span class=\"TreeRoot\">" + GetString("categories.rootpersonalcategory") + "</span>"; rootText = treeElemP.ReplaceMacros(treeElemP.NodeTemplate, 0, 6, rootName, "", 0, null, null); rootText = rootText.Replace("##NODECUSTOMNAME##", rootName); rootText = rootText.Replace("##NODECODENAME##", "PersonalCategoriesRoot"); rootText = rootText.Replace("##PARENTID##", PERSONAL_CATEGORIES_ROOT_PARENT_ID.ToString()); treeElemP.SetRoot(rootText, "NULL", null, null, null); // Prepare script for selecting category string script = @" var menuHiddenId = '" + hidSelectedElem.ClientID + @"'; function deleteConfirm() { return confirm(" + ScriptHelper.GetString(GetString("general.confirmdelete")) + @"); } function Refresh(catId, parentId) { // This method is used in Category cloning action NodeSelected(catId, parentId, true); } function NodeSelected(elementId, parentId, isEdit) { // Set menu actions value var menuElem = $cmsj('#' + menuHiddenId); if (menuElem.length = 1) { menuElem[0].value = elementId + '|' + parentId; } if (isEdit) { " + ControlsHelper.GetPostBackEventReference(hdnButton, "edit") + @" } else { " + ControlsHelper.GetPostBackEventReference(hdnButton, "tree") + @" } }"; ltlScript.Text = ScriptHelper.GetScript(script); } }
/// <summary> /// Generates tables /// </summary> private void GenerateTable() { tblData.Controls.Clear(); Hashtable ht = data.ConvertToHashtable(); TableHeaderRow th = new TableHeaderRow() { TableSection = TableRowSection.TableHeader }; TableHeaderCell ha = new TableHeaderCell(); TableHeaderCell hn = new TableHeaderCell(); TableHeaderCell hv = new TableHeaderCell(); th.CssClass = "unigrid-head"; ha.Text = GetString("unigrid.actions"); ha.CssClass = "unigrid-actions-header"; hn.Text = GetString("xmleditor.propertyname"); hn.Width = Unit.Pixel(180); hv.Text = GetString("xmleditor.propertyvalue"); hv.Width = Unit.Pixel(500); th.Cells.Add(ha); th.Cells.Add(hn); th.Cells.Add(hv); tblData.Rows.Add(th); ArrayList keys = new ArrayList(ht); keys.Sort(new CustomStringComparer()); foreach (DictionaryEntry okey in keys) { String key = ValidationHelper.GetString(okey.Key, String.Empty); String value = ValidationHelper.GetString(okey.Value, String.Empty); bool isInvalid = (key == INVALIDTOKEN); key = isInvalid ? invalidKey : key; if (value == String.Empty) { continue; } TableRow tr = new TableRow(); // Actions TableCell tna = new TableCell(); tna.CssClass = "unigrid-actions"; var imgEdit = new CMSGridActionButton(); imgEdit.OnClientClick = String.Format("displayEdit('{1}','{0}'); return false; ", key, ClientID); imgEdit.IconCssClass = "icon-edit"; imgEdit.IconStyle = GridIconStyle.Allow; imgEdit.ID = key + "_edit"; imgEdit.ToolTip = GetString("xmleditor.edititem"); var imgOK = new CMSGridActionButton(); imgOK.IconCssClass = "icon-check"; imgOK.IconStyle = GridIconStyle.Allow; imgOK.OnClientClick = String.Format("approveCustomChanges('{0}','{1}');return false;", ClientID, key); imgOK.ID = key + "_ok"; imgOK.ToolTip = GetString("xmleditor.approvechanges"); var imgDelete = new CMSGridActionButton(); imgDelete.OnClientClick = " if (confirm('" + GetString("xmleditor.deleteconfirm") + "')) {" + ControlsHelper.GetPostBackEventReference(tblData, "delete_" + key) + "} ;return false;"; imgDelete.IconCssClass = "icon-bin"; imgDelete.IconStyle = GridIconStyle.Critical; imgDelete.ID = key + "_del"; imgDelete.ToolTip = GetString("xmleditor.deleteitem"); var imgUndo = new CMSGridActionButton(); imgUndo.OnClientClick = String.Format("if (confirm('" + GetString("xmleditor.confirmcancel") + "')) undoCustomChanges('{0}','{1}'); return false;", ClientID, key); imgUndo.IconCssClass = "icon-arrow-crooked-left"; imgUndo.ID = key + "_undo"; imgUndo.ToolTip = GetString("xmleditor.undochanges"); tna.Controls.Add(imgEdit); tna.Controls.Add(imgOK); tna.Controls.Add(imgDelete); tna.Controls.Add(imgUndo); value = MacroSecurityProcessor.RemoveSecurityParameters(value, false, null); // Labels Label lblName = new Label(); lblName.ID = "sk" + key; lblName.Text = key; Label lblValue = new Label(); lblValue.ID = "sv" + key; lblValue.Text = HTMLHelper.HTMLEncode(value); // Textboxes CMSTextBox txtName = new CMSTextBox(); txtName.Text = key; txtName.ID = "tk" + key; txtName.CssClass = "XmlEditorTextbox"; CMSTextBox txtValue = new CMSTextBox(); txtValue.Text = value; txtValue.ID = "tv" + key; txtValue.CssClass = "XmlEditorTextbox"; txtValue.Width = Unit.Pixel(490); labels.Add(lblName); labels.Add(lblValue); textboxes.Add(txtName); textboxes.Add(txtValue); TableCell tcn = new TableCell(); tcn.Controls.Add(lblName); tcn.Controls.Add(txtName); TableCell tcv = new TableCell(); tcv.Controls.Add(lblValue); tcv.Controls.Add(txtValue); tr.Cells.Add(tna); tr.Cells.Add(tcn); tr.Cells.Add(tcv); tblData.Rows.Add(tr); lblValue.CssClass = String.Empty; lblName.CssClass = "CustomEditorKeyClass"; if (isInvalid) { imgDelete.AddCssClass("hidden"); imgEdit.AddCssClass("hidden"); lblName.AddCssClass("hidden"); lblValue.AddCssClass("hidden"); RegisterEnableScript(false); } else { imgOK.AddCssClass("hidden"); imgUndo.AddCssClass("hidden"); txtName.CssClass += " hidden"; txtValue.CssClass += " hidden"; } } }
private void Scanner_Progress(object sender, XInputMaskScannerEventArgs e) { if (ControlsHelper.InvokeRequired) { ControlsHelper.Invoke(() => Scanner_Progress(sender, e) ); return; } var scanner = (XInputMaskScanner)sender; var label = e.Level == 0 ? ScanProgressLevel0Label : ScanProgressLevel1Label; switch (e.State) { case XInputMaskScannerState.Started: label.Text = "Scanning..."; break; case XInputMaskScannerState.GameFound: lock (GameAddLock) { // Get game to add. var game = e.Game; var dirFullName = e.GameFileInfo.Directory.FullName.ToLower(); // Get existing games in the same folder. var oldGames = SettingsManager.UserGames.Items.Where(x => x.FullPath.ToLower().StartsWith(dirFullName)).ToList(); var oldGame = oldGames.FirstOrDefault(x => x.IsEnabled && x.DateCreated < ScanStarted); var enabledGame = oldGames.FirstOrDefault(x => x.IsEnabled); // If this is 32-bit windows but game is 64-bit then... if (!Environment.Is64BitOperatingSystem && game.Is64Bit) { // Disable game. game.IsEnabled = false; } // If list contains enabled old game for other platform before scan started then... else if (oldGame != null) { // Enable if platform is the same, disable otherwise. game.IsEnabled = game.ProcessorArchitecture == oldGame.ProcessorArchitecture; } // At this point, oldGames list contains only new games added during the scan. // If this is 64-bit game then... else if (game.Is64Bit) { foreach (var g in oldGames) { // Disable non 64-bit games. if (g.IsEnabled && !g.Is64Bit) { g.IsEnabled = false; } } } // If contains enabled game then... else if (enabledGame != null) { // Enable if platform is the same, disable otherwise. game.IsEnabled = game.ProcessorArchitecture == enabledGame.ProcessorArchitecture; } SettingsManager.UserGames.Add(game); } break; case XInputMaskScannerState.GameUpdated: e.Game.FullPath = e.GameFileInfo.FullName; if (string.IsNullOrEmpty(e.Game.FileProductName) && !string.IsNullOrEmpty(e.Program.FileProductName)) { e.Game.FileProductName = e.Program.FileProductName; } break; case XInputMaskScannerState.DirectoryUpdate: case XInputMaskScannerState.FileUpdate: var sb = new StringBuilder(); sb.AppendLine(e.Message); if (e.State == XInputMaskScannerState.DirectoryUpdate && e.Directories != null) { sb.AppendFormat("Current Folder: {0}", e.Directories[e.DirectoryIndex].FullName); } if (e.State == XInputMaskScannerState.FileUpdate && e.Files != null) { var file = e.Files[e.FileIndex]; var size = file.Length / 1024 / 1024; sb.AppendFormat("Current File ({0:0.0} MB): {1} ", size, file.FullName); } if (e.Level == 0) { sb.AppendLine(); sb.AppendFormat("Skipped = {0}, Added = {1}, Updated = {2}", e.Skipped, e.Added, e.Updated); } sb.AppendLine(); ControlsHelper.Invoke(() => { label.Text = sb.ToString(); }); break; case XInputMaskScannerState.Completed: ControlsHelper.Invoke(() => { ScanButton.IsEnabled = true; ScanProgressPanel.Visibility = Visibility.Collapsed; }); SettingsManager.Save(); break; default: break; } }
protected void Page_Load(object sender, EventArgs e) { // Register the main CMS script ScriptHelper.RegisterCMS(Page); if (StopProcessing) { ugRecycleBin.StopProcessing = true; return; } // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Set current UI culture currentCulture = CultureHelper.PreferredUICultureCode; // Get current user info currentUser = MembershipContext.AuthenticatedUser; // Set current site ID to filter filter.SiteID = (mSelectedSite != null) ? mSelectedSite.SiteID : UniSelector.US_ALL_RECORDS; PrepareGrid(); if (!RequestHelper.IsCallback()) { ControlsHelper.RegisterPostbackControl(btnOk); // Create action script StringBuilder actionScript = new StringBuilder(); actionScript.AppendLine("function PerformAction(selectionFunction, selectionField, dropId, validationLabel, whatId)"); actionScript.AppendLine("{"); actionScript.AppendLine(" var selectionFieldElem = document.getElementById(selectionField);"); actionScript.AppendLine(" var label = document.getElementById(validationLabel);"); actionScript.AppendLine(" var items = selectionFieldElem.value;"); actionScript.AppendLine(" var whatDrp = document.getElementById(whatId);"); actionScript.AppendLine(" var allDocs = whatDrp.value == '" + (int)What.AllDocuments + "';"); actionScript.AppendLine(" var action = document.getElementById(dropId).value;"); actionScript.AppendLine(" if (action == '" + (int)Action.SelectAction + "')"); actionScript.AppendLine(" {"); actionScript.AppendLine(" label.innerHTML = " + ScriptHelper.GetLocalizedString("massaction.selectsomeaction") + ";"); actionScript.AppendLine(" label.style.display = 'block';"); actionScript.AppendLine(" return false;"); actionScript.AppendLine(" }"); actionScript.AppendLine(" if(!eval(selectionFunction) || allDocs)"); actionScript.AppendLine(" {"); actionScript.AppendLine(" var confirmed = false;"); actionScript.AppendLine(" var confMessage = '';"); actionScript.AppendLine(" switch(action)"); actionScript.AppendLine(" {"); actionScript.AppendLine(" case '" + (int)Action.Restore + "':"); actionScript.AppendLine(" confMessage = " + ScriptHelper.GetLocalizedString("recyclebin.confirmrestores") + ";"); actionScript.AppendLine(" break;"); actionScript.AppendLine(" case '" + (int)Action.Delete + "':"); actionScript.AppendLine(" confMessage = allDocs ? " + ScriptHelper.GetLocalizedString("recyclebin.confirmemptyrecbin") + " : " + ScriptHelper.GetLocalizedString("recyclebin.confirmdeleteselected") + ";"); actionScript.AppendLine(" break;"); actionScript.AppendLine(" }"); actionScript.AppendLine(" return confirm(confMessage);"); actionScript.AppendLine(" }"); actionScript.AppendLine(" else"); actionScript.AppendLine(" {"); actionScript.AppendLine(" label.innerHTML = " + ScriptHelper.GetLocalizedString("documents.selectdocuments") + ";"); actionScript.AppendLine(" label.style.display = 'block';"); actionScript.AppendLine(" return false;"); actionScript.AppendLine(" }"); actionScript.AppendLine("}"); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "recycleBinScript", ScriptHelper.GetScript(actionScript.ToString())); // Set page size int itemsPerPage = ValidationHelper.GetInteger(ItemsPerPage, 0); if ((itemsPerPage > 0) && !RequestHelper.IsPostBack()) { ugRecycleBin.Pager.DefaultPageSize = itemsPerPage; } // Add action to button btnOk.OnClientClick = "return PerformAction('" + ugRecycleBin.GetCheckSelectionScript() + "','" + ugRecycleBin.GetSelectionFieldClientID() + "','" + drpAction.ClientID + "','" + lblValidation.ClientID + "', '" + drpWhat.ClientID + "');"; // Initialize dropdown lists if (!RequestHelper.IsPostBack()) { drpAction.Items.Add(new ListItem(GetString("general." + Action.Restore), Convert.ToInt32(Action.Restore).ToString())); drpAction.Items.Add(new ListItem(GetString("recyclebin.destroyhint"), Convert.ToInt32(Action.Delete).ToString())); drpWhat.Items.Add(new ListItem(GetString("contentlisting." + What.SelectedDocuments), Convert.ToInt32(What.SelectedDocuments).ToString())); drpWhat.Items.Add(new ListItem(GetString("contentlisting." + What.AllDocuments), Convert.ToInt32(What.AllDocuments).ToString())); } // Register the dialog script ScriptHelper.RegisterDialogScript(Page); // Register script for viewing versions string viewVersionScript = "function ViewVersion(versionHistoryId) {modalDialog('" + ResolveUrl("~/CMSModules/RecycleBin/Pages/ViewVersion.aspx") + "?noCompare=1&versionHistoryId=' + versionHistoryId, 'contentversion', 900, 600);}"; ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "viewVersionScript", ScriptHelper.GetScript(viewVersionScript)); // Initialize buttons btnCancel.Attributes.Add("onclick", ctlAsync.GetCancelScript(true) + "return false;"); string error = QueryHelper.GetString("displayerror", String.Empty); if (error != String.Empty) { ShowError(GetString("recyclebin.errorsomenotdestroyed")); } // Set visibility of panels pnlLog.Visible = false; } else { ugRecycleBin.StopProcessing = true; } // Initialize events ctlAsync.OnFinished += ctlAsync_OnFinished; ctlAsync.OnError += ctlAsync_OnError; ctlAsync.OnRequestLog += ctlAsync_OnRequestLog; ctlAsync.OnCancel += ctlAsync_OnCancel; }
/// <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; } }