How to create a tab control using ASP.NET and JavaScript

By Mohammad Mahdi Ramezanpour at November 16, 2008 19:54
Filed Under: .NET General, ASP.NET, Web design, JavaScript

It may happen to any ASP.NET Developer that the customers want to have a Tab Control in their websites. There are many ASP.NET components such as Telerik RAD Controls, ComponentArt, DevExpress, etc. which can help you out in this but sometimes they are expensive for your project capacity.

In this post, I’m going to show you how you can create a very simple Tab Control using ASP.NET and JavaScript.

You can do lots of thing in order to create a Tab Control but what I’m going to do is to create a class that is inherited from System.Web.UI.WebControl:

    public class TabControl : System.Web.UI.WebControls.WebControl
    {
    }

You can make your Tab Control flexible by adding some properties to it. For example, enable your developers to set CssClass to a TabItem:

 

private string _MainCssClass;
private string _ItemCssClass;
private string _InActiveCssClass;
private string _ActiveCssClass; 
private Unit _ItemWidth = 70;
private HorizontalAlign _HorizontalAlign = HorizontalAlign.NotSet;
private string _LinkCssClass;

They’re OK; but the interesting part is to use of a string array in order to store TabItem names:

private string[] _TabNames = { "Item1", "Item2" };

This is also a property, so developers can add their own items. Another important property is a list of Panels of those TabItems. Actually, Panels are the content of each TabName:

private List<Panel> _Panels = new List<Panel>();

In the field above, developers can add their specified panels for each TabItem. The most important method in creating custom web controls is the Render() method which enable you to design your control using HTML tags. Here is my Render() method:

 

