Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

Modify Menu Items at run time asp.net

Posted on 2007-11-28
7
Medium Priority
?
3,242 Views
Last Modified: 2013-11-26
I have a Website that uses 2 different Master pages. Administrators get given the Admin.master and the Customer is given the cust.master. This is working correctly. I have then a different sitemap for each of the Master pages. I want to be able to either disable or remove menu items from the menu at runtime. Ie Customer X does not have access to the warehouse module so the Warehouse Menu Item is either disabled or removed completely.
Is there a way that I can do this? I thought I could use something like onDataBound event and check the Menu options against the security rights. I am not using Security trimming and have my own security table that controls access to certain modules.
Failing this I was thinking of perhaps setting the different sitemaps at runtime however I would then need to have a sitemap for each module.
Please hlep

Thanx
0
Comment
Question by:andyd70
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
7 Comments
 
LVL 7

Expert Comment

by:Infinite_Recursion
ID: 20364735
are you using the Database or XML to set the sitemap??
0
 
LVL 1

Author Comment

by:andyd70
ID: 20364757
Hi there. I am using an XML Sitemap file. I would dearly love to use a Database as the Sitemap but I have not had any luck in getting this working properly. The Menu Control does not allow me to use a normal dataset as the datasource only XML or Sitemap datasources.
If you have any information on how to use a database as the menu sitemap this would answer my question as well.

regards
0
 
LVL 7

Expert Comment

by:Infinite_Recursion
ID: 20364868
OK, I am using the Database as a DataSource, how I am doing that in my MasterPage is by binding to a datasource that inherits from ObjectDataSource and implements IHierarchicalDataSource. I did this because I needed an ObjectDataSource that can display hierarchical data, something that is a requirement of being a source to the menu control, since the menu is hierarchical.
Instead of creating your ObjectHierarchicalDataSource, you can simply create an SqlHierarchicalDataSource that looks like this
public class SqlHierarchicalDataSource : SqlDataSource, IHierarchicalDataSource
you should research creating a hierarchical datasource, that helps you bind to the database.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 1

Author Comment

by:andyd70
ID: 20364895
That does sound similar to what I need. I gather once using a Datasource you can use the Menu's onDatabound events to turn on or off menu items depending on requirements ??

Sorry to sound like a noob could you please give me a sample of the way you have done it or provide some good links to where I can read up some more on it ??

Thanx
0
 
LVL 7

Accepted Solution

by:
Infinite_Recursion earned 2000 total points
ID: 20364957
OK, it is not that your a noob, it is just that his is a bit advanced but here goes:
Following is a list of files that you must place in your project, I have them in a seperate project (class library) that generates a dll that I can Add Reference in my web project.
the following is my AssemblyInfo, ObjectHierarchicalEnumerable.cs, ObjectHierarichalDataSource.cs, ObjectHierarichalDataSourceView.cs, ObjectNode.cs, and ObjectNodePropertyDescriptor.cs files, they all need to be placed in the same project and compiled into a dll, the AssemblyInfo.cs file is created automatically in your new class library project, following is how to use them in your web project the method GetAllUserMenuItems returns a datatable, so that should work for you, here is the code:

//AssembyInfo.cs Start
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
 
// General Information about an assembly is controlled through the following 
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ObjectHierarchicalDataSourceCtrl")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ObjectHierarchicalDataSourceCtrl")]
[assembly: AssemblyCopyright("Copyright ©  2006")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
 
 
// Setting ComVisible to false makes the types in this assembly not visible 
// to COM components.  If you need to access a type in this assembly from 
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
 
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("3d9506d5-5642-451c-a6de-a618cfb63397")]
 
// Version information for an assembly consists of the following four values:
//
//      Major Version
//      Minor Version 
//      Build Number
//      Revision
//
// You can specify all the values or you can default the Revision and Build Numbers 
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//AssemblyInfo.cs end
 
//--------------------
 
//ObjectHierarchicalEnumerable.cs start
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace MSDControls
{
    /// <summary>
    /// Summary description for ObjectHierarchicalEnumerable
    /// </summary>
    public class ObjectHierarchicalEnumerable : ArrayList, IHierarchicalEnumerable
    {
        public ObjectHierarchicalEnumerable() : base() { }
        public IHierarchyData GetHierarchyData(object enumeratedItem)
        {
            return enumeratedItem as IHierarchyData;
        }
    }
}
//ObjectHierarchicalEnumerable.cs end
 
//--------------------
 
//ObjectHierarichalDataSource.cs start
using System;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace MSDControls
{
    /// <summary>
    /// Summary description for ObjectHierarichalDataSource
    /// </summary>
    public class ObjectHierarchicalDataSource : ObjectDataSource, IHierarchicalDataSource
    {
        private string _dataKeyName;
        private string _dataParentKeyName;
 
 
        public event EventHandler DataSourceChanged;
 
        /// <summary>
        /// The database table primary key
        /// </summary>
        public string DataKeyName
        {
            get { return _dataKeyName; }
            set { _dataKeyName = value; }
        }
 
        /// <summary>
        /// The database table parent id
        /// </summary>
        public string DataParentKeyName
        {
            get { return _dataParentKeyName; }
            set { _dataParentKeyName = value; }
        }
 
        /// <summary>
        /// Return hierarchical data
        /// </summary>
        public HierarchicalDataSourceView GetHierarchicalView(string viewPath)
        {
            return new ObjectHierarchicalDataSourceView(this, viewPath);
        }
 
    }
 
}
//ObjectHierarichalDataSource.cs end
 
