/// <summary>
    /// Reloads the tree data.
    /// </summary>
    public void ReloadData()
    {
        var elementProvider = new UniTreeProvider
        {
            QueryName         = "cms.uielement.selecttree",
            DisplayNameColumn = "ElementDisplayName",
            IDColumn          = "ElementID",
            LevelColumn       = "ElementLevel",
            OrderColumn       = "ElementOrder",
            ParentIDColumn    = "ElementParentID",
            PathColumn        = "ElementIDPath",
            ValueColumn       = "ElementID",
            ChildCountColumn  = "ElementChildCount",
            ImageColumn       = "ElementIconPath",
            Parameters        = new QueryDataParameters {
                { "@RoleID", RoleID }
            },
            IconClassColumn = "ElementIconClass"
        };

        treeElem.ExpandTooltip    = GetString("general.expand");
        treeElem.CollapseTooltip  = GetString("general.collapse");
        treeElem.UsePostBack      = false;
        treeElem.EnableRootAction = false;
        treeElem.ProviderObject   = elementProvider;
        if (SingleModule)
        {
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(ModuleID);
            if (ri != null)
            {
                root = UIElementInfoProvider.GetModuleTopUIElement(ModuleID);
                if (root != null)
                {
                    treeElem.ExpandPath = root.ElementIDPath;
                    string links = null;
                    if (Enabled)
                    {
                        links = string.Format(SELECT_DESELECT_LINKS, root.ElementID, "false", CallbackRef, GetString("uiprofile.selectall"), GetString("uiprofile.deselectall"));
                    }
                    string rootText = HTMLHelper.HTMLEncode(ri.ResourceDisplayName) + links;
                    treeElem.SetRoot(rootText, root.ElementID.ToString(), ResolveUrl(root.ElementIconPath));
                    elementProvider.RootLevelOffset = root.ElementLevel;
                }

                if (!ShowAllElementsFromModuleSection)
                {
                    elementProvider.WhereCondition = "ElementResourceID = " + ModuleID;
                }
            }
        }
        else
        {
            if (ModuleID > 0)
            {
                var where = $@"ElementResourceID = {ModuleID} AND (ElementParentID IS NULL OR ElementParentID NOT IN (SELECT ElementID FROM CMS_UIElement WHERE ElementResourceID={ModuleID})) 
    AND (NOT EXISTS (SELECT  ElementIDPath FROM CMS_UIElement AS u WHERE CMS_UIElement.ElementIDPath LIKE u.ElementIDPath + '%' AND ElementResourceID = {ModuleID}
    AND u.ElementIDPath != CMS_UIElement.ElementIDPath))";

                var idPaths = UIElementInfoProvider.GetUIElements()
                              .Where(where)
                              .WhereNotEmpty("ElementIDPath")
                              .Columns("ElementIDPath")
                              .OrderByAscending("ElementLevel")
                              .GetListResult <string>();

                var expandedPath = String.Empty;

                if (idPaths.Any())
                {
                    expandedPath = String.Join(";", idPaths) + ";";
                }

                treeElem.ExpandPath = expandedPath;
            }
        }

        treeElem.ReloadData();
    }
コード例 #2
0
    protected void Page_Load(object sender, EventArgs e)
    {
        process = true;
        if (!Visible || StopProcessing)
        {
            EnableViewState = false;
            process         = false;
        }

        chkChangeName.CheckedChanged += new EventHandler(chkChangeName_CheckedChanged);

        if (ForumID > 0)
        {
            // Get information on current forum
            forum = ForumInfoProvider.GetForumInfo(ForumID);

            // Check whether the forum still exists
            EditedObject = forum;
        }

        // Get forum resource
        resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");

        if ((resForums != null) && (forum != null))
        {
            QueryDataParameters parameters = new QueryDataParameters();
            parameters.Add("@ID", resForums.ResourceId);
            parameters.Add("@ForumID", forum.ForumID);
            parameters.Add("@SiteID", CMSContext.CurrentSiteID);

            string where = "";
            int groupId = 0;
            if (IsGroupForum)
            {
                ForumGroupInfo fgi = ForumGroupInfoProvider.GetForumGroupInfo(forum.ForumGroupID);
                groupId = fgi.GroupGroupID;
            }

            // Build where condition
            if (groupId > 0)
            {
                where = "RoleGroupID=" + groupId.ToString() + " AND PermissionDisplayInMatrix = 0";
            }
            else
            {
                where = "RoleGroupID IS NULL AND PermissionDisplayInMatrix = 0";
            }

            // Setup matrix control
            gridMatrix.IsLiveSite      = IsLiveSite;
            gridMatrix.QueryParameters = parameters;
            gridMatrix.WhereCondition  = where;
            gridMatrix.ContentBefore   = "<table class=\"PermissionMatrix\" cellspacing=\"0\" cellpadding=\"0\" rules=\"rows\" border=\"1\" style=\"border-collapse:collapse;\">";
            gridMatrix.ContentAfter    = "</table>";
            gridMatrix.OnItemChanged  += new UniMatrix.ItemChangedEventHandler(gridMatrix_OnItemChanged);

            // Disable permission matrix if user has no MANAGE rights
            if (!CheckPermissions("cms.forums", PERMISSION_MODIFY))
            {
                Enable             = false;
                gridMatrix.Enabled = false;
                ShowError(String.Format(GetString("CMSSiteManager.AccessDeniedOnPermissionName"), "Manage"));
            }
        }
    }
コード例 #3
0
    /// <summary>
    /// Reloads the tree data.
    /// </summary>
    public void ReloadData()
    {
        // Prepare the parameters
        QueryDataParameters parameters = new QueryDataParameters();

        parameters.Add("@RoleID", RoleID);

        // Create and set UIElements provider
        UniTreeProvider elementProvider = new UniTreeProvider();

        elementProvider.QueryName         = "cms.uielement.selecttree";
        elementProvider.DisplayNameColumn = "ElementDisplayName";
        elementProvider.IDColumn          = "ElementID";
        elementProvider.LevelColumn       = "ElementLevel";
        elementProvider.OrderColumn       = "ElementOrder";
        elementProvider.ParentIDColumn    = "ElementParentID";
        elementProvider.PathColumn        = "ElementIDPath";
        elementProvider.ValueColumn       = "ElementID";
        elementProvider.ChildCountColumn  = "ElementChildCount";
        elementProvider.ImageColumn       = "ElementIconPath";
        elementProvider.Parameters        = parameters;
        elementProvider.IconClassColumn   = "ElementIconClass";

        treeElem.ExpandTooltip    = GetString("general.expand");
        treeElem.CollapseTooltip  = GetString("general.collapse");
        treeElem.UsePostBack      = false;
        treeElem.EnableRootAction = false;
        treeElem.ProviderObject   = elementProvider;
        if (SingleModule)
        {
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(ModuleID);
            if (ri != null)
            {
                root = UIElementInfoProvider.GetModuleTopUIElement(ModuleID);
                if (root != null)
                {
                    treeElem.ExpandPath = root.ElementIDPath;
                    string links = null;
                    if (Enabled)
                    {
                        links = string.Format(SELECT_DESELECT_LINKS, root.ElementID, "false", CallbackRef, GetString("uiprofile.selectall"), GetString("uiprofile.deselectall"));
                    }
                    string rootText = HTMLHelper.HTMLEncode(ri.ResourceDisplayName) + links;
                    treeElem.SetRoot(rootText, root.ElementID.ToString(), ResolveUrl(root.ElementIconPath));
                    elementProvider.RootLevelOffset = root.ElementLevel;
                }

                elementProvider.WhereCondition = "ElementResourceID=" + ModuleID;
            }
        }
        else
        {
            if (ModuleID > 0)
            {
                String where = String.Format(@"ElementResourceID = {0} AND (ElementParentID IS NULL OR ElementParentID NOT IN (SELECT ElementID FROM CMS_UIElement WHERE ElementResourceID={0})) 
                                                AND (NOT EXISTS (SELECT  ElementIDPath FROM CMS_UIElement AS u WHERE CMS_UIElement.ElementIDPath LIKE u.ElementIDPath + '%' AND ElementResourceID = {0}
                                                AND u.ElementIDPath != CMS_UIElement.ElementIDPath))", ModuleID);
                DataSet ds           = UIElementInfoProvider.GetUIElements(where, "ElementLevel ASC");
                String  expandedPath = String.Empty;
                if (!DataHelper.DataSourceIsEmpty(ds))
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        String path = ValidationHelper.GetString(dr["ElementIDPath"], String.Empty);
                        if (path != String.Empty)
                        {
                            expandedPath += path + ";";
                        }
                    }
                }

                treeElem.ExpandPath = expandedPath;
            }
        }

        treeElem.ReloadData();
    }
コード例 #4
0
    /// <summary>
    /// PreRender action on which security settings are set.
    /// </summary>
    private void Page_PreRender(object sender, EventArgs e)
    {
        if (mDocumentSaved)
        {
            TreeNode editedNode = Form.EditedObject as TreeNode;

            // Create or rebuild department content index
            CreateDepartmentContentSearchIndex(editedNode);

            if (AclInfoProvider.HasOwnAcl(editedNode))
            {
                ForumInfo        fi = ForumInfoProvider.GetForumInfo("Default_department_" + editedNode.NodeGUID, SiteContext.CurrentSiteID);
                MediaLibraryInfo mi = MediaLibraryInfoProvider.GetMediaLibraryInfo("Department_" + editedNode.NodeGUID, SiteContext.CurrentSiteName);

                // Check if forum of media library exists
                if ((fi != null) || (mi != null))
                {
                    // Get allowed roles ID
                    int     aclID     = ValidationHelper.GetInteger(editedNode.GetValue("NodeACLID"), 0);
                    DataSet listRoles = AclItemInfoProvider.GetAllowedRoles(aclID, NodePermissionsEnum.Read, "RoleID");
                    string  roleIDs   = null;

                    if (!DataHelper.DataSourceIsEmpty(listRoles))
                    {
                        IList <string> roles = DataHelper.GetStringValues(listRoles.Tables[0], "RoleID");
                        roleIDs = TextHelper.Join(";", roles);
                    }

                    // Set permissions for forum
                    if (fi != null)
                    {
                        // Get resource object
                        ResourceInfo resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");

                        // Get permissions IDs
                        DataSet dsForumPerm      = PermissionNameInfoProvider.GetPermissionNames("ResourceID = " + resForums.ResourceId + " AND (PermissionName != '" + CMSAdminControl.PERMISSION_READ + "' AND PermissionName != '" + CMSAdminControl.PERMISSION_MODIFY + "')", null, 0, "PermissionID");
                        string  forumPermissions = null;
                        if (!DataHelper.DataSourceIsEmpty(dsForumPerm))
                        {
                            foreach (DataRow drForumPerm in dsForumPerm.Tables[0].Rows)
                            {
                                forumPermissions += drForumPerm["PermissionID"] + ";";
                            }
                            forumPermissions = forumPermissions.TrimEnd(';');
                        }

                        // Delete old permissions apart attach file permission
                        ForumRoleInfoProvider.DeleteAllRoles("ForumID = " + fi.ForumID + " AND PermissionID IN (" + forumPermissions.Replace(";", ", ") + ")");

                        // Set forum permissions
                        ForumRoleInfoProvider.SetPermissions(fi.ForumID, roleIDs, forumPermissions);

                        // Log staging task
                        SynchronizationHelper.LogObjectChange(fi, TaskTypeEnum.UpdateObject);
                    }

                    // Set permissions for media library
                    if (mi != null)
                    {
                        // Get resource object
                        ResourceInfo resMediaLibs = ResourceInfoProvider.GetResourceInfo("CMS.MediaLibrary");

                        // Get permissions IDs
                        DataSet dsMediaLibPerm      = PermissionNameInfoProvider.GetPermissionNames("ResourceID = " + resMediaLibs.ResourceId + " AND (PermissionName = 'LibraryAccess' OR PermissionName = 'FileCreate')", null, 0, "PermissionID");
                        string  mediaLibPermissions = null;
                        if (!DataHelper.DataSourceIsEmpty(dsMediaLibPerm))
                        {
                            foreach (DataRow drMediaLibPerm in dsMediaLibPerm.Tables[0].Rows)
                            {
                                mediaLibPermissions += drMediaLibPerm["PermissionID"] + ";";
                            }
                            mediaLibPermissions = mediaLibPermissions.TrimEnd(';');
                        }

                        // Delete old permissions only for Create file and See library content permissions
                        MediaLibraryRolePermissionInfoProvider.DeleteAllRoles("LibraryID = " + mi.LibraryID + " AND PermissionID IN (" + mediaLibPermissions.Replace(";", ", ") + ")");

                        // Set media library permissions
                        MediaLibraryRolePermissionInfoProvider.SetPermissions(mi.LibraryID, roleIDs, mediaLibPermissions);

                        // Log staging task
                        SynchronizationHelper.LogObjectChange(mi, TaskTypeEnum.UpdateObject);
                    }
                }
            }
        }
    }
