Search This Blog

Tuesday, January 3, 2012

Obsolete and Conditional Attributes in C#, ASP.NET

C# Language: Attributes

Attributes are used to give more information about any method or function in asp.net c#.

Two types of Attributes

                                   1. Obsolete
                                   2. Conditional

Obsolete Attributes are used to give user defined warning or error message on the program code.
If true  is given in the attribute declaration or before defining any method then it will generate error message
If false or nothing is given in the attribute declaration then it will generate warning message.

Conditional Attribute is given and define that word then it will check the method,
If not define or undef then it will bypass that method and execute code another written after that method.


IN Console Application

#define DEBUG
#undef TRACE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            obsoleteMethod1();    //Warnig
            obsoleteMethod2();    //Error

            conditionalMethod1();
            conditionalMethod2();

            Console.ReadLine();
        }

        [Obsolete("msg...")]
        static void obsoleteMethod1()
        {
            Console.Write("\n\n\n ...");
        }

        [Obsolete("msg...", true)]
        static void obsoleteMethod2()
        {
            Console.Write("\n\n\n ...");
        }


        [Conditional("DEBUG")]
        static void conditionalMethod1()
        {
            Console.Write("\n\n\n Debug...");
        }

        [Conditional("TRACE")]
        static void conditionalMethod2()
        {
            Console.Write("\n\n\n Trace...");
        }
    }
}

How controls are created dynamically and working with the events which are user defined events created by you.

IN ASPX.cs File

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

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Button b = new Button();
        form1.Controls.Add(b);
        b.Click += new EventHandler(b_Click);
        b.Text = "Submit";

        LinkButton l = new LinkButton();
        form1.Controls.Add(l);
        l.Click += new EventHandler(l_Click);
        l.Text = "Save";

        TextBox t = new TextBox();
        form1.Controls.Add(t);
    }

    protected void b_Click(object sender, EventArgs e)
    {
        Response.Write("hello.....!!!!");
    }

    protected void l_Click(object sender, EventArgs e)
    {
        Response.Write("saved.....!!!!");
    }
}

1 comment: