Solved

Modify Menu Items at run time asp.net

Posted on 2007-11-28
7
3,218 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
  • 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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
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 500 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

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!

Question has a verified solution.

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

Today I had a very interesting conundrum that had to get solved quickly. Needless to say, it wasn't resolved quickly because when we needed it we were very rushed, but as soon as the conference call was over and I took a step back I saw the correct …
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Exchange organizations may use the Journaling Agent of the Transport Service to archive messages going through Exchange. However, if the Transport Service is integrated with some email content management application (such as an antispam), the admini…

713 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