コード例 #5
0
        public void Init()
        {
            // Ensure that the Foreign Keys and Views exist
            if (ResourceInfoProvider.GetResourceInfo("DynamicRouting.Kentico") != null)
            {
                try
                {
                    ConnectionHelper.ExecuteNonQuery("DynamicRouting.UrlSlug.InitializeSQLEntities");
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("DynamicRouting", "ErrorRunningSQLEntities", ex, additionalMessage: "Could not run DynamicRouting.UrlSlug.InitializeSQLEntities Query, this sets up Views and Foreign Keys vital to operation.  Please ensure these queries exist.");
                }
            }
            // Create Scheduled Tasks if it doesn't exist
            if (TaskInfoProvider.GetTasks().WhereEquals("TaskName", "CheckUrlSlugQueue").Count == 0)
            {
                try
                {
                    TaskInfo CheckUrlSlugQueueTask = new TaskInfo()
                    {
                        TaskName                       = "CheckUrlSlugQueue",
                        TaskDisplayName                = "Dynamic Routing - Check Url Slug Generation Queue",
                        TaskAssemblyName               = "DynamicRouting.Kentico",
                        TaskClass                      = "DynamicRouting.Kentico.DynamicRouteScheduledTasks",
                        TaskInterval                   = "hour;11/3/2019 4:54:30 PM;1;00:00:00;23:59:00;Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday",
                        TaskDeleteAfterLastRun         = false,
                        TaskRunInSeparateThread        = true,
                        TaskAllowExternalService       = true,
                        TaskUseExternalService         = false,
                        TaskRunIndividuallyForEachSite = false,
                        TaskEnabled                    = true,
                        TaskData                       = ""
                    };
                    CheckUrlSlugQueueTask.SetValue("TaskData", "");
                    TaskInfoProvider.SetTaskInfo(CheckUrlSlugQueueTask);
                }
                catch (Exception ex)
                {
                    EventLogProvider.LogException("DynamimcRouting", "ErrorCreatingUrlSlugQueue", ex, additionalMessage: "Could not create the CheckUrlSlugQueue scheduled task, please create a task with name 'CheckUrlSlugQueue' using assembly 'DynamicRouting.Kentico.DynamicRouteScheduledTasks' to run hourly.");
                }
            }

            // Detect Site Culture changes
            CultureSiteInfo.TYPEINFO.Events.Insert.After += CultureSite_InsertDelete_After;
            CultureSiteInfo.TYPEINFO.Events.Delete.After += CultureSite_InsertDelete_After;

            // Catch Site Default Culture and Builder setting updates
            SettingsKeyInfo.TYPEINFO.Events.Insert.After += SettingsKey_InsertUpdate_After;
            SettingsKeyInfo.TYPEINFO.Events.Update.After += SettingsKey_InsertUpdate_After;

            // Catch ClassURLPattern changes
            DataClassInfo.TYPEINFO.Events.Update.Before += DataClass_Update_Before;
            DataClassInfo.TYPEINFO.Events.Update.After  += DataClass_Update_After;

            // Document Changes
            DocumentEvents.ChangeOrder.After      += Document_ChangeOrder_After;
            DocumentEvents.Copy.After             += Document_Copy_After;
            DocumentEvents.Delete.After           += Document_Delete_After;
            DocumentEvents.Insert.After           += Document_Insert_After;
            DocumentEvents.InsertLink.After       += Document_InsertLink_After;
            DocumentEvents.InsertNewCulture.After += Document_InsertNewCulture_After;
            DocumentEvents.Move.Before            += Document_Move_Before;
            DocumentEvents.Move.After             += Document_Move_After;
            DocumentEvents.Sort.After             += Document_Sort_After;
            DocumentEvents.Update.After           += Document_Update_After;
            WorkflowEvents.Publish.After          += Document_Publish_After;

            // Handle 301 Redirect creation on Url Slug updates
            UrlSlugInfo.TYPEINFO.Events.Update.Before += UrlSlug_Update_Before_301Redirect;

            // Handle if IsCustom was true and is now false to re-build the slug, also handle preventing Url Slug staging tasks unless a custom action was done on the slug.
            UrlSlugInfo.TYPEINFO.Events.Update.Before += UrlSlug_Update_Before_IsCustomRebuild;
            UrlSlugInfo.TYPEINFO.Events.Update.After  += UrlSlug_Update_After_IsCustomRebuild;

            // Prevent Url Slug inserts from logging, these will always be "automatic" and should be handled normally
            UrlSlugInfo.TYPEINFO.Events.Insert.After += UrlSlug_Insert_After;

            // Add better name for tasks
            StagingEvents.LogTask.Before += LogTask_Before;

            // Handle the URL Slug events manually, will be checking for changes and adjusting.
            StagingEvents.ProcessTask.Before += StagingTask_ProcessTask_Before;
        }
コード例 #6
0
    protected void Page_Load(object sender, EventArgs e)
    {
        process = true;
        if (!Visible || StopProcessing)
        {
            EnableViewState = false;
            process         = false;
        }

        chkChangeName.CheckedChanged += chkChangeName_CheckedChanged;

        if (ForumID > 0)
        {
            // Get information on current forum
            forum = ForumInfoProvider.GetForumInfo(ForumID);

            // Check whether the forum still exists
            EditedObject = forum;
        }

        // Get forum resource
        resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");

        if ((resForums != null) && (forum != null))
        {
            QueryDataParameters parameters = new QueryDataParameters();
            parameters.Add("@ID", resForums.ResourceID);
            parameters.Add("@ForumID", forum.ForumID);
            parameters.Add("@SiteID", SiteContext.CurrentSiteID);

            string where = string.Empty;
            int groupId = 0;
            if (IsGroupForum)
            {
                ForumGroupInfo fgi = ForumGroupInfoProvider.GetForumGroupInfo(forum.ForumGroupID);
                groupId = fgi.GroupGroupID;
            }

            // Build where condition
            if (groupId > 0)
            {
                where = "RoleGroupID=" + groupId + " AND PermissionDisplayInMatrix = 0";
            }
            else
            {
                where = "RoleGroupID IS NULL AND PermissionDisplayInMatrix = 0";
            }

            // Setup matrix control
            gridMatrix.IsLiveSite      = IsLiveSite;
            gridMatrix.QueryParameters = parameters;
            gridMatrix.WhereCondition  = where;
            gridMatrix.CssClass        = "permission-matrix";
            gridMatrix.OnItemChanged  += gridMatrix_OnItemChanged;

            // Disable permission matrix if user has no Modify rights
            if (!CheckPermissions("cms.forums", PERMISSION_MODIFY))
            {
                Enable             = false;
                gridMatrix.Enabled = false;
                ShowError(String.Format(GetString("general.accessdeniedonpermissionname"), PERMISSION_MODIFY));
            }
        }
    }
コード例 #7
0
    /// <summary>
    /// Initializes the controls.
    /// </summary>
    private void SetupControl()
    {
        mQueryName = GetString("queryedit.newquery");

        DataClassInfo queryClass = null;

        // If the existing query is being edited
        if (QueryID > 0)
        {
            // Get information on existing query
            Query = QueryInfoProvider.GetQueryInfo(QueryID);
            if (Query != null)
            {
                queryClass = DataClassInfoProvider.GetDataClassInfo(Query.ClassID);
                ClassName  = queryClass.ClassName;
                QueryName  = Query.QueryName;

                if (!RequestHelper.IsPostBack())
                {
                    // Fills form with the existing query information
                    LoadValues();
                    txtQueryText.Focus();
                }
            }
        }
        // New query is being created
        else if (ClassID > 0)
        {
            Query      = new QueryInfo();
            queryClass = DataClassInfoProvider.GetDataClassInfo(ClassID);
            ClassName  = queryClass.ClassName;

            if (!RequestHelper.IsPostBack())
            {
                ucSelectString.Value = queryClass.ClassConnectionString;
            }

            txtQueryName.Focus();
        }

        plcLoadGeneration.Visible = SystemContext.DevelopmentMode;

        // Ensure generate button and custom checkbox for default queries
        if (SqlGenerator.IsSystemQuery(QueryName))
        {
            btnGenerate.Visible = true;
        }

        // Initialize the validator
        RequiredFieldValidatorQueryName.ErrorMessage = GetString("queryedit.erroremptyqueryname");

        if (ShowHelp)
        {
            DisplayHelperTable();
        }

        // Filter available only when creating new query in dialog mode
        plcDocTypeFilter.Visible = filter.Visible = DialogMode && !EditMode;

        // Set filter preselection
        if (plcDocTypeFilter.Visible)
        {
            filter.SelectedValue = QueryHelper.GetString("selectedvalue", null);
            filter.FilterMode    = QueryInfo.OBJECT_TYPE;
        }

        // Hide header actions when creating new query in dialog mode
        if ((DialogMode && !EditMode) || !Visible)
        {
            mCurrentMaster.HeaderActions.ActionsList.Clear();
        }

        txtQueryName.Enabled = !DialogMode || !EditMode;

        // Set dialog's content panel css class
        if (DialogMode)
        {
            if (EditMode)
            {
                mCurrentMaster.PanelContent.CssClass = "PageContent";
            }
            else
            {
                pnlContainer.CssClass = "PageContent";
            }
        }

        ResourceInfo resource = ResourceInfoProvider.GetResourceInfo(ModuleID);

        if ((resource != null) && !resource.IsEditable && (QueryID > 0))
        {
            if ((queryClass != null) && !queryClass.ClassShowAsSystemTable)
            {
                // Disable customization for module not in development and not customizable class
                pnlCustomization.StopProcessing = true;
                HeaderAction save = HeaderActions.ActionsList.FirstOrDefault(a => a is SaveAction);
                if (save != null)
                {
                    save.Enabled = false;
                    ShowInformation(GetString("cms.query.customization.disabled"));
                }
            }
            else
            {
                // Enable customization system tables in modules not in development
                pnlCustomization.HeaderActions       = HeaderActions;
                pnlCustomization.MessagesPlaceHolder = MessagesPlaceHolder;
            }
        }
        else
        {
            // Normal processing for new queries and queries in document types etc.
            pnlCustomization.StopProcessing = true;
        }
    }
