Search blog.co.uk

Posts archive for: 7 April, 2007
  • Delegates and Events in C# - More

    Go To Index Page

    Overview
    All of us have been exposed to event driven programming of some sort or the other. C# adds on value to the often mentioned world of event driven programming by adding support through events and delegates. The emphasis of this article would be to identify what exactly happens when you add an event handler to your common UI controls. A simple simulation of what could possibly be going on behind the scenes when the AddOnClick or any similar event is added to the Button class will be explained. This will help you understand better the nature of event handling using multi cast delegates.

    Delegates
    A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.

    Call a Function directly - No Delegate
    In most cases, when we call a function, we specify the function to be called directly. If the class MyClass has a function named Process, we'd normally call it like this (SimpleSample.cs):

    using System;

    namespace NoDelegate
    {
    public class MyClass
    {
    public void Process()
    {
    Console.WriteLine("Process() begin");
    Console.WriteLine("Process() end");
    }
    }

    public class Test
    {
    static void Main(string[] args)
    {
    MyClass myClass = new MyClass();
    myClass.Process();
    }
    }
    }

    That works well in most situations. Sometimes, however, we don't want to call a function directly - we'd like to be able to pass it to somebody else so that they can call it. This is especially useful in an event-driven system such as a graphical user interface, when I want some code to be executed when the user clicks on a button, or when I want to log some information but can't specify how it is logged.

    The very basic Delegate
    An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.

    The signature of a single cast delegate is shown below:

    delegate result-type identifier ([parameters]);

    where:

    result-type: The result type, which matches the return type of the function.
    identifier: The delegate name.
    parameters: The Parameters, that the function takes.

    Examples:

    public delegate void SimpleDelegate ()

    This declaration defines a delegate named SimpleDelegate, which will encapsulate any method that takes
    no parameters and returns no value.

    public delegate int ButtonClickHandler (object obj1, object obj2)

    This declaration defines a delegate named ButtonClickHandler, which will encapsulate any method that takes
    two objects as parameters and returns an int.

    A delegate will allow us to specify what the function we'll be calling looks like without having to specify which function to call. The declaration for a delegate looks just like the declaration for a function, except that in this case, we're declaring the signature of functions that this delegate can reference.

    There are three steps in defining and using delegates:

    Declaration
    Instantiation
    Invocation
    A very basic example (SimpleDelegate1.cs):

    using System;

    namespace BasicDelegate
    {
    // Declaration
    public delegate void SimpleDelegate();

    class TestDelegate
    {
    public static void MyFunc()
    {
    Console.WriteLine("I was called by delegate ...");
    }

    public static void Main()
    {
    // Instantiation
    SimpleDelegate simpleDelegate = new SimpleDelegate(MyFunc);

    // Invocation
    simpleDelegate();
    }
    }
    }

    Compile an test:

    # csc SimpleDelegate1.cs
    # SimpleDelegate1.exe
    I was called by delegate ...

    Calling Static Functions
    For our next, more advanced example (SimpleDelegate2.cs), declares a delegate that takes a single string parameter and has no return type:

    using System;

    namespace Akadia.SimpleDelegate
    {
    // Delegate Specification
    public class MyClass
    {
    // Declare a delegate that takes a single string parameter
    // and has no return type.
    public delegate void LogHandler(string message);

    // The use of the delegate is just like calling a function directly,
    // though we need to add a check to see if the delegate is null
    // (that is, not pointing to a function) before calling the function.
    public void Process(LogHandler logHandler)
    {
    if (logHandler != null)
    {
    logHandler("Process() begin");
    }

    if (logHandler != null)
    {
    logHandler ("Process() end");
    }
    }
    }

    // Test Application to use the defined Delegate
    public class TestApplication
    {
    // Static Function: To which is used in the Delegate. To call the Process()
    // function, we need to declare a logging function: Logger() that matches
    // the signature of the delegate.
    static void Logger(string s)
    {
    Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
    MyClass myClass = new MyClass();

    // Crate an instance of the delegate, pointing to the logging function.
    // This delegate will then be passed to the Process() function.
    MyClass.LogHandler myLogger = new MyClass.LogHandler(Logger);
    myClass.Process(myLogger);
    }
    }
    }

    Compile an test:

    # csc SimpleDelegate2.cs
    # SimpleDelegate2.exe
    Process() begin
    Process() end

    Calling Member Functions
    In the simple example above, the Logger( ) function merely writes the string out. A different function might want to log the information to a file, but to do this, the function needs to know what file to write the information to (SimpleDelegate3.cs)

    using System;
    using System.IO;

    namespace Akadia.SimpleDelegate
    {
    // Delegate Specification
    public class MyClass
    {
    // Declare a delegate that takes a single string parameter
    // and has no return type.
    public delegate void LogHandler(string message);

    // The use of the delegate is just like calling a function directly,
    // though we need to add a check to see if the delegate is null
    // (that is, not pointing to a function) before calling the function.
    public void Process(LogHandler logHandler)
    {
    if (logHandler != null)
    {
    logHandler("Process() begin");
    }

    if (logHandler != null)
    {
    logHandler ("Process() end");
    }
    }
    }

    // The FileLogger class merely encapsulates the file I/O
    public class FileLogger
    {
    FileStream fileStream;
    StreamWriter streamWriter;

    // Constructor
    public FileLogger(string filename)
    {
    fileStream = new FileStream(filename, FileMode.Create);
    streamWriter = new StreamWriter(fileStream);
    }

    // Member Function which is used in the Delegate
    public void Logger(string s)
    {
    streamWriter.WriteLine(s);
    }

    public void Close()
    {
    streamWriter.Close();
    fileStream.Close();
    }
    }

    // Main() is modified so that the delegate points to the Logger()
    // function on the fl instance of a FileLogger. When this delegate
    // is invoked from Process(), the member function is called and
    // the string is logged to the appropriate file.
    public class TestApplication
    {
    static void Main(string[] args)
    {
    FileLogger fl = new FileLogger("process.log");

    MyClass myClass = new MyClass();

    // Crate an instance of the delegate, pointing to the Logger()
    // function on the fl instance of a FileLogger.
    MyClass.LogHandler myLogger = new MyClass.LogHandler(fl.Logger);
    myClass.Process(myLogger);
    fl.Close();
    }
    }
    }

    The cool part here is that we didn't have to change the Process() function; the code to all the delegate is the same regardless of whether it refers to a static or member function.

    Compile an test:

    # csc SimpleDelegate3.cs
    # SimpleDelegate3.exe
    # cat process.log
    Process() begin
    Process() end

    Multicasting
    Being able to point to member functions is nice, but there are more tricks you can do with delegates. In C#, delegates are multicast, which means that they can point to more than one function at a time (that is, they're based off the System.MulticastDelegate type). A multicast delegate maintains a list of functions that will all be called when the delegate is invoked. We can add back in the logging function from the first example, and call both delegates. Here's what the code looks like:

    using System;
    using System.IO;

    namespace Akadia.SimpleDelegate
    {
    // Delegate Specification
    public class MyClass
    {
    // Declare a delegate that takes a single string parameter
    // and has no return type.
    public delegate void LogHandler(string message);

    // The use of the delegate is just like calling a function directly,
    // though we need to add a check to see if the delegate is null
    // (that is, not pointing to a function) before calling the function.
    public void Process(LogHandler logHandler)
    {
    if (logHandler != null)
    {
    logHandler("Process() begin");
    }

    if (logHandler != null)
    {
    logHandler ("Process() end");
    }
    }
    }

    // The FileLogger class merely encapsulates the file I/O
    public class FileLogger
    {
    FileStream fileStream;
    StreamWriter streamWriter;

    // Constructor
    public FileLogger(string filename)
    {
    fileStream = new FileStream(filename, FileMode.Create);
    streamWriter = new StreamWriter(fileStream);
    }

    // Member Function which is used in the Delegate
    public void Logger(string s)
    {
    streamWriter.WriteLine(s);
    }

    public void Close()
    {
    streamWriter.Close();
    fileStream.Close();
    }
    }

    // Test Application which calls both Delegates
    public class TestApplication
    {
    // Static Function which is used in the Delegate
    static void Logger(string s)
    {
    Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
    FileLogger fl = new FileLogger("process.log");

    MyClass myClass = new MyClass();

    // Crate an instance of the delegates, pointing to the static
    // Logger() function defined in the TestApplication class and
    // then to member function on the fl instance of a FileLogger.
    MyClass.LogHandler myLogger = null;
    myLogger += new MyClass.LogHandler(Logger);
    myLogger += new MyClass.LogHandler(fl.Logger);

    myClass.Process(myLogger);
    fl.Close();
    }
    }
    }

    Compile an test:

    # csc SimpleDelegate4.cs
    # SimpleDelegate4.exe
    Process() begin
    Process() end
    # cat process.log
    Process() begin
    Process() end

    Events
    The Event model in C# finds its roots in the event programming model that is popular in asynchronous programming. The basic foundation behind this programming model is the idea of "publisher and subscribers." In this model, you have publishers who will do some logic and publish an "event." Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.

    In C#, any object can publish a set of events to which other applications can subscribe. When the publishing class raises an event, all the subscribed applications are notified.

    Conventions
    The following important conventions are used with events:

    Event Handlers in the .NET Framework return void and take two parameters.
    The first paramter is the source of the event; that is the publishing object.
    The second parameter is an object derived from EventArgs.
    Events are properties of the class publishing the event.
    The keyword event controls how the event property is accessed by the subscribing classes.

    Simple Event
    Let's modify our logging example from above to use an event rather than a delegate:

    using System;
    using System.IO;

    namespace Akadia.SimpleEvent
    {
    /* ========= Publisher of the Event ============== */
    public class MyClass
    {
    // Define a delegate named LogHandler, which will encapsulate
    // any method that takes a string as the parameter and returns no value
    public delegate void LogHandler(string message);

    // Define an Event based on the above Delegate
    public event LogHandler Log;

    // Instead of having the Process() function take a delegate
    // as a parameter, we've declared a Log event. Call the Event,
    // using the OnXXXX Method, where XXXX is the name of the Event.
    public void Process()
    {
    OnLog("Process() begin");
    OnLog("Process() end");
    }

    // By Default, create an OnXXXX Method, to call the Event
    protected void OnLog(string message)
    {
    if (Log != null)
    {
    Log(message);
    }
    }
    }

    // The FileLogger class merely encapsulates the file I/O
    public class FileLogger
    {
    FileStream fileStream;
    StreamWriter streamWriter;

    // Constructor
    public FileLogger(string filename)
    {
    fileStream = new FileStream(filename, FileMode.Create);
    streamWriter = new StreamWriter(fileStream);
    }

    // Member Function which is used in the Delegate
    public void Logger(string s)
    {
    streamWriter.WriteLine(s);
    }

    public void Close()
    {
    streamWriter.Close();
    fileStream.Close();
    }
    }

    /* ========= Subscriber of the Event ============== */
    // It's now easier and cleaner to merely add instances
    // of the delegate to the event, instead of having to
    // manage things ourselves
    public class TestApplication
    {
    static void Logger(string s)
    {
    Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
    FileLogger fl = new FileLogger("process.log");
    MyClass myClass = new MyClass();

    // Subscribe the Functions Logger and fl.Logger
    myClass.Log += new MyClass.LogHandler(Logger);
    myClass.Log += new MyClass.LogHandler(fl.Logger);

    // The Event will now be triggered in the Process() Method
    myClass.Process();

    fl.Close();
    }
    }
    }

    Compile an test:

    # csc SimpleEvent.cs
    # SimpleEvent.exe
    Process() begin
    Process() end
    # cat process.log
    Process() begin
    Process() end

    The Second Change Event Example
    Suppose you want to create a Clock class that uses events to notify potential subscribers whenever the local time changes value by one second. Here is the complete, documented example:

    using System;
    using System.Threading;

    namespace SecondChangeEvent
    {
    /* ======================= Event Publisher =============================== */

    // Our subject -- it is this class that other classes
    // will observe. This class publishes one event:
    // SecondChange. The observers subscribe to that event.
    public class Clock
    {
    // Private Fields holding the hour, minute and second
    private int _hour;
    private int _minute;
    private int _second;

    // The delegate named SecondChangeHandler, which will encapsulate
    // any method that takes a clock object and a TimeInfoEventArgs
    // object as the parameter and returns no value. It's the
    // delegate the subscribers must implement.
    public delegate void SecondChangeHandler (
    object clock,
    TimeInfoEventArgs timeInformation
    );

    // The event we publish
    public event SecondChangeHandler SecondChange;

    // The method which fires the Event
    protected void OnSecondChange(
    object clock,
    TimeInfoEventArgs timeInformation
    )
    {
    // Check if there are any Subscribers
    if (SecondChange != null)
    {
    // Call the Event
    SecondChange(clock,timeInformation);
    }
    }

    // Set the clock running, it will raise an
    // event for each new second
    public void Run()
    {
    for(;;)
    {
    // Sleep 1 Second
    Thread.Sleep(1000);

    // Get the current time
    System.DateTime dt = System.DateTime.Now;

    // If the second has changed
    // notify the subscribers
    if (dt.Second != _second)
    {
    // Create the TimeInfoEventArgs object
    // to pass to the subscribers
    TimeInfoEventArgs timeInformation =
    new TimeInfoEventArgs(
    dt.Hour,dt.Minute,dt.Second);

    // If anyone has subscribed, notify them
    OnSecondChange (this,timeInformation);
    }

    // update the state
    _second = dt.Second;
    _minute = dt.Minute;
    _hour = dt.Hour;

    }
    }
    }

    // The class to hold the information about the event
    // in this case it will hold only information
    // available in the clock class, but could hold
    // additional state information
    public class TimeInfoEventArgs : EventArgs
    {
    public TimeInfoEventArgs(int hour, int minute, int second)
    {
    this.hour = hour;
    this.minute = minute;
    this.second = second;
    }
    public readonly int hour;
    public readonly int minute;
    public readonly int second;
    }

    /* ======================= Event Subscribers =============================== */

    // An observer. DisplayClock subscribes to the
    // clock's events. The job of DisplayClock is
    // to display the current time
    public class DisplayClock
    {
    // Given a clock, subscribe to
    // its SecondChangeHandler event
    public void Subscribe(Clock theClock)
    {
    theClock.SecondChange +=
    new Clock.SecondChangeHandler(TimeHasChanged);
    }

    // The method that implements the
    // delegated functionality
    public void TimeHasChanged(
    object theClock, TimeInfoEventArgs ti)
    {
    Console.WriteLine("Current Time: {0}:{1}:{2}",
    ti.hour.ToString(),
    ti.minute.ToString(),
    ti.second.ToString());
    }
    }

    // A second subscriber whose job is to write to a file
    public class LogClock
    {
    public void Subscribe(Clock theClock)
    {
    theClock.SecondChange +=
    new Clock.SecondChangeHandler(WriteLogEntry);
    }

    // This method should write to a file
    // we write to the console to see the effect
    // this object keeps no state
    public void WriteLogEntry(
    object theClock, TimeInfoEventArgs ti)
    {
    Console.WriteLine("Logging to file: {0}:{1}:{2}",
    ti.hour.ToString(),
    ti.minute.ToString(),
    ti.second.ToString());
    }
    }

    /* ======================= Test Application =============================== */

    // Test Application which implements the
    // Clock Notifier - Subscriber Sample
    public class Test
    {
    public static void Main()
    {
    // Create a new clock
    Clock theClock = new Clock();

    // Create the display and tell it to
    // subscribe to the clock just created
    DisplayClock dc = new DisplayClock();
    dc.Subscribe(theClock);

    // Create a Log object and tell it
    // to subscribe to the clock
    LogClock lc = new LogClock();
    lc.Subscribe(theClock);

    // Get the clock started
    theClock.Run();
    }
    }
    }

    The Clock class from the last sample could simply print the time rather tahn raising an event, so why bother with the introduction of using delegates? The advantage of the publisg / subscribe idiom is that any number of classes can be notified when an event is raised. The subscribing classes do not need to know how the Clock works, and the Clock does not need to know what they are going to do in response to the event. Similarly a button can publish an Onclick event, and any number of unrelated objects can subscribe to that event, receiving notification when the button is clicked.

    The publisher and the subscribers are decoupled by the delegate. This is highly desirable as it makes for more flexible and robust code. The clock can chnage how it detects time without breaking any of the subscribing classes. The subscribing classes can change how they respond to time changes without breaking the Clock. The two classes spin indepentdently of one another, which makes for code that is easier to maintain.

    New in C# 2.0 - Anonymous Method v/s Delegate :

    In versions of C# previous to 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduces anonymous methods.
    Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. For example:
    // Create a handler for a click event
    button1.Click += delegate(System.Object o, System.EventArgs e)
    { System.Windows.Forms.MessageBox.Show("Click!"); };

    or

    // Create a delegate instance
    delegate void Del(int x);
    // Instantiate the delegate using an anonymous method
    Del d = delegate(int k) { /* ... */ };
    By using anonymous methods, you reduce the coding overhead in instantiating delegates by eliminating the need to create a separate method.
    For example, specifying a code block in the place of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when launching a new thread. This class creates a thread and also contains the code that the thread executes, without the need for creating an additional method for the delegate.

    void StartThread()
    {
    System.Threading.Thread t1 = new System.Threading.Thread
    (delegate()
    {
    System.Console.Write("Hello, ");
    System.Console.WriteLine("World!");
    });
    t1.Start();
    }

    Remarks

    The scope of the parameters of an anonymous method is the anonymous-method-block.
    It is an error to have a jump statement, such as goto, break, or continue, inside the anonymous method block whose target is outside the block. It is also an error to have a jump statement, such as goto, break, or continue, outside the anonymous method block whose target is inside the block.
    The local variables and parameters whose scope contain an anonymous method declaration are called outer or captured variables of the anonymous method. For example, in the following code segment, n is an outer variable:

    int n = 0;
    Del d = delegate() { System.Console.WriteLine("Copy #:{0}", ++n); };
    Unlike local variables, the lifetime of the outer variable extends until the delegates that reference the anonymous methods are eligible for garbage collection. A reference to n is captured at the time the delegate is created.
    An anonymous method cannot access the ref or out parameters of an outer scope.
    No unsafe code can be accessed within the anonymous-method-block.
    var ExpCollDivStr = ExpCollDivStr;
    ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl142b95360,";
    var ExpCollImgStr = ExpCollImgStr;
    ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl14img,";

    Example

    The following example demonstrates the two ways of instantiating a delegate:
    Associating the delegate with an anonymous method.
    Associating the delegate with a named method (DoWork).
    In each case, a message is displayed when the delegate is invoked.

    // Declare a delegate
    delegate void Printer(string s);
    class TestClass
    {
    static void Main()
    {
    // Instatiate the delegate type using an anonymous method:
    Printer p = delegate(string j)
    {
    System.Console.WriteLine(j);
    };
    // Results from the anonymous delegate call:
    p("The delegate using the anonymous method is called.");
    // The delegate instantiation using a named method "DoWork":
    p = new Printer(TestClass.DoWork);
    // Results from the old style delegate call:
    p("The delegate using the named method is called.");
    }
    // The method associated with the named delegate:
    static void DoWork(string k)
    {
    System.Console.WriteLine(k);
    }
    }
    var ExpCollDivStr = ExpCollDivStr;
    ExpCollDivStr = ExpCollDivStr + "ctl00_LibFrame_ctl166bc53f5,";
    var ExpCollImgStr = ExpCollImgStr;
    ExpCollImgStr = ExpCollImgStr + "ctl00_LibFrame_ctl16img,";

    Output

    The delegate using the anonymous method is called.
    The delegate using the named method is called.

    Go To Index Page

  • Delegates & Events

    Go To Index Page

    Delegates in C# .Net:
    Delegate is similar to the C++ feature callback funciton but it is more type safe. This callback feature uses Pointers to Functions to pass them as parameters to other functions. A delegate can hold reference/s to one or more functions and invoke them as and when needed.
    Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked.
    A delegate needs the method's name and its parameters (input and output variables) when we create a delegate. But delegate is not a standalone construction. it's a class.
    Any delegate is inherited from base delegate class of .NET class library when it is declared. This can be from either of the two classes from System.Delegate or System.MulticastDelegate.
    If the delegate contains a return type of void, then it is automatically aliased to the type of System.MulticastDelegate. This can support multiple functions with a += operator. If the delegate contains a non-void return type then it is aliased to System.Delegate class and it cannot support multiple methods.
    Let us have a look at the following sample code.

    class Figure
    {
    public Figure(float a, float b, float c) { m_xPos = a; m_yPos = b; m_zPos = c; }
    public void InvertX() { m_xPos = - m_xPos; }
    public void InvertY() { m_yPos = - m_yPos; }
    public void InvertZ() { m_zPos = - m_zPos; }
    private float m_xPos = 0; private float m_yPos = 0; private float m_zPos = 0;
    }
    Now, we have a class named Figure and it has three private fields that use to store position and three methods to invert this position by every axis. In main class we declare delegate as follows:

    public delegate void FigureDelegate();
    And now in the main function we should use it like this:
    Figure figure = new Figure(10,20,30);
    FigureDelegate fx = new FigureDelegate(figure.InvertX);
    FigureDelegate fy = new FigureDelegate(figure.InvertY);
    FigureDelegate fz = new FigureDelegate(figure.InvertZ);
    MulticastDelegate f_del = fx+fy+fz;
    In this example we create three delegates of FigureDelegate type and attach to these elements our three methods from Figure class. Now every delegate keeps the address of the attached function. The last line of code is very interesting, here we create a delegate of base type (MulticastDelegate) and attach three of our already created delegates. As all our methods are of void return type they are automatically of type MutlticastDelegate and a MulticastDelegate can support multiple methods invocation also. Hence we can write
    Figure figure = new Figure(10,20,30);
    FigureDelegate fMulti = new FigureDelegate(figure.InvertX);
    fMulti += new FigureDelegate(figure.InvertY);
    fMulti();

    Events in C# .Net:
    Delegate usefulness does not just lie in the fact that it can hold the references to functions but in the fact that it can define and use function names at runtime and not at compile time. A large goal of design delegates is their applicability in events model of .Net. Events are the actions of the system on user manipulations (e.g. mouse clicks, key press, timer etc.) or any event triggered by the program. To understand the usage of delegates for event model, the previous examples are used here. We should add to our Figure class next things:

    public delegate void FigureHandler(string msg);
    public static event FigureHandler Inverted;
    public void InvertZ()
    {
    m_zPos = - m_zPos; Inverted("inverted by z-axis");
    }
    Now we have a delegate declared and event that uses this delegate's type. In every function we should call our event. The next code snippet should explain it clearly:
    static void Main(string[] args)
    {
    Figure figure = new Figure(10,20,30);
    Figure.Inverted+=new Test.Figure.FigureHandler(OnFigureInverted);
    figure.InvertX(); figure.InvertZ();
    }
    private static void OnFigureInverted(string msg)
    {
    Console.WriteLine("Figure was {0}",msg);
    }
    So, in the main function we should create an object of figure class and attach event handler to the method OnFigureInverted. And when we call any of invert methods the event is fired and it calls our event handler. The application will print the following string into the console: Figure was inverted by x-axis Figure was inverted by z-axis There was simple examples of using delegates and events and should be treated as a starting point to learn it more yourself. Download the C# Delegates source files from the link. To compile and run it need to run .NET command line. Just type: csc TestClass.cs. It creates TestClass.exe that can be run as standard executable file.

    Go To Index Page

  • Populating .Net Menu Control

    Go To Index Page

    Populating Menu using Database

    WAY 1.

    Create following tables in Database:

    Menu

    MenuID MenuText ParentMenuID MenuURL Description Status
    1 Home 0 ContentPage1.aspx Home Page 1
    2 Masters 0 # Masters 1
    3 Tools 0 # Tools 1
    4 Reports 0 # Reports 1
    5 Manage Companies 2 # Companies 1
    6 Parent Companies 5 ContentPage1.aspx Parent Companies 1
    7 Sub Companies 5 ContentPage1.aspx Sub Companies 1
    8 Users 2 # Users 1
    9 Promotions 2 ContentPage1.aspx Promotions 1
    10 Mobile Change 3 # Mobile Change 1
    11 Transactions 4 # Transactions 1
    12 Allocations 4 # Allocations 1
    13 Create User 8 # Create User 1
    14 View User 8 # View User 1
    15 Edit User 14 # Edit User 1

    Role

    RoleID UserDescription UserRoleKeyWord AccessLevel
    1 SUPER ADMINISTRATOR PSA 0
    2 ACCOUNT MANAGER PAM 1
    3 CUSTOMER SUPPORT MANAGER PCM 4
    4 RISK MANAGER PRM 5
    5 CUSTOMER SUPPORT EXECUTIVE PCE 6
    6 RISK EXECUTIVE PRE 7
    7 COMPANY ADMINISTRATOR CA 2
    8 COMPANY ACCOUNT MANAGER CAM 3
    9 OPERATION TEAM POT 100
    10 ALLIENCE TEAM PAT 100

    MenuRoleMatrix

    MatrixID MenuID RoleID Status
    1 1 1 1
    2 2 1 1
    3 3 1 1
    4 4 1 1
    5 5 1 1
    6 6 1 1
    7 7 1 1
    8 8 1 1
    9 9 1 1
    10 10 1 1
    11 11 1 1
    12 12 1 1
    13 13 1 1
    14 14 1 1
    15 15 1 1

    using System;
    using System.Data;
    using System.Configuration;
    using System.Collections;
    using System.Web;
    using System.Web.Security;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Web.UI.WebControls.WebParts;
    using System.Web.UI.HtmlControls;

    public partial class HMasterPage : System.Web.UI.MasterPage
    {
    protected void Page_Load(object sender, EventArgs e)
    {
    if(!Page.IsPostBack)
    {
    FillMenu();
    }
    }

    private void FillMenu()
    {
    clsUtilDA clsUDA = new clsUtilDA();
    DataSet ds = new DataSet();
    ds = clsUDA.GetDataSet("SELECT MENUID, MENUTEXT, PARENTMENUID, MENUURL FROM MENU WHERE STATUS = 1 AND MENUID IN (SELECT MENUID FROM MenuRoleMatrix WHERE STATUS = 1 AND ROLEID =1) ORDER BY PARENTMENUID");

    if(ds != null && ds.Tables[0] != null && ds.Tables[0].Rows.Count > 0 )
    {
    foreach(DataRow row in ds.Tables[0].Rows)
    {
    if(row["PARENTMENUID"].ToString() == "0")
    MenuMaster.Items.Add(new MenuItem(row["MENUTEXT"].ToString(),row["MENUID"].ToString(),"",row["MENUURL"].ToString(),"_self"));
    else
    {
    if(MenuMaster.FindItem(row["PARENTMENUID"].ToString()) != null)
    MenuMaster.FindItem(row["PARENTMENUID"].ToString()).ChildItems.Add(new MenuItem(row["MENUTEXT"].ToString(),row["MENUID"].ToString(),"",row["MENUURL"].ToString(),"_self"));
    else
    {
    foreach(MenuItem subMenu in MenuMaster.Items)
    {
    DigMenu(subMenu, row["PARENTMENUID"].ToString(),row["MENUTEXT"].ToString(),row["MENUID"].ToString(),row["MENUURL"].ToString());
    }
    }
    }
    }
    }
    }

    private void DigMenu(MenuItem subMenu,string parentID,string text,string mid,string mUrl)
    {
    if(subMenu.ChildItems.Count > 0)
    {
    foreach(MenuItem itm in subMenu.ChildItems)
    {
    if(itm.Value == parentID)
    {
    itm.ChildItems.Add(new MenuItem(text,mid,"",mUrl,"_self"));
    break;
    }
    else
    DigMenu(itm,parentID,text,mid,mUrl);
    }
    }
    }
    }

    WAY 2.

    Suppose that you have some data in the database tables using which you want to populate the Menu. Although I prefer the .sitemap technique since that is its sole purpose, the code below shows how you can use database as a data source.

    private void PopulateMenu()
    {
    DataSet ds = GetDataSetForMenu();
    Menu menu = new Menu();

    foreach (DataRow parentItem in ds.Tables["Categories"].Rows)
    {
    MenuItem categoryItem = new MenuItem((string)parentItem["CategoryName"]);
    menu.Items.Add(categoryItem);

    foreach (DataRow childItem in parentItem.GetChildRows("Children"))
    {
    MenuItem childrenItem = new MenuItem((string)childItem["ProductName"]);
    categoryItem.ChildItems.Add(childrenItem);
    }
    }

    Panel1.Controls.Add(menu);
    Panel1.DataBind();
    }

    private DataSet GetDataSetForMenu()
    {
    SqlConnection myConnection = new SqlConnection(GetConnectionString());
    SqlDataAdapter adCat = new SqlDataAdapter("SELECT * FROM Categories", myConnection);
    SqlDataAdapter adProd = new SqlDataAdapter("SELECT * FROM Products", myConnection);

    DataSet ds = new DataSet();
    adCat.Fill(ds, "Categories");
    adProd.Fill(ds, "Products");
    ds.Relations.Add("Children",
    ds.Tables["Categories"].Columns["CategoryID"],
    ds.Tables["Products"].Columns["CategoryID"]);
    return ds;
    }
    Let's first look at the GetDataSetForMenu() since its being called from PopulateMenu(). In the GetDataSetForMenu() method we make a relationship between the Categories table and the Products table.

    The PopulateMenu() methods receives the DataSet from the GetDataSetForMenu() and iterates through the DataSet. For each iteration it creates a new MenuItem and adds it into the menu items collection.

    -------------------

    Populating the Menu using SiteMapDataSource
    This is the preferred way of populating the Menu control. SiteMapDataSource allows you to read the information from the .sitemap file which is simply an XML file. Let's take a look at the .sitemap file. As you can see in the file below, all you need to do is to assign the values to the nodes and that's it.

    Now let's see how we build our menu using the .sitemap file above. All we are doing in the GetSiteMapDataSource method is getting the information from the Web.sitemap file and building the menu based on the contents of that file.

    private void CreateMenuControl()
    {
    Menu1.DataSource = GetSiteMapDataSource();
    Menu1.DataBind();
    }

    private SiteMapDataSource GetSiteMapDataSource()
    {
    XmlSiteMapProvider xmlSiteMap = new XmlSiteMapProvider();
    System.Collections.Specialized.NameValueCollection
    myCollection = new
    System.Collections.Specialized.NameValueCollection(1);
    myCollection.Add("siteMapFile", "Web.sitemap");
    xmlSiteMap.Initialize("provider", myCollection);
    xmlSiteMap.BuildSiteMap();
    SiteMapDataSource siteMap = new SiteMapDataSource();
    return siteMap;
    }

    -----------------------------

    Populating the Menu Control Using an XML File
    private void CreateMenuWithXmlFile()
    {
    string path = @"C:\MyXmlFile.xml";
    DataSet ds = new DataSet();
    ds.ReadXml(path);
    Menu menu = new Menu();
    menu.MenuItemClick += new MenuEventHandler(menu_MenuItemClick);

    for (int i = 0; i < ds.Tables.Count; i++)
    {
    MenuItem parentItem = new MenuItem((string)ds.Tables[i].TableName);
    menu.Items.Add(parentItem);

    for (int c = 0; c < ds.Tables[i].Columns.Count; c++)
    {
    MenuItem column = new MenuItem((string)ds.Tables[i].Columns[c].ColumnName);
    menu.Items.Add(column);

    for (int r = 0; r < ds.Tables[i].Rows.Count; r++)
    {
    MenuItem row = new MenuItem((string)ds.Tables[i].Rows[r][c].ToString());
    parentItem.ChildItems.Add(row);
    }
    }
    }

    Panel1.Controls.Add(menu);
    Panel1.DataBind();
    }
    I get the XML from the DataSet ReadXML() method. And after that it's just a matter of iterating through the DataSet and making MenuItems.

    Go To Index Page

Recent posts

more posts…

Footer:

The content of this website belongs to a private person, blog.co.uk is not responsible for the content of this website.