protected void btnSave_Click(object sender, EventArgs e) { // Email format validation string emailAddress = txtEmailAddress.Text.Trim(); if (!String.IsNullOrEmpty(emailAddress) && !ValidationHelper.IsEmail(emailAddress)) { ShowError(GetString("Administration-User_New.WrongEmailFormat")); return; } // Find whether user name is valid string result = null; if (!ucUserName.IsValid()) { result = ucUserName.ValidationError; } // Additional validation if (String.IsNullOrEmpty(result)) { result = new Validator().NotEmpty(txtFullName.Text, GetString("Administration-User_New.RequiresFullName")).Result; } userName = ValidationHelper.GetString(ucUserName.Value, String.Empty).Trim(); // Check if user with the same user name exists if (UserInfoProvider.GetUserInfo(userName) != null) { ShowError(GetString("Administration-User_New.UserExists")); return; } SiteInfo siteInfo = SiteContext.CurrentSite; // Check if username with site prefix exists on current site var userNameWithPrefix = UserInfoProvider.GetUserInfo(UserInfoProvider.EnsureSitePrefixUserName(userName, siteInfo)); if (userNameWithPrefix != null) { ShowError(GetString("Administration-User_New.siteprefixeduserexists")); return; } // If site prefixed allowed - add site prefix to user name if (((SiteID != 0) || (chkAssignToSite.Checked && AllowAssignToWebsite)) && UserInfoProvider.UserNameSitePrefixEnabled(siteInfo.SiteName)) { if (!UserInfoProvider.IsSitePrefixedUser(userName)) { userName = UserInfoProvider.EnsureSitePrefixUserName(userName, siteInfo); } } // User without site prefix is going to be created -> check if site prefixed user does not exist in solution else if (!UserInfoProvider.IsUserNamePrefixUnique(userName, 0)) { ShowError(GetString("Administration-User_New.siteprefixeduserexists")); return; } if (String.IsNullOrEmpty(result)) { if (txtConfirmPassword.Text == passStrength.Text) { // Check whether password is valid according to policy if (passStrength.IsValid()) { int userId = SaveNewUser(); if (userId != -1) { var uiElementUrl = UIContextHelper.GetElementUrl("CMS.Users", QueryHelper.GetString("editelem", ""), false); var url = URLHelper.AppendQuery(uiElementUrl, "siteid=" + SiteID + "&objectid=" + userId); URLHelper.Redirect(url); } } else { ShowError(AuthenticationHelper.GetPolicyViolationMessage(siteInfo.SiteName)); } } else { ShowError(GetString("Administration-User_Edit_Password.PasswordsDoNotMatch")); } } else { ShowError(result); } }
private CMSButtonAction GetControlAction(HeaderAction headerAction) { var controlAction = new CMSButtonAction(); controlAction.Text = headerAction.Text; controlAction.Enabled = headerAction.Enabled && Enabled; controlAction.ToolTip = headerAction.Tooltip; // Register script only when action is active if (Enabled && headerAction.Enabled && !headerAction.Inactive) { // Wrap script from OnClick property into anonymous function so it won't cancel the following script in case this property scipt returns true. // The execution of following script is canceled only when anonymous function returns false. if (!String.IsNullOrEmpty(headerAction.OnClientClick)) { string onClickScript = "var onClickWrapper = function(sender) { " + headerAction.OnClientClick + "}; if (onClickWrapper(this) === false) { return false; }"; if (controlAction.ToolTip.ToLower() == "save the page" || controlAction.ToolTip.ToLower() == "submit for approval") { onClickScript = onClickScript + "if(formValid()===false){return false;}"; } controlAction.OnClientClick = onClickScript; } string commandName = !string.IsNullOrEmpty(headerAction.CommandName) ? headerAction.CommandName : headerAction.EventName; // Perform post-back if (!String.IsNullOrEmpty(commandName) || !String.IsNullOrEmpty(headerAction.CommandArgument)) { string argument = string.Join(";", new[] { commandName, headerAction.CommandArgument }); var opt = new PostBackOptions(this, argument) { PerformValidation = true, ValidationGroup = headerAction.ValidationGroup }; string postbackScript = ControlsHelper.GetPostBackEventReference(this, opt, false, !PerformFullPostBack); controlAction.OnClientClick += postbackScript + ";"; } else { // Use URL only for standard link if (!String.IsNullOrEmpty(headerAction.RedirectUrl)) { var target = headerAction.Target ?? "_self"; var url = ScriptHelper.ResolveUrl(headerAction.RedirectUrl); if (headerAction.OpenInDialog) { url = URLHelper.AddParameterToUrl(url, "dialog", "1"); url = UIContextHelper.AppendDialogHash(url); ScriptHelper.RegisterDialogScript(Page); controlAction.OnClientClick = ScriptHelper.GetModalDialogScript(url, "action" + headerAction.Index, headerAction.DialogWidth, headerAction.DialogHeight, false); } else { controlAction.OnClientClick += "window.open('" + url + "','" + target + "');"; } } } // Stop automatic postback rendered by asp button controlAction.OnClientClick += " return false;"; } return(controlAction); }
/// <summary> /// Generates panel with buttons loaded from given UI Element. /// </summary> /// <param name="uiElementId">ID of the UI Element</param> protected Panel GetButtons(int uiElementId) { const int bigButtonMinimalWidth = 40; const int smallButtonMinimalWidth = 66; Panel pnlButtons = null; // Load the buttons manually from UI Element DataSet ds = UIElementInfoProvider.GetChildUIElements(uiElementId); // When no child found if (DataHelper.DataSourceIsEmpty(ds)) { // Try to use group element as button ds = UIElementInfoProvider.GetUIElements("ElementID = " + uiElementId, null); if (!DataHelper.DataSourceIsEmpty(ds)) { DataRow dr = ds.Tables[0].Rows[0]; string url = ValidationHelper.GetString(dr["ElementTargetURL"], ""); // Use group element as button only if it has URL specified if (string.IsNullOrEmpty(url)) { ds = null; } } } if (!DataHelper.DataSourceIsEmpty(ds)) { // Filter the dataset according to UI Profile FilterElements(ds); int small = 0; int count = ds.Tables[0].Rows.Count; // No buttons, render nothing if (count == 0) { return(null); } // Prepare the panel pnlButtons = new Panel(); pnlButtons.CssClass = "ActionButtons"; // Prepare the table Table tabGroup = new Table(); TableRow tabGroupRow = new TableRow(); tabGroup.CellPadding = 0; tabGroup.CellSpacing = 0; tabGroup.EnableViewState = false; tabGroupRow.EnableViewState = false; tabGroup.Rows.Add(tabGroupRow); List <Panel> panels = new List <Panel>(); for (int i = 0; i < count; i++) { // Get current and next button UIElementInfo uiElement = new UIElementInfo(ds.Tables[0].Rows[i]); UIElementInfo sel = UIContextHelper.CheckSelectedElement(uiElement, UIContext); if (sel != null) { String selectionSuffix = ValidationHelper.GetString(UIContext["selectionSuffix"], String.Empty); StartingPage = UIContextHelper.GetElementUrl(sel, UIContext) + selectionSuffix; HighlightItem = uiElement.ElementName; } // Raise button creating event if (OnButtonCreating != null) { OnButtonCreating(this, new UniMenuArgs { UIElement = uiElement }); } UIElementInfo uiElementNext = null; if (i < count - 1) { uiElementNext = new UIElementInfo(ds.Tables[0].Rows[i + 1]); } // Set the first button if (mFirstUIElement == null) { mFirstUIElement = uiElement; } // Get the sizes of current and next button. Button is large when it is the only in the group bool isSmall = (uiElement.ElementSize == UIElementSizeEnum.Regular) && (count > 1); bool isResized = (uiElement.ElementSize == UIElementSizeEnum.Regular) && (!isSmall); bool isNextSmall = (uiElementNext != null) && (uiElementNext.ElementSize == UIElementSizeEnum.Regular); // Set the CSS class according to the button size string cssClass = (isSmall ? "SmallButton" : "BigButton"); string elementName = uiElement.ElementName; // Display only caption - do not substitute with Display name when empty string elementCaption = ResHelper.LocalizeString(uiElement.ElementCaption); // Create main button panel CMSPanel pnlButton = new CMSPanel() { ID = "pnlButton" + elementName, ShortID = "b" + elementName }; pnlButton.Attributes.Add("name", elementName); pnlButton.CssClass = cssClass; // Remember the first button if (firstPanel == null) { firstPanel = pnlButton; } // Remember the selected button if ((preselectedPanel == null) && elementName.EqualsCSafe(HighlightItem, true)) { preselectedPanel = pnlButton; // Set the selected button if (mHighlightedUIElement == null) { mHighlightedUIElement = uiElement; } } // URL or behavior string url = uiElement.ElementTargetURL; if (!string.IsNullOrEmpty(url) && url.StartsWithCSafe("javascript:", true)) { pnlButton.Attributes["onclick"] = url.Substring("javascript:".Length); } else { url = UIContextHelper.GetElementUrl(uiElement, UIContext); if (url != String.Empty) { string buttonSelection = (RememberSelectedItem ? "SelectButton(this);" : ""); // Ensure hash code if required url = MacroResolver.Resolve(URLHelper.EnsureHashToQueryParameters(url)); if (!String.IsNullOrEmpty(TargetFrameset)) { if (uiElement.ElementType == UIElementTypeEnum.PageTemplate) { url = URLHelper.UpdateParameterInUrl(url, "displaytitle", "false"); } String target = UseIFrame ? String.Format("frames['{0}']", TargetFrameset) : String.Format("parent.frames['{0}']", TargetFrameset); pnlButton.Attributes["onclick"] = String.Format("{0}{1}.location.href = '{2}';", buttonSelection, target, URLHelper.ResolveUrl(url)); } else { pnlButton.Attributes["onclick"] = String.Format("{0}self.location.href = '{1}';", buttonSelection, URLHelper.ResolveUrl(url)); } } } // Tooltip if (!string.IsNullOrEmpty(uiElement.ElementDescription)) { pnlButton.ToolTip = ResHelper.LocalizeString(uiElement.ElementDescription); } else { pnlButton.ToolTip = elementCaption; } pnlButton.EnableViewState = false; // Ensure correct grouping of small buttons if (isSmall && (small == 0)) { small++; Panel pnlSmallGroup = new Panel() { ID = "pnlGroupSmall" + uiElement.ElementName }; if (IsRTL) { pnlSmallGroup.Style.Add("float", "right"); pnlSmallGroup.Style.Add("text-align", "right"); } else { pnlSmallGroup.Style.Add("float", "left"); pnlSmallGroup.Style.Add("text-align", "left"); } pnlSmallGroup.EnableViewState = false; pnlSmallGroup.Controls.Add(pnlButton); panels.Add(pnlSmallGroup); } // Generate button link HyperLink buttonLink = new HyperLink() { ID = "lnkButton" + uiElement.ElementName, EnableViewState = false }; // Generate button image Image buttonImage = new Image() { ID = "imgButton" + uiElement.ElementName, ImageAlign = (isSmall ? ImageAlign.AbsMiddle : ImageAlign.Top), AlternateText = elementCaption, EnableViewState = false }; // Use icon path if (!string.IsNullOrEmpty(uiElement.ElementIconPath)) { string iconPath = GetImagePath(uiElement.ElementIconPath); // Check if element size was changed if (isResized) { // Try to get larger icon string largeIconPath = iconPath.Replace("list.png", "module.png"); if (FileHelper.FileExists(largeIconPath)) { iconPath = largeIconPath; } } buttonImage.ImageUrl = GetImageUrl(iconPath); buttonLink.Controls.Add(buttonImage); } // Use Icon class else if (!string.IsNullOrEmpty(uiElement.ElementIconClass)) { var icon = new CMSIcon { ID = "ico" + identifier, EnableViewState = false, ToolTip = pnlButton.ToolTip, CssClass = "cms-icon-80 " + uiElement.ElementIconClass }; buttonLink.Controls.Add(icon); } // Load default module icon if ElementIconPath is not specified else { buttonImage.ImageUrl = GetImageUrl("CMSModules/module.png"); buttonLink.Controls.Add(buttonImage); } // Generate caption text Literal captionLiteral = new Literal() { ID = "ltlCaption" + uiElement.ElementName, Text = (isSmall ? "\n" : "<br />") + elementCaption, EnableViewState = false }; buttonLink.Controls.Add(captionLiteral); //Generate button table (IE7 issue) Table tabButton = new Table(); TableRow tabRow = new TableRow(); TableCell tabCellLeft = new TableCell(); TableCell tabCellMiddle = new TableCell(); TableCell tabCellRight = new TableCell(); tabButton.CellPadding = 0; tabButton.CellSpacing = 0; tabButton.EnableViewState = false; tabRow.EnableViewState = false; tabCellLeft.EnableViewState = false; tabCellMiddle.EnableViewState = false; tabCellRight.EnableViewState = false; tabButton.Rows.Add(tabRow); tabRow.Cells.Add(tabCellLeft); tabRow.Cells.Add(tabCellMiddle); tabRow.Cells.Add(tabCellRight); // Generate left border Panel pnlLeft = new Panel() { ID = "pnlLeft" + uiElement.ElementName, CssClass = "Left" + cssClass, EnableViewState = false }; // Generate middle part of button Panel pnlMiddle = new Panel() { ID = "pnlMiddle" + uiElement.ElementName, CssClass = "Middle" + cssClass }; pnlMiddle.Controls.Add(buttonLink); Panel pnlMiddleTmp = new Panel() { EnableViewState = false }; if (isSmall) { pnlMiddle.Style.Add("min-width", smallButtonMinimalWidth + "px"); // IE7 issue with min-width pnlMiddleTmp.Style.Add("width", smallButtonMinimalWidth + "px"); pnlMiddle.Controls.Add(pnlMiddleTmp); } else { pnlMiddle.Style.Add("min-width", bigButtonMinimalWidth + "px"); // IE7 issue with min-width pnlMiddleTmp.Style.Add("width", bigButtonMinimalWidth + "px"); pnlMiddle.Controls.Add(pnlMiddleTmp); } pnlMiddle.EnableViewState = false; // Generate right border Panel pnlRight = new Panel() { ID = "pnlRight" + uiElement.ElementName, CssClass = "Right" + cssClass, EnableViewState = false }; // Add inner controls tabCellLeft.Controls.Add(pnlLeft); tabCellMiddle.Controls.Add(pnlMiddle); tabCellRight.Controls.Add(pnlRight); pnlButton.Controls.Add(tabButton); // If there were two small buttons in a row end the grouping div if ((small == 2) || (isSmall && !isNextSmall)) { small = 0; // Add the button to the small buttons grouping panel panels[panels.Count - 1].Controls.Add(pnlButton); } else { if (small == 0) { // Add the generated button into collection panels.Add(pnlButton); } } if (small == 1) { small++; } // Raise button created event if (OnButtonCreated != null) { OnButtonCreated(this, new UniMenuArgs { UIElement = uiElement, TargetUrl = url, ButtonControl = pnlButton, ImageControl = buttonImage }); } } // Add all panels to control foreach (Panel panel in panels) { TableCell tabGroupCell = new TableCell() { VerticalAlign = VerticalAlign.Top, EnableViewState = false }; tabGroupCell.Controls.Add(panel); tabGroupRow.Cells.Add(tabGroupCell); } pnlButtons.Controls.Add(tabGroup); } return(pnlButtons); }
private void forumNew_OnSaved(object sender, EventArgs e) { string url = UIContextHelper.GetElementUrl("cms.forums", "EditGroupForum"); url = URLHelper.AddParameterToUrl(url, "forumid", forumNew.ForumID.ToString()); url = URLHelper.AddParameterToUrl(url, "parentobjectid", forumNew.ForumGroup.GroupID.ToString()); URLHelper.Redirect(URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("cms.forums", "EditGroupForum", false), "forumid", Convert.ToString(forumNew.ForumID)), "parentobjectid", Convert.ToString(forumNew.ForumGroup.GroupID)), "saved", "1")); }
/// <summary> /// Reloads the data in the selector. /// </summary> public void ReloadData() { uniSelector.IsLiveSite = IsLiveSite; uniSelector.ButtonClear.Visible = false; uniSelector.AllowEmpty = DisplayClearButton; uniSelector.SetValue("FilterMode", TransformationInfo.OBJECT_TYPE); uniSelector.EditDialogWindowWidth = 1200; // Set default value from settings as textbox watermark if (!String.IsNullOrEmpty(WatermarkValueSettingKey)) { string watermark = SettingsKeyInfoProvider.GetValue(SiteContext.CurrentSiteName + "." + WatermarkValueSettingKey); if (!String.IsNullOrEmpty(watermark)) { uniSelector.TextBoxSelect.WatermarkText = watermark; } } // Check if user can edit the transformation var currentUser = MembershipContext.AuthenticatedUser; bool deskAuthorized = currentUser.IsAuthorizedPerUIElement("CMS.Content", "Content"); bool contentAuthorized = currentUser.IsAuthorizedPerUIElement("CMS.Design", new[] { "Design", "Design.WebPartProperties" }, SiteContext.CurrentSiteName); if (deskAuthorized && contentAuthorized) { bool editAuthorized = currentUser.IsAuthorizedPerUIElement("CMS.Design", new[] { "WebPartProperties.EditTransformations" }, SiteContext.CurrentSiteName); bool createAuthorized = currentUser.IsAuthorizedPerUIElement("CMS.Design", new[] { "WebPartProperties.NewTransformations" }, SiteContext.CurrentSiteName); // Alias path for preview transformation string aliasPath = QueryHelper.GetString("aliaspath", String.Empty); string aliasPathParam = (aliasPath == String.Empty) ? "" : "&aliaspath=" + aliasPath; // Instance GUID string instanceGUID = QueryHelper.GetString("instanceGUID", String.Empty); string instanceGUIDParam = (instanceGUID == String.Empty) ? "" : "&instanceguid=" + instanceGUID; // Transformation editing authorized if (editAuthorized) { string isSiteManagerStr = IsSiteManager ? "&siteManager=true" : String.Empty; string query = String.Format("objectid=##ITEMID##{0}&editonlycode=1&dialog=1", isSiteManagerStr) + aliasPathParam + instanceGUIDParam; string url = UIContextHelper.GetElementUrl("CMS.DocumentEngine", "EditTransformation"); url = URLHelper.AppendQuery(url, query); uniSelector.EditItemPageUrl = url; } // Creating of new transformation authorized if (createAuthorized) { string isSiteManagerStr = IsSiteManager ? "&siteManager=true" : String.Empty; string url = NewDialogPath + "?editonlycode=1&dialog=1" + isSiteManagerStr + "&selectedvalue=##ITEMID##" + aliasPathParam + instanceGUIDParam; url = URLHelper.AddParameterToUrl(url, "hash", QueryHelper.GetHash("?editonlycode=1")); uniSelector.NewItemPageUrl = url; uniSelector.EditDialogWindowHeight = 760; } } string where = null; if (!ShowHierarchicalTransformation) { where = "(TransformationIsHierarchical IS NULL) OR (TransformationIsHierarchical = 0)"; } if (!string.IsNullOrEmpty(WhereCondition)) { where = SqlHelper.AddWhereCondition(where, WhereCondition); } if (where != null) { uniSelector.WhereCondition = where; } }
/// <summary> /// OnSave event handler. /// </summary> private void PollNew_OnSaved(object sender, EventArgs e) { string error = null; // Show possible license limitation error if (!String.IsNullOrEmpty(PollNew.LicenseError)) { error = "&error=" + PollNew.LicenseError; } string editActionUrl = URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl( URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("CMS.Polls", "EditPoll"), "objectid", PollNew.ItemID.ToString()), "siteid", siteId.ToString()), "displaytitle", "false"), "saved", "1"); URLHelper.Redirect(editActionUrl + error); }
/// <summary> /// Edit selected subscriber. /// </summary> private void Edit(object actionArgument) { var url = UIContextHelper.GetElementUrl("cms.newsletter", "Newsletters.SubscriberProperties", false, ValidationHelper.GetInteger(actionArgument, 0)); URLHelper.Redirect(url); }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (!StopProcessing) { plcError.Visible = false; // Check renamed DLL library if (!SystemContext.IsFullTrustLevel) { // Error label is displayed when OpenID library is not enabled lblError.Text = ResHelper.GetString("socialnetworking.fulltrustrequired"); plcError.Visible = true; plcContent.Visible = false; } // Check if OpenID module is enabled if (!SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOpenID") && !plcError.Visible) { // Error label is displayed only in Design mode if (PortalContext.IsDesignMode(PortalContext.ViewMode)) { StringBuilder parameter = new StringBuilder(); parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> "); parameter.Append(GetString("settingscategory.cmsmembership") + " -> "); parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> "); parameter.Append(GetString("settingscategory.cmsopenid")); if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)) { // Make it link for Admin parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(UIContextHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">"); parameter.Append("</a>"); } lblError.Text = String.Format(GetString("mem.openid.disabled"), parameter.ToString()); plcError.Visible = true; plcContent.Visible = false; } // In other modes is webpart hidden else { Visible = false; } } // Display webpart when no error occured if (!plcError.Visible && Visible) { if (!AuthenticationHelper.IsAuthenticated()) { plcPasswordNew.Visible = AllowFormsAuthentication; pnlExistingUser.Visible = AllowExistingUser; // Initialize OpenID session response = (Dictionary <string, object>)SessionHelper.GetValue(SESSION_NAME_USERDATA); userProviderUrl = ValidationHelper.GetString(SessionHelper.GetValue(SESSION_NAME_URL), null); // Check that OpenID is not already registered if (response != null) { UserInfo ui = OpenIDUserInfoProvider.GetUserInfoByOpenID((string)response["ClaimedIdentifier"]); // OpenID is already registered to some user if (ui != null) { plcContent.Visible = false; plcError.Visible = true; lblError.Text = GetString("mem.openid.openidregistered"); } } // There is no OpenID response object stored in session - hide all if (response == null) { if (HideForNoOpenID) { Visible = false; } } else if (!RequestHelper.IsPostBack()) { LoadData(); } } // Hide webpart for authenticated users else { Visible = false; } } } // Hide control when StopProcessing = TRUE else { Visible = false; } }
protected void groupNewElem_OnSaved(object sender, EventArgs e) { URLHelper.Redirect(URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("cms.forums", "EditForumGroup", false), "objectid", groupNewElem.GroupID.ToString())); }
protected void Page_Load(object sender, EventArgs e) { mEditedObject = UIContext.EditedObject as BaseInfo; // If saved is found in query string if (!RequestHelper.IsPostBack() && (QueryHelper.GetInteger("saved", 0) == 1)) { ShowChangesSaved(); } string before; string after; string objectType = UIContextHelper.GetObjectType(UIContext); switch (objectType.ToLowerCSafe()) { case "cms.webpart": mDefaultValueColumName = "WebPartDefaultValues"; before = PortalFormHelper.GetWebPartProperties(WebPartTypeEnum.Standard, PropertiesPosition.Before); after = PortalFormHelper.GetWebPartProperties(WebPartTypeEnum.Standard, PropertiesPosition.After); mDefaultSet = FormHelper.CombineFormDefinitions(before, after); WebPartInfo wi = mEditedObject as WebPartInfo; // If inherited web part load parent properties if (wi.WebPartParentID > 0) { WebPartInfo parentInfo = WebPartInfoProvider.GetWebPartInfo(wi.WebPartParentID); if (parentInfo != null) { mWebPartProperties = FormHelper.MergeFormDefinitions(parentInfo.WebPartProperties, wi.WebPartProperties); } } else { mWebPartProperties = wi.WebPartProperties; } break; case "cms.widget": before = PortalFormHelper.LoadProperties("Widget", "Before.xml"); after = PortalFormHelper.LoadProperties("Widget", "After.xml"); mDefaultSet = FormHelper.CombineFormDefinitions(before, after); mDefaultValueColumName = "WidgetDefaultValues"; WidgetInfo wii = mEditedObject as WidgetInfo; if (wii != null) { WebPartInfo wiiWp = WebPartInfoProvider.GetWebPartInfo(wii.WidgetWebPartID); if (wiiWp != null) { mWebPartProperties = FormHelper.MergeFormDefinitions(wiiWp.WebPartProperties, wii.WidgetProperties); } } break; } // Get the web part info if (mEditedObject != null) { String defVal = ValidationHelper.GetString(mEditedObject.GetValue(mDefaultValueColumName), string.Empty); mDefaultSet = LoadDefaultValuesXML(mDefaultSet); fieldEditor.Mode = FieldEditorModeEnum.SystemWebPartProperties; fieldEditor.FormDefinition = FormHelper.MergeFormDefinitions(mDefaultSet, defVal); fieldEditor.OnAfterDefinitionUpdate += fieldEditor_OnAfterDefinitionUpdate; fieldEditor.OriginalFormDefinition = mDefaultSet; fieldEditor.WebPartId = mEditedObject.Generalized.ObjectID; } ScriptHelper.HideVerticalTabs(Page); }
/// <summary> /// Handles the gridElem's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void gridElem_OnAction(string actionName, object actionArgument) { int orderId = ValidationHelper.GetInteger(actionArgument, 0); OrderInfo oi; OrderStatusInfo osi; switch (actionName.ToLowerCSafe()) { case "edit": string redirectToUrl = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "orderproperties", false, orderId); URLHelper.Redirect(redirectToUrl); break; case "delete": // Check 'ModifyOrders' and 'EcommerceModify' permission if (!ECommerceContext.IsUserAuthorizedForPermission(EcommercePermissions.ORDERS_MODIFY)) { return; } // Delete OrderInfo object from database OrderInfoProvider.DeleteOrderInfo(orderId); break; case "previous": // Check 'ModifyOrders' and 'EcommerceModify' permission if (!ECommerceContext.IsUserAuthorizedForPermission(EcommercePermissions.ORDERS_MODIFY)) { return; } oi = OrderInfoProvider.GetOrderInfo(orderId); if (oi != null) { osi = OrderStatusInfoProvider.GetPreviousEnabledStatus(oi.OrderStatusID); if (osi != null) { oi.OrderStatusID = osi.StatusID; // Save order status changes OrderInfoProvider.SetOrderInfo(oi); } } break; case "next": // Check 'ModifyOrders' and 'EcommerceModify' permission if (!ECommerceContext.IsUserAuthorizedForPermission(EcommercePermissions.ORDERS_MODIFY)) { return; } oi = OrderInfoProvider.GetOrderInfo(orderId); if (oi != null) { osi = OrderStatusInfoProvider.GetNextEnabledStatus(oi.OrderStatusID); if (osi != null) { oi.OrderStatusID = osi.StatusID; // Save order status changes OrderInfoProvider.SetOrderInfo(oi); } } break; } }
protected void Page_Load(object sender, EventArgs e) { // Control initializations rfvDisplayName.ErrorMessage = GetString("general.requiresdisplayname"); rfvName.ErrorMessage = GetString("Task_Edit.EmptyName"); lblFrom.Text = GetString("scheduler.from"); btnReset.OnClientClick = "if (!confirm(" + ScriptHelper.GetLocalizedString("tasks.reset") + ")) return false;"; plcDevelopment.Visible = developmentMode; // Show 'Allow run in external service' check-box in development mode plcAllowExternalService.Visible = developmentMode; string currentTask = GetString("Task_Edit.NewItemCaption"); if (TaskID > 0) { // Set edited object EditedObject = TaskInfo; if (TaskInfo != null) { // Global task and user is not global administrator and task's site id is different than current site id if (!MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) && ((TaskInfo.TaskSiteID == 0) || (TaskInfo.TaskSiteID != SiteID))) { RedirectToAccessDenied(GetString("general.nopermission")); } currentTask = TaskInfo.TaskDisplayName; if (!RequestHelper.IsPostBack()) { ReloadData(); // Show that the task was created or updated successfully if (QueryHelper.GetBoolean("saved", false)) { ShowChangesSaved(); } } } } else { // Check "modify" permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } if (WebFarmContext.WebFarmEnabled) { if (!RequestHelper.IsPostBack()) { chkAllServers.Visible = true; } chkAllServers.Attributes.Add("onclick", "document.getElementById('" + txtServerName.ClientID + "').disabled = document.getElementById('" + chkAllServers.ClientID + "').checked;"); } } plcRunIndividually.Visible = (SiteID <= 0); // Initializes page title control BreadcrumbItem tasksLink = new BreadcrumbItem(); tasksLink.Text = GetString("Task_Edit.ItemListLink"); bool notSystem = (TaskInfo == null) || (TaskInfo.TaskType != ScheduledTaskTypeEnum.System); string listUrl = UIContextHelper.GetElementUrl("CMS.ScheduledTasks", GetElementName(notSystem ? "Tasks" : "SystemTasks"), true); listUrl = URLHelper.AddParameterToUrl(listUrl, "siteid", SiteID.ToString()); tasksLink.RedirectUrl = listUrl; PageBreadcrumbs.Items.Add(tasksLink); PageBreadcrumbs.Items.Add(new BreadcrumbItem { Text = currentTask }); }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Check "modify" permission if (!MembershipContext.AuthenticatedUser.IsAuthorizedPerResource("CMS.ScheduledTasks", "Modify")) { RedirectToAccessDenied("CMS.ScheduledTasks", "Modify"); } // Check required fields format string errorMessage = new Validator() .NotEmpty(txtTaskDisplayName.Text, rfvDisplayName.ErrorMessage) .NotEmpty(txtTaskName.Text, rfvName.ErrorMessage) .IsCodeName(txtTaskName.Text, GetString("Task_Edit.InvalidTaskName")) .MatchesCondition(schedInterval.StartTime.SelectedDateTime, DataTypeManager.IsValidDate, String.Format("{0} {1}.", GetString("BasicForm.ErrorInvalidDateTime"), DateTime.Now)) .Result; if ((errorMessage == String.Empty) && !schedInterval.CheckIntervalPreceedings()) { errorMessage = GetString("Task_Edit.BetweenIntervalPreceedingsError"); } if ((errorMessage == String.Empty) && !schedInterval.CheckOneDayMinimum()) { errorMessage = GetString("Task_Edit.AtLeastOneDayError"); } // Validate assembly, but only if task is enabled (so tasks for not-installed modules can be disabled) if ((errorMessage == String.Empty) && chkTaskEnabled.Checked && !assemblyElem.IsValid()) { errorMessage = assemblyElem.ErrorMessage; } // Checking date/time limit (SQL limit) if (errorMessage == String.Empty) { TaskInterval ti = SchedulingHelper.DecodeInterval(schedInterval.ScheduleInterval); if ((ti != null) && ((ti.StartTime < DataTypeManager.MIN_DATETIME) || (ti.StartTime > DataTypeManager.MAX_DATETIME))) { ti.StartTime = DateTime.Now; schedInterval.ScheduleInterval = SchedulingHelper.EncodeInterval(ti); } } // Check macro condition length if ((errorMessage == String.Empty) && (ucMacroEditor.Text.Length > 400)) { errorMessage = String.Format(GetString("task_edit.invalidlength"), 400); } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } else { // Check existing task name TaskInfo existingTask = TaskInfoProvider.GetTaskInfo(txtTaskName.Text.Trim(), SiteInfo != null ? SiteInfo.SiteName : null); if ((existingTask != null) && ((TaskInfo == null) || (existingTask.TaskID != TaskInfo.TaskID))) { ShowError(GetString("Task_Edit.TaskNameExists").Replace("%%name%%", existingTask.TaskName)); return; } if (TaskInfo == null) { // create new item -> insert TaskInfo = new TaskInfo { TaskSiteID = SiteID }; if (!developmentMode) { TaskInfo.TaskAllowExternalService = true; } } TaskInfo.TaskAssemblyName = assemblyElem.AssemblyName.Trim(); TaskInfo.TaskClass = assemblyElem.ClassName.Trim(); TaskInfo.TaskData = txtTaskData.Text.Trim(); TaskInfo.TaskName = txtTaskName.Text.Trim(); TaskInfo.TaskEnabled = chkTaskEnabled.Checked; TaskInfo.TaskDeleteAfterLastRun = chkTaskDeleteAfterLastRun.Checked; TaskInfo.TaskInterval = schedInterval.ScheduleInterval; TaskInfo.TaskDisplayName = txtTaskDisplayName.Text.Trim(); TaskInfo.TaskServerName = txtServerName.Text.Trim(); TaskInfo.TaskRunInSeparateThread = chkRunTaskInSeparateThread.Checked; TaskInfo.TaskUseExternalService = chkTaskUseExternalService.Checked; TaskInfo.TaskCondition = ucMacroEditor.Text; TaskInfo.TaskRunIndividuallyForEachSite = chkRunIndividually.Checked; if (plcAllowExternalService.Visible) { TaskInfo.TaskAllowExternalService = chkTaskAllowExternalService.Checked; } if (plcUseExternalService.Visible) { TaskInfo.TaskUseExternalService = chkTaskUseExternalService.Checked; } TaskInfo.TaskNextRunTime = SchedulingHelper.GetFirstRunTime(SchedulingHelper.DecodeInterval(TaskInfo.TaskInterval)); if (drpModule.Visible) { TaskInfo.TaskResourceID = ValidationHelper.GetInteger(drpModule.Value, 0); } TaskInfo.TaskUserID = ValidationHelper.GetInteger(ucUser.Value, 0); // Set synchronization to true (default is false for Scheduled task) TaskInfo.Generalized.StoreSettings(); TaskInfo.Generalized.LogSynchronization = SynchronizationTypeEnum.LogSynchronization; TaskInfo.Generalized.LogIntegration = true; TaskInfo.Generalized.LogEvents = true; // If web farm support, create the tasks for all servers if (chkAllServers.Checked) { TaskInfoProvider.CreateWebFarmTasks(TaskInfo); } else { TaskInfoProvider.SetTaskInfo(TaskInfo); } // Restore original settings TaskInfo.Generalized.RestoreSettings(); bool notSystem = (TaskInfo == null) || (TaskInfo.TaskType != ScheduledTaskTypeEnum.System); string url = UIContextHelper.GetElementUrl("CMS.ScheduledTasks", GetElementName(notSystem ? "EditTask" : "EditSystemTask"), true); // Add task ID and saved="1" query parameters url = URLHelper.AddParameterToUrl(String.Format(url, TaskInfo.TaskID), "saved", "1"); // Add site ID query parameter and redirect to the finished URL URLHelper.Redirect(URLHelper.AddParameterToUrl(url, "siteid", SiteID.ToString())); } }
protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterDialogScript(Page); ScriptHelper.RegisterApplicationConstants(Page); // Get the object type string param = ContextMenu.Parameter; string objectType = null; bool showMoveActions = false; if (param != null) { string[] parameters = param.Split(';'); objectType = parameters[0]; showMoveActions = (parameters.Length >= 3) && ValidationHelper.GetBoolean(parameters[2], false); } // Get empty info GeneralizedInfo emptyObject = null; ObjectTypeInfo ti = null; var uiContext = UIContextHelper.GetUIContext(this); if (objectType != null) { var uiContextSiteId = ValidationHelper.GetInteger(uiContext["SiteID"], 0); emptyObject = UniGridFunctions.GetEmptyObjectWithSiteID(objectType, uiContextSiteId); ti = emptyObject.TypeInfo; // Get correct info for listings if (ti.IsListingObjectTypeInfo) { emptyObject = UniGridFunctions.GetEmptyObjectWithSiteID(ti.OriginalObjectType, uiContextSiteId); } } if (emptyObject == null) { Visible = false; return; } var curUser = MembershipContext.AuthenticatedUser; string curSiteName = SiteContext.CurrentSiteName; string menuId = ContextMenu.MenuID; if (ti.OrderColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN && showMoveActions) { iMoveUp.Attributes.Add("onclick", "ContextMoveObject_" + ClientID + "('#moveup', GetContextMenuParameter('" + menuId + "'))"); iMoveDown.Attributes.Add("onclick", "ContextMoveObject_" + ClientID + "('#movedown', GetContextMenuParameter('" + menuId + "'))"); } else { iMoveUp.Visible = false; iMoveDown.Visible = false; } // Export if (ti.ImportExportSettings.AllowSingleExport) { if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "ExportObjects", curSiteName)) { iExport.Attributes.Add("onclick", "ContextExportObject(GetContextMenuParameter('" + menuId + "'), false);"); } else { iExport.Visible = false; } if (ti.GUIDColumn != ObjectTypeInfo.COLUMN_NAME_UNKNOWN) { if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "BackupObjects", curSiteName)) { iBackup.Attributes.Add("onclick", "ContextExportObject(GetContextMenuParameter('" + menuId + "'), true);"); } else { iBackup.Visible = false; } if (curUser.IsAuthorizedPerResource("cms.globalpermissions", "RestoreObjects", curSiteName)) { iRestore.Attributes.Add("onclick", "ContextRestoreObject(GetContextMenuParameter('" + menuId + "'), true);"); } else { iRestore.Visible = false; } } else { iBackup.Visible = false; iRestore.Visible = false; } } else { iExport.Visible = false; iBackup.Visible = false; iRestore.Visible = false; } // Versioning if (ObjectVersionManager.AllowObjectRestore(emptyObject) && UniGridFunctions.ObjectSupportsDestroy(emptyObject) && curUser.IsAuthorizedPerObject(PermissionsEnum.Destroy, emptyObject, curSiteName)) { iDestroy.Attributes.Add("onclick", "ContextDestroyObject_" + ClientID + "(GetContextMenuParameter('" + menuId + "'))"); } else { iDestroy.Visible = false; } // Clonning if ((emptyObject.AllowClone) && (curUser.IsAuthorizedPerObject(PermissionsEnum.Modify, emptyObject, curSiteName)) && (curUser.IsAuthorizedPerObject(PermissionsEnum.Create, emptyObject, curSiteName))) { iClone.Attributes.Add("onclick", "ContextCloneObject" + "(GetContextMenuParameter('" + menuId + "'))"); } else { iClone.Visible = false; } bool ancestor = (iClone.Visible || iDestroy.Visible); sepCloneDestroy.Visible = ancestor; sepExport.Visible = (iBackup.Visible || iRestore.Visible || iExport.Visible) && ancestor; ancestor |= (iBackup.Visible || iRestore.Visible || iExport.Visible); sepMove.Visible = (iMoveUp.Visible || iMoveDown.Visible) && ancestor; Visible = iExport.Visible || iBackup.Visible || iDestroy.Visible || iClone.Visible || iMoveUp.Visible || iMoveDown.Visible; }
/// <summary> /// Edit poll click handler. /// </summary> private void pollsList_OnEdit(object sender, EventArgs e) { string editActionUrl = URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("CMS.Polls", "Groups.EditGroup.EditPoll", false, pollsList.SelectedItemID), "groupid", groupID.ToString()); URLHelper.Redirect(editActionUrl); }
/// <summary> /// Handles form's after data load event. /// </summary> protected void EditForm_OnAfterDataLoad(object sender, EventArgs e) { etaCode.Language = LanguageEnum.HTML; cssLayoutEditor.Editor.Language = LanguageEnum.CSS; cssLayoutEditor.Editor.ShowBookmarks = true; // Do not check changes DocumentManager.RegisterSaveChangesScript = false; EditForm.OnBeforeSave += EditForm_OnBeforeSave; etaCode.Language = LanguageEnum.HTML; wpli = UIContext.EditedObject as WebPartLayoutInfo; layoutID = QueryHelper.GetInteger("layoutid", 0); isSiteManager = ((MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && layoutID != 0) || QueryHelper.GetBoolean("sitemanager", false)); isNew = (LayoutCodeName == "|new|"); isDefault = (LayoutCodeName == "|default|") || (!isSiteManager && string.IsNullOrEmpty(LayoutCodeName)); if ((wpli == null) || (wpli.WebPartLayoutID <= 0)) { isNew |= isSiteManager; editMenuElem.ObjectManager.ObjectType = WebPartLayoutInfo.OBJECT_TYPE; } ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "PreviewHierarchyPerformAction", ScriptHelper.GetScript("function actionPerformed(action) { if (action == 'saveandclose') { document.getElementById('" + hdnClose.ClientID + "').value = '1'; } " + editMenuElem.ObjectManager.GetJSFunction(ComponentEvents.SAVE, null, null) + "; }")); currentUser = MembershipContext.AuthenticatedUser; // Get web part instance (if edited in administration) if ((webpartId != "") && !isSiteManager) { // Get page info pi = CMSWebPartPropertiesPage.GetPageInfo(aliasPath, templateId, culture); if (pi == null) { ShowInformation(GetString("WebPartProperties.WebPartNotFound"), persistent: false); } else { // Get page template pti = pi.UsedPageTemplateInfo; if ((pti != null) && ((pti.TemplateInstance != null))) { webPart = pti.TemplateInstance.GetWebPart(instanceGuid, zoneVariantId, variantId) ?? pti.TemplateInstance.GetWebPart(webpartId); } } } // If the web part is not found, try web part ID if (webPart == null) { wpi = WebPartInfoProvider.GetWebPartInfo(ValidationHelper.GetInteger(webpartId, 0)); if (wpi == null) { ShowError(GetString("WebPartProperties.WebPartNotFound")); return; } } else { // CMS desk wpi = WebPartInfoProvider.GetWebPartInfo(webPart.WebPartType); if (string.IsNullOrEmpty(LayoutCodeName)) { // Get the current layout name LayoutCodeName = ValidationHelper.GetString(webPart.GetValue("WebPartLayout"), ""); } } if (wpi != null) { // Load the web part information webPartInfo = wpi; bool loaded = false; if (!RequestHelper.IsPostBack()) { if (wpli != null) { editMenuElem.MenuPanel.Visible = true; // Read-only code text area etaCode.Editor.ReadOnly = false; loaded = true; } if (!loaded) { string fileName = WebPartInfoProvider.GetFullPhysicalPath(webPartInfo); // Check if filename exist if (!FileHelper.FileExists(fileName)) { ShowError(GetString("WebPartProperties.FileNotExist")); pnlContent.Visible = false; editMenuElem.ObjectEditMenu.Visible = false; } else { // Load default web part layout code etaCode.Text = File.ReadAllText(Server.MapPath(fileName)); // Load default web part CSS cssLayoutEditor.Text = wpi.WebPartCSS; } } } } if (((wpli == null) || (wpli.WebPartLayoutID <= 0)) && isSiteManager) { editMenuElem.Title.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = GetString("WebParts.Layout"), RedirectUrl = String.Format("{0}&parentobjectid={1}&displaytitle={2}", UIContextHelper.GetElementUrl("CMS.Design", "WebPart.Layout"), QueryHelper.GetInteger("webpartid", 0), false) }); editMenuElem.Title.Breadcrumbs.AddBreadcrumb(new BreadcrumbItem { Text = GetString("webparts_layout_newlayout"), }); } ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "ApplyButton", ScriptHelper.GetScript( "function SetRefresh(refreshpage) { document.getElementById('" + hidRefresh.ClientID + @"').value = refreshpage; } function OnApplyButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('save');refreshPreview(); } function OnOKButton(refreshpage) { SetRefresh(refreshpage); actionPerformed('saveandclose'); } ")); InitLayoutForm(); }
protected void Page_Load(object sender, EventArgs e) { // Register script for pendingCallbacks repair ScriptHelper.FixPendingCallbacks(Page); // Handle export settings if (!RequestHelper.IsCallback() && !RequestHelper.IsPostBack()) { ExportSettings = GetNewSettings(); } if (!RequestHelper.IsCallback()) { // Display BETA warning lblBeta.Visible = CMSVersion.IsBetaVersion(); lblBeta.Text = string.Format(GetString("export.BETAwarning"), CMSVersion.GetFriendlySystemVersion(false)); bool notTargetPermissions = false; bool notTempPermissions = false; ctrlAsync.OnFinished += ctrlAsync_OnFinished; ctrlAsync.OnError += ctrlAsync_OnError; // Init steps if (wzdExport.ActiveStepIndex < 2) { configExport.Settings = ExportSettings; if (!RequestHelper.IsPostBack()) { configExport.SiteId = SiteId; } pnlExport.Settings = ExportSettings; // Ensure directories and check permissions try { DirectoryHelper.EnsureDiskPath(ExportSettings.TargetPath + "\\temp.file", ExportSettings.WebsitePath); notTargetPermissions = !DirectoryHelper.CheckPermissions(ExportSettings.TargetPath, true, true, false, false); } catch (UnauthorizedAccessException) { notTargetPermissions = true; } catch (IOExceptions.IOException ex) { pnlWrapper.Visible = false; SetErrorLabel(ex.Message); return; } try { DirectoryHelper.EnsureDiskPath(ExportSettings.TemporaryFilesPath + "\\temp.file", ExportSettings.WebsitePath); notTempPermissions = !DirectoryHelper.CheckPermissions(ExportSettings.TemporaryFilesPath, true, true, false, false); } catch (UnauthorizedAccessException) { notTempPermissions = true; } catch (IOExceptions.IOException ex) { pnlWrapper.Visible = false; SetErrorLabel(ex.Message); return; } } if (notTargetPermissions || notTempPermissions) { string folder = (notTargetPermissions) ? ExportSettings.TargetPath : ExportSettings.TemporaryFilesPath; pnlWrapper.Visible = false; SetErrorLabel(String.Format(GetString("ExportSite.ErrorPermissions"), folder, WindowsIdentity.GetCurrent().Name)); pnlPermissions.Visible = true; lnkPermissions.Target = "_blank"; lnkPermissions.Text = GetString("Install.ErrorPermissions"); lnkPermissions.NavigateUrl = UIContextHelper.GetDocumentationTopicUrl(HELP_TOPIC_DISKPERMISSIONS_LINK); } else { // Try to delete temporary files from previous export if (!RequestHelper.IsPostBack()) { try { ExportProvider.DeleteTemporaryFiles(ExportSettings, false); } catch (Exception ex) { pnlWrapper.Visible = false; SetErrorLabel(GetString("ImportSite.ErrorDeletionTemporaryFiles") + ex.Message); return; } } PortalHelper.EnsureScriptManager(Page).EnablePageMethods = true; // Javascript functions string script = @"var exMessageText = ''; var exErrorText = ''; var exWarningText = ''; var exMachineName = '" + SystemContext.MachineName.ToLowerCSafe() + @"'; var getBusy = false; function GetExportState(cancel) { if (window.Activity) { window.Activity(); } if (getBusy) return; getBusy = true; setTimeout('getBusy = false;', 2000); var argument = cancel + ';' + exMessageText.length + ';' + exErrorText.length + ';' + exWarningText.length + ';' + exMachineName; " + Page.ClientScript.GetCallbackEventReference(this, "argument", "SetExportStateMssg", "argument", false) + @"; } function SetExportStateMssg(rValue, context) { getBusy = false; if (rValue!='') { var args = context.split(';'); var values = rValue.split('" + SiteExportSettings.SEPARATOR + @"'); var messageElement = document.getElementById('" + lblProgress.ClientID + @"'); var errorElement = document.getElementById('" + lblError.ClientID + @"'); var warningElement = document.getElementById('" + lblWarning.ClientID + @"'); var messageText = exMessageText; messageText = values[1] + messageText.substring(messageText.length - args[1]); if (messageText.length > exMessageText.length) { exMessageText = messageElement.innerHTML = messageText; } var errorText = exErrorText; errorText = values[2] + errorText.substring(errorText.length - args[2]); if (errorText.length > exErrorText.length) { exErrorText = errorElement.innerHTML = errorText; document.getElementById('" + pnlError.ClientID + @"').style.removeProperty('display'); } var warningText = exWarningText; warningText = values[3] + warningText.substring(warningText.length - args[3]); if (warningText.length > exWarningText.length) { exWarningText = warningElement.innerHTML = warningText; document.getElementById('" + pnlWarning.ClientID + @"').style.removeProperty('display'); } if ((values=='') || (values[0]=='F')) { StopExportStateTimer(); var actDiv = document.getElementById('actDiv'); if (actDiv != null) { actDiv.style.display = 'none'; } BTN_Enable('" + FinishButton.ClientID + @"'); try { BTN_Disable('" + CancelButton.ClientID + @"'); } catch(err) { } } } }"; // Register the script to perform get flags for showing buttons retrieval callback ScriptHelper.RegisterClientScriptBlock(this, GetType(), "GetSetExportState", ScriptHelper.GetScript(script)); // Add cancel button attribute CancelButton.Attributes.Add("onclick", "BTN_Disable('" + CancelButton.ClientID + "'); return CancelExport();"); wzdExport.NextButtonClick += wzdExport_NextButtonClick; wzdExport.PreviousButtonClick += wzdExport_PreviousButtonClick; wzdExport.FinishButtonClick += wzdExport_FinishButtonClick; if (!RequestHelper.IsPostBack()) { configExport.InitControl(); } } } }
/// <summary> /// Handles the OnAfterAction event of the ObjectManager control. /// </summary> protected void ObjectManager_OnAfterAction(object sender, SimpleObjectManagerEventArgs e) { wpli = EditForm.EditedObject as WebPartLayoutInfo; if ((wpli == null) || (wpli.WebPartLayoutID <= 0) || (!e.IsValid)) { // Do not continue if the object has not been created return; } LayoutCodeName = wpli.WebPartLayoutCodeName; if (e.ActionName == ComponentEvents.SAVE) { if (EditForm.ValidateData()) { if (!isSiteManager) { SetCurrentLayout(true); } if (ValidationHelper.GetBoolean(hdnClose.Value, false)) { // If window to close, register close script CloseDialog(); } else { // Redirect parent for new if (isNew) { if (isSiteManager) { URLHelper.Redirect(String.Format("{0}&parentobjectid={1}&objectid={2}&displaytitle={3}", UIContextHelper.GetElementUrl("CMS.Design", "Edit.WebPartLayout"), webPartInfo.WebPartID, wpli.WebPartLayoutID, false)); } else { var codeName = (wpli != null) ? wpli.WebPartLayoutCodeName : string.Empty; var redirectUrl = ResolveUrl("~/CMSModules/PortalEngine/UI/WebParts/WebPartProperties_layout_frameset.aspx") + URLHelper.UpdateParameterInUrl(RequestContext.CurrentQueryString, "layoutcodename", codeName); ScriptHelper.RegisterClientScriptBlock(Page, typeof(string), "RefreshHeader", ScriptHelper.GetScript("parent.location ='" + redirectUrl + "'")); // Reload the parent page after save EnsureParentPageRefresh(); } } else { if (!isSiteManager) { // Reload the parent page after save EnsureParentPageRefresh(); } // If all ok show changes saved RegisterRefreshScript(); } } } // Clear warning text editMenuElem.MessagesPlaceHolder.WarningText = ""; } if (DialogMode) { switch (e.ActionName) { case ComponentEvents.SAVE: case ComponentEvents.CHECKOUT: case ComponentEvents.UNDO_CHECKOUT: case ComponentEvents.CHECKIN: ScriptHelper.RegisterStartupScript(Page, typeof(string), "wopenerRefresh", ScriptHelper.GetScript("if (wopener && wopener.refresh) { wopener.refresh(); }")); break; } } if (isSiteManager && (e.ActionName != ComponentEvents.CHECKOUT) && EditForm.DisplayNameChanged) { ScriptHelper.RegisterClientScriptBlock(Page, typeof(String), "RefreshBreadcrumbs", ScriptHelper.GetScript("if (parent.refreshBreadcrumbs != null && parent.document.pageLoaded) {parent.refreshBreadcrumbs('" + ResHelper.LocalizeString(EditForm.EditedObject.Generalized.ObjectDisplayName) + "')}")); } }
protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterJQuery(Page); SitePanel.Visible = ShowHeaderPanel && ShowSiteSelector; ActionsPanel.Visible = ShowHeaderPanel && !SitePanel.Visible; plcActionSelectionScript.Visible = ShowHeaderPanel && !ShowSiteSelector; plcSelectionScript.Visible = !plcActionSelectionScript.Visible; if (RootCategory != null) { string levelWhere = (MaxRelativeLevel <= 0 ? "" : " AND (CategoryLevel <= " + (RootCategory.CategoryLevel + MaxRelativeLevel) + ")"); // Restrict CategoryChildCount to MaxRelativeLevel. If level < MaxRelativeLevel, use count of non-group children. string levelColumn = "CASE CategoryLevel WHEN " + MaxRelativeLevel + " THEN 0 ELSE (SELECT COUNT(*) AS CountNonGroup FROM CMS_SettingsCategory AS sc WHERE (sc.CategoryParentID = CMS_SettingsCategory.CategoryID) AND (sc.CategoryIsGroup = 0)) END AS CategoryChildCount"; // Create and set category provider UniTreeProvider provider = new UniTreeProvider(); provider.RootLevelOffset = RootCategory.CategoryLevel; provider.ObjectType = "CMS.SettingsCategory"; provider.DisplayNameColumn = "CategoryDisplayName"; provider.IDColumn = "CategoryID"; provider.LevelColumn = "CategoryLevel"; provider.OrderColumn = "CategoryOrder"; provider.ParentIDColumn = "CategoryParentID"; provider.PathColumn = "CategoryIDPath"; provider.ValueColumn = "CategoryID"; provider.ChildCountColumn = "CategoryChildCount"; provider.ImageColumn = "CategoryIconPath"; provider.WhereCondition = "((CategoryIsGroup IS NULL) OR (CategoryIsGroup = 0)) " + levelWhere; if (!ShowEmptyCategories) { var where = "CategoryID IN (SELECT CategoryParentID FROM CMS_SettingsCategory WHERE (CategoryIsGroup = 0) OR (CategoryIsGroup = 1 AND CategoryID IN (SELECT KeyCategoryID FROM CMS_SettingsKey WHERE ISNULL(SiteID, 0) = 0 AND ISNULL(KeyIsHidden, 0) = 0"; if (SiteID > 0) { where += " AND KeyIsGlobal = 0"; } where += ")))"; provider.WhereCondition = SqlHelper.AddWhereCondition(provider.WhereCondition, where); } provider.Columns = "CategoryID, CategoryName, CategoryDisplayName, CategoryLevel, CategoryOrder, CategoryParentID, CategoryIDPath, CategoryIconPath, CategoryResourceID, " + levelColumn; if (String.IsNullOrEmpty(JavaScriptHandler)) { Tree.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS## ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME##');\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>"; Tree.NodeTemplate = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS##\" onclick=\"SelectNode('##NODECODENAME##');\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>"; } else { Tree.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS## ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME##'); if (" + JavaScriptHandler + ") { " + JavaScriptHandler + "('##NODECODENAME##',##NODEID##, ##SITEID##, ##PARENTID##, ##RESOURCEID##); }\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>"; Tree.NodeTemplate = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS##\" onclick=\"SelectNode('##NODECODENAME##'); if (" + JavaScriptHandler + ") { " + JavaScriptHandler + "('##NODECODENAME##',##NODEID##, ##SITEID##, ##PARENTID##, ##RESOURCEID##); }\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>"; } Tree.UsePostBack = false; Tree.ProviderObject = provider; Tree.ExpandPath = RootCategory.CategoryIDPath; Tree.OnNodeCreated += Tree_OnNodeCreated; } GetExpandedPaths(); NewItemButton.ToolTip = GetString("settings.newelem"); DeleteItemButton.ToolTip = GetString("settings.deleteelem"); MoveUpItemButton.ToolTip = GetString("settings.modeupelem"); MoveDownItemButton.ToolTip = GetString("settings.modedownelem"); // Create new element javascript NewItemButton.OnClientClick = "return newItem();"; // Confirm delete DeleteItemButton.OnClientClick = "if(!deleteConfirm()) { return false; }"; var isPostback = RequestHelper.IsPostBack(); if (!isPostback) { Tree.ReloadData(); if (QueryHelper.GetBoolean("reloadtreeselect", false)) { var category = SettingsCategoryInfo.Provider.Get(CategoryID); // Select requested category RegisterSelectNodeScript(category); } } if (ShowSiteSelector) { if (!isPostback) { if (QueryHelper.Contains("selectedSiteId")) { // Get from URL SiteID = QueryHelper.GetInteger("selectedSiteId", 0); SiteSelector.Value = SiteID; } } else { SiteID = ValidationHelper.GetInteger(SiteSelector.Value, 0); } // Style site selector SiteSelector.SetValue("AllowGlobal", true); SiteSelector.SetValue("GlobalRecordValue", 0); bool reload = QueryHelper.GetBoolean("reload", true); // URL for tree selection string script = "var categoryURL = '" + UIContextHelper.GetElementUrl(ModuleName.CMS, "Settings.Keys") + "';\n"; script += "var doNotReloadContent = false;\n"; // Select category SettingsCategoryInfo sci = SettingsCategoryInfo.Provider.Get(CategoryID); if (sci != null) { // Stop reloading of right frame, if explicitly set if (!reload) { script += "doNotReloadContent = true;"; } script += SelectAtferLoad(sci.CategoryIDPath, sci.CategoryName, sci.CategoryID, sci.CategoryParentID); } ScriptHelper.RegisterStartupScript(Page, typeof(string), "SelectCat", ScriptHelper.GetScript(script)); } else { ResourceInfo resource = ResourceInfo.Provider.Get(ModuleID); StringBuilder sb = new StringBuilder(); sb.Append(@" var frameURL = '", UIContextHelper.GetElementUrl(ModuleName.CMS, "EditSettingsCategory", false), @"'; var rootId = ", (RootCategory != null ? RootCategory.CategoryID : 0), @"; var selectedModuleId = ", ModuleID, @"; var developmentMode = ", SystemContext.DevelopmentMode ? "true" : "false", @"; var resourceInDevelopment = ", (resource != null) && resource.ResourceIsInDevelopment ? "true" : "false", @"; var postParentId = ", CategoryID, @"; function newItem() { var hidElem = document.getElementById('" + hidSelectedElem.ClientID + @"'); var ids = hidElem.value.split('|'); if (window.parent != null && window.parent.frames['settingsmain'] != null) { window.parent.frames['settingsmain'].location = '" + ResolveUrl("~/CMSModules/Modules/Pages/Settings/Category/Edit.aspx") + @"?moduleid=" + ModuleID + @"&parentId=' + ids[0]; } return false; } function deleteConfirm() { return confirm(" + ScriptHelper.GetString(GetString("settings.categorydeleteconfirmation")) + @"); } "); ScriptHelper.RegisterClientScriptBlock(this, typeof(string), "setupTreeScript", ScriptHelper.GetScript(sb.ToString())); } }
/// <summary> /// Initializes the control properties. /// </summary> protected void SetupControl() { if (StopProcessing) { Visible = false; } else { if (SystemContext.IsFullTrustLevel) { // Check if OpenID module is enabled if (SettingsKeyInfoProvider.GetBoolValue(SiteContext.CurrentSiteName + ".CMSEnableOpenID")) { ltlScript.Text = ScriptHelper.GetScriptTag(PROVIDERS_LOCATION + "OpenIDSelector.js"); lblError.Text = GetString("openid.invalidid"); SetProviders(); DisplayButtons(); openIDhelper = new CMSOpenIDHelper(); CheckStatus(); } else { // Error label is displayed in Design mode when OpenID is disabled if (PortalContext.IsDesignMode(PortalContext.ViewMode)) { StringBuilder parameter = new StringBuilder(); parameter.Append(UIElementInfoProvider.GetApplicationNavigationString("cms", "Settings") + " -> "); parameter.Append(GetString("settingscategory.cmsmembership") + " -> "); parameter.Append(GetString("settingscategory.cmsmembershipauthentication") + " -> "); parameter.Append(GetString("settingscategory.cmsopenid")); if (MembershipContext.AuthenticatedUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin)) { // Make it link for Admin parameter.Insert(0, "<a href=\"" + URLHelper.GetAbsoluteUrl(UIContextHelper.GetApplicationUrl("cms", "settings")) + "\" target=\"_top\">"); parameter.Append("</a>"); } lblError.Text = String.Format(GetString("mem.openid.disabled"), parameter.ToString()); lblError.Visible = true; txtInput.Visible = false; } else { Visible = false; } } } // Error label is displayed in Design mode when OpenID library is not enabled else { lblError.Text = ResHelper.GetString("socialnetworking.fulltrustrequired"); lblError.Visible = true; txtInput.Visible = false; } } }
protected void Page_Load(object sender, EventArgs e) { SiteInfo currentSite = SiteContext.CurrentSite; mBounceLimit = NewsletterHelper.BouncedEmailsLimit(currentSite.SiteName); mBounceInfoAvailable = NewsletterHelper.MonitorBouncedEmails(currentSite.SiteName); // Initialize unigrid UniGrid.OnAction += uniGrid_OnAction; UniGrid.OnExternalDataBound += uniGrid_OnExternalDataBound; UniGrid.WhereCondition = "SubscriberSiteID = " + currentSite.SiteID; UniGrid.FilteredZeroRowsText = GetString("subscriber_list.nodata.filtered"); if (LicenseContext.CurrentLicenseInfo.Edition == ProductEditionEnum.EnterpriseMarketingSolution) { UniGrid.ZeroRowsText = string.Format(GetString("subscriber_list.nodata.ems"), URLHelper.ResolveUrl(UIContextHelper.GetApplicationUrl(ModuleName.ONLINEMARKETING, "ContactsFrameset", "?tabname=Contacts"))); } else { UniGrid.ZeroRowsText = GetString("subscriber_list.nodata.noems"); } }
protected override void OnLoad(EventArgs e) { // Show message when reordering and not all reordered product were added to cart if (!URLHelper.IsPostback() && QueryHelper.GetBoolean("notallreordered", false)) { lblError.Text = GetString("com.notallreordered"); } if ((ShoppingCart != null) && IsLiveSite) { // Get order information OrderInfo oi = OrderInfoProvider.GetOrderInfo(ShoppingCart.OrderId); // If order is paid if ((oi != null) && (oi.OrderIsPaid)) { // Clean shopping cart if paid order cart is still in customers current cart on LS ShoppingCartControl.CleanUpShoppingCart(); } } if ((ShoppingCart != null) && (ShoppingCart.CountryID == 0) && (SiteContext.CurrentSite != null)) { string countryName = ECommerceSettings.DefaultCountryName(SiteContext.CurrentSiteName); CountryInfo ci = CountryInfoProvider.GetCountryInfo(countryName); ShoppingCart.CountryID = (ci != null) ? ci.CountryID : 0; // Set currency selectors site ID selectCurrency.SiteID = ShoppingCart.ShoppingCartSiteID; } lnkNewItem.Text = GetString("ecommerce.shoppingcartcontent.additem"); btnUpdate.Text = GetString("ecommerce.shoppingcartcontent.btnupdate"); btnEmpty.Text = GetString("ecommerce.shoppingcartcontent.btnempty"); btnEmpty.OnClientClick = string.Format("return confirm({0});", ScriptHelper.GetString(GetString("ecommerce.shoppingcartcontent.emptyconfirm"))); // Add new product dialog string addProductUrl = UIContextHelper.GetElementDialogUrl(ModuleName.ECOMMERCE, "order.addorderitems", 0, GetCMSDeskShoppingCartSessionNameQuery()); lnkNewItem.OnClientClick = ScriptHelper.GetModalDialogScript(addProductUrl, "addproduct", 1000, 620); gridData.Columns[4].HeaderText = GetString("general.remove"); gridData.Columns[5].HeaderText = GetString("ecommerce.shoppingcartcontent.actions"); gridData.Columns[6].HeaderText = GetString("ecommerce.shoppingcartcontent.skuname"); gridData.Columns[7].HeaderText = GetString("ecommerce.shoppingcartcontent.skuunits"); gridData.Columns[8].HeaderText = GetString("ecommerce.shoppingcartcontent.unitprice"); gridData.Columns[9].HeaderText = GetString("ecommerce.shoppingcartcontent.unitdiscount"); gridData.Columns[10].HeaderText = GetString("ecommerce.shoppingcartcontent.tax"); gridData.Columns[11].HeaderText = GetString("ecommerce.shoppingcartcontent.subtotal"); gridData.RowDataBound += gridData_RowDataBound; // Hide "add product" action for live site order if (!ShoppingCartControl.IsInternalOrder) { pnlNewItem.Visible = false; ShoppingCartControl.ButtonBack.Text = GetString("ecommerce.cartcontent.buttonbacktext"); ShoppingCartControl.ButtonBack.ButtonStyle = ButtonStyle.Default; ShoppingCartControl.ButtonNext.Text = GetString("ecommerce.cartcontent.buttonnexttext"); if (!ShoppingCartControl.IsCurrentStepPostBack) { // Get shopping cart item parameters from URL ShoppingCartItemParameters itemParams = ShoppingCartItemParameters.GetShoppingCartItemParameters(); // Set item in the shopping cart AddProducts(itemParams); } } // Set sending order notification when editing existing order according to the site settings if (ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems) { if (!ShoppingCartControl.IsCurrentStepPostBack) { if (!string.IsNullOrEmpty(ShoppingCart.SiteName)) { chkSendEmail.Checked = ECommerceSettings.SendOrderNotification(ShoppingCart.SiteName); } } // Show send email checkbox chkSendEmail.Visible = true; chkSendEmail.Text = GetString("shoppingcartcontent.sendemail"); // Setup buttons ShoppingCartControl.ButtonBack.Visible = false; ShoppingCart.CheckAvailableItems = false; ShoppingCartControl.ButtonNext.Text = GetString("general.next"); if ((!ExistAnotherStepsExceptPayment) && (ShoppingCartControl.PaymentGatewayProvider == null)) { ShoppingCartControl.ButtonNext.Text = GetString("general.ok"); } } // Fill dropdownlist if (!ShoppingCartControl.IsCurrentStepPostBack) { if (!ShoppingCart.IsEmpty || ShoppingCartControl.IsInternalOrder) { if (ShoppingCart.ShoppingCartCurrencyID == 0) { // Select customer preferred currency if (ShoppingCart.Customer != null) { CustomerInfo customer = ShoppingCart.Customer; ShoppingCart.ShoppingCartCurrencyID = (customer.CustomerUser != null) ? customer.CustomerUser.GetUserPreferredCurrencyID(SiteContext.CurrentSiteName) : 0; } } if (ShoppingCart.ShoppingCartCurrencyID == 0) { if (SiteContext.CurrentSite != null) { var mainCurrency = CurrencyInfoProvider.GetMainCurrency(SiteContext.CurrentSiteID); if (mainCurrency != null) { ShoppingCart.ShoppingCartCurrencyID = mainCurrency.CurrencyID; } } } selectCurrency.SelectedID = ShoppingCart.ShoppingCartCurrencyID; // Fill textbox with discount coupon code if (!String.IsNullOrEmpty(ShoppingCart.ShoppingCartCouponCode)) { txtCoupon.Text = ShoppingCart.ShoppingCartCouponCode; } } ReloadData(); } // Check if customer is enabled if ((ShoppingCart.Customer != null) && (!ShoppingCart.Customer.CustomerEnabled)) { HideCartContent(GetString("ecommerce.cartcontent.customerdisabled")); } // Ensure order currency in selector if ((ShoppingCartControl.CheckoutProcessType == CheckoutProcessEnum.CMSDeskOrderItems) && (ShoppingCart.Order != null)) { selectCurrency.AdditionalItems += ShoppingCart.Order.OrderCurrencyID + ";"; } // Turn on available items checking after content is loaded ShoppingCart.CheckAvailableItems = true; base.OnLoad(e); }
/// <summary> /// OnLoad event handler. /// </summary> /// <param name="e">Event argument</param> protected override void OnLoad(EventArgs e) { base.OnLoad(e); EditForm.RedirectUrlAfterCreate = URLHelper.AppendQuery(UIContextHelper.GetElementUrl("CMS.Scoring", "ScoringProperties"), "displayTitle=0&tabname=Scoring.General&objectid={%EditedObject.ID%}&saved=1"); }
private void grid_OnAction(string actionName, object actionArgument) { int skuId = ValidationHelper.GetInteger(actionArgument, 0); switch (actionName.ToLowerCSafe()) { case "edit": // Show product tabs for type Products, otherwise show only general tab { string url = (categoryObj.CategoryType == OptionCategoryTypeEnum.Products) ? UIContextHelper.GetElementUrl("CMS.ECommerce", "ProductOptions.Options.Edit") : "~/CMSModules/Ecommerce/Pages/Tools/Products/Product_Edit_General.aspx"; url = URLHelper.AddParameterToUrl(url, "displaytitle", "false"); url = URLHelper.AddParameterToUrl(url, "productId", skuId.ToString()); url = URLHelper.AddParameterToUrl(url, "categoryid", categoryId.ToString()); url = URLHelper.AddParameterToUrl(url, "siteId", categoryObj.CategorySiteID.ToString()); url = URLHelper.AddParameterToUrl(url, "objectid", categoryId.ToString()); url = URLHelper.AddParameterToUrl(url, "dialog", QueryHelper.GetString("dialog", "0")); // Add parent product id if (parentProductId > 0) { url += "&parentProductId=" + parentProductId; } URLHelper.Redirect(url); } break; case "delete": // Check permissions CheckModifyPermission(); // Check dependencies if (SKUInfoProvider.CheckDependencies(skuId)) { // Show error message ShowError(GetString("Ecommerce.DeleteDisabled")); return; } // Check if same variant is defined by this option DataSet variants = VariantOptionInfoProvider.GetVariantOptions() .TopN(1) .Columns("VariantSKUID") .WhereEquals("OptionSKUID", skuId); if (!DataHelper.DataSourceIsEmpty(variants)) { // Option is used in some variant ShowError(GetString("com.option.usedinvariant")); return; } SKUInfoProvider.DeleteSKUInfo(skuId); ugOptions.ReloadData(); break; case "moveup": // Check permissions CheckModifyPermission(); SKUInfoProvider.MoveSKUOptionUp(skuId); break; case "movedown": // Check permissions CheckModifyPermission(); SKUInfoProvider.MoveSKUOptionDown(skuId); break; } }
/// <summary> /// Sets data to database. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { string errorMessage = new Validator().NotEmpty(txtWordExpression.Text, GetString("general.requiresvalue")).Result; if (errorMessage == string.Empty) { if (badWordObj == null) { badWordObj = new BadWordInfo(); } // Set edited object EditedObject = badWordObj; // If bad word doesn't already exist, create new one if (!(((badWordId <= 0) || WordExpressionHasChanged()) && BadWordInfoProvider.BadWordExists(txtWordExpression.Text.Trim()))) { badWordObj.WordExpression = txtWordExpression.Text.Trim(); BadWordActionEnum action = (BadWordActionEnum)Convert.ToInt32(SelectBadWordActionControl.Value.ToString().Trim()); badWordObj.WordAction = !chkInheritAction.Checked ? action : 0; badWordObj.WordReplacement = (!chkInheritReplacement.Checked && (action == BadWordActionEnum.Replace)) ? txtWordReplacement.Text : null; badWordObj.WordLastModified = DateTime.Now; badWordObj.WordIsRegularExpression = chkIsRegular.Checked; badWordObj.WordMatchWholeWord = chkMatchWholeWord.Checked; if (badWordId <= 0) { badWordObj.WordIsGlobal = true; } BadWordInfoProvider.SetBadWordInfo(badWordObj); if (badWordId <= 0) { string redirectTo = badWordId <= 0 ? UIContextHelper.GetElementUrl("CMS.Badwords", "Administration.BadWords.Edit") : UIContextHelper.GetElementUrl("CMS.Badwords", "Administration.BadWords.Edit.General"); redirectTo = URLHelper.AddParameterToUrl(redirectTo, "objectid", badWordObj.WordID.ToString()); redirectTo = URLHelper.AddParameterToUrl(redirectTo, "saved", "1"); URLHelper.Redirect(redirectTo); } else { ScriptHelper.RefreshTabHeader(Page, txtWordExpression.Text.Trim()); ShowChangesSaved(); } } else { ShowError(GetString("badwords_edit.badwordexists")); } } else { ShowError(errorMessage); } }
/// <summary> /// Handles the grid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void gridElem_OnAction(string actionName, object actionArgument) { int orderId = ValidationHelper.GetInteger(actionArgument, 0); switch (actionName.ToLowerInvariant()) { case "edit": string redirectToUrl = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "OrderProperties", false, orderId); if (customerId > 0) { redirectToUrl += "&customerId=" + customerId; } URLHelper.Redirect(redirectToUrl); break; case "previous": { // Check 'ModifyOrders' and 'EcommerceModify' permission if (!ECommerceContext.IsUserAuthorizedForPermission(EcommercePermissions.ORDERS_MODIFY)) { AccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifyOrders"); } var oi = OrderInfoProvider.GetOrderInfo(orderId); if (oi != null) { var osi = OrderStatusInfoProvider.GetPreviousEnabledStatus(oi.OrderStatusID); if (osi != null) { oi.OrderStatusID = osi.StatusID; // Save order status changes OrderInfoProvider.SetOrderInfo(oi); } } break; } case "next": { // Check 'ModifyOrders' and 'EcommerceModify' permission if (!ECommerceContext.IsUserAuthorizedForPermission(EcommercePermissions.ORDERS_MODIFY)) { AccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifyOrders"); } var oi = OrderInfoProvider.GetOrderInfo(orderId); if (oi != null) { var osi = OrderStatusInfoProvider.GetNextEnabledStatus(oi.OrderStatusID); if (osi != null) { oi.OrderStatusID = osi.StatusID; // Save order status changes OrderInfoProvider.SetOrderInfo(oi); } } break; } } }
/// <summary> /// Handles the OptionCategoryGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void OptionCategoryGrid_OnAction(string actionName, object actionArgument) { int categoryId = ValidationHelper.GetInteger(actionArgument, 0); switch (actionName.ToLowerCSafe()) { case "edit": URLHelper.Redirect(UIContextHelper.GetElementUrl("CMS.Ecommerce", "EditOptionCategory", false, categoryId)); break; case "delete": OptionCategoryInfo categoryObj = OptionCategoryInfoProvider.GetOptionCategoryInfo(categoryId); if (categoryObj == null) { break; } // Check permissions if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(categoryObj)) { // Check module permissions if (categoryObj.CategoryIsGlobal) { RedirectToAccessDenied("CMS.Ecommerce", "EcommerceGlobalModify"); } else { RedirectToAccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyProducts"); } } // Check category dependencies if (categoryObj.Generalized.CheckDependencies()) { // Show error message ShowError(GetString("Ecommerce.DeleteDisabled")); return; } DataSet options = SKUInfoProvider.GetSKUOptions(categoryId, false); // Check option category options dependencies if (!DataHelper.DataSourceIsEmpty(options)) { // Check if some attribute option is not used in variant if (categoryObj.CategoryType == OptionCategoryTypeEnum.Attribute) { var optionIds = DataHelper.GetIntegerValues(options.Tables[0], "SKUID"); // Check if some variant is defined by this option DataSet variants = VariantOptionInfoProvider.GetVariantOptions() .TopN(1) .Column("VariantSKUID") .WhereIn("OptionSKUID", optionIds); if (!DataHelper.DataSourceIsEmpty(variants)) { // Option is used in some variant ShowError(GetString("com.option.categoryoptiosusedinvariant")); return; } } // Check other dependencies (shopping cart, order) foreach (DataRow option in options.Tables[0].Rows) { if (SKUInfoProvider.CheckDependencies(ValidationHelper.GetInteger(option["SKUID"], 0))) { // Show error message ShowError(GetString("Ecommerce.DeleteDisabled")); return; } } } // Delete option category from database OptionCategoryInfoProvider.DeleteOptionCategoryInfo(categoryObj); break; } }
/// <summary> /// Handles the UniGrid's OnAction event. /// </summary> /// <param name="actionName">Name of item (button) that throws event</param> /// <param name="actionArgument">ID (value of Primary key) of corresponding data row</param> protected void Control_OnAction(string actionName, object actionArgument) { SiteInfo si = SiteInfoProvider.GetSiteInfo(ValidationHelper.GetInteger(actionArgument, 0)); if (si != null) { string siteName = si.SiteName; switch (actionName) { case "delete": URLHelper.Redirect("~/CMSModules/Sites/Pages/site_delete.aspx?siteid=" + actionArgument); break; case "editContent": { // Build URL for site in format 'http(s)://sitedomain/application/admin' string sitedomain = si.DomainName.TrimEnd('/'); string application = null; // Support of multiple web sites on single domain if (!sitedomain.Contains("/")) { application = UrlResolver.ResolveUrl("~/.").TrimEnd('/'); } // Application includes string '/admin'. application += "/admin/"; string url = RequestContext.CurrentScheme + "://" + sitedomain + application; ScriptHelper.RegisterStartupScript(Control.Page, typeof(string), "EditContentScript", ScriptHelper.GetScript("window.open('" + url + "');")); } break; case "openLiveSite": { string url; if (si.SiteIsContentOnly) { // Site is ContentOnly -> just redirect to sites's presentation URL url = si.SitePresentationURL; } else { // Make url for site in form 'http(s)://sitedomain/application'. string sitedomain = si.DomainName.TrimEnd('/'); string application = null; // Support of multiple web sites on single domain if (!sitedomain.Contains("/")) { application = UrlResolver.ResolveUrl("~/.").TrimEnd('/'); } url = RequestContext.CurrentScheme + "://" + sitedomain + application + "/"; } ScriptHelper.RegisterStartupScript(Control.Page, typeof(string), "OpenLiveSiteScript", ScriptHelper.GetScript("window.open('" + url + "');")); } break; case "start": try { SiteInfoProvider.RunSite(siteName); } catch (Exception ex) { Control.ShowError(ResHelper.GetString("Site_List.ErrorMsg"), ex.Message, null); } break; case "stop": SiteInfoProvider.StopSite(siteName); SessionManager.Clear(siteName); break; case "export": URLHelper.Redirect(URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ModuleName.CMS, "Export", false), "siteID=" + actionArgument)); break; } } }
protected TreeNode treeElem_OnNodeCreated(DataRow itemData, TreeNode defaultNode) { // Get data if (itemData != null) { int id = ValidationHelper.GetInteger(itemData["ElementID"], 0); int childCount = ValidationHelper.GetInteger(itemData["ElementChildCount"], 0); bool selected = ValidationHelper.GetBoolean(itemData["ElementSelected"], false); string displayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(itemData["ElementDisplayName"], string.Empty))); string elementName = ValidationHelper.GetString(itemData["ElementName"], string.Empty).ToLowerCSafe(); int parentID = ValidationHelper.GetInteger(itemData["ElementParentID"], 0); int resourceID = ValidationHelper.GetInteger(itemData["ElementResourceID"], 0); string nodePath = ValidationHelper.GetString(itemData["ElementIDPath"], string.Empty); string itemClass = "ContentTreeItem"; string onClickDeclaration = string.Format(" var chkElem_{0} = document.getElementById('chk_{0}'); ", id); string onClickCommon = string.Format(" hdnValue.value = {0} + ';' + chkElem_{0}.checked; {1};", id, CallbackRef); string onClickSpan = string.Format(" chkElem_{0}.checked = !chkElem_{0}.checked; ", id); // Expand for root if (parentID == 0) { defaultNode.Expanded = true; } string[] paths = treeElem.ExpandPath.ToLowerCSafe().Split(';'); if (!nodePath.EndsWith("/")) { nodePath += "/"; } bool chkEnabled = Enabled; if (!SingleModule && (ModuleID > 0)) { bool isEndItem = false; bool isChild = false; bool isParent = false; // Check expanded paths for (int i = 0; i < paths.Length; i++) { String path = paths[i]; if (path != String.Empty) { // Add slash - select only children if (!path.EndsWith("/")) { path += "/"; } if (!isChild) { isChild = nodePath.StartsWith(path); } // Module node is same node as specified in paths collection isEndItem = (path == nodePath); // Test for parent - expand if ((path.StartsWithCSafe(nodePath))) { defaultNode.Expanded = true; isParent = true; break; } } } // Display for non selected module items if (resourceID != ModuleID) { // Parent special css if (isParent) { itemClass += " highlighted disabled"; } else { // Disable non parent chkEnabled = false; itemClass += " disabled"; } } else if (isEndItem) { // Special class for end module item itemClass += " highlighted"; } } // Get button links string links = null; string nodeText; if (!String.IsNullOrEmpty(GroupPreffix) && elementName.ToLowerCSafe().StartsWithCSafe(GroupPreffix.ToLowerCSafe())) { if (childCount > 0 && chkEnabled) { links = string.Format(SELECT_DESELECT_LINKS, id, "false", CallbackRef, GetString("uiprofile.selectall"), GetString("uiprofile.deselectall")); } nodeText = string.Format("<span class='{0}'>{1}</span>{2}", itemClass, displayName, links); } else { string warning = string.Empty; if (SiteName != null) { if (!ResourceSiteInfoProvider.IsResourceOnSite(UIContextHelper.GetResourceName(resourceID), SiteName)) { warning = UIHelper.GetAccessibleIconTag("icon-exclamation-triangle", String.Format(GetString("uiprofile.warningmodule"), "cms." + elementName), additionalClass: "color-orange-80"); } } if (childCount > 0 && chkEnabled) { links = string.Format(SELECT_DESELECT_LINKS, id, "true", CallbackRef, GetString("uiprofile.selectall"), GetString("uiprofile.deselectall")); } nodeText = string.Format(@"<span class='checkbox tree-checkbox'><input type='checkbox' id='chk_{0}' name='chk_{0}'{1}{2} onclick=""{3}"" /><label for='chk_{0}'> </label><span class='{4}' onclick=""{5} return false;""><span class='Name'>{6}</span></span>{7}</span>{8}", id, chkEnabled ? string.Empty : " disabled='disabled'", selected ? " checked='checked'" : string.Empty, chkEnabled ? onClickDeclaration + onClickCommon : "return false;", itemClass, chkEnabled ? onClickDeclaration + onClickSpan + onClickCommon : "return false;", displayName, warning, links); } defaultNode.ToolTip = string.Empty; defaultNode.Text = nodeText; } return(defaultNode); }
protected void editOptionCategory_OnAfterSave(object sender, EventArgs e) { if (EditedCategory == null) { EditedObject = null; return; } // New option category if (!Editing) { // For new TEXT option category create text option if (SelectedCategoryType == OptionCategoryTypeEnum.Text) { CreateTextOption(); } // Assign option category to product if (ParentProduct != null) { SKUOptionCategoryInfoProvider.AddOptionCategoryToSKU(EditedCategory.CategoryID, ParentProduct.SKUID); } // Redirect from new form dialog to option category edit. string query = QueryHelper.BuildQuery("saved", "1", "productid", ProductID.ToString(), "siteid", CategorySiteID.ToString()); if (ParentProduct == null) { URLHelper.Redirect(UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "EditOptionCategory", false, EditedCategory.CategoryID, query)); } else { URLHelper.Redirect(ApplicationUrlHelper.GetElementDialogUrl(ModuleName.ECOMMERCE, "EditProductOptionCategory", EditedCategory.CategoryID, query)); } } if (Editing) { // Refresh breadcrumbs var append = EditedCategory.IsGlobal ? " " + GetString("general.global") : ""; ScriptHelper.RefreshTabHeader(Page, EditedCategory.CategoryDisplayName + append); // Category options DataSet options = SKUInfoProvider.GetSKUOptions(EditedCategory.CategoryID, false); // Option category type may be changed during editing and additional action is required switch (SelectedAdditionalAction) { case AdditionalActionEnum.DeleteOptionsAndCreateTextOption: DestroyOptions(options); CreateTextOption(); break; case AdditionalActionEnum.DeleteTextOption: DestroyOptions(options); CategoryHasOptions = false; break; case AdditionalActionEnum.ConvertAttributeToProduct: ChangeAttributeToProduct(options); break; case AdditionalActionEnum.ConvertProductToAttribute: ChangeProductToAttribute(options); break; case AdditionalActionEnum.None: break; } editOptionCategory.SubmitButton.OnClientClick = ""; } }