コード例 #8
0
        private IEnumerable <KeyValuePair <string, string> > GetMetricData()
        {
            string stringData = null;
            IEnumerable <KeyValuePair <string, string> > tupleData = null;

            // Gather data for each row, return special message if data is null
            switch (MetricCodeName)
            {
            // Categories
            case MetricDataEnum.support_metrics:
            case MetricDataEnum.support_metrics_system:
            case MetricDataEnum.support_metrics_environment:
            case MetricDataEnum.support_metrics_counters:
            case MetricDataEnum.support_metrics_ecommerce:
            case MetricDataEnum.support_metrics_tasks:
            case MetricDataEnum.support_metrics_eventlog:
                return(null);

                #region System

            case MetricDataEnum.support_metrics_system_version:
                stringData = CMSVersion.GetVersion(true, true, true, true);
                break;

            case MetricDataEnum.support_metrics_system_appname:
                stringData = SettingsHelper.AppSettings["CMSApplicationName"];
                break;

            case MetricDataEnum.support_metrics_system_instancename:
                stringData = SystemContext.InstanceName;
                break;

            case MetricDataEnum.support_metrics_system_physicalpath:
                stringData = SystemContext.WebApplicationPhysicalPath;
                break;

            case MetricDataEnum.support_metrics_system_apppath:
                stringData = SystemContext.ApplicationPath;
                break;

            case MetricDataEnum.support_metrics_system_uiculture:
                stringData = LocalizationContext.CurrentUICulture.CultureName;
                break;

            case MetricDataEnum.support_metrics_system_installtype:
                stringData = SystemContext.IsWebApplicationProject ? "Web App" : "Web site";
                break;

            case MetricDataEnum.support_metrics_system_portaltemplatepage:
                stringData = URLHelper.PortalTemplatePage;
                break;

            case MetricDataEnum.support_metrics_system_timesinceapprestart:
                stringData = (DateTime.Now - CMSApplication.ApplicationStart).ToString(@"dd\:hh\:mm\:ss");
                break;

            case MetricDataEnum.support_metrics_system_discoveredassemblies:
                tupleData = AssemblyDiscoveryHelper.GetAssemblies(true).Select((a, i) => GetKeyValuePair(i, a.FullName));
                break;

            case MetricDataEnum.support_metrics_system_targetframework:
                HttpRuntimeSection httpRuntime = ConfigurationManager.GetSection("system.web/httpRuntime") as HttpRuntimeSection;
                stringData = httpRuntime.TargetFramework;
                break;

            case MetricDataEnum.support_metrics_system_authmode:
                AuthenticationSection Authentication = ConfigurationManager.GetSection("system.web/authentication") as AuthenticationSection;
                stringData = Authentication?.Mode.ToString();
                break;

            case MetricDataEnum.support_metrics_system_sessionmode:
                SessionStateSection SessionState = ConfigurationManager.GetSection("system.web/sessionState") as SessionStateSection;
                stringData = SessionState?.Mode.ToString();
                break;

            case MetricDataEnum.support_metrics_system_debugmode:
                CompilationSection Compilation = ConfigurationManager.GetSection("system.web/compilation") as CompilationSection;
                stringData = Compilation?.Debug.ToString();
                break;

            case MetricDataEnum.support_metrics_system_runallmanagedmodules:
                var xmlDoc = new System.Xml.XmlDocument();
                xmlDoc.Load(URLHelper.GetPhysicalPath("~/Web.config"));
                stringData = xmlDoc.SelectSingleNode("/configuration/system.webServer/modules").Attributes["runAllManagedModulesForAllRequests"]?.Value;
                break;

                #endregion System

                #region Environment

            case MetricDataEnum.support_metrics_environment_trustlevel:

                AspNetHostingPermissionLevel trustLevel = AspNetHostingPermissionLevel.None;

                if (!SystemContext.IsWebSite)
                {
                    trustLevel = AspNetHostingPermissionLevel.Unrestricted;
                }

                // Check the trust level by evaluation of levels
                foreach (AspNetHostingPermissionLevel permissionLevel in new[] {
                    AspNetHostingPermissionLevel.Unrestricted,
                    AspNetHostingPermissionLevel.High,
                    AspNetHostingPermissionLevel.Medium,
                    AspNetHostingPermissionLevel.Low,
                    AspNetHostingPermissionLevel.Minimal
                })
                {
                    try
                    {
                        new AspNetHostingPermission(permissionLevel).Demand();
                    }
                    catch (SecurityException)
                    {
                        continue;
                    }

                    trustLevel = permissionLevel;
                    break;
                }

                stringData = trustLevel.ToString();
                break;

            case MetricDataEnum.support_metrics_environment_iisversion:
                stringData = MetricServerVariables["SERVER_SOFTWARE"];
                break;

            case MetricDataEnum.support_metrics_environment_https:
                stringData = MetricServerVariables["HTTPS"];
                break;

            case MetricDataEnum.support_metrics_environment_windowsversion:
                using (RegistryKey versionKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"))
                {
                    var productName  = versionKey?.GetValue("ProductName");
                    var currentBuild = versionKey?.GetValue("CurrentBuild");
                    var releaseId    = versionKey?.GetValue("ReleaseId");

                    stringData = String.Format("{0}, build {1}, release {2}", productName.ToString(), currentBuild.ToString(), releaseId.ToString());
                }
                break;

            case MetricDataEnum.support_metrics_environment_netversion:
                using (RegistryKey ndpKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32).OpenSubKey(@"SOFTWARE\Microsoft\NET Framework Setup\NDP\v4\Full\"))
                {
                    var keyValue = ndpKey?.GetValue("Release");
                    if (keyValue != null)
                    {
                        var releaseKey = (int)keyValue;
                        if (releaseKey >= 461808)
                        {
                            stringData = "4.7.2 or later";
                        }
                        else
                        if (releaseKey >= 461308)
                        {
                            stringData = "4.7.1";
                        }
                        else
                        if (releaseKey >= 460798)
                        {
                            stringData = "4.7";
                        }
                        else
                        if (releaseKey >= 394802)
                        {
                            stringData = "4.6.2";
                        }
                        else
                        if (releaseKey >= 394254)
                        {
                            stringData = "4.6.1";
                        }
                        else
                        if (releaseKey >= 393295)
                        {
                            stringData = "4.6";
                        }
                        else
                        if (releaseKey >= 379893)
                        {
                            stringData = "4.5.2";
                        }
                        else
                        if (releaseKey >= 378675)
                        {
                            stringData = "4.5.1";
                        }
                        else
                        if (releaseKey >= 378389)
                        {
                            stringData = "4.5";
                        }
                    }
                }
                break;

            case MetricDataEnum.support_metrics_environment_sqlserverversion:
                var dtm = new TableManager(null);
                stringData = dtm.DatabaseServerVersion;
                break;

            case MetricDataEnum.support_metrics_environment_azure:
                var azureStats = new Dictionary <string, string>(4)
                {
                    { "Is a Cloud Service", (SettingsHelper.AppSettings["CMSAzureProject"] == "true").ToString("false") },
                    { "Is file system on Azure", (SettingsHelper.AppSettings["CMSExternalStorageName"] == "azure").ToString("false") },
                    { "Azure storage account", SettingsHelper.AppSettings["CMSAzureAccountName"] ?? String.Empty },
                    { "Azure CDN endpoint", SettingsHelper.AppSettings["CMSAzureCDNEndpoint"] ?? String.Empty }
                };

                tupleData = azureStats.Select(s => GetKeyValuePair(s.Key, s.Value));
                break;

            case MetricDataEnum.support_metrics_environment_amazon:
                var amazonStats = new Dictionary <string, string>(3)
                {
                    { "Is file system on Amazon", (SettingsHelper.AppSettings["CMSExternalStorageName"] == "amazon").ToString() },
                    { "Amazon bucket name", SettingsHelper.AppSettings["CMSAmazonBucketName"] ?? String.Empty },
                    { "Amazon public access", SettingsHelper.AppSettings["CMSAmazonPublicAccess"] ?? String.Empty },
                };

                tupleData = amazonStats.Select(s => GetKeyValuePair(s.Key, s.Value));
                break;

            case MetricDataEnum.support_metrics_environment_services:
                tupleData = ServiceManager.GetServices().Select(s => GetKeyValuePair(s.ServiceName, s.Status));
                break;

                #endregion Environment

                #region Counters

            case MetricDataEnum.support_metrics_counters_webfarmservers:
                stringData = CoreServices.WebFarm.GetEnabledServerNames().Count().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_stagingservers:
                stringData = ServerInfoProvider.GetServers().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_pagemostchildren:
                CMS.DocumentEngine.TreeProvider tree = new CMS.DocumentEngine.TreeProvider();

                var pageWithMostChildren = tree.SelectNodes().OnCurrentSite().Published()
                                           .ToDictionary(n => n, n => n.Children.Count)
                                           .Aggregate((l, r) => l.Value > r.Value ? l : r);

                tupleData = new[] { GetKeyValuePair(URLHelper.GetAbsoluteUrl("~" + pageWithMostChildren.Key.NodeAliasPath), pageWithMostChildren.Value) };
                break;

            case MetricDataEnum.support_metrics_counters_modules:
                stringData = ResourceInfoProvider.GetResources().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_medialibraries:
                stringData = MediaLibraryInfoProvider.GetMediaLibraries().WhereNull("LibraryGroupID").GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_activities:
                stringData = ActivityInfoProvider.GetActivities().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_contacts:
                stringData = ContactInfoProvider.GetContacts().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_contactgroups:
                stringData = ContactGroupInfoProvider.GetContactGroups().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_omrules:
                stringData = RuleInfoProvider.GetRules().GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_counters_products:
                stringData = SKUInfoProvider.GetSKUs(SiteContext.CurrentSiteID).WhereNull("SKUOptionCategoryID").GetCount().ToString();
                break;

                #endregion Counters

                #region Tasks

            case MetricDataEnum.support_metrics_tasks_webfarm:
                stringData = WebFarmTaskInfoProvider.GetWebFarmTasks()
                             .WhereLessThan("TaskCreated", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_staging:
                stringData = StagingTaskInfoProvider.GetTasks()
                             .WhereLessThan("TaskTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_integration:
                stringData = IntegrationTaskInfoProvider.GetIntegrationTasks()
                             .WhereLessThan("TaskTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_scheduled:
                stringData = TaskInfoProvider.GetTasks()
                             .WhereTrue("TaskDeleteAfterLastRun")
                             .WhereLessThan("TaskNextRunTime", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_search:
                stringData = SearchTaskInfoProvider.GetSearchTasks()
                             .WhereLessThan("SearchTaskCreated", DateTime.Now.AddDays(-1))
                             .GetCount().ToString();
                break;

            case MetricDataEnum.support_metrics_tasks_email:
                stringData = EmailInfoProvider.GetEmailCount("EmailStatus = 1 AND EmailLastSendResult IS NOT NULL").ToString();
                break;

                #endregion Tasks

                #region Event log

            case MetricDataEnum.support_metrics_eventlog_macroerrors:
                var macroErrors = EventLogProvider.GetEvents()
                                  .WhereEquals("Source", "MacroResolver")
                                  .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                  .OrderByDescending("EventTime")
                                  .TopN(10);

                tupleData = macroErrors.Select(e =>
                                               GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                               e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                               );
                break;

            case MetricDataEnum.support_metrics_eventlog_stagingerrors:
                var stagingErrors = EventLogProvider.GetEvents()
                                    .WhereEquals("Source", "staging")
                                    .WhereIn("EventType", new[] { "E", "W" })
                                    .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                    .OrderByDescending("EventTime")
                                    .TopN(10);

                tupleData = stagingErrors.Select(e =>
                                                 GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                 e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                 );
                break;

            case MetricDataEnum.support_metrics_eventlog_searcherrors:
                var searchErrors = EventLogProvider.GetEvents()
                                   .WhereEquals("Source", "search")
                                   .WhereIn("EventType", new[] { "E", "W" })
                                   .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                   .OrderByDescending("EventTime")
                                   .TopN(10);

                tupleData = searchErrors.Select(e =>
                                                GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                );
                break;

            case MetricDataEnum.support_metrics_eventlog_contenterrors:
                var contentErrors = EventLogProvider.GetEvents()
                                    .WhereEquals("Source", "content")
                                    .WhereIn("EventType", new[] { "E", "W" })
                                    .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                    .OrderByDescending("EventTime")
                                    .TopN(10);

                tupleData = contentErrors.Select(e =>
                                                 GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                 e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                 );
                break;

            case MetricDataEnum.support_metrics_eventlog_exceptions:
                var exceptions = EventLogProvider.GetEvents()
                                 .WhereEquals("EventCode", "exception")
                                 .WhereGreaterThan("EventTime", DateTime.Now.Subtract(TimeSpan.FromDays(7)))
                                 .OrderByDescending("EventTime")
                                 .TopN(10);

                tupleData = exceptions.Select(e =>
                                              GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                              e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                              );
                break;

            case MetricDataEnum.support_metrics_eventlog_upgrade:

                EventLogInfo upgrade = EventLogProvider.GetEvents().WhereLike("Source", "upgrade%").FirstOrDefault();
                var          version = upgrade?.Source.Split(' ')[2];

                if (!String.IsNullOrEmpty(version))
                {
                    var parameters = new QueryDataParameters
                    {
                        { "@versionnumber", version }
                    };

                    var events = ConnectionHelper.ExecuteQuery("SupportHelper.CustomMetric.checkupgrade", parameters);

                    tupleData = (from DataRow row in events.Tables[0]?.Rows select row)
                                .Select(r => new EventLogInfo(r)).Select(e =>
                                                                         GetKeyValuePair(String.Format("{0} from {1} at {2} in {3}", e.EventCode, e.Source, e.EventTime, e.EventMachineName),
                                                                                         e.EventDescription.Length > CUTOFF ? e.EventDescription.Substring(0, CUTOFF) : e.EventDescription)
                                                                         );
                }
                break;

                #endregion Event log
            }

            if (tupleData?.Count() > 0)
            {
                return(tupleData);
            }

            if (stringData != null)
            {
                return(new[] { GetKeyValuePair(0, stringData) });
            }

            return(new[] { GetKeyValuePair(0, ResHelper.GetStringFormat("support.metrics.invalid", MetricDisplayName, MetricCodeName)) });
        }
コード例 #9
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Handle the preselection
        preselectedItem = QueryHelper.GetString(this.QueryParameterName, "");
        if (preselectedItem.StartsWith("cms.", StringComparison.InvariantCultureIgnoreCase))
        {
            preselectedItem = preselectedItem.Substring(4);
        }

        uniMenu.HighlightItem = preselectedItem;

        // If element name is not set, use root module element
        string elemName = this.ElementName;

        if (String.IsNullOrEmpty(elemName))
        {
            elemName = this.ModuleName.Replace(".", "");
        }

        // Get the UI elements
        DataSet ds = UIElementInfoProvider.GetChildUIElements(this.ModuleName, elemName);

        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            FilterElements(ds);

            int count = ds.Tables[0].Rows.Count;
            string[,] groups = new string[count, 4];

            // Prepare the list of elements
            int i = 0;
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string url = ValidationHelper.GetString(dr["ElementTargetURL"], "");

                if (url.EndsWith("ascx"))
                {
                    groups[i, 1] = url;
                }
                else
                {
                    groups[i, 3] = ValidationHelper.GetString(dr["ElementID"], "");
                }

                groups[i, 2] = "ContentMenuGroup";
                groups[i, 0] = ResHelper.LocalizeString(ValidationHelper.GetString(dr["ElementCaption"], ""));

                i++;
            }

            uniMenu.Groups = groups;

            // Button created & filtered event handler
            if (OnButtonCreated != null)
            {
                uniMenu.OnButtonCreated += new CMSAdminControls_UI_UniMenu_UniMenu.ButtonCreatedEventHandler(uniMenu_OnButtonCreated);
            }
            if (OnButtonFiltered != null)
            {
                uniMenu.OnButtonFiltered += new CMSAdminControls_UI_UniMenu_UniMenu.ButtonFilterEventHandler(uniMenu_OnButtonFiltered);
            }
        }

        // Add editing icon in development mode
        if (SettingsKeyProvider.DevelopmentMode && CMSContext.CurrentUser.IsGlobalAdministrator)
        {
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(this.ModuleName);
            if (ri != null)
            {
                ltlAfter.Text += UIHelper.GetResourceUIElementsLink(this.Page, ri.ResourceId);
            }
        }
    }
    /// <summary>
    /// PreRender action on which security settings are set.
    /// </summary>
    private void Page_PreRender(object sender, EventArgs e)
    {
        if ((Form == null) || !mDocumentSaved)
        {
            return;
        }

        TreeNode editedNode = Form.EditedObject as TreeNode;

        // Create or rebuild department content index
        CreateDepartmentContentSearchIndex(editedNode);

        if ((editedNode == null) || !editedNode.NodeIsACLOwner)
        {
            return;
        }

        ForumInfo        fi = ForumInfoProvider.GetForumInfo("Default_department_" + editedNode.NodeGUID, SiteContext.CurrentSiteID);
        MediaLibraryInfo mi = MediaLibraryInfoProvider.GetMediaLibraryInfo("Department_" + editedNode.NodeGUID, SiteContext.CurrentSiteName);

        // Check if forum of media library exists
        if ((fi == null) && (mi == null))
        {
            return;
        }

        // Get allowed roles ID
        int         aclID     = ValidationHelper.GetInteger(editedNode.GetValue("NodeACLID"), 0);
        DataSet     listRoles = AclItemInfoProvider.GetAllowedRoles(aclID, NodePermissionsEnum.Read, "RoleID");
        IList <int> roleIds   = null;


        if (!DataHelper.DataSourceIsEmpty(listRoles))
        {
            roleIds = DataHelper.GetIntegerValues(listRoles.Tables[0], "RoleID") as List <int>;
        }

        // Set permissions for forum
        if (fi != null)
        {
            // Get resource object
            ResourceInfo resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");

            // Get permissions IDs
            var forumPermissions = PermissionNameInfoProvider.GetPermissionNames()
                                   .Column("PermissionID")
                                   .WhereEquals("ResourceID", resForums.ResourceID)
                                   .WhereNotEquals("PermissionName", CMSAdminControl.PERMISSION_READ)
                                   .WhereNotEquals("PermissionName", CMSAdminControl.PERMISSION_MODIFY);

            // Delete old permissions apart attach file permission
            ForumRoleInfoProvider.DeleteAllRoles(new WhereCondition().WhereEquals("ForumID", fi.ForumID).WhereIn("PermissionID", forumPermissions));

            // Set forum permissions
            ForumRoleInfoProvider.SetPermissions(fi.ForumID, roleIds, forumPermissions.Select(p => p.PermissionId).ToArray());

            // Log staging task
            SynchronizationHelper.LogObjectChange(fi, TaskTypeEnum.UpdateObject);
        }

        // Set permissions for media library
        if (mi == null)
        {
            return;
        }

        // Get resource object
        ResourceInfo resMediaLibs = ResourceInfoProvider.GetResourceInfo("CMS.MediaLibrary");

        // Get permissions IDs
        var where = new WhereCondition()
                    .WhereEquals("ResourceID", resMediaLibs.ResourceID)
                    .And()
                    .Where(new WhereCondition()
                           .WhereEquals("PermissionName", "LibraryAccess")
                           .Or()
                           .WhereEquals("PermissionName", "FileCreate"));

        DataSet     dsMediaLibPerm         = PermissionNameInfoProvider.GetPermissionNames().Where(where).Column("PermissionID");
        IList <int> mediaLibPermissionsIds = null;

        if (!DataHelper.DataSourceIsEmpty(dsMediaLibPerm))
        {
            mediaLibPermissionsIds = DataHelper.GetIntegerValues(dsMediaLibPerm.Tables[0], "PermissionID");
        }

        var deleteWhere = new WhereCondition()
                          .WhereEquals("LibraryID", mi.LibraryID)
                          .WhereIn("PermissionID", mediaLibPermissionsIds);

        // Delete old permissions only for Create file and See library content permissions
        MediaLibraryRolePermissionInfoProvider.DeleteAllRoles(deleteWhere.ToString(true));

        MediaLibraryRolePermissionInfoProvider.SetPermissions(mi.LibraryID, roleIds, mediaLibPermissionsIds);

        // Log staging task;
        SynchronizationHelper.LogObjectChange(mi, TaskTypeEnum.UpdateObject);
    }
コード例 #11
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Logging out of Facebook
        if (QueryHelper.GetInteger("logout", 0) > 0)
        {
            btnSignOut_Click(this, EventArgs.Empty);
        }
        btnSignOut.OnClientClick = FacebookConnectHelper.FacebookConnectInitForSignOut(CMSContext.CurrentSiteName, LiteralScript);

        this.LabelMessage.Text    = GetString("CMSMessages.AccessDenied");
        this.titleElem.TitleText  = GetString("CMSDesk.AccessDenied");
        this.titleElem.TitleImage = GetImageUrl("Others/Messages/denied.png");

        // If specification parameters given, display custom message
        string resourceName = QueryHelper.GetString("resource", null);
        int    nodeId       = QueryHelper.GetInteger("nodeid", 0);
        string message      = QueryHelper.GetText("message", null);

        if (!String.IsNullOrEmpty(resourceName))
        {
            // Access denied to resource
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(resourceName);
            if (ri != null)
            {
                this.titleElem.TitleText = String.Format(GetString("CMSSiteManager.AccessDeniedOnResource"), ri.ResourceDisplayName);
            }
        }
        else if (nodeId > 0)
        {
            // Access denied to document
            TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
            TreeNode     node = tree.SelectSingleNode(nodeId);
            if (node != null)
            {
                this.titleElem.TitleText = String.Format(GetString("CMSSiteManager.AccessDeniedOnNode"), HTMLHelper.HTMLEncode(node.DocumentName));
            }
        }
        else if (!String.IsNullOrEmpty(message))
        {
            // Custom message
            this.LabelMessage.Text = ResHelper.LocalizeString(message);
        }

        // Add missing permission name message
        string permission = QueryHelper.GetText("permission", null);

        if (!String.IsNullOrEmpty(permission))
        {
            this.LabelMessage.Text = String.Format(GetString("CMSSiteManager.AccessDeniedOnPermissionName"), permission);
        }

        // Display SignOut button
        if (CMSContext.CurrentUser.IsAuthenticated())
        {
            if (!RequestHelper.IsWindowsAuthentication())
            {
                this.btnSignOut.Visible = true;
            }
        }
        else
        {
            this.btnLogin.Visible = true;
        }

        this.lnkGoBack.Text = GetString("CMSDesk.GoBack");
    }
コード例 #12
0
    protected void Page_Load(object sender, EventArgs e)
    {
        int moduleId = QueryHelper.GetInteger("moduleid", 0);
        int parentId = QueryHelper.GetInteger("parentId", 0);

        ScriptHelper.RegisterJQuery(Page);

        // Use images according to culture
        if (CultureHelper.IsUICultureRTL())
        {
            uniTree.LineImagesFolder = GetImageUrl("RTL/Design/Controls/Tree", false, false);
        }
        else
        {
            uniTree.LineImagesFolder = GetImageUrl("Design/Controls/Tree", false, false);
        }

        if (!RequestHelper.IsPostBack())
        {
            // Get module root element
            UIElementInfo elemInfo = UIElementInfoProvider.GetRootUIElementInfo(moduleId);
            if (elemInfo != null)
            {
                uniTree.SelectPath = elemInfo.ElementIDPath;
                uniTree.ExpandPath = elemInfo.ElementIDPath + "/";
                menuElem.Value     = elemInfo.ElementID + "|" + elemInfo.ElementParentID;
            }
            else
            {
                // Get current resource
                ResourceInfo resInfo = ResourceInfoProvider.GetResourceInfo(moduleId);
                if (resInfo != null)
                {
                    // Create new UI element
                    elemInfo = new UIElementInfo();
                    elemInfo.ElementResourceID  = moduleId;
                    elemInfo.ElementDisplayName = resInfo.ResourceDisplayName;
                    elemInfo.ElementName        = resInfo.ResourceName.ToLowerCSafe().Replace(".", "");
                    elemInfo.ElementIsCustom    = false;

                    UIElementInfoProvider.SetUIElementInfo(elemInfo);
                    uniTree.SelectPath = elemInfo.ElementIDPath;
                    uniTree.ExpandPath = elemInfo.ElementIDPath;
                    menuElem.Value     = elemInfo.ElementID + "|0";
                }
            }
        }

        menuElem.ResourceID   = moduleId;
        menuElem.AfterAction += new OnActionEventHandler(menuElem_AfterAction);

        // Create and set UIElements provider
        UniTreeProvider elementProvider = new UniTreeProvider();

        elementProvider.ObjectType        = "CMS.UIElement";
        elementProvider.DisplayNameColumn = "ElementDisplayName";
        elementProvider.IDColumn          = "ElementID";
        elementProvider.LevelColumn       = "ElementLevel";
        elementProvider.OrderColumn       = "ElementOrder";
        elementProvider.ParentIDColumn    = "ElementParentID";
        elementProvider.PathColumn        = "ElementIDPath";
        elementProvider.ValueColumn       = "ElementID";
        elementProvider.ChildCountColumn  = "ElementChildCount";
        elementProvider.WhereCondition    = "ElementResourceID = " + moduleId;
        elementProvider.Columns           = "ElementID,ElementLevel,ElementOrder,ElementParentID,ElementIDPath,ElementChildCount,ElementDisplayName";

        uniTree.UsePostBack     = false;
        uniTree.ProviderObject  = elementProvider;
        uniTree.ExpandTooltip   = GetString("general.expand");
        uniTree.CollapseTooltip = GetString("general.collapse");

        uniTree.NodeTemplate         = "<span id=\"node_##NODEID##\" onclick=\"SelectNode(##NODEID##,##PARENTNODEID##," + moduleId + "); return false;\" name=\"treeNode\" class=\"ContentTreeItem\"><span class=\"Name\">##NODENAME##</span></span>";
        uniTree.SelectedNodeTemplate = "<span id=\"node_##NODEID##\" onclick=\"SelectNode(##NODEID##,##PARENTNODEID##," + moduleId + "); return false;\" name=\"treeNode\" class=\"ContentTreeItem ContentTreeSelectedItem\"><span class=\"Name\">##NODENAME##</span></span>";

        if (!RequestHelper.IsPostBack())
        {
            string selectedPath = QueryHelper.GetString("path", String.Empty);
            int    elementId    = QueryHelper.GetInteger("elementId", 0);

            if (!string.IsNullOrEmpty(selectedPath))
            {
                uniTree.SelectPath = selectedPath;
            }

            if (elementId > 0)
            {
                menuElem.ElementID = elementId;
                menuElem.ParentID  = parentId;
                menuElem.Value     = elementId + "|" + parentId;
            }
        }

        // Load data
        uniTree.ReloadData();

        string script = "var frameURL = '" + ResolveUrl("~/CMSModules/Modules/Pages/Development/Module_UI_EditFrameset.aspx") + "';";

        script += "var newURL = '" + ResolveUrl("~/CMSModules/Modules/Pages/Development/Module_UI_New.aspx") + "';";
        script += "var postParentId = " + parentId + ";";

        ltlScript.Text = ScriptHelper.GetScript(script);
    }
コード例 #13
0
    protected void Page_Load(object sender, EventArgs e)
    {
        CurrentUserInfo currentUser = CMSContext.CurrentUser;

        // Fill the menu with UIElement data for specified module
        if (!String.IsNullOrEmpty(this.ModuleName) & (currentUser != null))
        {
            DataSet dsModules = UIElementInfoProvider.GetUIMenuElements(ModuleName);

            List <object[]> categoriesTmp = new List <object[]>();

            if (!DataHelper.DataSourceIsEmpty(dsModules))
            {
                foreach (DataRow drModule in dsModules.Tables[0].Rows)
                {
                    UIElementInfo moduleElement = new UIElementInfo(drModule);

                    // Proceed if user has permissions for this UI element
                    if (currentUser.IsAuthorizedPerUIElement(this.ModuleName, moduleElement.ElementName))
                    {
                        // Category title
                        string categoryTitle = ResHelper.LocalizeString(moduleElement.ElementDisplayName);

                        // Category name
                        string categoryName = ResHelper.LocalizeString(moduleElement.ElementName);

                        // Category URL
                        string categoryUrl = CMSContext.ResolveMacros(URLHelper.EnsureHashToQueryParameters(moduleElement.ElementTargetURL));

                        // Category image URL
                        string categoryImageUrl = this.GetImagePath(moduleElement.ElementIconPath.Replace("list.png", "module.png"));
                        if (!FileHelper.FileExists(categoryImageUrl))
                        {
                            categoryImageUrl = this.GetImagePath("CMSModules/module.png");
                        }

                        // Category tooltip
                        string categoryTooltip = ResHelper.LocalizeString(moduleElement.ElementDescription);

                        // Category actions
                        DataSet dsActions = UIElementInfoProvider.GetChildUIElements(moduleElement.ElementID);

                        List <string[]> actionsTmp = new List <string[]>();

                        foreach (DataRow drAction in dsActions.Tables[0].Rows)
                        {
                            UIElementInfo actionElement = new UIElementInfo(drAction);

                            // Proceed if user has permissions for this UI element
                            if (currentUser.IsAuthorizedPerUIElement(this.ModuleName, actionElement.ElementName))
                            {
                                actionsTmp.Add(new string[] { ResHelper.LocalizeString(actionElement.ElementDisplayName), CMSContext.ResolveMacros(URLHelper.EnsureHashToQueryParameters(actionElement.ElementTargetURL)) });
                            }
                        }

                        int actionsCount = actionsTmp.Count;

                        string[,] categoryActions = new string[actionsCount, 2];

                        for (int i = 0; i < actionsCount; i++)
                        {
                            categoryActions[i, 0] = actionsTmp[i][0];
                            categoryActions[i, 1] = actionsTmp[i][1];
                        }

                        CategoryCreatedEventArgs args = new CategoryCreatedEventArgs(moduleElement, categoryName, categoryTitle, categoryUrl, categoryImageUrl, categoryTooltip, categoryActions);

                        // Raise additional initialization events for this category
                        if (this.CategoryCreated != null)
                        {
                            this.CategoryCreated(this, args);
                        }

                        // Add to categories, if further processing of this category was not cancelled
                        if (!args.Cancel)
                        {
                            categoriesTmp.Add(new object[] { args.CategoryTitle, args.CategoryName, args.CategoryURL, args.CategoryImageURL, args.CategoryTooltip, args.CategoryActions });
                        }
                    }
                }
            }

            int categoriesCount = categoriesTmp.Count;

            object[,] categories = new object[categoriesCount, 6];

            for (int i = 0; i < categoriesCount; i++)
            {
                categories[i, 0] = categoriesTmp[i][0];
                categories[i, 1] = categoriesTmp[i][1];
                categories[i, 2] = categoriesTmp[i][2];
                categories[i, 3] = categoriesTmp[i][3];
                categories[i, 4] = categoriesTmp[i][4];
                categories[i, 5] = categoriesTmp[i][5];
            }
            if (categoriesCount > 0)
            {
                this.panelMenu.Categories   = categories;
                this.panelMenu.ColumnsCount = this.ColumnsCount;
            }
            else
            {
                RedirectToUINotAvailable();
            }

            // Add editing icon in development mode
            if (SettingsKeyProvider.DevelopmentMode && currentUser.IsGlobalAdministrator)
            {
                ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(this.ModuleName);
                if (ri != null)
                {
                    ltlAfter.Text += "<div class=\"AlignRight\">" + UIHelper.GetResourceUIElementsLink(this.Page, ri.ResourceId) + "</div>";
                }
            }
        }
    }
コード例 #14
0
    /// <summary>
    /// Generates the permission matrix for the current forum.
    /// </summary>
    private void CreateMatrix()
    {
        // Get forum resource info
        if (resForums == null)
        {
            resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");
        }

        // Get forum object
        if ((forum == null) && (ForumID > 0))
        {
            forum = ForumInfoProvider.GetForumInfo(ForumID);
        }

        if ((resForums != null) && (forum != null))
        {
            // Get permission matrix for roles of the current site/group
            int groupId = 0;
            if (IsGroupForum)
            {
                ForumGroupInfo fgi = ForumGroupInfoProvider.GetForumGroupInfo(forum.ForumGroupID);
                groupId = fgi.GroupGroupID;
            }

            // Get permissions for the current forum resource
            DataSet permissions = PermissionNameInfoProvider.GetResourcePermissions(resForums.ResourceId);
            if (DataHelper.DataSourceIsEmpty(permissions))
            {
                ShowInformation(GetString("general.emptymatrix"));
            }
            else
            {
                TableRow headerRow = new TableRow();
                headerRow.CssClass = "UniGridHead";
                TableCell       newCell       = new TableCell();
                TableHeaderCell newHeaderCell = new TableHeaderCell();
                newHeaderCell.Text = "&nbsp;";
                newHeaderCell.Attributes["style"] = "width:200px;";
                headerRow.Cells.Add(newHeaderCell);

                foreach (string permission in allowedPermissions)
                {
                    DataRow[] drArray = permissions.Tables[0].DefaultView.Table.Select("PermissionName = '" + permission + "'");
                    if ((drArray != null) && (drArray.Length > 0))
                    {
                        DataRow dr = drArray[0];
                        newHeaderCell = new TableHeaderCell();
                        newHeaderCell.Attributes["style"] = "text-align:center;white-space:nowrap;";
                        newHeaderCell.Text            = dr["PermissionDisplayName"].ToString();
                        newHeaderCell.ToolTip         = dr["PermissionDescription"].ToString();
                        newHeaderCell.HorizontalAlign = HorizontalAlign.Center;
                        headerRow.Cells.Add(newHeaderCell);
                    }
                    else
                    {
                        throw new Exception("[Security matrix] Column '" + permission + "' cannot be found.");
                    }
                }
                newHeaderCell      = new TableHeaderCell();
                newHeaderCell.Text = "&nbsp;";
                headerRow.Cells.Add(newHeaderCell);

                tblMatrix.Rows.Add(headerRow);

                // Render forum access permissions
                object[,] accessNames = new object[5, 2];
                accessNames[0, 0]     = GetString("security.nobody");
                accessNames[0, 1]     = SecurityAccessEnum.Nobody;
                accessNames[1, 0]     = GetString("security.allusers");
                accessNames[1, 1]     = SecurityAccessEnum.AllUsers;
                accessNames[2, 0]     = GetString("security.authenticated");
                accessNames[2, 1]     = SecurityAccessEnum.AuthenticatedUsers;
                accessNames[3, 0]     = GetString("security.groupmembers");
                accessNames[3, 1]     = SecurityAccessEnum.GroupMembers;
                accessNames[4, 0]     = GetString("security.authorizedroles");
                accessNames[4, 1]     = SecurityAccessEnum.AuthorizedRoles;

                TableRow newRow   = null;
                int      rowIndex = 0;
                for (int access = 0; access <= accessNames.GetUpperBound(0); access++)
                {
                    SecurityAccessEnum currentAccess = ((SecurityAccessEnum)accessNames[access, 1]);

                    // If the security isn't displayed as part of group section
                    if ((currentAccess == SecurityAccessEnum.GroupMembers) && (!IsGroupForum))
                    {
                        // Do not render this access item
                    }
                    else
                    {
                        // Generate cell holding access item name
                        newRow           = new TableRow();
                        newRow.CssClass  = ((rowIndex % 2 == 0) ? "EvenRow" : "OddRow");
                        newCell          = new TableCell();
                        newCell.Text     = accessNames[access, 0].ToString();
                        newCell.Wrap     = false;
                        newCell.CssClass = "MatrixHeader";
                        newCell.Width    = new Unit(28, UnitType.Percentage);
                        newRow.Cells.Add(newCell);
                        rowIndex++;

                        // Render the permissions access items
                        bool isAllowed       = false;
                        bool isDisabled      = true;
                        int  permissionIndex = 0;
                        for (int permission = 0; permission < (tblMatrix.Rows[0].Cells.Count - 2); permission++)
                        {
                            newCell = new TableCell();

                            // Check if the currently processed access is applied for permission
                            isAllowed  = CheckPermissionAccess(currentAccess, permission, tblMatrix.Rows[0].Cells[permission + 1].Text);
                            isDisabled = ((currentAccess == SecurityAccessEnum.AllUsers) && (permission == 1)) || (!Enable);

                            // Disable column in roles grid if needed
                            if ((currentAccess == SecurityAccessEnum.AuthorizedRoles) && !isAllowed)
                            {
                                gridMatrix.DisableColumn(permissionIndex);
                            }

                            // Insert the radio button for the current permission
                            string permissionText = tblMatrix.Rows[0].Cells[permission + 1].Text;
                            string elemId         = ClientID + "_" + permission + "_" + access;
                            newCell.Text = "<label style=\"display:none;\" for=\"" + elemId + "\">" + permissionText + "</label><input type=\"radio\" id=\"" + elemId + "\" name=\"" + permissionText + "\" onclick=\"" +
                                           ControlsHelper.GetPostBackEventReference(this, permission.ToString() + ";" + Convert.ToInt32(currentAccess).ToString()) + "\" " +
                                           ((isAllowed) ? "checked = \"checked\"" : "") + ((isDisabled) ? " disabled=\"disabled\"" : "") + "/>";

                            newCell.Wrap            = false;
                            newCell.Width           = new Unit(12, UnitType.Percentage);
                            newCell.HorizontalAlign = HorizontalAlign.Center;
                            newRow.Cells.Add(newCell);
                            permissionIndex++;
                        }

                        newCell      = new TableCell();
                        newCell.Text = "&nbsp;";
                        newRow.Cells.Add(newCell);

                        // Add the access row to the table
                        tblMatrix.Rows.Add(newRow);
                    }
                }

                // Check if forum has some roles assigned
                mNoRolesAvailable = !gridMatrix.HasData;

                // Get permission matrix for current forum resource
                if (!mNoRolesAvailable)
                {
                    // Security - Role separator
                    newRow       = new TableRow();
                    newCell      = new TableCell();
                    newCell.Text = "&nbsp;";
                    newCell.Attributes.Add("colspan", Convert.ToString(tblMatrix.Rows[0].Cells.Count));
                    newRow.Controls.Add(newCell);
                    tblMatrix.Rows.Add(newRow);

                    // Security - Role separator text
                    newRow           = new TableRow();
                    newCell          = new TableCell();
                    newCell.CssClass = "MatrixLabel";
                    newCell.Text     = GetString("SecurityMatrix.RolesAvailability");
                    newCell.Attributes.Add("colspan", Convert.ToString(tblMatrix.Rows[0].Cells.Count));
                    newRow.Controls.Add(newCell);
                    tblMatrix.Rows.Add(newRow);
                }
            }
        }
    }
コード例 #15
0
    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 AND ISNULL(KeyIsHidden, 0) = 0";
                if (SiteID > 0)
                {
                    where += " AND KeyIsGlobal = 0";
                }
                where += ")))";
                provider.WhereCondition = SqlHelper.AddWhereCondition(provider.WhereCondition, where);
            }
            provider.Columns = "CategoryID, CategoryName, CategoryDisplayName, CategoryLevel, CategoryOrder, CategoryParentID, CategoryIDPath, CategoryIconPath, CategoryResourceID, " + levelColumn;

            if (String.IsNullOrEmpty(JavaScriptHandler))
            {
                Tree.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS## ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME##');\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
                Tree.NodeTemplate         = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS##\" onclick=\"SelectNode('##NODECODENAME##');\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
            }
            else
            {
                Tree.SelectedNodeTemplate = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS## ContentTreeSelectedItem\" onclick=\"SelectNode('##NODECODENAME##'); if (" + JavaScriptHandler + ") { " + JavaScriptHandler + "('##NODECODENAME##',##NODEID##, ##SITEID##, ##PARENTID##, ##RESOURCEID##); }\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
                Tree.NodeTemplate         = "<span id=\"node_##NODECODENAME##\" name=\"treeNode\" class=\"ContentTreeItem ##NAMECSSCLASS##\" onclick=\"SelectNode('##NODECODENAME##'); if (" + JavaScriptHandler + ") { " + JavaScriptHandler + "('##NODECODENAME##',##NODEID##, ##SITEID##, ##PARENTID##, ##RESOURCEID##); }\">##ICON##<span class=\"Name\">##NODECUSTOMNAME##</span></span>";
            }

            Tree.UsePostBack    = false;
            Tree.ProviderObject = provider;
            Tree.ExpandPath     = RootCategory.CategoryIDPath;

            Tree.OnNodeCreated += Tree_OnNodeCreated;
        }

        GetExpandedPaths();

        NewItemButton.ToolTip      = GetString("settings.newelem");
        DeleteItemButton.ToolTip   = GetString("settings.deleteelem");
        MoveUpItemButton.ToolTip   = GetString("settings.modeupelem");
        MoveDownItemButton.ToolTip = GetString("settings.modedownelem");

        // Create new element javascript
        NewItemButton.OnClientClick = "return newItem();";

        // Confirm delete
        DeleteItemButton.OnClientClick = "if(!deleteConfirm()) { return false; }";

        var isPostback = RequestHelper.IsPostBack();

        if (!isPostback)
        {
            Tree.ReloadData();

            if (QueryHelper.GetBoolean("reloadtreeselect", false))
            {
                var category = 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()));
        }
    }
コード例 #16
0
    /// <summary>
    /// Handles btnOK's OnClick event - Update resource info.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // finds whether required fields are not empty
        string result = new Validator().NotEmpty(tbModuleDisplayName.Text.Trim(), GetString("Administration-Module_New.ErrorEmptyModuleDisplayName")).NotEmpty(tbModuleCodeName.Text, GetString("Administration-Module_New.ErrorEmptyModuleCodeName"))
                        .IsCodeName(tbModuleCodeName.Text, GetString("general.invalidcodename"))
                        .Result;

        if (this.chkShowInDevelopment.Checked && String.IsNullOrEmpty(this.txtResourceUrl.Text.Trim()))
        {
            result = GetString("module_edit.emptyurl");
        }

        if (result == "")
        {
            // Check unique name
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(tbModuleCodeName.Text);
            if ((ri == null) || (ri.ResourceId == moduleId))
            {
                // Get object
                if (ri == null)
                {
                    ri = ResourceInfoProvider.GetResourceInfo(moduleId);
                    if (ri == null)
                    {
                        ri = new ResourceInfo();
                    }
                }

                //Update resource info
                ri.ResourceId          = moduleId;
                ri.ResourceName        = tbModuleCodeName.Text;
                ri.ResourceDescription = txtModuleDescription.Text.Trim();
                ri.ResourceDisplayName = tbModuleDisplayName.Text.Trim();

                ri.ShowInDevelopment = chkShowInDevelopment.Checked;
                ri.ResourceUrl       = (ri.ShowInDevelopment ? txtResourceUrl.Text : "");
                pnlResourceUrl.Style.Add("display", (ri.ShowInDevelopment ? "block" : "none"));

                ResourceInfoProvider.SetResourceInfo(ri);

                // Update root UIElementInfo of the module
                UIElementInfo elemInfo = UIElementInfoProvider.GetRootUIElementInfo(ri.ResourceId);
                if (elemInfo == null)
                {
                    elemInfo = new UIElementInfo();
                }
                elemInfo.ElementResourceID  = ri.ResourceId;
                elemInfo.ElementDisplayName = ri.ResourceDisplayName;
                elemInfo.ElementName        = ri.ResourceName.ToLower().Replace(".", "");
                elemInfo.ElementIsCustom    = false;
                UIElementInfoProvider.SetUIElementInfo(elemInfo);

                lblInfo.Visible = true;
                lblInfo.Text    = GetString("General.ChangesSaved");
            }
            else
            {
                lblInfo.Visible  = false;
                lblError.Visible = true;
                lblError.Text    = GetString("Administration-Module_New.UniqueCodeName");
            }
        }
        else
        {
            lblInfo.Visible  = false;
            lblError.Visible = true;
            lblError.Text    = result;
        }
    }
    private void btnSelectClick(object sender, EventArgs e)
    {
        Hashtable selectedParameters = SessionHelper.GetValue("DialogSelectedParameters") as Hashtable;
        string    filePath           = null;

        if (selectedParameters != null)
        {
            filePath = ValidationHelper.GetString(selectedParameters[DialogParameters.ITEM_PATH], null);
        }

        if (filePath == null)
        {
            page.ShowError(ResHelper.GetString("cms.resourcelibrary.noselectionerror"), null, null, false);

            return;
        }

        ResourceLibraryInfo libraryInfo = new ResourceLibraryInfo
        {
            ResourceLibraryPath       = filePath,
            ResourceLibraryResourceID = QueryHelper.GetInteger("resourceid", -1),
        };

        // Check if resource has the library already referenced
        if (!ResourceLibraryInfoProvider.ValidateLibraryUniqueness(libraryInfo.ResourceLibraryResourceID, libraryInfo.ResourceLibraryPath))
        {
            page.ShowError(ResHelper.GetString("cms.resourcelibrary.collision"), null, null, false);

            return;
        }
        else if (ResourceLibraryInfoProvider.IsImplicitlyIncludedLibrary(libraryInfo, ResourceInfoProvider.GetResourceInfo(libraryInfo.ResourceLibraryResourceID)))
        {
            page.ShowError(ResHelper.GetString("cms.resourcelibrary.implicitlyincludedlibrary"), null, null, false);

            return;
        }
        else
        {
            ResourceLibraryInfoProvider.SetResourceLibraryInfo(libraryInfo);
        }

        SessionHelper.Remove("DialogSelectedParameters");
        ScriptHelper.RegisterStartupScript(page, typeof(string), "Close dialog", ScriptHelper.GetScript("CloseDialog(true);"));
    }
