/// <summary> /// Takes all sites offline. /// </summary> private void TakeSitesOffline() { var sites = SiteInfoProvider.GetSites() .WhereNull("SiteIsOffline") .Or() .WhereEquals("SiteIsOffline", 0) .TypedResult; var siteIDs = new List <int>(sites.Items.Count); foreach (var site in sites) { site.SiteIsOffline = true; SiteInfoProvider.SetSiteInfo(site); siteIDs.Add(site.SiteID); } PersistentStorageHelper.SetValue("SeparateDBSites", siteIDs); }
/// <summary> /// Binds site combobox /// </summary> private void BindSites() { if (ImportProfile.Sites.Count > 0) { DataSet sites = SiteInfoProvider.GetSites() .WhereIn("SiteName", ImportProfile.Sites.Keys) .OrderBy("SiteDisplayName") .Columns("SiteID, SiteName, SiteDisplayName, SiteGUID"); if (!DataHelper.DataSourceIsEmpty(sites)) { foreach (DataRow site in sites.Tables[0].Rows) { // Localize display names site["SiteDisplayName"] = CMS.Helpers.ResHelper.LocalizeString(site["SiteDisplayName"].ToString()); } cmbSites.DataSource = sites.Tables[0]; } } }
protected void Page_Load(object sender, EventArgs e) { lblAvialable.Text = GetString("Administration-PageTemplate_Sites.SiteTitle"); if (PageTemplateID > 0) { // Get the active sites DataSet ds = SiteInfoProvider.GetSites("SiteID IN (SELECT SiteID FROM CMS_PageTemplateSite WHERE PageTemplateID = " + PageTemplateID + ")", null, "SiteID", 0); if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", SystemDataHelper.GetStringValues(ds.Tables[0], "SiteID")); } if (!RequestHelper.IsPostBack()) { usSites.Value = currentValues; } } usSites.OnSelectionChanged += usSites_OnSelectionChanged; }
private List <HeaderAction> GetSitesAvailableForVirtualAccess() { List <HeaderAction> actions = new List <HeaderAction>(); CacheHelper.Cache(() => { var sitesData = SiteInfoProvider.GetSites() .Columns("SiteName", "SiteDisplayName") .OrderBy("SiteDisplayName") .TypedResult; foreach (SiteInfo s in sitesData) { // 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" }; actions.Add(site); } return(actions); }, new CacheSettings(60, "DevMenu", "Sites", "VirtualContext") { GetCacheDependency = () => CacheHelper.GetCacheDependency(new[] { SiteInfo.OBJECT_TYPE + "|all", }) }); return(actions); }
protected void Page_Load(object sender, EventArgs e) { lblAvialable.Text = GetString("WebContainers_Edit_Sites.SiteTitle"); containerId = QueryHelper.GetInteger("containerId", 0); if (containerId > 0) { // Get the active sites DataSet ds = SiteInfoProvider.GetSites("SiteID IN (SELECT SiteID FROM CMS_WebPartContainerSite WHERE ContainerID = " + containerId + ")", null, "SiteID", 0); if (!DataHelper.DataSourceIsEmpty(ds)) { currentValues = TextHelper.Join(";", SqlHelperClass.GetStringValues(ds.Tables[0], "SiteID")); } if (!RequestHelper.IsPostBack()) { usSites.Value = currentValues; } } usSites.OnSelectionChanged += usSites_OnSelectionChanged; }
private void SettingsKey_InsertUpdate_After(object sender, ObjectEventArgs e) { SettingsKeyInfo Key = (SettingsKeyInfo)e.Object; switch (Key.KeyName.ToLower()) { case "cmsdefaultculturecode": if (Key.SiteID > 0) { string SiteName = DynamicRouteHelper.GetSite(Key.SiteID).SiteName; DynamicRouteEventHelper.SiteDefaultLanguageChanged(SiteName); } else { foreach (string SiteName in SiteInfoProvider.GetSites().Select(x => x.SiteName)) { DynamicRouteEventHelper.SiteDefaultLanguageChanged(SiteName); } } break; case "generateculturevariationurlslugs": if (Key.SiteID > 0) { string SiteName = DynamicRouteHelper.GetSite(Key.SiteID).SiteName; DynamicRouteEventHelper.CultureVariationSettingsChanged(SiteName); } else { foreach (string SiteName in SiteInfoProvider.GetSites().Select(x => x.SiteName)) { DynamicRouteEventHelper.CultureVariationSettingsChanged(SiteName); } } break; } }
/// <summary> /// Saves data of edited user from TextBoxes into DB. /// </summary> protected void btnOk_Click(object sender, EventArgs e) { // Check "modify" permission if (!currentUser.IsAuthorizedPerResource("CMS.Users", "Modify")) { RedirectToAccessDenied("CMS.Users", "Modify"); } string result = ValidateGlobalAndDeskAdmin(userId); // Find whether user name is valid if (result == String.Empty) { if (!ucUserName.IsValid()) { result = ucUserName.ValidationError; } } String userName = ValidationHelper.GetString(ucUserName.Value, String.Empty); if (result == String.Empty) { // Finds whether required fields are not empty result = new Validator().NotEmpty(txtFullName.Text, GetString("Administration-User_New.RequiresFullName")).Result; } if ((result == String.Empty) && (ui != null)) { // If site prefixed allowed - ad site prefix if ((SiteID != 0) && UserInfoProvider.UserNameSitePrefixEnabled(CMSContext.CurrentSiteName)) { if (!UserInfoProvider.IsSitePrefixedUser(userName)) { userName = UserInfoProvider.EnsureSitePrefixUserName(userName, CMSContext.CurrentSite); } } // Validation for site prefixed users if (!UserInfoProvider.IsUserNamePrefixUnique(userName, ui.UserID)) { result = GetString("Administration-User_New.siteprefixeduserexists"); } // Ensure same password password = ui.GetValue("UserPassword").ToString(); // Test for unique username UserInfo uiTest = UserInfoProvider.GetUserInfo(userName); if ((uiTest == null) || (uiTest.UserID == userId)) { if (ui == null) { ui = new UserInfo(); } bool globAdmin = ui.IsGlobalAdministrator; bool editor = ui.IsEditor; // Email format validation string email = txtEmail.Text.Trim(); if ((email != string.Empty) && (!ValidationHelper.IsEmail(email))) { lblError.Visible = true; lblError.Text = GetString("Administration-User_New.WrongEmailFormat"); return; } bool oldGlobal = ui.IsGlobalAdministrator; bool oldEditor = ui.IsEditor; if (ui.UserName != userName) { // Refresh the breadcrumb ScriptHelper.RefreshTabHeader(Page, null); } ui.Email = email; ui.FirstName = txtFirstName.Text.Trim(); ui.FullName = txtFullName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.MiddleName = txtMiddleName.Text.Trim(); ui.UserName = userName; ui.Enabled = CheckBoxEnabled.Checked; ui.IsEditor = CheckBoxIsEditor.Checked; ui.UserIsHidden = chkIsHidden.Checked; // Only admins who have access to site manager can set this if (!currentUser.UserSiteManagerDisabled) { ui.UserSiteManagerDisabled = chkSiteManagerDisabled.Checked; // Only admin who have access to site manager can create another global admin ui.IsGlobalAdministrator = currentUser.IsGlobalAdministrator && CheckBoxLabelIsGlobalAdministrator.Checked; } ui.IsExternal = chkIsExternal.Checked; ui.UserIsDomain = chkIsDomain.Checked; ui.SetValue("UserPassword", password); ui.UserID = userId; ui.UserStartingAliasPath = txtUserStartingPath.Text.Trim(); LoadUserLogon(ui); // Set values of cultures. string culture = ValidationHelper.GetString(cultureSelector.Value, ""); ui.PreferredCultureCode = culture; if (lstUICulture.SelectedValue == "0") { ui.PreferredUICultureCode = ""; } else { UICultureInfo ciUI = UICultureInfoProvider.GetUICultureInfo(Convert.ToInt32(lstUICulture.SelectedValue)); ui.PreferredUICultureCode = ciUI.UICultureCode; } // Define domain variable string domains = null; // Get all user sites DataTable ds = UserInfoProvider.GetUserSites(ui.UserID, null, null, 0, "SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Rows) { domains += ValidationHelper.GetString(dr["SiteDomainName"], string.Empty) + ";"; } // Remove ";" at the end if (domains != null) { domains = domains.Remove(domains.Length - 1); } } else { DataSet siteDs = SiteInfoProvider.GetSites(null, null, "SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(siteDs)) { domains = TextHelper.Join(";", SqlHelperClass.GetStringValues(siteDs.Tables[0], "SiteDomainName")); } } // Check limitations for Global administrator if (ui.IsGlobalAdministrator && !oldGlobal) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.GlobalAdmininistrators, VersionActionEnum.Insert, globAdmin)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedGlobal"); } } // Check limitations for editors if (ui.IsEditor && !oldEditor) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Editors, VersionActionEnum.Insert, editor)) { lblError.Visible = true; lblError.Text = GetString("License.MaxItemsReachedEditor"); } } // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(email, ui)) { lblError.Visible = true; lblError.Text = GetString("UserInfo.EmailAlreadyExist"); return; } if (!lblError.Visible) { // Check whether the username of the currently logged user has been changed if ((currentUser != null) && (currentUser.UserID == ui.UserID) && (currentUser.UserName != ui.UserName)) { // Ensure that an update search task will be created but NOT executed when updating the user CMSActionContext.EnableSearchIndexer = false; } // Update the user UserInfoProvider.SetUserInfo(ui); lblInfo.Visible = true; lblInfo.Text = GetString("General.ChangesSaved"); } } else { lblError.Visible = true; lblError.Text = GetString("Administration-User_New.UserExists"); } } else { lblError.Visible = true; lblError.Text = result; } // Display impersonation link if current user is global administrator if (CurrentMaster.HeaderActions.Actions != null) { if (currentUser.IsGlobalAdministrator && RequestHelper.IsFormsAuthentication() && (ui != null) && (ui.UserID != currentUser.UserID)) { if (!currentUser.UserSiteManagerDisabled || !ui.UserIsGlobalAdministrator || ui.UserSiteManagerDisabled) { string message = GetImpersonalMessage(ui); CurrentMaster.HeaderActions.Actions[0, 2] = "if (!confirm('" + message + "')) { return false; }"; CurrentMaster.HeaderActions.ReloadData(); } } } }
/// <summary> /// Check site settings of all sites. /// </summary> /// <param name="settingKey">Setting key to be checked for all sites.</param> /// <returns> Return true if all sites have that site setting set true. Otherwise returns false.</returns> private bool CheckAllSitesSetting(string settingKey) { return(!SiteInfoProvider.GetSites().Any(site => !SettingsKeyInfoProvider.GetBoolValue(settingKey, site.SiteName))); }
/// <summary> /// Button Ok click. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Arguments</param> protected void btnOk_Click(object sender, EventArgs e) { // Validate file name string fileName = txtFileName.Text.Trim(); string errorMessage = new Validator().NotEmpty(fileName, GetString("lincense.export.filenameempty")).IsFileName(fileName, GetString("license.export.notvalidfilename")).Result; if (!string.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } else { try { // Create writers string path = ImportExportHelper.GetSiteUtilsFolder() + "Export\\" + fileName; DirectoryHelper.EnsureDiskPath(path, SettingsKeyProvider.WebApplicationPhysicalPath); using (FileStream file = FileStream.New(path, FileMode.Create)) { using (StreamWriter sw = StreamWriter.New(file)) { // Array list for duplicity checking ArrayList allSites = new ArrayList(); // Get all sites DataSet sites = SiteInfoProvider.GetSites(null, null, "SiteID,SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(sites)) { foreach (DataRow dr in sites.Tables[0].Rows) { // Get domain string domain = ValidationHelper.GetString(dr["SiteDomainName"], ""); if (!string.IsNullOrEmpty(domain)) { domain = GetDomain(domain); // Add to file if (!allSites.Contains(domain)) { sw.WriteLine(domain); allSites.Add(domain); } // Add all domain aliases DataSet aliases = SiteDomainAliasInfoProvider.GetDomainAliases("SiteID=" + ValidationHelper.GetString(dr["SiteID"], ""), null, "SiteDomainAliasName"); if (!DataHelper.DataSourceIsEmpty(aliases)) { foreach (DataRow drAlias in aliases.Tables[0].Rows) { // Get domain domain = ValidationHelper.GetString(drAlias["SiteDomainAliasName"], ""); if (!string.IsNullOrEmpty(domain)) { domain = GetDomain(domain); // Add to file if (!allSites.Contains(domain)) { sw.WriteLine(domain); allSites.Add(domain); } } } } } } } } } // Output string downloadPath = ImportExportHelper.GetSiteUtilsFolderRelativePath(); string location = null; // Path is relative path if (downloadPath != null) { string externalUrl = null; string fullPath = downloadPath + "Export/" + fileName; // Handle external storage URL if (StorageHelper.IsExternalStorage(fullPath)) { externalUrl = File.GetFileUrl(fullPath, CMSContext.CurrentSiteName); } // Handle default URL if (string.IsNullOrEmpty(externalUrl)) { location = URLHelper.ResolveUrl(downloadPath + "Export/" + fileName); } else { location = externalUrl; } location = String.Format("<a href=\"{0}\" target=\"_blank\">{0}</a>", location); } else { location = "<b>" + path + "</b>"; } ShowConfirmation(GetString("license.export.exported")); ShowInformation(String.Format(GetString("license.export.download"), location)); plcTextBox.Visible = false; } catch (Exception ex) { ShowError(ex.Message); } } }
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> /// Button Ok click. /// </summary> /// <param name="sender">Sender</param> /// <param name="e">Arguments</param> protected void btnOk_Click(object sender, EventArgs e) { // Validate file name string fileName = txtFileName.Text.Trim(); string errorMessage = new Validator().NotEmpty(fileName, GetString("lincense.export.filenameempty")).IsFileName(fileName, GetString("license.export.notvalidfilename")).Result; if (!string.IsNullOrEmpty(errorMessage)) { ShowError(errorMessage); } else { try { // Create writers string path = ImportExportHelper.GetSiteUtilsFolder() + "Export\\" + fileName; DirectoryHelper.EnsureDiskPath(path, SystemContext.WebApplicationPhysicalPath); using (FileStream file = FileStream.New(path, FileMode.Create)) { using (StreamWriter sw = StreamWriter.New(file)) { // Array list for duplicity checking ArrayList allSites = new ArrayList(); // Get all sites DataSet sites = SiteInfoProvider.GetSites().Columns("SiteID,SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(sites)) { foreach (DataRow dr in sites.Tables[0].Rows) { // Get domain string domain = ValidationHelper.GetString(dr["SiteDomainName"], ""); if (!string.IsNullOrEmpty(domain)) { domain = GetDomain(domain); // Add to file if (!allSites.Contains(domain)) { sw.WriteLine(domain); allSites.Add(domain); } // Add all domain aliases DataSet aliases = SiteDomainAliasInfoProvider.GetDomainAliases() .Column("SiteDomainAliasName") .Where("SiteID", QueryOperator.Equals, ValidationHelper.GetInteger(dr["SiteID"], 0)); if (!DataHelper.DataSourceIsEmpty(aliases)) { foreach (DataRow drAlias in aliases.Tables[0].Rows) { // Get domain domain = ValidationHelper.GetString(drAlias["SiteDomainAliasName"], ""); if (!string.IsNullOrEmpty(domain)) { domain = GetDomain(domain); // Add to file if (!allSites.Contains(domain)) { sw.WriteLine(domain); allSites.Add(domain); } } } } } } } } } // Output string url = ImportExportHelper.GetExportPackageUrl(fileName, SiteContext.CurrentSiteName); string downloadLink = (url != null) ? String.Format("<a href=\"{0}\" target=\"_blank\">{1}</a>", url, GetString("license.export.clicktodownload")) : ""; string storageName = (StorageHelper.IsExternalStorage(path)) ? GetString("Export.StorageProviderName." + StorageHelper.GetStorageProvider(path).Name) : ""; string relativePath = ImportExportHelper.GetSiteUtilsFolderRelativePath() + "Export/" + txtFileName.Text; ShowConfirmation(GetString("license.export.exported")); ShowInformation(String.Format(GetString("license.export.download"), storageName, relativePath, downloadLink)); plcTextBox.Visible = false; } catch (Exception ex) { ShowError(ex.Message); } } }
protected void RunInternal() { try { RunningInternal = true; ProgressMessageBuffer.Add("Starting cleaning process..."); var attachmentIDs = AttachmentInfoProvider .GetAttachments(null, "AttachmentName", false) .Select(att => att.AttachmentID); if (attachmentIDs == null) { return; } var sites = SiteInfoProvider.GetSites(); // Configure attachment storage setting keys. Mover won't work without this: SettingsKeyInfoProvider.SetValue("CMSStoreFilesInFileSystem", "True", false); SettingsKeyInfoProvider.SetValue("CMSStoreFilesInDatabase", "False", false); foreach (var aID in attachmentIDs) { if (Cancelled) { RunningInternal = false; Cancelled = false; return; } var att = AttachmentInfoProvider.GetAttachmentInfo(aID, false); var attSite = sites.FirstOrDefault(s => s.SiteID == att.AttachmentSiteID); if (attSite == null) { continue; } AttachmentInfoProvider.EnsurePhysicalFile(att, attSite.SiteName); att.AttachmentBinary = null; att.Generalized.UpdateData(); ProgressMessageBuffer.Add(att.AttachmentName + " copied to file system."); } ProgressMessageBuffer.Add("Cleaning Process Complete"); RunningInternal = false; } catch (Exception e) { ProgressMessageBuffer.Add("ERROR --------------------------"); ProgressMessageBuffer.Add(e.Message); ProgressMessageBuffer.Add(e.StackTrace); RunningInternal = false; } }
public Site[] GetSites() { return(mapper.Map <Site[]>(SiteInfoProvider.GetSites().ToArray())); }
private void SettingsKey_InsertUpdate_After(object sender, ObjectEventArgs e) { SettingsKeyInfo Key = (SettingsKeyInfo)e.Object; switch (Key.KeyName.ToLower()) { case "cmsdefaultculturecode": try { if (Key.SiteID > 0) { string SiteName = DynamicRouteInternalHelper.GetSite(Key.SiteID).SiteName; DynamicRouteEventHelper.SiteDefaultLanguageChanged(SiteName); } else { foreach (string SiteName in SiteInfoProvider.GetSites().Select(x => x.SiteName)) { DynamicRouteEventHelper.SiteDefaultLanguageChanged(SiteName); } } } catch (UrlSlugCollisionException ex) { LogErrorsInSeparateThread(ex, "DynamicRouting", "UrlSlugConflict", $"Occurred on Settings Key Update After for Key {Key.KeyName}"); e.Cancel(); } catch (Exception ex) { LogErrorsInSeparateThread(ex, "DynamicRouting", "Error", $"Occurred on Settings Key Update After for Key {Key.KeyName}"); } break; case "generateculturevariationurlslugs": try { if (Key.SiteID > 0) { string SiteName = DynamicRouteInternalHelper.GetSite(Key.SiteID).SiteName; DynamicRouteEventHelper.CultureVariationSettingsChanged(SiteName); } else { foreach (string SiteName in SiteInfoProvider.GetSites().Select(x => x.SiteName)) { DynamicRouteEventHelper.CultureVariationSettingsChanged(SiteName); } } } catch (UrlSlugCollisionException ex) { LogErrorsInSeparateThread(ex, "DynamicRouting", "UrlSlugConflict", $"Occurred on Settings Key Update After for Key {Key.KeyName}"); e.Cancel(); } catch (Exception ex) { LogErrorsInSeparateThread(ex, "DynamicRouting", "Error", $"Occurred on Settings Key Update After for Key {Key.KeyName}"); } break; } }
private void EnsureAuthenticatedRole() { // Handle Global First RoleInfo AuthenticatedUserRole = GetOrCreateRole(_AuthenticatedRole, _AuthenticatedRoleDisplayName, _AuthenticatedRoleDescription, null); RoleInfo NotAuthenticatedUserRole = GetOrCreateRole(_NotAuthenticatedRole, _NotAuthenticatedRoleDisplayName, _NotAuthenticatedRoleDescription, null); RoleInfo EveryoneUserRole = GetOrCreateRole(_EveryoneRole, _EveryoneRoleDisplayName, _EveryoneRoleDescription, null); // Public user UserInfoProvider.GetUsers() .WhereEquals("username", "public") .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", NotAuthenticatedUserRole.RoleID) .TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x => { HandleUserRole(x.UserID, NotAuthenticatedUserRole.RoleID); }); // Non public users UserInfoProvider.GetUsers() .WhereNotEquals("username", "public") .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", AuthenticatedUserRole.RoleID).TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x => { HandleUserRole(x.UserID, AuthenticatedUserRole.RoleID); }); // Now everyone UserInfoProvider.GetUsers() .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", EveryoneUserRole.RoleID).TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x => { HandleUserRole(x.UserID, EveryoneUserRole.RoleID); }); // Now go through Site Users foreach (SiteInfo Site in SiteInfoProvider.GetSites()) { RoleInfo SiteAuthenticatedUserRole = GetOrCreateRole(_AuthenticatedRole, _AuthenticatedRoleDisplayName, _AuthenticatedRoleDescription, Site.SiteID); RoleInfo SiteNotAuthenticatedUserRole = GetOrCreateRole(_NotAuthenticatedRole, _NotAuthenticatedRoleDisplayName, _NotAuthenticatedRoleDescription, Site.SiteID); RoleInfo SiteEveryoneUserRole = GetOrCreateRole(_EveryoneRole, _EveryoneRoleDisplayName, _EveryoneRoleDescription, Site.SiteID); // Public user UserInfoProvider.GetUsers() .WhereEquals("username", "public") .WhereIn("UserID", UserSiteInfoProvider.GetUserSites().WhereEquals("SiteID", Site.SiteID).TypedResult.Select(x => x.UserID).ToArray()) .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", SiteAuthenticatedUserRole.RoleID) .TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x => { HandleUserRole(x.UserID, SiteAuthenticatedUserRole.RoleID); }); // Non public users UserInfoProvider.GetUsers() .WhereNotEquals("username", "public") .WhereIn("UserID", UserSiteInfoProvider.GetUserSites().WhereEquals("SiteID", Site.SiteID).TypedResult.Select(x => x.UserID).ToArray()) .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", SiteNotAuthenticatedUserRole.RoleID).TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x => { HandleUserRole(x.UserID, SiteNotAuthenticatedUserRole.RoleID); }); // Now everyone UserInfoProvider.GetUsers() .WhereIn("UserID", UserSiteInfoProvider.GetUserSites().WhereEquals("SiteID", Site.SiteID).TypedResult.Select(x => x.UserID).ToArray()) .WhereNotIn("UserID", UserRoleInfoProvider.GetUserRoles().WhereEquals("RoleID", SiteEveryoneUserRole.RoleID).TypedResult.Select(x => x.UserID).ToArray()).ForEachObject(x => { HandleUserRole(x.UserID, SiteEveryoneUserRole.RoleID); }); } }
/// <summary> /// Saves data of edited user from TextBoxes into DB. /// </summary> protected void btnOk_Click(object sender, EventArgs e) { UserPrivilegeLevelEnum privilegeLevel = (UserPrivilegeLevelEnum)drpPrivilege.Value.ToInteger(0); // Check "modify" permission if (!CurrentUser.IsAuthorizedPerResource("CMS.Users", "Modify")) { RedirectToAccessDenied("CMS.Users", "Modify"); } string result = ValidateGlobalAndDeskAdmin(userId); // Find whether user name is valid if (result == String.Empty) { if (!ucUserName.IsValid()) { result = ucUserName.ValidationError; } } String userName = ValidationHelper.GetString(ucUserName.Value, String.Empty); if (result == String.Empty) { // Finds whether required fields are not empty result = new Validator().NotEmpty(txtFullName.Text, GetString("Administration-User_New.RequiresFullName")).Result; } // Store the old display name var oldDisplayName = ui.Generalized.ObjectDisplayName; if ((result == String.Empty) && (ui != null)) { // If site prefixed allowed - ad 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, ui.UserID)) { ShowError(GetString("Administration-User_New.siteprefixeduserexists")); return; } // Ensure same password password = ui.GetValue("UserPassword").ToString(); // Test for unique username UserInfo uiTest = UserInfoProvider.GetUserInfo(userName); if ((uiTest == null) || (uiTest.UserID == userId)) { if (ui == null) { ui = new UserInfo(); } bool globAdmin = ui.IsGlobalAdministrator; bool editor = ui.IsEditorInternal; // Email format validation string email = txtEmail.Text.Trim(); if ((email != string.Empty) && (!ValidationHelper.IsEmail(email))) { ShowError(GetString("Administration-User_New.WrongEmailFormat")); return; } bool oldGlobal = ui.IsGlobalAdministrator; bool oldEditor = ui.IsEditorInternal; // Define domain variable string domains = null; // Get all user sites DataTable ds = UserInfoProvider.GetUserSites(userId, null, null, 0, "SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(ds)) { foreach (DataRow dr in ds.Rows) { domains += ValidationHelper.GetString(dr["SiteDomainName"], string.Empty) + ";"; } // Remove ";" at the end if (domains != null) { domains = domains.Remove(domains.Length - 1); } } else { DataSet siteDs = SiteInfoProvider.GetSites().Columns("SiteDomainName"); if (!DataHelper.DataSourceIsEmpty(siteDs)) { // Create list of available site domains domains = TextHelper.Join(";", DataHelper.GetStringValues(siteDs.Tables[0], "SiteDomainName")); } } // Check limitations for Global administrator if (CurrentUser.IsGlobalAdministrator && ((privilegeLevel == UserPrivilegeLevelEnum.GlobalAdmin) || (privilegeLevel == UserPrivilegeLevelEnum.Admin)) && !oldGlobal) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Administrators, ObjectActionEnum.Insert, globAdmin)) { ShowError(GetString("License.MaxItemsReachedGlobal")); return; } } // Check limitations for editors if ((privilegeLevel == UserPrivilegeLevelEnum.Editor) && !oldEditor) { if (!UserInfoProvider.LicenseVersionCheck(domains, FeatureEnum.Editors, ObjectActionEnum.Insert, editor)) { ShowError(GetString("License.MaxItemsReachedEditor")); return; } } // Check whether email is unique if it is required if (!UserInfoProvider.IsEmailUnique(email, ui)) { ShowError(GetString("UserInfo.EmailAlreadyExist")); return; } // Set properties ui.Email = email; ui.FirstName = txtFirstName.Text.Trim(); ui.FullName = txtFullName.Text.Trim(); ui.LastName = txtLastName.Text.Trim(); ui.MiddleName = txtMiddleName.Text.Trim(); ui.UserName = userName; ui.Enabled = CheckBoxEnabled.Checked; ui.UserIsHidden = chkIsHidden.Checked; ui.IsExternal = chkIsExternal.Checked; ui.UserIsDomain = chkIsDomain.Checked; ui.SetValue("UserPassword", password); ui.UserID = userId; ui.UserStartingAliasPath = txtUserStartingPath.Text.Trim(); ui.UserMFRequired = chkIsMFRequired.Checked; // Global admin can set anything if (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.GlobalAdmin) // Other users can set only editor and non privileges || ((privilegeLevel != UserPrivilegeLevelEnum.Admin) && (privilegeLevel != UserPrivilegeLevelEnum.GlobalAdmin)) // Admin can manage his own privilege || ((privilegeLevel == UserPrivilegeLevelEnum.Admin) && (CurrentUser.CheckPrivilegeLevel(UserPrivilegeLevelEnum.Admin) && (CurrentUser.UserID == ui.UserID)))) { ui.SetPrivilegeLevel(privilegeLevel); } LoadUserLogon(ui); // Set values of cultures. string culture = ValidationHelper.GetString(cultureSelector.Value, ""); ui.PreferredCultureCode = culture; if (lstUICulture.SelectedValue == "0") { ui.PreferredUICultureCode = ""; } else { // Set preferred UI culture CultureInfo ci = CultureInfoProvider.GetCultureInfo(ValidationHelper.GetInteger(lstUICulture.SelectedValue, 0)); ui.PreferredUICultureCode = ci.CultureCode; } // Refresh page breadcrumbs if display name changed if (ui.Generalized.ObjectDisplayName != oldDisplayName) { ScriptHelper.RefreshTabHeader(Page, ui.FullName); } using (CMSActionContext context = new CMSActionContext()) { // Check whether the username of the currently logged user has been changed if (CurrentUserChangedUserName()) { // Ensure that an update search task will be created but NOT executed when updating the user context.EnableSmartSearchIndexer = false; } // Update the user UserInfoProvider.SetUserInfo(ui); // Check whether the username of the currently logged user has been changed if (CurrentUserChangedUserName()) { // Ensure that current user is not logged out if he changes his user name if (RequestHelper.IsFormsAuthentication()) { FormsAuthentication.SetAuthCookie(ui.UserName, false); // Update current user MembershipContext.AuthenticatedUser = new CurrentUserInfo(ui, true); // Reset current user CurrentUser = null; } } } ShowChangesSaved(); } else { // If user exists ShowError(GetString("Administration-User_New.UserExists")); } } else { ShowError(result); } if ((ui.UserInvalidLogOnAttempts == 0) && (ui.UserAccountLockReason != UserAccountLockCode.FromEnum(UserAccountLockEnum.MaximumInvalidLogonAttemptsReached))) { btnResetLogonAttempts.Enabled = false; } LoadPasswordExpiration(ui); }
/// <summary> /// Updates settings key for all sites (or only global if the IsGlobal checkbox is checked). /// </summary> /// <param name="siteKeyName">CodeName of the SettingsKey for the site</param> /// <param name="keyObj">Instance of the SettingsKey object</param> /// <param name="putNullValues">If set to <c>true</c> null value will be set as KeyValue</param> /// <returns>CodeName of the SettingsKey objects.</returns> private string UpdateAllSitesKey(string siteKeyName, SettingsKeyInfo keyObj, bool putNullValues) { int oldKeyCategoryID = keyObj.KeyCategoryID; keyObj.KeyName = txtKeyName.Text.Trim(); keyObj.KeyDisplayName = txtKeyDisplayName.Text.Trim(); keyObj.KeyDescription = txtKeyDescription.Text.Trim(); keyObj.KeyType = drpKeyType.SelectedValue; keyObj.KeyCategoryID = mSelectedGroupId >= 0 ? mSelectedGroupId : drpCategory.SelectedCategory; keyObj.KeyIsGlobal = chkKeyIsGlobal.Checked; keyObj.KeyIsHidden = chkKeyIsHidden.Checked; keyObj.KeyIsCustom = mIsCustomSetting; if (putNullValues) { keyObj.KeyValue = DefaultValue; } keyObj.KeyValidation = (string.IsNullOrEmpty(txtKeyValidation.Text.Trim()) ? null : txtKeyValidation.Text.Trim()); keyObj.KeyDefaultValue = (string.IsNullOrEmpty(DefaultValue) ? null : DefaultValue); keyObj.KeyEditingControlPath = (string.IsNullOrEmpty(txtFormControl.Text.Trim()) ? null : txtFormControl.Text.Trim()); if (drpGeneration.Value >= 0) { keyObj.KeyLoadGeneration = drpGeneration.Value; } // Update information on setting key concerning application level if (chkKeyIsGlobal.Checked) { keyObj.SiteID = 0; } // If category changed set new order or if new set on the end of key list if (keyObj.KeyCategoryID != oldKeyCategoryID) { DataSet ds = SettingsKeyProvider.GetSettingsKeys(0, keyObj.KeyCategoryID); if (!DataHelper.DataSourceIsEmpty(ds)) { DataTable keyTable = ds.Tables[0]; keyTable.DefaultView.Sort = "KeyOrder DESC"; keyTable = keyTable.DefaultView.ToTable(); // Set new KeyOrder as last setings key keyObj.KeyOrder = ValidationHelper.GetInteger(keyTable.Rows[0]["KeyOrder"], 0) + 1; } else { // Move into empty category keyObj.KeyOrder = 1; } } SettingsKeyProvider.SetValue(keyObj); // Update all sites keys DataSet sites = SiteInfoProvider.GetSites(null, null, "SiteID"); foreach (DataRow dr in sites.Tables[0].Rows) { int siteId = ValidationHelper.GetInteger(dr["SiteID"], 0); // Get site specific key information SettingsKeyInfo keySite = SettingsKeyProvider.GetSettingsKeyInfo(siteKeyName, siteId); if ((keySite == null) && (!keyObj.KeyIsGlobal)) { keySite = new SettingsKeyInfo(); // Default value for new key for site-specific setting is to inherit from global keySite.KeyDefaultValue = null; } if (!keyObj.KeyIsGlobal && (keySite != null)) { keySite.KeyName = txtKeyName.Text; keySite.KeyDisplayName = txtKeyDisplayName.Text; keySite.KeyDescription = txtKeyDescription.Text; keySite.KeyValidation = txtKeyValidation.Text; keySite.KeyCategoryID = keyObj.KeyCategoryID; keySite.SiteID = siteId; keySite.KeyOrder = keyObj.KeyOrder; keySite.KeyType = drpKeyType.SelectedValue; keySite.KeyEditingControlPath = keyObj.KeyEditingControlPath; keySite.KeyIsHidden = chkKeyIsHidden.Checked; keySite.KeyIsCustom = mIsCustomSetting; if (drpGeneration.Value >= 0) { keySite.KeyLoadGeneration = drpGeneration.Value; } if (putNullValues) { keySite.KeyValue = null; } SettingsKeyProvider.SetValue(keySite); } else { // Remove the site specific key as setting key isn't local any more SettingsKeyProvider.DeleteKey(keySite); } } return(keyObj.KeyName); }
private void BindSites() { // Create new datatable DataTable sitesTable = new DataTable(); // Create columns DataColumn selectedCol = new DataColumn(COLUMN_SELECTED, typeof(Boolean)); DataColumn siteNameCol = new DataColumn(COLUMN_SITENAME, typeof(String)); DataColumn codeNameCol = new DataColumn(COLUMN_CODENAME, typeof(String)); // Add columns to datatable sitesTable.Columns.Add(selectedCol); sitesTable.Columns.Add(siteNameCol); sitesTable.Columns.Add(codeNameCol); // Bind DataGridView to CMS sites DataSet sites = SiteInfoProvider.GetSites() .OrderBy("SiteDisplayName") .Columns("SiteDisplayName, SiteName"); bool sitesAvailable = !DataHelper.DataSourceIsEmpty(sites); pnlImportGroups.Enabled = sitesAvailable; if (sitesAvailable) { // Remove non-existing sites IEnumerator sitesEnumerator = ImportProfile.Sites.GetEnumerator(); List <string> removeSites = new List <string>(); while (sitesEnumerator.MoveNext()) { // Get site if (sitesEnumerator.Current != null) { KeyValuePair <string, List <Guid> > importedSite = (KeyValuePair <string, List <Guid> >)sitesEnumerator.Current; // Clear hash tables ProviderHelper.ClearHashtables(SiteInfo.OBJECT_TYPE, true); // Get info object SiteInfo site = SiteInfoProvider.GetSiteInfo(importedSite.Key); // If site is not present if (site == null) { // Add to removal list removeSites.Add(importedSite.Key); } } } foreach (string siteToRemove in removeSites) { ImportProfile.Sites.Remove(siteToRemove.ToLowerCSafe()); } foreach (DataRow site in sites.Tables[0].Rows) { // Create new row with the table schema DataRow dr = sitesTable.NewRow(); // Preselect sites bool checkSite = (ImportProfile.Sites.ContainsKey(site["SiteName"].ToString().ToLowerCSafe())); // Localize display name string siteDisplayName = CMS.Helpers.ResHelper.LocalizeString(site["SiteDisplayName"].ToString()); // Add data to row object[] dataRow = { checkSite, siteDisplayName, site["SiteName"] }; dr.ItemArray = dataRow; // Add row to table sitesTable.Rows.Add(dr); } // Bind table as a grid's datasource grdSites.DataSource = sitesTable; // Adjust columns DataGridViewColumn columnSelected = grdSites.Columns[COLUMN_SELECTED]; if (columnSelected != null) { columnSelected.HeaderText = ResHelper.GetString("General_Import"); columnSelected.AutoSizeMode = DataGridViewAutoSizeColumnMode.ColumnHeader; } DataGridViewColumn columnSiteName = grdSites.Columns[COLUMN_SITENAME]; if (columnSiteName != null) { columnSiteName.HeaderText = ResHelper.GetString("General_Sitename"); columnSiteName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; columnSiteName.ReadOnly = true; } DataGridViewColumn columnCodeName = grdSites.Columns[COLUMN_CODENAME]; if (columnCodeName != null) { columnCodeName.Visible = false; } } else { // No sites to import ImportProfile.Sites.Clear(); } }