//--------------------
 
//ObjectHierarichalDataSourceView.cs start
using System;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace MSDControls
{
    /// <summary>
    /// Summary description for ObjectHierarichalDataSourceView
    /// </summary>
    public class ObjectHierarchicalDataSourceView : HierarchicalDataSourceView
    {
        private ObjectHierarchicalDataSource _owner;
        private string _viewPath;
        private DataTable _data;
 
        public ObjectHierarchicalDataSourceView(ObjectHierarchicalDataSource owner, string viewPath
    )
        {
            _owner = owner;
            _viewPath = viewPath;
        }
 
 
        /// <summary>
        /// The DataTable which contains all rows from
        /// underlying database table
        /// </summary>
        public DataTable Data
        {
            get { return _data; }
        }
 
        /// <summary>
        /// We need to expose this for the objectNodes
        /// </summary>
        public string DataKeyName
        {
            get { return _owner.DataKeyName; }
        }
 
        /// <summary>
        /// We need to expose this for the objectNodes
        /// </summary>
        public string DataParentKeyName
        {
            get { return _owner.DataParentKeyName; }
        }
 
        /// <summary>
        /// Get the top-level rows (rows without parent rows)
        /// </summary>
        /// <returns></returns>
        public override IHierarchicalEnumerable Select()
        {
 
            // Verify DataKeyName and DataParentKeyName properties
            if (String.IsNullOrEmpty(DataKeyName))
                throw new Exception("You must set the DataKeyName property");
            if (String.IsNullOrEmpty(DataParentKeyName))
                throw new Exception("You must set the DataParentKeyName property");
 
            DataView view = (DataView)_owner.Select();
            _data = view.Table;
 
            // Get the root rows
            string filter = string.Format("{0} IS NULL", this.DataParentKeyName);
            DataRow[] rootRows = _data.Select(filter);
 
            // Build up the hierarchical collection
            ObjectHierarchicalEnumerable en = new ObjectHierarchicalEnumerable();
            foreach (DataRow row in rootRows)
                en.Add(new ObjectNode(this, row));
            return en;
        }
 
 
    }
 
}
//ObjectHierarichalDataSourceView.cs end
 
//--------------------
 
//ObjectNode.cs start
using System;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Collections.Generic;
 
namespace MSDControls
{
    /// <summary>
    /// Summary description for ObjectNode
    /// </summary>
    public class ObjectNode : IHierarchyData, ICustomTypeDescriptor
    {
 
        private ObjectHierarchicalDataSourceView _owner;
        private DataRow _row;
 
 
        public ObjectNode(ObjectHierarchicalDataSourceView owner, DataRow row)
        {
            _owner = owner;
            _row = row;
        }
 
        public override string ToString()
        {
            return _row[0].ToString();
        }
        #region IHierarchyData Members
 
        public IHierarchicalEnumerable GetChildren()
        {
 
            string filter = string.Format("{0}={1}", _owner.DataParentKeyName, _row[_owner.DataKeyName]);
            DataRow[] childRows = _owner.Data.Select(filter);
 
            ObjectHierarchicalEnumerable en = new ObjectHierarchicalEnumerable();
            foreach (DataRow row in childRows)
                en.Add(new ObjectNode(_owner, row));
            return en;
        }
 
        public IHierarchyData GetParent()
        {
            string filter = string.Format("{0}={1}", _owner.DataKeyName, _row[_owner.DataParentKeyName]);
            DataRow[] parentRows = _owner.Data.Select(filter);
 
            if (parentRows.Length > 0)
                return new ObjectNode(_owner, parentRows[0]);
            else
                return null;
 
        }
 
        public bool HasChildren
        {
            get
            {
                string filter = String.Format("{0}={1}", _owner.DataParentKeyName, _row[_owner.DataKeyName]);
                DataRow[] childRows = _owner.Data.Select(filter);
 
                return childRows.Length > 0;
            }
        }
 
        public object Item
        {
            get { return _row; }
        }
 
        public string Path
        {
            get { return _row[_owner.DataKeyName].ToString(); }
        }
 
 
        public string Type
        {
            get { return "ObjectNode"; }
        }
 
        #endregion
        /// <summary>
        /// Get the list of properties supported by the SqlNode
        /// </summary>
        public PropertyDescriptorCollection GetProperties()
        {
            List<PropertyDescriptor> props = new List<PropertyDescriptor>();
            foreach (DataColumn col in _owner.Data.Columns)
                props.Add(new ObjectNodePropertyDescriptor(col.ColumnName));
            return new PropertyDescriptorCollection(props.ToArray());
        }
 
 
        // The following properties and methods are required by the
        // ICustomTypeDescriptor interface but are not implemented
 