コード例 #18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Unigrid
        gridElem.HideControlForZeroRows = false;
        gridElem.OrderBy              = "KeyOrder";
        gridElem.OnAction            += KeyAction;
        gridElem.OnExternalDataBound += gridElem_OnExternalDataBound;
        gridElem.ZeroRowsText         = GetString("settings.group.nokeysfound");

        if (Category != null)
        {
            string catIdStr = Category.CategoryID.ToString();

            // Action buttons
            var rightPanel = cpCategory.RightPanel;

            // Edit action
            var editButton = new CMSAccessibleButton
            {
                ToolTip      = GetString("general.edit"),
                IconCssClass = "icon-edit",
                IconOnly     = true
            };

            editButton.Click += (eventSender, args) => CategoryActionPerformed(eventSender, new CommandEventArgs("edit", catIdStr));
            rightPanel.Controls.Add(editButton);

            if (AllowEdit)
            {
                // Delete action
                var deleteButton = new CMSAccessibleButton
                {
                    ToolTip       = GetString("general.delete"),
                    IconCssClass  = "icon-bin",
                    IconOnly      = true,
                    OnClientClick = string.Format("if (!confirm({0})) {{ return false; }}", ScriptHelper.GetString(GetString("Development.CustomSettings.GroupDeleteConfirmation")))
                };

                deleteButton.Click += (eventSender, args) => CategoryActionPerformed(eventSender, new CommandEventArgs("delete", catIdStr));
                rightPanel.Controls.Add(deleteButton);

                // Move up action
                var moveUpButton = new CMSAccessibleButton
                {
                    ToolTip      = GetString("general.moveup"),
                    IconCssClass = "icon-chevron-up",
                    IconOnly     = true
                };

                moveUpButton.Click += (eventSender, args) => CategoryActionPerformed(eventSender, new CommandEventArgs("moveup", catIdStr));
                rightPanel.Controls.Add(moveUpButton);

                // Move down action
                var moveDownButton = new CMSAccessibleButton
                {
                    ToolTip      = GetString("general.movedown"),
                    IconCssClass = "icon-chevron-down",
                    IconOnly     = true
                };

                moveDownButton.Click += (eventSender, args) => CategoryActionPerformed(eventSender, new CommandEventArgs("movedown", catIdStr));
                rightPanel.Controls.Add(moveDownButton);

                // Setup "Add key" button
                btnNewKey.Text   = ResHelper.GetString("Development.CustomSettings.NewKey");
                btnNewKey.Click += CreateNewKey;

                cprModuleInfoRow.Visible = false;
                cprRow01.Visible         = true;
            }
            else
            {
                ResourceInfo currentModule  = ResourceInfoProvider.GetResourceInfo(ModuleID);
                ResourceInfo categoryModule = ResourceInfoProvider.GetResourceInfo(Category.CategoryResourceID);

                // Show warning if current module is in development mode, if not global warning is shown on the top of page
                if ((categoryModule != null) && (currentModule != null) && currentModule.ResourceIsInDevelopment)
                {
                    lblAnotherModule.Text    = HTMLHelper.HTMLEncode(String.Format(GetString("settingscategory.disablededitting"), categoryModule.ResourceDisplayName));
                    cprModuleInfoRow.Visible = true;
                }
                else
                {
                    cprModuleInfoRow.Visible = false;
                }

                cprRow01.Visible = false;
            }

            gridElem.ShowObjectMenu = AllowEdit;

            // Panel title for group
            cpCategory.Text = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(Category.CategoryDisplayName));

            // Filter out only records for this group
            gridElem.WhereCondition = "KeyCategoryID = " + Category.CategoryID;
        }

        // Apply site filter if required.
        if (!string.IsNullOrEmpty(gridElem.WhereCondition))
        {
            gridElem.WhereCondition += " AND ";
        }

        gridElem.WhereCondition += "SiteID IS NULL";
    }