protected override void Render(System.Web.UI.HtmlTextWriter w)
{
    if (_Panels.Count == 0 || _Panels == null)
        throw new NullReferenceException("Please specify at least one panel.");
 
    w.WriteLine("<!-- Developed by Mohammad Mahdi Ramezanpour. © 2008 Marlik. -->");
    w.WriteLine(String.Format(@"<table cellpadding=""0"" cellspacing=""0""
    class=""{0}""><tr id=""MarlikTabControl"">", _MainCssClass));
    foreach (Panel p in this.Panels)
    {
        cols.Add("Tab_" + _itemIndex);
        w.WriteLine(String.Format(@"<td onmouseover=""javascript:this.style.cursor='hand';""
        class=""{0} {3}"" align=""{5}"" id=""Tab_{4}"" 
        onclick=""ShowTabContent('{1}', 'Tab_{4}');"" width=""{2}"">",
         _ItemCssClass, p.ClientID, this._ItemWidth, this._InActiveCssClass, 
         this._itemIndex, this._HorizontalAlign.ToString()));
        w.WriteLine(String.Format(@"<a class=""{1} {2}"">{0}</a>",
        _TabNames[_itemIndex], _LinkCssClass,  _ItemCssClass));
        _itemIndex++;
        w.WriteEndTag("td");
    }
    w.Write("</tr></table>");
    w.WriteLine(JavaFunctions().ToString());
    base.Render(w);
}

How it works?

In the first I checked for available panels and if there was no panels so an exception will be throwing using NullReferenceException.

As you know, there is a writer parameter as System.Web.UI.HtmlTextWriter in Render() method that enable you to generate HTML codes in your web component. You have to use that if you want to use HTML or any client-side code in your web control. Add I did above is to create a HTML <table></table> tag but rows and columns will be generating dynamically using HtmlTextWriter.

You can download the full code here: TabControl

Google Chrome, A Web-Browser from Google

By Mohammad Mahdi Ramezanpour at September 08, 2008 01:08
Filed Under: Other, Web design

Google Chrome

Google Chrome is a new web-browser released by Google that I think it's one of my best web-browsers I've ever seen. It's very similar to Safari and it have some other features based on Google Search and more. The best part is that it have a really good interface specially on Windows Vista because I just like this User Interface:

Chrome

There is a lot of features included in this web-browser that is available in Google Chrome official website: http://www.google.com/chrome. You can also download it from from that page.

 

By the way for those who are living in Iran or other restricted countries, you can download it from my friend, Omid Mafakher's website.

An overview of Caching in ASP.NET

By Mohammad Mahdi Ramezanpour at August 11, 2008 11:08
Filed Under: ASP.NET, Web design

Centered around the Cache object, the ASP.NET caching API is much more than simply a container of global data shared by all sessions. Preserved for backward compatibility with classic ASP applications, the Application intrinsic object presents itself as a global container of data with an indexer property and a user-callable locking mechanism. The Cache object is a smarter and thread-safe container that can automatically remove unused items, support various forms of dependencies, and optionally provide removal callbacks and priorities.

The Application object is maintained for backward compatibility with legacy applications; new ASP.NET applications should use the Cache object.

The Cache Class

The Cache class is exposed by the System.Web.Caching namespace and is a new entry in the set of tools that provide state management in ASP.NET. The Cache class works like an application-wide repository for data and objects, but this is the only aspect that it has in common with the HttpApplicationState class, as we'll see in a moment.

An instance of the Cache class is created on a per-AppDomain basis and remains valid until that AppDomain is up and running. The current instance of the application's ASP.NET cache is returned by the Cache property of the HttpContext object or the Cache property of the Page object.

Cache and Other State Objects

In spite of their common goal—to serve as a global data repository for ASP.NET applications—Cache and HttpApplicationState classes are quite different. Cache is a thread-safe object and does not require you to explicitly lock and unlock before access. All critical sections in the internal code are adequately protected using synchronization constructs. Another key difference with the HttpApplicationState class is that data stored in Cache doesn't necessarily live as long as the application does. The Cache object lets you associate a duration as well as a priority with any of the items you store.

Any cached item can be configured to expire after a specified number of seconds, freeing up some memory. By setting a priority on items, you help the Cache object to select which items can be safely disposed of in case of memory shortage. Items can be associated with various types of dependencies, such as the timestamp of one or more files and directories, changes on other cached items, database table changes, and external events. When something happens to break the link, the cached item is invalidated and is no longer accessible by the application.

Both Cache and HttpApplicationState are globally visible classes and span all active sessions. However, neither works in a Web farm or Web garden scenario; in general, they don't work outside the current AppDomain.

  Note 

When more than one AppDomain is involved (for example, in a Web farm), presumably all AppDomains would contain the same cached data, assuming that the cached information is not dynamic. Unlike with session state, this isn't too troubling because the assumption is that application-wide static values can be read upon initialization and cache timeout. If the cached information is dynamic, that's a different story. In that case, you should consider a global cross-machine container, as we'll discuss shortly.

The Cache object is unique in its capability to automatically scavenge the memory and get rid of unused items. Aside from that, it provides the same dictionary-based and familiar programming interface as Application and Session. Unlike Session, the Cache class does not store data on a per-user basis. Furthermore, when the session state is managed in-process, all currently running sessions are stored as distinct items in the ASP.NET Cache.

  Note 

If you're looking for a global repository object that, like Session, works across a Web farm or Web garden architecture, you might become frustrated. No such object exists in the Microsoft .NET Framework. To build a cross-machine container, you need to resort to a shared and remote resource, such as an external service or perhaps an installation of Microsoft SQL Server or another database. This means that each access to data will require serialization and is subject to network latency. In general, this scheme is complex enough to invalidate most of the advantages you get from data caching. As far as caching is involved, the tradeoff to evaluate is accessing ready-made data versus running the query to fetch a fresh copy of desired data. ASP.NET provides an effective infrastructure for caching data locally because that is what you need most of the time. Adding to the infrastructure to cover Web farms is up to you.

 

An instance of the Cache object is associated with each running application and shares the associated application's lifetime. The cache holds references to data and proactively verifies validity and expiration. When the system runs short of memory, the Cache object automatically removes some little-used items and frees valuable server resources. Each item—when stored into the cache—can be given special attributes that determine a priority and an expiration policy. All these are system-provided tools to help programmers control the scavenging mechanism of the ASP.NET cache.

Inserting New Items in the Cache

A cache item is characterized by a handful of attributes that can be specified as input arguments of both Add and Insert. In particular, an item stored in the ASP.NET Cache object can have the following properties:

  • Key. A case-sensitive string, it is the key used to store the item in the internal hashtable the ASP.NET cache relies upon. If this value is null, an exception is thrown. If the key already exists, what happens depends on the particular method you're using: Add fails, while Insert just overwrites the existing item.

  • Value. A non-null value of type Object that references the information stored in the cache. The value is managed and returned as an Object and needs casting to become useful in the application context.

  • Dependencies. Object of type CacheDependency, tracks a physical dependency between the item being added to the cache and files, directories, database tables, or other objects in the application's cache. Whenever any of the monitored sources are modified, the newly added item is marked obsolete and automatically removed.

  • Absolute Expiration Date. A DateTime object that represents the absolute expiration date for the item being added. When this time arrives, the object is automatically removed from the cache. Items not subject to absolute expiration dates must use the NoAbsoluteExpiration constants representing the farthest allowable date. The absolute expiration date doesn't change after the item is used in either reading or writing.

  • Sliding Expiration. A TimeSpan object, represents a relative expiration period for the item being added. When you set the parameter to a non-null value, the expiration-date parameter is automatically set to the current time plus the sliding period. If you explicitly set the sliding expiration, you cannot set the absolute expiration date, too. From the user's perspective, these are mutually exclusive parameters. If the item is accessed before its natural expiration time, the sliding period is automatically renewed.

  • Priority. A value picked out of the CacheItemPriority enumeration; it denotes the priority of the item. It is a value ranging from Low to NotRemovable. The default level of priority is Normal. The priority level determines the importance of the item; items with a lower priority are removed first.

  • Removal Callback. If specified, indicates the function that the ASP.NET Cache object calls back when the item will be removed from the cache. In this way, applications can be notified when their own items are removed from the cache no matter what the reason is. When the session state works in InProc mode, a removal callback function is used to fire the Session_End event. The delegate type used for this callback is CacheItemRemoveCallback.

There are basically three ways to add new items to the ASP.NET Cache object—the set accessor of Item property, the Add method, and the Insert method. The Item property allows you to indicate only the key and the value. The Add method has only one signature that includes all the aforementioned arguments. The Insert method is the most flexible of all options and provides the following four overloads:

	public void Insert(string, object);public void Insert(string, object, CacheDependency);
	public void Insert(string, object, CacheDependency, DateTime, TimeSpan);
	public void Insert(string, object, CacheDependency, DateTime, TimeSpan, CacheItemPriority, CacheItemRemovedCallback);

The following code snippet shows the typical call that is performed under the hood when the Item set accessor is used:

Insert(key, value, null, Cache.NoAbsoluteExpiration,    Cache.NoSlidingExpiration, CacheItemPriority.Normal, null);

If you use the Add method to insert an item whose key matches that of an existing item, no exception is raised, nothing happens, and the method returns null.

Upcoming Project: WithXml

By Mohammad Mahdi Ramezanpour at July 30, 2008 15:59
Filed Under: .NET General, ASP.NET, Web design

I've just started working on my new project named WithXml with my friend Omid Mafakher.

What is WithXml?

WithXml is a core for publishing website in a full-XML-based environment for make websites faster like never before.

As you know XML is a common data storage for blogging engines and most of blog engines like Dasblog, BlogEngine.NET and more are using XML as a data storage.

WithXml is a very easy to use engine enable you to create blogs, forums, pages and even websites using XML technologies and Microsoft .NET Framework 3.5 or later.

WithXml project will be available to download and use in 2 months.

What is Master Page?

By Mohammad Mahdi Ramezanpour at July 26, 2008 11:04
Filed Under: ASP.NET, Web design

master page is similar to an ordinary ASP.NET page except for the top @Master directive and the presence of one or more ContentPlaceHolder server controls. A ContentPlaceHolder control defines a region in the master page that can be customized in a derived page. A master page without content placeholders is technically correct and will be processed correctly by the ASP.NET runtime. However, a placeholderless master fails in its primary goal—to be the supertemplate of multiple pages that look alike. A master page devoid of placeholders works like an ordinary Web page but with the extra burden required to process master pages. Here is a simple master page:

<%@ Master Language="C#" CodeFile="Simple.master.cs" Inherits="Simple" %>
<html>
<head runat="server">
    <title>Hello, master pages</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Panel ID="HeaderPanel" runat="server"
            BackImageUrl="Images/SkyBkgnd.png" Width="100%">

            <asp:Label ID="TitleBox" runat="server"
                Text="Programming ASP.NET 2.0" />
        </asp:Panel>
        <asp:contentplaceholder id="PageBody" runat="server">
         <!-- derived pages will define content for this placeholder -->
       </asp:contentplaceholder>
        <asp:Panel ID="FooterPanel" runat="server"
            BackImageUrl="Images/SeaBkgnd.png">
            <asp:Label ID="SubTitleBox" runat="server"
                 Text="Dino Esposito" />
        </asp:Panel>
    </form>
</body>
</html>

As you can see, the master page looks like a standard ASP.NET page. Aside from the identifying @Master directive, the only key differences are ContentPlaceHolder controls. A page bound to this master automatically inherits all the contents of the master (the header and footer, in this case) and can attach custom markup and server controls to each defined placeholder. The content placeholder element is fully identified by its ID property and normally doesn't require other attributes.

The @Master Directive

The @Master directive distinguishes master pages from content pages and allows the ASP.NET runtime to properly handle each. A master page file is compiled to a class that derives from the MasterPage class. The MasterPage class, in turn, inherits UserControl. So, at the end of the day, a master page is treated as a special kind of ASP.NET user control.

Description

ClassName

Specifies the name for the class that will be created to render the master page. This value can be any valid class name but should not include a namespace. By default, the class name for simple.master is ASP.simple_master.

CodeFile

Indicates the URL to the file that contains any source code associated with the master page.

Inherits

Specifies a code-behind class for the master page to inherit. This can be any class derived from MasterPage.

MasterPageFile

Specifies the name of the master page file that this master refers to. A master can refer to another master through the same mechanisms a page uses to attach to a master. If this attribute is set, you will have nested masters.

The master page is associated with a code file that looks like the following:

public partial class Simple : System.Web.UI.MasterPage {
    protected void Page_Load(object sender, EventArgs e) {
        ...
    }
}

The @Master directive doesn't override attributes set at the @Page directive level. For example, you can have the master set the language to Visual Basic .NET and one of the content pages can use C#. The language set at the master page level never influences the choice of the language at the content page level. You can use other ASP.NET directives in a master page—for example, @Import. However, the scope of these directives is limited to the master file and does not extend to child pages generated from the master.

Note

You can create master pages programmatically. You build your own class and make it inherit MasterPage. Then you create .master files in which the Inherits attribute points to the fully qualified name of your class. Rapid application development (RAD) designers such as the one embedded in Microsoft Visual Studio .NET 2005 use this approach to create master pages.

The ContentPlaceHolder Container Control

The ContentPlaceHolder control acts as a container placed in a master page. It marks places in the master where related pages can insert custom content. A content placeholder is uniquely identified by an ID. Here's an example:

<asp:contentplaceholder runat="server" ID="PageBody" />

A content page is an ASP.NET page that contains only <asp:Content> server tags. This element corresponds to an instance of the Content class that provides the actual content for a particular placeholder in the master. The link between placeholders and content is established through the ID of the placeholder. The content of a particular instance of the Content server control is written to the placeholder whose ID matches the value of the ContentPlaceHolderID property, as shown here:

<asp:Content runat="server" contentplaceholderID="PageBody">
    ...
</asp:Content>

In a master page, you define as many content placeholders as there are customizable regions in the page. A content page doesn't have to fill all the placeholders defined in the bound master. However, a content page can't do more than just fill placeholders defined in the master.

Note

A placeholder can't be bound to more than one content region in a single content page. If you have multiple <asp:Content> server tags in a content page, each must point to a distinct placeholder in the master.

Specifying Default Content

A content placeholder can be assigned default content that will show up if the content page fails to provide a replacement. Each ContentPlaceHolder control in the master page can contain default content. If a content page does not reference a given placeholder in the master, the default content will be used. The following code snippet shows how to define default content:

<asp:contentplaceholder runat="server" ID="PageBody">
    <!-- Use the following markup if no custom
        content is provided by the content page -->
    ...
</asp:contentplaceholder>

The default content is completely ignored if the content page populates the placeholder. The default content is never merged with the custom markup provided by the content page.

Note

A ContentPlaceHolder control can be used only in a master page. Content placeholders are not valid on regular ASP.NET pages. If such a control is found in an ordinary Web page, a parser error occurs.

Writing a Content Page

The master page defines the skeleton of the resulting page. If you need to share layout or any UI block among all the pages, placing it in a master page will greatly simplify management of the pages in the application. You create the master and then think of your pages in terms of a delta from the master. The master defines the common parts of a certain group of pages and leaves placeholders for customizable regions. Each content page, in turn, defines what the content of each region has to be for a particular ASP.NET page.

The Content Control

The key part of a content page is the Content control—a mere container for other controls. The Content control is used only in conjunction with a corresponding ContentPlaceHolder and is not a standalone control. The master file that we considered earlier defines a single placeholder named PageBody. This placeholder represents the body of the page and is placed right below an HTML table that provides the page's header.

Attaching Pages to a Master

In the previous example, the content page is bound to the master by using the MasterPageFile attribute in the @Page directive. The attribute points to a string representing the path to the master page. Page-level binding is just one possibility—although it is the most common one.

You can also set the binding between the master and the content at the application or folder level. Application-level binding means that you link all the pages of an application to the same master. You configure this behavior by setting the Master attribute in the <pages> element of the principal web.config file:

<configuration>
    <system.web>
        <pages master="MyApp.master" />
    </system.web>
</configuration>

If the same setting is expressed in a child web.config file—a web.config file stored in a site subdirectory—all ASP.NET pages in the folder are bound to a specified master page.

Note that if you define binding at the application or folder level, all the Web pages in the application (or the folder) must have Content controls mapped to one or more placeholders in the master page. In other words, application-level binding prevents you from having (or later adding) a page to the site that is not configured as a content page. Any classic ASP.NET page in the application (or folder) that contains server controls will throw an exception.

Device-Specific Masters

Like all ASP.NET pages and controls, master pages can detect the capabilities of the underlying browser and adapt their output to the specific device in use. ASP.NET 2.0 makes choosing a device-specific master easier than ever. If you want to control how certain pages of your site appear on a particular browser, you can build them from a common master and design the master to address the specific features of the browser. In other words, you can create multiple versions of the same master, each targeting a different type of browser.

How do you associate a particular version of the master and a particular browser? In the content page, you define multiple bindings using the same MasterPageFile attribute, but you prefix it with the identifier of the device. For example, suppose you want to provide ad hoc support for Microsoft Internet Explorer and Netscape browsers and use a generic master for any other browsers that users employ to visit the site. You use the following syntax:

<%@ Page masterpagefile="Base.master"
    ie:masterpagefile="ieBase.master"
    netscape6to9:masterpagefile="nsBase.master" %>

The ieBase.master file will be used for Internet Explorer; the nsBase.master, on the other hand, will be used if the browser belongs to the Netscape family, versions 6.x to 9.0. In any other case, a device-independent master (Base.master) will be used.

Currently Reading

Quote of the day

Send Persian SMS