protected void Page_Load(object sender, EventArgs e) { filter.SiteID = SiteID; filter.DisableGeneratingSiteClause = true; modifyPermission = AccountHelper.AuthorizedModifyAccount(SiteID, false); if (SiteID == UniSelector.US_GLOBAL_AND_SITE_RECORD) { modifyGlobal = AccountHelper.AuthorizedModifyAccount(UniSelector.US_GLOBAL_RECORD, false); modifySite = AccountHelper.AuthorizedModifyAccount(SiteContext.CurrentSiteID, false); } // Edit action URL string url = UIContextHelper.GetElementUrl(ModuleName.ONLINEMARKETING, "EditAccount", false); url = URLHelper.AddParameterToUrl(url, "objectid", "{0}"); url = URLHelper.AddParameterToUrl(url, "siteid", SiteID.ToString()); if (ContactHelper.IsSiteManager) { url = URLHelper.AddParameterToUrl(url, "issitemanager", "1"); } // Setup UniGrid gridElem.OnBeforeDataReload += gridElem_OnBeforeDataReload; gridElem.OnExternalDataBound += gridElem_OnExternalDataBound; gridElem.WhereCondition = SqlHelper.AddWhereCondition(gridElem.WhereCondition, WhereCondition); gridElem.EditActionUrl = url; gridElem.ZeroRowsText = GetString("om.account.noaccountsfound"); // Initialize dropdown lists if (!RequestHelper.IsPostBack()) { drpAction.Items.Add(new ListItem(GetString("general." + Action.SelectAction), Convert.ToInt32(Action.SelectAction).ToString())); if ((modifyPermission || ContactGroupHelper.AuthorizedModifyContactGroup(SiteID, false)) && ContactGroupHelper.AuthorizedReadContactGroup(SiteID, false)) { drpAction.Items.Add(new ListItem(GetString("om.account." + Action.AddToGroup), Convert.ToInt32(Action.AddToGroup).ToString())); } if (modifyPermission) { drpAction.Items.Add(new ListItem(GetString("general.delete"), Convert.ToInt32(Action.Delete).ToString())); drpAction.Items.Add(new ListItem(GetString("om.account." + Action.Merge), Convert.ToInt32(Action.Merge).ToString())); drpAction.Items.Add(new ListItem(GetString("om.account." + Action.ChangeStatus), Convert.ToInt32(Action.ChangeStatus).ToString())); } drpWhat.Items.Add(new ListItem(GetString("om.account." + What.Selected), Convert.ToInt32(What.Selected).ToString())); drpWhat.Items.Add(new ListItem(GetString("om.account." + What.All), Convert.ToInt32(What.All).ToString())); } else { if (ControlsHelper.CausedPostBack(btnOk)) { // Set delayed reload for UniGrid if mass action is performed gridElem.DelayedReload = true; } } if (Request.Params[Page.postEventArgumentID] == ACCOUNTS_MERGED) { ShowConfirmation(GetString("om.account.merginglist")); } // Register JS scripts RegisterScripts(); }
/// <summary> /// Creates new web part. /// </summary> protected void btnOK_Click(object sender, EventArgs e) { // Validate the text box fields string errorMessage = new Validator().IsCodeName(txtWebPartName.Text, GetString("general.invalidcodename")).Result; // Validate and trim file name textbox only if it's visible if (radNewWebPart.Checked && radNewFile.Checked) { if (String.IsNullOrEmpty(errorMessage)) { errorMessage = new Validator().IsFileName(Path.GetFileName(txtCodeFileName.Text), GetString("WebPart_Clone.InvalidFileName")).Result; } } // Check file name if (radExistingFile.Checked && radNewWebPart.Checked) { if (String.IsNullOrEmpty(errorMessage)) { string webpartPath = WebPartInfoProvider.GetWebPartPhysicalPath(FileSystemSelector.Value.ToString()); errorMessage = new Validator().IsFileName(Path.GetFileName(webpartPath), GetString("WebPart_Clone.InvalidFileName")).Result; } } if (!String.IsNullOrEmpty(errorMessage)) { ShowError(HTMLHelper.HTMLEncode(errorMessage)); return; } // Run in transaction using (var tr = new CMSTransactionScope()) { WebPartInfo wi = new WebPartInfo(); // Check if new name is unique WebPartInfo webpart = WebPartInfoProvider.GetWebPartInfo(txtWebPartName.Text); if (webpart != null) { ShowError(GetString("Development.WebParts.WebPartNameAlreadyExist").Replace("%%name%%", txtWebPartName.Text)); return; } string filename = String.Empty; if (radNewWebPart.Checked) { if (radExistingFile.Checked) { filename = FileSystemSelector.Value.ToString().Trim(); if (filename.ToLowerCSafe().StartsWithCSafe("~/cmswebparts/")) { filename = filename.Substring("~/cmswebparts/".Length); } } else { filename = txtCodeFileName.Text.Trim(); if (!filename.EndsWithCSafe(".ascx")) { filename += ".ascx"; } } } wi.WebPartDisplayName = txtWebPartDisplayName.Text.Trim(); wi.WebPartFileName = filename; wi.WebPartName = txtWebPartName.Text.Trim(); wi.WebPartCategoryID = QueryHelper.GetInteger("parentobjectid", 0); wi.WebPartDescription = ""; wi.WebPartDefaultValues = "<form></form>"; // Initialize WebPartType - fill it with the default value wi.WebPartType = wi.WebPartType; wi.WebPartIconClass = PortalHelper.DefaultWebPartIconClass; // Inherited web part if (radInherited.Checked) { // Check if is selected webpart and isn't category item if (ValidationHelper.GetInteger(webpartSelector.Value, 0) <= 0) { ShowError(GetString("WebPartNew.InheritedCategory")); return; } int parentId = ValidationHelper.GetInteger(webpartSelector.Value, 0); var parent = WebPartInfoProvider.GetWebPartInfo(parentId); if (parent != null) { wi.WebPartType = parent.WebPartType; wi.WebPartResourceID = parent.WebPartResourceID; wi.WebPartSkipInsertProperties = parent.WebPartSkipInsertProperties; wi.WebPartIconClass = parent.WebPartIconClass; } wi.WebPartParentID = parentId; // Create empty default values definition wi.WebPartProperties = "<defaultvalues></defaultvalues>"; } else { // Check if filename was added if (FileSystemSelector.Visible && !FileSystemSelector.IsValid()) { ShowError(FileSystemSelector.ValidationError); return; } wi.WebPartProperties = "<form></form>"; wi.WebPartParentID = 0; } // Save the web part WebPartInfoProvider.SetWebPartInfo(wi); if (radNewFile.Checked && radNewWebPart.Checked) { string physicalFile = WebPartInfoProvider.GetFullPhysicalPath(wi); if (!File.Exists(physicalFile)) { // Write the files try { var generator = new WebPartCodeGenerator(SystemContext.ApplicationPath, SystemContext.IsWebApplicationProject); var result = generator.GenerateWebPartCode(wi); string folder = Path.GetDirectoryName(physicalFile); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } File.WriteAllText(physicalFile, result.Markup); File.WriteAllText(physicalFile + ".cs", result.Code); // Designer file if (!String.IsNullOrEmpty(result.Designer)) { File.WriteAllText(physicalFile + ".designer.cs", result.Designer); } } catch (Exception ex) { LogAndShowError("WebParts", "GENERATEFILES", ex, true); return; } } else { ShowError(String.Format(GetString("General.FileExistsPath"), physicalFile)); return; } } // Refresh web part tree ScriptHelper.RegisterStartupScript(this, typeof(string), "reloadframee", ScriptHelper.GetScript( "parent.location = '" + UIContextHelper.GetElementUrl("cms.design", "Development.Webparts", false, wi.WebPartID) + "';")); PageBreadcrumbs.Items[1].Text = HTMLHelper.HTMLEncode(wi.WebPartDisplayName); ShowChangesSaved(); plcTable.Visible = false; tr.Commit(); } }
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(UIContextHelper.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 = ""; } }
private void grid_OnAction(string actionName, object actionArgument) { if (string.IsNullOrEmpty(actionName)) { return; } int skuId = ValidationHelper.GetInteger(actionArgument, 0); switch (actionName.ToLowerInvariant()) { case "edit": // Show product tabs for type Products, otherwise show only general tab { var url = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "ProductOptions.Options.General"); 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", skuId.ToString()); // To be able to hide tax class tab for attribute and text option url = URLHelper.AddParameterToUrl(url, "parentobjectid", categoryId.ToString()); // Add parent product id if (parentProductId > 0) { url += "&parentProductId=" + parentProductId; } if (QueryHelper.GetBoolean("isindialog", false)) { url = URLHelper.AddParameterToUrl(url, "isindialog", "1"); url = ApplicationUrlHelper.AppendDialogHash(url); } URLHelper.Redirect(url); } break; case "delete": // Check permissions CheckModifyPermission(); // Check dependencies if (SKUInfoProvider.CheckDependencies(skuId)) { // Show error message ShowError(EcommerceUIHelper.GetDependencyMessage(SKUInfoProvider.GetSKUInfo(skuId))); 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; } }
private static string GetParentConsentUrl(ConsentInfo consent) { var uiElementUrl = UIContextHelper.GetElementUrl("CMS.DataProtection", "Consents.ConsentArchive"); return($"{uiElementUrl}&parentobjectid={consent.ConsentID}&displaytitle={false}"); }
/// <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(); }
/// <summary> /// Edit poll click handler. /// </summary> private void PollsList_OnEdit(object sender, EventArgs e) { // Propagate selected item from ddlist to breadcrumbs on edit page string editActionUrl = URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("CMS.Polls", "EditPoll"), "objectid", PollsList.SelectedItemID.ToString()), "siteid", fltSite.SiteID.ToString()), "displaytitle", "false"); URLHelper.Redirect(editActionUrl); }
protected void btnSave_Click(object sender, EventArgs e) { // Email format validation if (!txtEmailAddress.IsValid()) { 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 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")); }
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 void ButtonOK_Click(object sender, EventArgs e) { // Email format validation if ((TextBoxEmail.Text.Trim() != "") && (!ValidationHelper.IsEmail(TextBoxEmail.Text))) { 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(TextBoxFullName.Text, GetString("Administration-User_New.RequiresFullName")).Result; } userName = ValidationHelper.GetString(ucUserName.Value, String.Empty); // If site prefixed allowed - add site prefix if ((SiteID != 0) && UserInfoProvider.UserNameSitePrefixEnabled(SiteContext.CurrentSiteName)) { if (!UserInfoProvider.IsSitePrefixedUser(userName)) { userName = UserInfoProvider.EnsureSitePrefixUserName(userName, SiteContext.CurrentSite); } } // Validation for site prefixed users if (!UserInfoProvider.IsUserNamePrefixUnique(userName, 0)) { result = GetString("Administration-User_New.siteprefixeduserexists"); } if (result == "") { if (TextBoxConfirmPassword.Text == passStrength.Text) { // Check whether password is valid according to policy if (passStrength.IsValid()) { if (UserInfoProvider.GetUserInfo(userName) == null) { 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(GetString("Administration-User_New.UserExists")); } } else { ShowError(AuthenticationHelper.GetPolicyViolationMessage(SiteContext.CurrentSiteName)); } } else { ShowError(GetString("Administration-User_Edit_Password.PasswordsDoNotMatch")); } } else { ShowError(result); } }
private void roleEditElem_OnSaved(object sender, EventArgs e) { URLHelper.Redirect(String.Format("{0}&roleId={1}&groupid={2}&objectid={1}&displaytitle=false", UIContextHelper.GetElementUrl("CMS.Roles", "EditRole.Groups"), roleEditElem.RoleID, roleEditElem.GroupID)); }
private void GoToOrderDetail() { URLHelper.Redirect(UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "OrderProperties", false, ShoppingCart.OrderId) + "&customerid=" + customerId); }
protected void Page_Load(object sender, EventArgs e) { objectType = UIContextHelper.GetObjectType(UIContext); CloneItemButton.Visible = DisplayCloneButton; // Pass tabindex int tabIndex = ValidationHelper.GetInteger(UIContext["TabIndex"], 0); if (tabIndex != 0) { tabIndexStr = "&tabindex=" + tabIndex; } String editElem = ValidationHelper.GetString(UIContext["itemEdit"], String.Empty); String categoryElem = ValidationHelper.GetString(UIContext["categoryedit"], String.Empty); categoryPathColumn = ValidationHelper.GetString(UIContext["pathColumn"], String.Empty); categoryParentColumn = ValidationHelper.GetString(UIContext["categoryparentcolumn"], String.Empty); categoryObjectType = ValidationHelper.GetString(UIContext["parentobjecttype"], String.Empty); itemParentColumn = ValidationHelper.GetString(UIContext["parentColumn"], String.Empty); newItem = ValidationHelper.GetString(UIContext["newitem"], String.Empty); if (!ValidateInput()) { return; } itemLocation = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ResourceName, editElem), "?tabslayout=horizontal&displaytitle=false"); categoryLocation = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ResourceName, categoryElem), "?tabslayout=horizontal&displaytitle=false"); RegisterExportScript(); RegisterTreeScript(); InitTree(); // Setup menu action scripts String newItemText = newItem.StartsWithCSafe("javascript", true) ? newItem : "NewItem('item'); return false;"; AddButon.Actions.Add(new CMSButtonAction { Text = GetString(objectType + ".newitem"), OnClientClick = newItemText }); AddButon.Actions.Add(new CMSButtonAction { Text = GetString("development.tree.newcategory"), OnClientClick = "NewItem('category'); return false;" }); DeleteItemButton.OnClientClick = "DeleteItem(); return false;"; ExportItemButton.OnClientClick = "ExportObject(); return false;"; CloneItemButton.OnClientClick = "if ((selectedItemId > 0) && (selectedItemType == 'item')) { modalDialog('" + URLHelper.ResolveUrl("~/CMSModules/Objects/Dialogs/CloneObjectDialog.aspx?reloadall=1&displaytitle=" + UIContext["displaytitle"] + "&objecttype=" + objectType + "&objectid=") + "' + selectedItemId, 'Clone item', 750, 470); } return false;"; // Tooltips DeleteItemButton.ToolTip = GetString("development.tree.deleteselected"); ExportItemButton.ToolTip = GetString("exportobject.title"); CloneItemButton.ToolTip = GetString(objectType + ".clone"); // URLs for menu actions String script = "var doNotReloadContent = false;\n"; // Script for deleting widget or category string delPostback = ControlsHelper.GetPostBackEventReference(this, "##"); string deleteScript = "function DeleteItem() { \n" + " if ((selectedItemId > 0) && (selectedItemParent > 0) && " + " confirm(" + ScriptHelper.GetLocalizedString("general.deleteconfirmation") + ")) {\n " + delPostback.Replace("'##'", "selectedItemType+';'+selectedItemId+';'+selectedItemParent") + ";\n" + "}\n" + "}\n"; script += deleteScript; // Preselect tree item if (!RequestHelper.IsPostBack()) { int parentobjectid = QueryHelper.GetInteger("parentobjectid", 0); int objectID = QueryHelper.GetInteger("objectID", 0); // Select category if (parentobjectid > 0) { BaseInfo biParent = BaseAbstractInfoProvider.GetInfoById(categoryObjectType, parentobjectid); if (biParent != null) { String path = ValidationHelper.GetString(biParent.GetValue(categoryPathColumn), String.Empty); int parentID = ValidationHelper.GetInteger(biParent.GetValue(categoryParentColumn), 0); script += SelectAfterLoad(path, parentobjectid, "category", parentID, true, true); } } // Select item else if (objectID > 0) { BaseInfo bi = BaseAbstractInfoProvider.GetInfoById(objectType, objectID); if (bi != null) { script += SelectItem(bi); } } else { // Selection by hierarchy URL BaseInfo biSel = UIContext.EditedObject as BaseInfo; BaseInfo biParent = UIContext.EditedObjectParent as BaseInfo; // Check for category selection if ((biParent != null) && (biParent.TypeInfo.ObjectType == categoryObjectType)) { String path = ValidationHelper.GetString(biParent.GetValue(categoryPathColumn), String.Empty); int parentID = ValidationHelper.GetInteger(biParent.GetValue(categoryParentColumn), 0); script += SelectAfterLoad(path, biParent.Generalized.ObjectID, "category", parentID, false, true); } // Check for item selection else if ((biSel != null) && (biSel.TypeInfo.ObjectType == objectType)) { script += SelectItem(biSel); } else { // Select root by default BaseInfo bi = BaseAbstractInfoProvider.GetInfoByName(categoryObjectType, "/"); if (bi != null) { script += SelectAfterLoad("/", bi.Generalized.ObjectID, "category", 0, true, true); } } } } ltlScript.Text += ScriptHelper.GetScript(script); }
/// <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) { // Id of parent if creating new category. mParentId = QueryHelper.GetInteger("parentid", -1); // Id of category if editing existing category. mCategoryId = QueryHelper.GetInteger("categoryid", -1); // Set isGroup flag. catEdit.IsGroupEdit = QueryHelper.GetBoolean("isgroup", false); catEdit.IncludeRootCategory = !catEdit.IsGroupEdit; if (ViewState["newId"] != null) { mCategoryId = ValidationHelper.GetInteger(ViewState["newId"], 0); } catEdit.OnSaved += catEdit_OnSaved; // Set up of root category in parent selector and refreshing catEdit.DisplayOnlyCategories = true; catEdit.SettingsCategoryID = mCategoryId; // Set tree refreshing catEdit.TreeRefreshUrl = "~/CMSModules/Modules/Pages/Settings/Tree.aspx?moduleid=" + moduleId; // Get root category: Settings or CustomSettings SettingsCategoryInfo settingsRoot = SettingsCategoryInfoProvider.GetSettingsCategoryInfoByName("CMS.Settings"); if (mCategoryId <= 0) { catEdit.ShowParentSelector = false; if (catEdit.SettingsCategoryObj == null) { catEdit.RootCategoryID = mParentId; } // Redirect to editing form if (catEdit.IsGroupEdit) { catEdit.ContentRefreshUrl = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ModuleName.CMS, "Modules.Settings.EditCategory", false), "moduleId=" + moduleId); } else { catEdit.ContentRefreshUrl = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ModuleName.CMS, "EditSettingsCategory", false), "tabName=Modules.Settings.EditCategory&moduleId=" + moduleId); } } else { SetEditEnabled(false); // Do not show root category if (catEdit.SettingsCategoryObj.CategoryID != settingsRoot.CategoryID) { SetEditEnabled(true); // Allow assigning of all categories in edit mode catEdit.RootCategoryID = settingsRoot.CategoryID; catEdit.IsGroupEdit = catEdit.SettingsCategoryObj.CategoryIsGroup; } else { ShowInformation(GetString("settingcategory.rootcategorywarning")); } } }
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 }); }
protected override void OnInit(EventArgs e) { base.OnInit(e); couponCountsDataProvider = new ObjectTransformationDataProvider(); couponCountsDataProvider.SetDefaultDataHandler(GetCountsDataHandler); // Init Unigrid SetDiscountStatusFilterType(); ugDiscounts.OnAction += ugDiscounts_OnAction; ugDiscounts.OnExternalDataBound += ugDiscounts_OnExternalDataBound; ugDiscounts.GridView.AllowSorting = false; ugDiscounts.WhereCondition = new WhereCondition() .WhereEquals("DiscountSiteID", SiteID) .WhereEquals("DiscountApplyTo", DiscountType.ToStringRepresentation()) .ToString(true); switch (DiscountType) { case DiscountApplicationEnum.Products: AddHeaderAction(new HeaderAction { Text = GetString("com.discount.newcatalogdiscount"), RedirectUrl = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "NewCatalogDiscount", false) }); SetTitle(GetString("com.discount.catalogdiscounts")); // Set empty grid messages ugDiscounts.ZeroRowsText = GetString("com.nocatalogdiscounts"); ugDiscounts.FilteredZeroRowsText = GetString("com.nocatalogdiscounts.filtered"); break; case DiscountApplicationEnum.Order: AddHeaderAction(new HeaderAction { Text = GetString("com.discount.neworderdiscount"), RedirectUrl = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "NewOrderDiscount", false) }); SetTitle(GetString("com.discount.orderdiscounts")); // Set empty grid messages ugDiscounts.ZeroRowsText = GetString("com.noorderdiscounts"); ugDiscounts.FilteredZeroRowsText = GetString("com.noorderdiscounts.filtered"); break; case DiscountApplicationEnum.Shipping: AddHeaderAction(new HeaderAction { Text = GetString("com.discount.newshippingdiscount"), RedirectUrl = UIContextHelper.GetElementUrl(ModuleName.ECOMMERCE, "NewShippingDiscount", false) }); SetTitle(GetString("com.discount.shippingdiscounts")); // Set empty grid messages ugDiscounts.ZeroRowsText = GetString("com.noshippingdiscounts"); ugDiscounts.FilteredZeroRowsText = GetString("com.noshippingdiscounts.filtered"); break; } }
/// <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; } }
/// <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) + "')}")); } }
/// <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.GetStringValue(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> /// 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); OrderInfo oi = null; OrderStatusInfo osi = null; switch (actionName.ToLowerCSafe()) { case "edit": string redirectToUrl = UIContextHelper.GetElementUrl("CMS.Ecommerce", "OrderProperties", false, orderId); if (customerId > 0) { redirectToUrl += "&customerId=" + customerId; } URLHelper.Redirect(redirectToUrl); break; case "delete": // Check 'ModifyOrders' and 'EcommerceModify' permission if (!ECommerceContext.IsUserAuthorizedForPermission("ModifyOrders")) { AccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyOrders"); } // delete OrderInfo object from database OrderInfoProvider.DeleteOrderInfo(orderId); break; case "previous": // Check 'ModifyOrders' and 'EcommerceModify' permission if (!ECommerceContext.IsUserAuthorizedForPermission("ModifyOrders")) { AccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyOrders"); } 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("ModifyOrders")) { AccessDenied("CMS.Ecommerce", "EcommerceModify OR ModifyOrders"); } 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) { Grid.OnExternalDataBound += new OnExternalDataBoundEventHandler(Grid_OnExternalDataBound); Grid.OnAction += new OnActionEventHandler(Grid_OnAction); // Don't display rooms scheduled to deletion and WhisperRooms (the same as ChatRoomInfo's IsWhisperRoom) string whereCondition = "ChatRoomScheduledToDelete IS NULL AND (ChatRoomIsOneToOne = 0 OR ChatRoomIsSupport = 1)"; // Single site is selected. if (SiteID > 0) { whereCondition += string.Format(" AND ChatRoomSiteID = {0}", SiteID); } // Global is selected else if (SiteID == -4) { whereCondition += " AND ChatRoomSiteID IS NULL"; } // Global and current is selected else if (SiteID == -5) { whereCondition += string.Format(" AND (ChatRoomSiteID = {0} OR ChatRoomSiteID IS NULL)", SiteContext.CurrentSiteID); } Grid.WhereCondition = whereCondition; Grid.EditActionUrl = URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(URLHelper.AddParameterToUrl(UIContextHelper.GetElementUrl("CMS.Chat", "EditChatRoom"), "objectid", "{0}"), "siteid", SiteID.ToString()), "displaytitle", "false"); RegisterRefreshUsingPostBackScript(); }
/// <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> /// Saved 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", "Groups.EditGroup.EditPoll"), "objectid", PollNew.ItemID.ToString()), "groupid", groupId.ToString()), "displaytitle", "false"), "saved", "1"); URLHelper.Redirect(editActionUrl + error); }
/// <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(ModuleName.ECOMMERCE, "EditOptionCategory", false, categoryId)); break; case "delete": OptionCategoryInfo categoryObj = OptionCategoryInfo.Provider.Get(categoryId); if (categoryObj == null) { break; } // Check permissions if (!ECommerceContext.IsUserAuthorizedToModifyOptionCategory(categoryObj)) { // Check module permissions if (categoryObj.CategoryIsGlobal) { RedirectToAccessDenied(ModuleName.ECOMMERCE, EcommercePermissions.ECOMMERCE_MODIFYGLOBAL); } else { RedirectToAccessDenied(ModuleName.ECOMMERCE, "EcommerceModify OR ModifyProducts"); } } // Check category dependencies if (categoryObj.Generalized.CheckDependencies()) { // Show error message ShowError(EcommerceUIHelper.GetDependencyMessage(categoryObj)); 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 = VariantOptionInfo.Provider.Get() .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) { var skuid = ValidationHelper.GetInteger(option["SKUID"], 0); var sku = SKUInfo.Provider.Get(skuid); if (SKUInfoProvider.CheckDependencies(skuid)) { // Show error message ShowError(EcommerceUIHelper.GetDependencyMessage(sku)); return; } } } // Delete option category from database OptionCategoryInfo.Provider.Delete(categoryObj); break; } }
protected void Page_Load(object sender, EventArgs e) { ScriptHelper.RegisterJQuery(Page); SitePanel.Visible = ShowSiteSelector; ActionsPanel.Visible = !ShowSiteSelector; plcSelectionScript.Visible = ShowSiteSelector; plcActionSelectionScript.Visible = !ShowSiteSelector; 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"; 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 = SettingsCategoryInfoProvider.GetSettingsCategoryInfo(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 = SettingsCategoryInfoProvider.GetSettingsCategoryInfo(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 = ResourceInfoProvider.GetResourceInfo(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())); } }
protected void Page_Load(object sender, EventArgs e) { if (SystemContext.DevelopmentMode) { // Restart application menu.AddAction(new HeaderAction { Text = GetString("administration-system.btnrestart"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("administration-system.btnrestart"), OnClientClick = "function RestartPerformed() {return alert('" + GetString("administration-system.restartsuccess") + "');} if (confirm('" + GetString("system.restartconfirmation") + "')) {" + Page.ClientScript.GetCallbackEventReference(this, "'restart'", "RestartPerformed", String.Empty, true) + "}" }); // Clear cache menu.AddAction(new HeaderAction { Text = GetString("administration-system.btnclearcache"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("administration-system.btnclearcache"), OnClientClick = "function ClearCachePerformed() {return alert('" + GetString("administration-system.clearcachesuccess") + "');} if (confirm('" + GetString("system.clearcacheconfirmation") + "')) {" + Page.ClientScript.GetCallbackEventReference(this, "'clearcache'", "ClearCachePerformed", String.Empty, true) + "}" }); // Event log HeaderAction eventLog = new HeaderAction { Text = GetString("administration.ui.eventlog"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("administration.ui.eventlog"), RedirectUrl = "~/CMSModules/EventLog/EventLog.aspx", Target = "_blank" }; // Event log items DataSet ds = EventLogProvider.GetEvents() .OrderByDescending("EventTime") .TopN(10) .Columns("EventTime", "EventType", "Source", "EventCode"); foreach (DataRow row in ds.Tables[0].Rows) { HeaderAction ev = new HeaderAction { Text = string.Format("{0} {1} {2} {3}", row["EventTime"], row["EventType"], row["Source"], row["EventCode"]), ButtonStyle = ButtonStyle.Default }; eventLog.AlternativeActions.Add(ev); } menu.AddAction(eventLog); // Debug menu.AddAction(new HeaderAction { Text = GetString("Administration-System.Debug"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("Administration-System.Debug"), RedirectUrl = URLHelper.AppendQuery(UIContextHelper.GetElementUrl(ModuleName.CMS, "Debug"), "displaytitle=true"), Target = "_blank" }); // Submit defect menu.AddAction(new HeaderAction { Text = "Submit defect", ButtonStyle = ButtonStyle.Default, Tooltip = "Submit defect", RedirectUrl = "https://kentico.atlassian.net/secure/CreateIssue!default.jspa", Target = "_blank" }); // Virtual site HeaderAction sites = new HeaderAction { Text = GetString("devmenu.sites"), ButtonStyle = ButtonStyle.Default, Tooltip = GetString("devmenu.sites"), Inactive = true }; // Site items var sitesDs = SiteInfoProvider.GetSites().Columns("SiteName", "SiteDisplayName").OrderBy("SiteDisplayName"); foreach (SiteInfo s in sitesDs) { // Prepare the parameters NameValueCollection values = new NameValueCollection(); values.Add(VirtualContext.PARAM_SITENAME, s.SiteName); HeaderAction site = new HeaderAction { Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(s.DisplayName)), ButtonStyle = ButtonStyle.Default, RedirectUrl = VirtualContext.GetVirtualContextPath(Request.Path, values), Target = "_blank" }; sites.AlternativeActions.Add(site); } menu.AddAction(sites); } else { Visible = false; } }
/// <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); }