コード例 #19
0
    /// <summary>
    /// Generates the permission matrix for the current forum.
    /// </summary>
    private void CreateMatrix()
    {
        // Get forum resource info
        if (resForums == null)
        {
            resForums = ResourceInfoProvider.GetResourceInfo("CMS.Forums");
        }

        // Get forum object
        if ((forum == null) && (ForumID > 0))
        {
            forum = ForumInfoProvider.GetForumInfo(ForumID);
        }

        if ((resForums != null) && (forum != null))
        {
            // Get permissions for the current forum resource
            DataSet permissions = PermissionNameInfoProvider.GetResourcePermissions(resForums.ResourceID);
            if (DataHelper.DataSourceIsEmpty(permissions))
            {
                ShowInformation(GetString("general.emptymatrix"));
            }
            else
            {
                TableHeaderRow headerRow = new TableHeaderRow();
                headerRow.CssClass     = "unigrid-head";
                headerRow.TableSection = TableRowSection.TableHeader;
                TableCell       newCell       = new TableCell();
                TableHeaderCell newHeaderCell = new TableHeaderCell();
                newHeaderCell.CssClass = "first-column";
                headerRow.Cells.Add(newHeaderCell);

                foreach (string permission in allowedPermissions)
                {
                    DataRow[] drArray = permissions.Tables[0].DefaultView.Table.Select("PermissionName = '" + permission + "'");
                    if (drArray.Length > 0)
                    {
                        DataRow dr = drArray[0];
                        newHeaderCell         = new TableHeaderCell();
                        newHeaderCell.Text    = dr["PermissionDisplayName"].ToString();
                        newHeaderCell.ToolTip = dr["PermissionDescription"].ToString();
                        headerRow.Cells.Add(newHeaderCell);
                    }
                    else
                    {
                        throw new Exception("[Security matrix] Column '" + permission + "' cannot be found.");
                    }
                }

                tblMatrix.Rows.Add(headerRow);

                // Render forum access permissions
                object[,] accessNames = new object[5, 2];
                accessNames[0, 0]     = GetString("security.nobody");
                accessNames[0, 1]     = SecurityAccessEnum.Nobody;
                accessNames[1, 0]     = GetString("security.allusers");
                accessNames[1, 1]     = SecurityAccessEnum.AllUsers;
                accessNames[2, 0]     = GetString("security.authenticated");
                accessNames[2, 1]     = SecurityAccessEnum.AuthenticatedUsers;
                accessNames[3, 0]     = GetString("security.groupmembers");
                accessNames[3, 1]     = SecurityAccessEnum.GroupMembers;
                accessNames[4, 0]     = GetString("security.authorizedroles");
                accessNames[4, 1]     = SecurityAccessEnum.AuthorizedRoles;

                TableRow newRow = null;
                for (int access = 0; access <= accessNames.GetUpperBound(0); access++)
                {
                    SecurityAccessEnum currentAccess = ((SecurityAccessEnum)accessNames[access, 1]);

                    // If the security isn't displayed as part of group section
                    if ((currentAccess == SecurityAccessEnum.GroupMembers) && (!IsGroupForum))
                    {
                        // Do not render this access item
                    }
                    else
                    {
                        // Generate cell holding access item name
                        newRow           = new TableRow();
                        newCell          = new TableCell();
                        newCell.Text     = accessNames[access, 0].ToString();
                        newCell.CssClass = "matrix-header";
                        newRow.Cells.Add(newCell);

                        // Render the permissions access items
                        bool isAllowed       = false;
                        bool isEnabled       = true;
                        int  permissionIndex = 0;
                        for (int permission = 0; permission < (tblMatrix.Rows[0].Cells.Count - 1); permission++)
                        {
                            newCell = new TableCell();

                            // Check if the currently processed access is applied for permission
                            isAllowed = CheckPermissionAccess(currentAccess, permission, tblMatrix.Rows[0].Cells[permission + 1].Text);
                            isEnabled = ((currentAccess != SecurityAccessEnum.AllUsers) || (permission != 1)) && Enable;

                            // Disable column in roles grid if needed
                            if ((currentAccess == SecurityAccessEnum.AuthorizedRoles) && !isAllowed)
                            {
                                gridMatrix.DisableColumn(permissionIndex);
                            }

                            // Insert the radio button for the current permission
                            var radio = new CMSRadioButton
                            {
                                Checked = isAllowed,
                                Enabled = isEnabled,
                            };
                            radio.Attributes.Add("onclick", ControlsHelper.GetPostBackEventReference(this, permission + ";" + Convert.ToInt32(currentAccess)));
                            newCell.Controls.Add(radio);

                            newRow.Cells.Add(newCell);
                            permissionIndex++;
                        }

                        // Add the access row to the table
                        tblMatrix.Rows.Add(newRow);
                    }
                }

                // Check if forum has some roles assigned
                headTitle.Visible = gridMatrix.HasData;
            }
        }
    }
コード例 #20
0
    protected TreeNode treeElem_OnNodeCreated(DataRow itemData, TreeNode defaultNode)
    {
        // Get data
        if (itemData != null)
        {
            int    id          = ValidationHelper.GetInteger(itemData["ElementID"], 0);
            int    childCount  = ValidationHelper.GetInteger(itemData["ElementChildCount"], 0);
            bool   selected    = ValidationHelper.GetBoolean(itemData["ElementSelected"], false);
            string displayName = HTMLHelper.HTMLEncode(ResHelper.LocalizeString(ValidationHelper.GetString(itemData["ElementDisplayName"], "")));
            string elementName = ValidationHelper.GetString(itemData["ElementName"], "").ToLowerCSafe();
            string iconUrl     = ValidationHelper.GetString(itemData["ElementIconPath"], "");

            string onClickDeclaration = " var chkElem_" + id + " = document.getElementById('chk_" + id + "'); ";
            string onClickCommon      = "  hdnValue.value = " + id + " + ';' + chkElem_" + id + ".checked; " + CallbackRef;
            string onClickSpan        = " chkElem_" + id + ".checked = !chkElem_" + id + ".checked; ";

            string nodeText = "";
            if (!String.IsNullOrEmpty(GroupPreffix) && elementName.ToLowerCSafe().StartsWithCSafe(GroupPreffix.ToLowerCSafe()))
            {
                nodeText = "<span>" + displayName + "</span>" +
                           (childCount > 0 ? "&nbsp;<span class=\"UITreeSelectButton\">(<span onclick=\"" + (Enabled ? "SelectAllSubelements($j(this), " + id + ", false);" + CallbackRef + ";" : "return false;") + "\" >" + GetString("uiprofile.selectall") + "</span>,&nbsp;<span onclick=\"" + (Enabled ? "DeselectAllSubelements($j(this), " + id + ", false);" + CallbackRef + ";" : "return false;") + "\" >" + GetString("uiprofile.deselectall") + "</span>)</span>" : "");
            }
            else
            {
                string warning = "";

                if (SiteName != null)
                {
                    if ((ResourceInfoProvider.GetResourceInfo("cms." + elementName) != null) &&
                        !ResourceSiteInfoProvider.IsResourceOnSite("cms." + elementName, SiteName))
                    {
                        warning = "<img style=\"width: 12px; height: 12px; border:none; cursor:help;\" alt=\"warning\" title=\"" + String.Format(GetString("uiprofile.warningmodule"), "cms." + elementName) + "\" src=\"" + GetImageUrl("/Design/Controls/UniGrid/Actions/Warning.png") + "\" />";
                    }
                }

                string icon = "";
                if (!String.IsNullOrEmpty(iconUrl))
                {
                    try
                    {
                        if (ValidationHelper.IsURL(iconUrl) || FileHelper.FileExists(GetImageUrl(iconUrl)))
                        {
                            icon = "<img class=\"Image16\" style=\"border:none;\" alt=\"" + HTMLHelper.HTMLEncode(displayName) + "\" src=\"" + GetImageUrl(iconUrl) + "\" />&nbsp;";
                        }
                        else
                        {
                            icon = "<img class=\"Image16\" style=\"border:none;\" alt=\"" + HTMLHelper.HTMLEncode(displayName) + "\" src=\"" + GetImageUrl("/CMSModules/list.png") + "\" />&nbsp;";
                        }
                    }
                    catch (Exception)
                    {
                    }
                }

                nodeText = "<input type=\"checkbox\" id=\"chk_" + id + "\" name=\"chk_" + id + "\" " + (Enabled ? "" : "disabled=\"disabled\" ") + (selected ? "checked=\"checked\"" : "") + " onclick=\"" + (Enabled ? onClickDeclaration + onClickCommon : "return false;") + "\" />" +
                           "<span onclick=\"" + (Enabled ? onClickDeclaration + onClickSpan + onClickCommon : "return false;") + "\" >" + icon + displayName + "</span>" + warning +
                           (childCount > 0 ? "&nbsp;<span class=\"UITreeSelectButton\">(<span onclick=\"" + (Enabled ? "SelectAllSubelements($j(this), " + id + ", true); " + CallbackRef + ";" : "return false;") + "\" >" + GetString("uiprofile.selectall") + "</span>,&nbsp;<span onclick=\"" + (Enabled ? " DeselectAllSubelements($j(this), " + id + ", true);" + CallbackRef + ";" : "return false;") + "\" >" + GetString("uiprofile.deselectall") + "</span>)</span>" : "");
            }

            defaultNode.ToolTip = "";
            defaultNode.Text    = nodeText;
        }

        return(defaultNode);
    }
コード例 #21
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Initialize header actions
        string[,] actions = new string[2, 7];

        actionsElem.ActionsList.Add(new HeaderAction
        {
            ControlType = HeaderActionTypeEnum.LinkButton,
            Text        = GetString("uiprofile.expandall"),
            Tooltip     = GetString("uiprofile.expandall"),
            ImageUrl    = GetImageUrl("Objects/CMS_UIElement/expandall.png"),
            CommandName = "expandall"
        });

        actionsElem.ActionsList.Add(new HeaderAction
        {
            ControlType = HeaderActionTypeEnum.LinkButton,
            Text        = GetString("uiprofile.collapseall"),
            Tooltip     = GetString("uiprofile.collapseall"),
            ImageUrl    = GetImageUrl("Objects/CMS_UIElement/collapseall.png"),
            CommandName = "collapseall"
        });

        actionsElem.ActionPerformed += new CommandEventHandler(actionsElem_ActionPerformed);

        // Hide checkboxes with "group." prefix for WYSIWYG Editor
        treeElem.GroupPreffix = "group.";

        // Initialize selectors
        if (ResourceID > 0)
        {
            plcModule.Visible           = false;
            selectModule.StopProcessing = true;
        }
        else
        {
            selectModule.UniSelector.OnSelectionChanged   += new EventHandler(selectModule_OnSelectionChanged);
            selectModule.DropDownSingleSelect.AutoPostBack = true;
            lblModule.AssociatedControlClientID            = selectModule.DropDownSingleSelect.ClientID;
            if (!URLHelper.IsPostback())
            {
                // Module preselection from query string
                string selectedModule = QueryHelper.GetString("module", null);
                if (!String.IsNullOrEmpty(selectedModule))
                {
                    ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(selectedModule);
                    if (ri != null)
                    {
                        selectModule.Value = ri.ResourceId;
                    }
                }
            }
        }

        selectRole.CurrentSelector.SelectionMode       = SelectionModeEnum.SingleDropDownList;
        selectRole.DropDownSingleSelect.AutoPostBack   = true;
        selectRole.CurrentSelector.OnSelectionChanged += new EventHandler(selectRole_OnSelectionChanged);
        lblRole.AssociatedControlClientID              = selectRole.DropDownSingleSelect.ClientID;

        if (HideSiteSelector)
        {
            plcSite.Visible = false;
        }
        else
        {
            selectSite.AllowGlobal = true;
            selectSite.DropDownSingleSelect.AutoPostBack = true;
            selectSite.UniSelector.OnSelectionChanged   += new EventHandler(selectSite_OnSelectionChanged);
            selectSite.IsLiveSite             = IsLiveSite;
            lblSite.AssociatedControlClientID = selectSite.DropDownSingleSelect.ClientID;
        }

        if (!URLHelper.IsPostback())
        {
            // Site selector in direct UI personalization
            if (SiteID <= 0)
            {
                selectSite.SiteID = ValidationHelper.GetInteger(selectSite.GlobalRecordValue, 0);
                globalRoles       = true;
            }
            else
            {
                selectSite.SiteID = CurrentSiteID;
            }

            ReloadRoles();
            if (ResourceID <= 0)
            {
                ReloadModules();
            }
        }

        globalRoles = (ValidationHelper.GetString(selectSite.Value, "") == selectSite.GlobalRecordValue);

        if (RoleID > 0)
        {
            plcRole.Visible = false;
        }
        else
        {
            selectRole.SiteID = CurrentSiteID;
        }

        if (RoleID > 0 && ((SiteID > 0) || HideSiteSelector) && ResourceID > 0)
        {
            pnlActions.Visible = false;
        }

        selectModule.SiteID = CurrentSiteID;

        // Check manage permission
        if (!CMSContext.CurrentUser.IsAuthorizedPerResource("CMS.UIPersonalization", CMSAdminControl.PERMISSION_MODIFY))
        {
            treeElem.Enabled = false;
            lblInfo.Text     = String.Format(GetString("CMSSiteManager.AccessDeniedOnPermissionName"), CMSAdminControl.PERMISSION_MODIFY);
            lblInfo.Visible  = true;
        }

        ReloadTree();
        ucDisabledModule.InfoText = GetString("uiprofile.disabled");
    }
コード例 #22
0
    /// <summary>
    /// Generates the permission matrix for the cutrrent group.
    /// </summary>
    private void CreateMatrix()
    {
        // Get group resource info
        if (resGroups == null)
        {
            resGroups = ResourceInfoProvider.GetResourceInfo("CMS.Groups");
        }

        if (resGroups != null)
        {
            group = GroupInfoProvider.GetGroupInfo(this.GroupID);

            // Get permissions for the current group resource
            DataSet permissions = PermissionNameInfoProvider.GetResourcePermissions(resGroups.ResourceId);
            if (DataHelper.DataSourceIsEmpty(permissions))
            {
                lblInfo.Text = GetString("general.emptymatrix");
            }
            else
            {
                TableRow headerRow = new TableRow();
                headerRow.CssClass = "UniGridHead";
                TableCell       newCell       = new TableCell();
                TableHeaderCell newHeaderCell = new TableHeaderCell();

                newHeaderCell.Text                = "&nbsp;";
                newHeaderCell.CssClass            = "MatrixHeader";
                newHeaderCell.Attributes["style"] = "width:30%;";
                headerRow.Cells.Add(newHeaderCell);

                foreach (string permission in allowedPermissions)
                {
                    DataRow[] drArray = permissions.Tables[0].DefaultView.Table.Select("PermissionName = '" + permission + "'");
                    if ((drArray != null) && (drArray.Length > 0))
                    {
                        DataRow dr = drArray[0];
                        newHeaderCell                     = new TableHeaderCell();
                        newHeaderCell.CssClass            = "MatrixHeader";
                        newHeaderCell.Attributes["style"] = "width:18%;text-align:center;white-space:nowrap;";
                        newHeaderCell.Text                = dr["PermissionDisplayName"].ToString();
                        newHeaderCell.ToolTip             = dr["PermissionDescription"].ToString();
                        newHeaderCell.HorizontalAlign     = HorizontalAlign.Center;

                        headerRow.Cells.Add(newHeaderCell);
                    }
                    else
                    {
                        throw new Exception("[Security matrix] Column '" + permission + "' cannot be found.");
                    }
                }
                // Insert the empty cell at the end
                newHeaderCell      = new TableHeaderCell();
                newHeaderCell.Text = "&nbsp;";
                headerRow.Cells.Add(newHeaderCell);
                tblMatrix.Rows.Add(headerRow);

                // Render group access permissions
                object[,] accessNames = new object[5, 2];
                accessNames[0, 0]     = GetString("security.nobody");
                accessNames[0, 1]     = SecurityAccessEnum.Nobody;
                accessNames[1, 0]     = GetString("security.allusers");
                accessNames[1, 1]     = SecurityAccessEnum.AllUsers;
                accessNames[2, 0]     = GetString("security.authenticated");
                accessNames[2, 1]     = SecurityAccessEnum.AuthenticatedUsers;
                accessNames[3, 0]     = GetString("security.groupmembers");
                accessNames[3, 1]     = SecurityAccessEnum.GroupMembers;
                accessNames[4, 0]     = GetString("security.authorizedroles");
                accessNames[4, 1]     = SecurityAccessEnum.AuthorizedRoles;

                TableRow newRow   = null;
                int      rowIndex = 0;

                for (int access = 0; access <= accessNames.GetUpperBound(0); access++)
                {
                    SecurityAccessEnum currentAccess = ((SecurityAccessEnum)accessNames[access, 1]);

                    // Generate cell holding access item name
                    newRow           = new TableRow();
                    newRow.CssClass  = ((rowIndex % 2 == 0) ? "EvenRow" : "OddRow");
                    newCell          = new TableCell();
                    newCell.CssClass = "MatrixHeader";
                    newCell.Text     = accessNames[access, 0].ToString();
                    newCell.Wrap     = false;
                    newRow.Cells.Add(newCell);
                    rowIndex++;

                    // Render the permissions access items
                    bool isAllowed       = false;
                    int  permissionIndex = 0;
                    for (int permission = 0; permission < (tblMatrix.Rows[0].Cells.Count - 2); permission++)
                    {
                        newCell                 = new TableCell();
                        newCell.CssClass        = "MatrixCell";
                        newCell.HorizontalAlign = HorizontalAlign.Center;

                        // Check if the currently processed access is applied for permission
                        isAllowed = CheckPermissionAccess(currentAccess, permission, tblMatrix.Rows[0].Cells[permission + 1].Text);

                        // Disable column in roles grid if needed
                        if ((currentAccess == SecurityAccessEnum.AuthorizedRoles) && !isAllowed)
                        {
                            gridMatrix.DisableColumn(permissionIndex);
                        }

                        // Insert the radio button for the current permission
                        string permissionText = tblMatrix.Rows[0].Cells[permission + 1].Text;
                        string elemId         = ClientID + "_" + permission + "_" + access;
                        string disabled       = null;
                        if (!this.Enabled)
                        {
                            disabled = "disabled=\"disabled\"";
                        }
                        newCell.Text = "<label style=\"display:none;\" for=\"" + elemId + "\">" + permissionText + "</label><input type=\"radio\" id=\"" + elemId + "\" name=\"" + permissionText + "\" " + disabled + " onclick=\"" +
                                       ControlsHelper.GetPostBackEventReference(this, permission.ToString() + ";" + Convert.ToInt32(currentAccess).ToString()) + "\" " +
                                       ((isAllowed) ? "checked = \"checked\"" : "") + "/>";

                        newCell.Wrap = false;
                        newRow.Cells.Add(newCell);
                        permissionIndex++;
                    }

                    newCell      = new TableCell();
                    newCell.Text = "&nbsp;";
                    newRow.Cells.Add(newCell);
                    // Add the access row to the table
                    tblMatrix.Rows.Add(newRow);
                }

                // Get permission matrix for current group resource
                bool rowIsSeparator = false;

                // Get permission matrix for the current group resource
                this.mNoRolesAvailable = !gridMatrix.HasData;

                if (!this.mNoRolesAvailable)
                {
                    // Security - Role separator
                    newRow       = new TableRow();
                    newCell      = new TableCell();
                    newCell.Text = "&nbsp;";
                    newCell.Attributes.Add("colspan", Convert.ToString(tblMatrix.Rows[0].Cells.Count));
                    newRow.Controls.Add(newCell);
                    tblMatrix.Rows.Add(newRow);

                    // Security - Role separator text
                    newRow           = new TableRow();
                    newCell          = new TableCell();
                    newCell.CssClass = "MatrixLabel";
                    newCell.Text     = GetString("SecurityMatrix.RolesAvailability");
                    newCell.Attributes.Add("colspan", Convert.ToString(tblMatrix.Rows[0].Cells.Count - 1));
                    newRow.Controls.Add(newCell);
                    tblMatrix.Rows.Add(newRow);
                }

                // Add the latest row if present
                if (newRow != null)
                {
                    // The row is only role row and at the same time is divider between accesses section and roles section - make border higher
                    if (rowIsSeparator)
                    {
                        rowIsSeparator = false;
                    }
                    if (!mNoRolesAvailable)
                    {
                        newRow.Cells.Add(new TableCell());
                        tblMatrix.Rows.Add(newRow);
                    }
                }
            }
        }
    }
