Aug 14 2007

Extension Methods in C# 3.0 and ASP.NET Code-Inline

Category: C# 3.0 | LinqBil@l @ 00:14

I was customizing a ListView today to show a small key gif beside each article listed to indicate that the article requires a login to be viewed based on whether the user is authenticated or not. So I decided to use inline checking to see if the current user is logged in or not and accordingly show/hide the Image. The code is like this:

                <asp:Image runat="server" ID="imgKey" ImageUrl="~/Images/key.gif" AlternateText="Requires login"
                    Visible='<%# (bool)Eval("OnlyForMembers") && !Page.IsAuthenticated() %>' />

Notice the Page.IsAuthenticated() method. I have added this as an extension method that targets the Page class as follows:

        /// <summary>
        /// A Method that returns whether the user checkin the webpage
        /// is currently authenticated or not.
        /// </summary> 
        /// <param name="page">A <see cref="System.Web.UI.Page"/> instance</param>
        /// <returns>A <see cref="System.Boolean"/> that specifies whether the user is currently authenticated or not</returns>
        public static bool IsAuthenticated(this System.Web.UI.Page page)
            HttpContext context = HttpContext.Current;

            if (context.User != null && context.User.Identity != null && !String.IsNullOrEmpty(context.User.Identity.Name))
                return true;

            return false;

When using this extension method inside the code-behind, you should import the class library that holds the class that adds an extension method. What I discovered today was that, even if you had imported the class library in the code behind, if you want to use any extension method inside the HTML you should add another import to the page header using the Import tag.

Hope this helps,

Tags: ,

Comments are closed