        public System.ComponentModel.AttributeCollection GetAttributes()
        {
            throw new Exception("Not implemented.");
        }
 
        public string GetClassName()
        {
            throw new Exception("Not implemented.");
        }
 
        public string GetComponentName()
        {
            throw new Exception("Not implemented.");
        }
 
        public TypeConverter GetConverter()
        {
            throw new Exception("Not implemented.");
        }
 
        public EventDescriptor GetDefaultEvent()
        {
            throw new Exception("Not implemented.");
        }
 
        public PropertyDescriptor GetDefaultProperty()
        {
            throw new Exception("Not implemented.");
        }
 
        public object GetEditor(Type editorBaseType)
        {
            throw new Exception("Not implemented.");
        }
 
        public EventDescriptorCollection GetEvents(Attribute[] attributes)
        {
            throw new Exception("Not implemented.");
        }
 
        public EventDescriptorCollection GetEvents()
        {
            throw new Exception("Not implemented.");
        }
 
        public PropertyDescriptorCollection GetProperties(Attribute[] attributes)
        {
            throw new Exception("Not implemented.");
        }
 
        public object GetPropertyOwner(PropertyDescriptor pd)
        {
            throw new Exception("Not implemented.");
        }
 
 
    }
 
}
//ObjectNode.cs end
 
//--------------------
 
//ObjectNodePropertyDescriptor.cs start
using System;
using System.Data;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
 
namespace MSDControls
{
    /// <summary>
    /// Summary description for ObjectNodePorpertyDescriptor
    /// </summary>
    public class ObjectNodePropertyDescriptor : PropertyDescriptor
    {
        public ObjectNodePropertyDescriptor(string name) : base(name, null) { }
 
 
        /// <summary>
        /// Return the value of a DataColumn represented by
        /// a particular SqlNode
        /// </summary>
        public override object GetValue(object component)
        {
            ObjectNode node = (ObjectNode)component;
            return ((DataRow)node.Item)[this.Name];
        }
 
 
        // Don't bother to implement any of the other methods or properties
        // of this class
 
        public override bool CanResetValue(object component)
        {
            throw new Exception("Not implemented.");
        }
 
        public override Type ComponentType
        {
            get { throw new Exception("Not implemented."); }
        }
 
        public override bool IsReadOnly
        {
            get { throw new Exception("Not implemented."); }
        }
 
        public override Type PropertyType
        {
            get { throw new Exception("Not implemented."); }
        }
 
        public override void ResetValue(object component)
        {
            throw new Exception("Not implemented.");
        }
 
        public override void SetValue(object component, object value)
        {
            throw new Exception("Not implemented.");
        }
 
        public override bool ShouldSerializeValue(object component)
        {
            throw new Exception("Not implemented.");
        }
    }
 
}
//ObjectNodePropertyDescriptor.cs end
 
//--------------------
 
//Client Code in Master Page start
<asp:Menu ID="Menu1" runat="server" DataSourceID="odsMenuData" OnMenuItemDataBound="Menu1_MenuItemDataBound"
                                        StaticDisplayLevels="1" Orientation="horizontal">
                                        <DataBindings>
                                            <asp:MenuItemBinding TextField="MENU_ITEM_TEXT" ValueField="MENU_ITEM_ID" NavigateUrlField="MENU_ITEM_URL" />
                                        </DataBindings>
                                        <StaticMenuItemStyle CssClass="menuItemStatic" />
                                        <DynamicMenuItemStyle CssClass="menuItemDynamic" />
                                        <DynamicHoverStyle CssClass="menuItemHoverDynamic" />
                                        <StaticHoverStyle CssClass="menuItemHoverStatic" />
                                    </asp:Menu>
                                    <cc1:ObjectHierarchicalDataSource ID="odsMenuData" runat="server" EnableCaching="true"
                                        CacheDuration="300" SelectMethod="GetAllUserMenuItems" TypeName="DBObjects.DBAccess"
                                        DataKeyName="MENU_ITEM_ID" DataParentKeyName="PARENT_MENU_ITEM_ID" CacheKeyDependency="MenuDataCKDep">
                                        <SelectParameters>
                                            <asp:SessionParameter Name="username" SessionField="Username" />
                                        </SelectParameters>
                                    </cc1:ObjectHierarchicalDataSource>
//Client Code in Master Page end

Open in new window

0
 
LVL 1

Author Closing Comment

by:andyd70
ID: 31597121
Thank you for your Answer. I didn't get an email stating that anyone had answered hence I didn't get a chance to look at what you had written. Looks very complex but I will decipher it....I hope. Sorry for the delay in getting you the points.
0

Featured Post

On Demand Webinar: Networking for the Cloud Era

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
In this video, Percona Solutions Engineer Barrett Chambers discusses some of the basic syntax differences between MySQL and MongoDB. To learn more check out our webinar on MongoDB administration for MySQL DBA: https://www.percona.com/resources/we…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question