コード例 #23
0
    /// <summary>
    /// Handles btnOK's OnClick event - Update or save permission info.
    /// </summary>
    protected void btnOK_Click(object sender, EventArgs e)
    {
        // Finds whether required fields are not empty
        string result = new Validator().NotEmpty(tbPermissionDisplayName.Text.Trim(), GetString("Administration-Module_Edit_PermissionName_Edit.ErrorEmptyPermissionDisplayName")).NotEmpty(tbPermissionCodeName.Text.Trim(), GetString("Administration-Module_Edit_PermissionName_Edit.ErrorEmptyPermissionCodeName"))
                        .IsCodeName(tbPermissionCodeName.Text.Trim(), GetString("general.invalidcodename")).Result;

        if (result == "")
        {
            int resourceId = QueryHelper.GetInteger("moduleid", 0);
            if ((resourceId <= 0) && (mCurrentPermission != null))
            {
                resourceId = mCurrentPermission.ResourceId;
            }

            string resourceName = "";

            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(resourceId);
            if (ri != null)
            {
                resourceName = ri.ResourceName;
            }

            PermissionNameInfo pni = PermissionNameInfoProvider.GetPermissionNameInfo(tbPermissionCodeName.Text.Trim(), resourceName, null);

            if ((pni == null) || (pni.PermissionId == mPermissionId))
            {
                if (pni == null)
                {
                    pni = PermissionNameInfoProvider.GetPermissionNameInfo(mPermissionId);
                    if (pni == null)
                    {
                        pni = new PermissionNameInfo();
                    }
                }

                pni.PermissionName            = tbPermissionCodeName.Text.Trim();
                pni.PermissionDisplayName     = tbPermissionDisplayName.Text.Trim();
                pni.PermissionDescription     = txtPermissionDescription.Text.Trim();
                pni.PermissionDisplayInMatrix = chkPermissionDisplayInMatrix.Checked;
                pni.ClassId    = 0;
                pni.ResourceId = resourceId;
                pni.PermissionEditableByGlobalAdmin = chkGlobalAdmin.Checked;

                if (pni.PermissionOrder == 0)
                {
                    pni.PermissionOrder = PermissionNameInfoProvider.GetLastPermissionOrder(0, resourceId) + 1;
                }

                // Update or save permission info
                PermissionNameInfoProvider.SetPermissionInfo(pni);

                // Redirect to edit page if editing existing permission
                if (mPermissionId > 0)
                {
                    URLHelper.Redirect("Module_Edit_PermissionName_Edit.aspx?moduleID=" + pni.ResourceId + "&permissionID=" + pni.PermissionId + "&saved=1&hidebreadcrumbs=" + (mHideBreadcrumbs ? "1" : "0"));
                }
                // Redirect to whole frameset if creating new
                else
                {
                    URLHelper.Redirect(string.Format(@"Module_Edit_PermissionName_Edit_Frameset.aspx?moduleId={0}&permissionId={1}&saved=1", pni.ResourceId, pni.PermissionId));
                }
            }
            else
            {
                // Show error message
                ShowError(GetString("Administration-Module_Edit_PermissionName_Edit.UniqueCodeName"));
            }
        }
        else
        {
            // Show error message
            ShowError(result);
        }
    }
コード例 #24
0
    protected void Page_Load(object sender, EventArgs e)
    {
        bool displayNone = false;
        bool currentIsCustomizedOfInstalled = false;

        if ((UIContext.EditedObject != null) && ((UIElementInfo)UIContext.EditedObject).ElementID > 0)
        {
            elemInfo = (UIElementInfo)UIContext.EditedObject;
            ParentID = elemInfo.ElementParentID;

            EditForm.FieldControls["ElementPageTemplateID"].SetValue("ItemGuid", elemInfo.ElementGUID);
            EditForm.FieldControls["ElementPageTemplateID"].SetValue("ItemName", elemInfo.ElementDisplayName);

            // Exclude current element and children from dropdown list
            EditForm.FieldControls["ElementParentID"].SetValue("WhereCondition", "ElementIDPath NOT LIKE N'" + elemInfo.ElementIDPath + "%'");

            // Enable editing only for current module. Disable for root
            EditForm.Enabled = ((!UIElementInfoProvider.AllowEditOnlyCurrentModule || (ResourceID == elemInfo.ElementResourceID) && elemInfo.ElementIsCustom) &&
                                (elemInfo.ElementParentID != 0));

            // Allow global application checkbox only for applications
            if (!elemInfo.IsApplication && !elemInfo.ElementIsGlobalApplication)
            {
                EditForm.FieldsToHide.Add("ElementIsGlobalApplication");
            }

            // Show info for customized elements
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(elemInfo.ElementResourceID);
            if (ri != null)
            {
                if (elemInfo.ElementIsCustom && !ri.ResourceIsInDevelopment)
                {
                    currentIsCustomizedOfInstalled = true;
                    ShowInformation(GetString("module.customeleminfo"));
                }
            }
        }
        // New item
        else
        {
            isNew = true;
            if (!RequestHelper.IsPostBack())
            {
                EditForm.FieldControls["ElementFromVersion"].Value = CMSVersion.GetVersion(true, true, false, false);
            }

            // Predefine current resource if is in development
            ResourceInfo ri = CurrentResourceInfo;
            if ((ri != null) && ri.ResourceIsInDevelopment)
            {
                EditForm.FieldControls["ElementResourceID"].Value = ResourceID;
            }
            // Display none if is under not-development resource
            else
            {
                displayNone = true;
            }

            EditForm.FieldControls["ElementParentID"].Value = ParentID;
            EditForm.FieldsToHide.Add("ElementParentID");

            var parent = UIElementInfoProvider.GetUIElementInfo(ParentID);
            if ((parent == null) || (parent.ElementLevel != 2) || !parent.IsInAdministrationScope)
            {
                EditForm.FieldsToHide.Add("ElementIsGlobalApplication");
            }
        }

        if (!SystemContext.DevelopmentMode)
        {
            EditForm.FieldsToHide.Add("ElementFromVersion");
        }

        EditForm.OnAfterSave      += EditForm_OnAfterSave;
        EditForm.OnBeforeSave     += EditForm_OnBeforeSave;
        EditForm.OnItemValidation += EditForm_OnItemValidation;

        // Allow only modules in development mode
        FormEngineUserControl resourceCtrl = EditForm.FieldControls["ElementResourceID"];

        if (resourceCtrl != null)
        {
            resourceCtrl.SetValue("DisplayOnlyModulesInDevelopmentMode", true);
        }

        // Disable form and add customize button if element is not custom and not development mode
        if (!SystemContext.DevelopmentMode && (elemInfo != null) && (ResourceID == elemInfo.ElementResourceID) && !elemInfo.ElementIsCustom && (elemInfo.ElementParentID != 0))
        {
            ICMSMasterPage master = Page.Master as ICMSMasterPage;
            if (master != null)
            {
                master.HeaderActions.AddAction(new HeaderAction
                {
                    Text          = GetString("general.customize"),
                    CommandName   = "customize",
                    OnClientClick = "if (!confirm(" + ScriptHelper.GetString(ResHelper.GetString("module.customizeconfirm")) + ")) { return false; }"
                });

                master.HeaderActions.ActionPerformed += HeaderActions_ActionPerformed;
            }

            EditForm.Enabled = false;
        }

        if (resourceCtrl != null)
        {
            // Display all modules in disabled UI
            if (!EditForm.Enabled)
            {
                resourceCtrl.SetValue("DisplayOnlyModulesInDevelopmentMode", false);
            }
            // Display all modules in customized element but do not allow change the module
            else if (currentIsCustomizedOfInstalled)
            {
                resourceCtrl.SetValue("DisplayOnlyModulesInDevelopmentMode", false);
                resourceCtrl.Enabled = false;
            }

            // Display none if needed
            resourceCtrl.SetValue("DisplayNone", displayNone);
        }
    }
コード例 #25
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (StopProcessing)
        {
            return;
        }

        // Handle the pre-selection
        preselectedItem = QueryHelper.GetString(QueryParameterName, "");
        if (preselectedItem.StartsWithCSafe("cms.", true))
        {
            preselectedItem = preselectedItem.Substring(4);
        }

        uniMenu.HighlightItem = preselectedItem;

        // If element name is not set, use root module element
        string elemName = ElementName;
        if (String.IsNullOrEmpty(elemName))
        {
            elemName = ModuleName.Replace(".", "");
        }

        // Get the UI elements
        DataSet ds = UIElementInfoProvider.GetChildUIElements(ModuleName, elemName);
        if (!DataHelper.DataSourceIsEmpty(ds))
        {
            FilterElements(ds);

            // Prepare the list of elements
            foreach (DataRow dr in ds.Tables[0].Rows)
            {
                string url = ValidationHelper.GetString(dr["ElementTargetURL"], "");

                Group group = new Group();
                if (url.EndsWithCSafe("ascx"))
                {
                    group.ControlPath = url;
                }
                else
                {
                    group.UIElementID = ValidationHelper.GetInteger(dr["ElementID"], 0);
                }

                group.CssClass = "ContentMenuGroup";

                if (GenerateElementCssClass)
                {
                    string name = ValidationHelper.GetString(dr["ElementName"], String.Empty).Replace(".", String.Empty);
                    group.CssClass += " ContentMenuGroup" + name;
                    group.SeparatorCssClass = "UniMenuSeparator" + name;

                }

                group.Caption = ResHelper.LocalizeString(ValidationHelper.GetString(dr["ElementCaption"], ""));
                uniMenu.Groups.Add(group);
            }

            // Raise groups created event
            if (OnGroupsCreated != null)
            {
                OnGroupsCreated(this, uniMenu.Groups);
            }

            // Button created & filtered event handler
            if (OnButtonCreating != null)
            {
                uniMenu.OnButtonCreating += uniMenu_OnButtonCreating;
            }
            if (OnButtonCreated != null)
            {
                uniMenu.OnButtonCreated += uniMenu_OnButtonCreated;
            }
            if (OnButtonFiltered != null)
            {
                uniMenu.OnButtonFiltered += uniMenu_OnButtonFiltered;
            }
        }

        // Add editing icon in development mode
        if (SettingsKeyProvider.DevelopmentMode && CMSContext.CurrentUser.IsGlobalAdministrator && !DisableEditIcon)
        {
            ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(ModuleName);
            if (ri != null)
            {
                ltlAfter.Text += String.Format("<div class=\"UIElementsLink\" >{0}</div>", UIHelper.GetResourceUIElementsLink(Page, ri.ResourceId));
            }
        }
    }
コード例 #26
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Logging out of Facebook
        if (QueryHelper.GetInteger("logout", 0) > 0)
        {
            btnSignOut_Click(this, EventArgs.Empty);
        }
        btnSignOut.OnClientClick = FacebookConnectHelper.FacebookConnectInitForSignOut(CMSContext.CurrentSiteName, ltlScript);

        bool hideLinks = false;

        // Default message
        this.lblMessage.Text = GetString("CMSSiteManager.IsNotAdminMsg");

        CurrentMaster.Title.TitleText  = GetString("CMSSiteManager.AccessDenied");
        CurrentMaster.Title.TitleImage = GetImageUrl("Others/Messages/denied.png");

        // Resource access denied
        string resourceName = QueryHelper.GetString("resource", null);

        if (resourceName != null)
        {
            switch (resourceName.ToLower())
            {
            // Not enabled admin interface
            case "cms.adminui":
            {
                this.lblMessage.Text = GetString("CMSSiteManager.AdminUINotEnabled");
            }
            break;

            // Standard resource permission
            default:
            {
                ResourceInfo ri = ResourceInfoProvider.GetResourceInfo(resourceName);
                if (ri != null)
                {
                    CurrentMaster.Title.TitleText = String.Format(GetString("CMSSiteManager.AccessDeniedOnResource"), ri.ResourceDisplayName);
                }
            }
            break;
            }
        }

        // Access denied to document
        int nodeId = QueryHelper.GetInteger("nodeid", 0);

        if (nodeId > 0)
        {
            TreeProvider tree = new TreeProvider(CMSContext.CurrentUser);
            TreeNode     node = tree.SelectSingleNode(nodeId);
            if (node != null)
            {
                CurrentMaster.Title.TitleText = String.Format(GetString("CMSSiteManager.AccessDeniedOnNode"), HTMLHelper.HTMLEncode(node.DocumentName));
            }
        }

        // Custom message
        string message = QueryHelper.GetText("message", null);

        if (message != null)
        {
            this.lblMessage.Text = ResHelper.LocalizeString(message);
            hideLinks            = true;
        }

        // Add missing permission name message
        string permission = QueryHelper.GetText("permission", null);

        if (permission != null)
        {
            this.lblMessage.Text = String.Format(GetString("CMSSiteManager.AccessDeniedOnPermissionName"), permission);
            hideLinks            = true;
        }

        // Override displaying of links
        hideLinks = QueryHelper.GetBoolean("hidelinks", hideLinks);

        if (!hideLinks)
        {
            this.lnkGoBack.Text = GetString("CMSSiteManager.GoBack");

            // Hide for windows authentication
            if (RequestHelper.IsWindowsAuthentication())
            {
                btnSignOut.Visible = false;
            }
        }
        else
        {
            btnSignOut.Visible = false;
            lnkGoBack.Visible  = false;
        }
    }