asp tutorials, asp.net tutorials, sample code, and Microsoft news from 15Seconds
Data Access  |   Troubleshooting  |   Security  |   Performance  |   ADSI  |   Upload  |   Email  |   Control Building  |   Component Building  |   Forms  |   XML  |   Web Services  |   ASP.NET  |   .NET Features  |   .NET 2.0  |   App Development  |   App Architecture  |   IIS  |   Wireless
 
Pioneering Active Server
 Power Search





Active News
15 Seconds Weekly Newsletter
• Complete Coverage
• Site Updates
• Upcoming Features

More Free Newsletters
Reference
News
Articles
Archive
Writers
Code Samples
Components
Tools
FAQ
Feedback
Books
Links
DL Archives
Community
Messageboard
List Servers
Mailing List
WebHosts
Consultants
Tech Jobs
15 Seconds
Home
Site Map
Press
Legal
Privacy Policy
internet.commerce














internet.com
IT
Developer
Internet News
Small Business
Personal Technology

Search internet.com
Advertise
Corporate Info
Newsletters
Tech Jobs
E-mail Offers

HardwareCentral
Compare products, prices, and stores at Hardware Central!

Implementing Paging and XSLT Extensions Using XSLT in .NET - Part 2
By Thiru Thangarathinam
Rating: 3.9 out of 5
Rate this article


  • email this article to a colleague
  • suggest an article



    Introduction

    This article will show how to invoke the methods of an extension object from a stylesheet. Before looking at an example that illustrates the use of XSLT Extension objects, let's learn the concepts behind XSLT Extension objects.

  • download source code

    What are XSLT Extension objects?

    Apart from allowing us to pass parameters, the XsltArgumentList class also allows us to add extension objects to it. Once added to the XsltArgumentList class, the extension objects (that provide a specific functionality) can then be invoked from an XSL stylesheet. Alternatively, you can accomplish the same functionality by using embedded scripts in the XSL stylesheet. However, the XSLT extension approach provides a number of advantages over embedded script:

    • Better encapsulation by containing the code in reusable classes.
    • Code in the stylesheet is minimal, increasing the maintainability of the XSL stylesheet
    • Can also pass result tree fragments to the stylesheet with the use of the XPathNavigator object.

    Using the XSLT Extension object requires following these steps:

    • Add an extension object to the XsltArgumentList class using the AddExtensionObject
    • Add support in the XSL stylesheet to invoke the extension objects from the stylesheet
    • Pass the XsltArgumentList to the Transform method

    Now that the theory behind XSLT extension objects is covered, it's time to look at an example.

    Implementation

    Let us say, for instance, in our listing of products, we want to show each category in a different background color, meaning that a set of products that belong to one category will have the same background color. We can accomplish this using extension objects.

    We will name the class that determines the specific background color to be returned for a given category ID, BGColor. The BGColor is declared as follows.

    public class BGColor
    {
    	public string ReturnBGColor(int categoryID)
    	{
    		string bgColor=null;				
    
    switch (categoryID)
    		{
    			case (1):
    				bgColor = "#FFFFC0";
    				break;
    			case (2):
    				bgColor = "#80FF80";
    				break;
    			case (3):
    				bgColor = "#FFE0C0";
    				break;
    			case (4):
    				bgColor = "#C0C0FF";
    				break;
    			case (5):
    				bgColor = "#C0FFFF";
    				break;
    			case (6):
    				bgColor = "#FFC0FF";
    				break;
    			case (7):
    				bgColor = "#FFC0C0";
    				break;
    			case (8):
    				bgColor = "#C0FFC0";
    				break;				
    		}
    		return  (bgColor);
    	}
    }
    
    The code for the method ReturnBGColor is pretty straightforward, and it simply returns an appropriate background color based on the passed category ID.

    Now that we have seen the implementation of the BGColor, let us see how to invoke its ReturnBGColor method from the stylesheet. To accomplish this, add a new XSL stylesheet named xmlpaging3.xsl to the Web application. The stylesheet looks like the following:

    <?xml version="1.0" ?>
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:myColor="urn:myColor">
    <xsl:output method="html" />
    <!--Set the paging characteristics - number of records per page, page number and the record count-->
    <!-- Set the number of records per page-->
    <xsl:param name="recordsPerPage" select="77" />
    <!-- Page Number field -->
    <xsl:param name="pageNumber" select="0" />
    <!--Record Count Field-->
    <xsl:param name="recordCount" select="77" />
    <xsl:template match="/">
    <HTML>
    <HEAD>
    <TITLE> XSLT In .NET </TITLE>
    </HEAD>
    <BODY>
    	<span align="center" style="color:Blue;background-color:White;font-
    weight:bold;height:25px;width:634px;Z-INDEX: 102; LEFT: 203px; 
    POSITION: absolute; TOP: 69px"> This is a sample Application to illustrate 
    XSLT in .NET
    	</span>
    	<table style="Z-INDEX: 101; LEFT: 171px; WIDTH: 501px; POSITION: 
    absolute; TOP: 125px; HEIGHT: 322px" border="1" cellSpacing="1" 
    cellPadding="1">
    	<center>
    		<xsl:for-each select="//Products">
    		<!--this performs the output in table format - and shows 
    only that many records passed in the recordcount parameter -->
    		<xsl:if test="position() > $recordsPerPage * 
    number($pageNumber) and
    		position() <= number($recordsPerPage * number($pageNumber) +
    		$recordsPerPage)">
    		<!-- Each record on a seperate row -->
    		<xsl:element name="tr">
    			<xsl:attribute name="bgcolor">
    		         <xsl:value-of 
    select="myColor:ReturnBGColor(CategoryID)"/>
    			</xsl:attribute>
    		<xsl:element name="td">
    											
    			<xsl:value-of select="ProductID" />
    		</xsl:element>
    		<xsl:element name="td">
    			<xsl:value-of select="ProductName" />
    		</xsl:element>
    		<xsl:element name="td">
    			<xsl:attribute 
    name="align">center</xsl:attribute>
    			<xsl:value-of select="SupplierID" />
    		</xsl:element>
    		<xsl:element name="td">
    			<xsl:attribute 
    name="align">center</xsl:attribute>
    			<xsl:value-of select="CategoryID" />
    		</xsl:element>
    		<xsl:element name="td">
    			<xsl:attribute 
    name="align">center</xsl:attribute>
    			<xsl:value-of select="QuantityPerUnit" />
    		</xsl:element>
    	</xsl:element>
    	</xsl:if>
    	</xsl:for-each>
    	</center>
    	</table>
    	<!-- Start Of Show previous/next page links-->
    	<!-- Show the previous page, only if pageNumber>0  -->
    	<span style="Z-INDEX: 101; LEFT: 261px; WIDTH: 501px; POSITION: 
    absolute; TOP: 500px; HEIGHT: 62px">
    		<xsl:if test="$pageNumber > 0">
    			<xsl:element name="a">
    				<xsl:attribute 
    name="href">?pagenumber=<xsl:value-
    of select="number($pageNumber)-1" />
    				</xsl:attribute>
    				<< Previous Page 
    			</xsl:element>		        
    		</xsl:if>
    		<!-- Next page, do not show when at end() of listing -->
    		<xsl:if test="($recordCount - ((1+number($pageNumber)) * 
    $recordsPerPage))> 0">
    			<xsl:element name="a">
    				<xsl:attribute 
    name="href">?pagenumber=<xsl:value-
    of select="number($pageNumber)+1" />
    				</xsl:attribute>
                                   Next page >>
    			</xsl:element>
    		</xsl:if>
    		<!-- End Of Show previous/next page links-->
    		</span>
    		</BODY>
    		</HTML>
    	</xsl:template>
    </xsl:stylesheet>
    
    The adjustments made to the stylesheet are minimal. To the xsl:stylesheet element, we add the attribute xmlns:myColor="urn:myColor". This associates a namespace URI for our extension object. It is shown below.
    <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:myColor="urn:myColor">
    
    Once we have the association between the object and the namespace URI in place, we then can invoke the methods of the object from the stylesheet as if it is part of the stylesheet.

    The following lines of code demonstrate this. When the TR element is being rendered, we add an attribute called bgcolor to it, and the value for this attribute is obtained from the ReturnBGColor method. As we have already seen, the ReturnBGColor takes a category ID as an argument and returns the backcolor as the return value. Since we have associated the bgcolor to the TR element, all the TD elements in that row use the same bgcolor.

    <xsl:element name="tr">
    	<xsl:attribute name="bgcolor">
            <xsl:value-of select="myColor:ReturnBGColor(CategoryID)"/>
    	</xsl:attribute>
    	<xsl:element name="td">
    		<xsl:value-of select="ProductID" />
    	</xsl:element>
    	<xsl:element name="td">
    		<xsl:value-of select="ProductName" />
    	</xsl:element>
    	<xsl:element name="td">
    		<xsl:attribute name="align">center</xsl:attribute>
    		<xsl:value-of select="SupplierID" />
    	</xsl:element>
    	<xsl:element name="td">
    		<xsl:attribute name="align">center</xsl:attribute>
    		<xsl:value-of select="CategoryID" />
    	</xsl:element>
    	<xsl:element name="td">
    		<xsl:attribute name="align">center</xsl:attribute>
    		<xsl:value-of select="QuantityPerUnit" />
    	</xsl:element>
    </xsl:element>
    
    Now we will turn our focus to the code required to pass the extension object to the stylesheet so that it can invoke the methods of the extension object. For this example, let us add a new Web form named XslTransformExample3.aspx and modify the code in the Page_Load event to the following:
    private void Page_Load(object sender, System.EventArgs e)
    {            		
    	//Retrieve the connection string from the web.config file
    	string connString = 
    System.Configuration.ConfigurationSettings.AppSettings["connectionString"];
    	SqlConnection sqlConn = new SqlConnection(connString);
    	//Open the connection to the database
    	sqlConn.Open();
    	//Instantiate the SqlCommand object and pass the query to be executed
    	SqlCommand sqlCommand = new SqlCommand
    ("Select * from Products for xml auto,elements",sqlConn); //Execute the query
    	XmlReader reader = sqlCommand.ExecuteXmlReader();			
    	//Associate the XmlReader object with the XPathDocument object
    	XPathDocument xpathDoc = new XPathDocument(reader);
    	//Close the connection to the database
    	sqlConn.Close();
    	XslTransform transform = new XslTransform();
    	//Load the XSL stylsheet into the XslTransform object
    	transform.Load(Server.MapPath("xmlpaging3.xsl"));
    	XsltArgumentList argsList = new XsltArgumentList();
    	//Retrieve the pageNumber from querystring
    	int pageNumber = Convert.ToInt32(Request.QueryString["pagenumber"]);
    	//Add the required parameters to the XsltArgumentList object
    	argsList.AddParam("recordsPerPage","",10);
    	argsList.AddParam("pageNumber","",pageNumber);			
    	argsList.AddParam("recordCount","",77);					
    	//Instantiate the object to be added to the XsltArgumentList object
    	BGColor obj = new BGColor();
    	//Add the Extension object to XsltArgumentList object
    	argsList.AddExtensionObject("urn:myColor",obj);
    	//Invoke the transform method, passing in the XsltArgumentList object
    	transform.Transform(xpathDoc,argsList,Response.Output);
    }
    

    In the above code, we start by retrieving the connection string from the web.config file. The web.config file contains the following entry to store the connection string.

    <appSettings>
    		<add key="connectionString" 
    value="server=localhost;database=northwind;uid=sa;pwd=thiru;">
    </add>
    	</appSettings>
    
    Once the connection string is retrieved into a local variable, we then pass it to the constructor of the SqlConnection object. Then we open the connection by invoking the Open method of the SqlConnection object.
    	SqlConnection sqlConn = new SqlConnection(connString);
    	//Open the connection to the database
    	sqlConn.Open();
    
    Here we create an instance of the SqlCommand object, passing in the SQL command to be executed and the SqlConnection object as arguments. We use the FOR XML clause in the SQL query to retrieve XML data directly from the database.
    	//Instantiate the SqlCommand object and pass the query to be executed
    SqlCommand sqlCommand = new SqlCommand("Select * from Products for xml 
    auto,elements",sqlConn);			
    
    Then we execute the SQL query by invoking the ExecuteXmlReader method of the SqlCommand object and assign the returned XML stream to an XmlReader object.
    	//Execute the query
    	XmlReader reader = sqlCommand.ExecuteXmlReader();			
    
    Now we load the XML data into an XPathDocument object by passing in the XmlReader object to the constructor of the XPathDocument object.
    	//Associate the XmlReader object with the XPathDocument object
    	XPathDocument xpathDoc = new XPathDocument(reader);
    	//Close the connection to the database
    	sqlConn.Close();
    
    Here we create an instance of the XslTransform object and then load the XSL stylesheet into an XslTransform object by invoking the Load method of the XslTransform object.
    						
    	XslTransform transform = new XslTransform();
    	//Load the XSL stylsheet into the XslTransform object
    	transform.Load(Server.MapPath("xmlpaging.xsl"));
    
    Then we create an instance of the XsltArgumentList.
    XsltArgumentList argsList = new XsltArgumentList();
    
    We then retrieve the value of the pagenumber that is passed in the query string.
    	//Retrieve the pageNumber from querystring
    	int pageNumber = Convert.ToInt32(Request.QueryString["pagenumber"]);
    
    After that we add all the parameters to the XsltArgumentList object by invoking the AddParam method.
    	//Add the required parameters to the XsltArgumentList object
    	argsList.AddParam("recordsPerPage","",10);
    	argsList.AddParam("pageNumber","",pageNumber);			
    	argsList.AddParam("recordCount","",77);	
    
    Now we create a new instance of the BGColor class as shown below.
    	BGColor obj = new BGColor();
    
    After creating an instance of the object, the next step is to add the instantiated object to the XsltArgumentList object.
    argsList.AddExtensionObject("urn:myColor",obj);
    
    Finally, we pass the instantiated object along with the rest of the parameters to the stylesheet using the following line of code.
    transform.Transform(xpathDoc,argsList,Response.Output);
    
    When you navigate to the above Web form using the browser, you will get an output that is somewhat similar to the following.

    The output above shows products that belong to the same category using the same background color. If you click on Next Page in the above screen, you will get the following output.

    Conclusion

    In this series of articles, we have discussed the implementation of a paging solution with XSL and XML using support provided by the .NET Framework. We have have also seen the procedures involved in declaring parameters in an XSL stylesheet and supply parameters to it using the XsltArgumentList class. Finally, we examined XSLT Extension objects and then discussed an example of XSLT Extension objects.

    I hope you find this article useful, and thanks for reading.

    About the Author

    Thiru has many years of experience in architecting, designing, developing and implementing applications using Object Oriented Application development methodologies. He also possesses a thorough understanding of software life cycle (design, development and testing).

    He is an expert with ASP.NET, .NET Framework, Visual C#.NET, Visual Basic.NET, ADO.NET, XML Web Services and .NET Remoting and holds MCAD for .NET, MCSD and MCP certifications.

    Thiru has authored numerous books and articles. He can be reached at thiruthangarathinam@yahoo.com.

  • Rate This Article
    Not HelpfulMost Helpful
    1 2 3 4 5
    Supporting Products/Tools
    Proposion N2N
    Proposion N2N connects Microsoft .NET applications to Lotus Notes and Lotus Domino databases. This ADO.NET managed data provider allows you to perform blindingly fast queries and updates of Notes data from ASP.NET pages, .NET web services, Windows, or Mobile applications. An innovative SQL-like query language leverages the unique features of Notes and makes collaborative software accessible to relational database programmers.
    [Top]
    Other Articles
    Apr 21, 2005 - Building a FAQ Module for the ASP.NET Community Starter Kit
    This sample chapter from Packt Publishing's "Building Websites with the ASP.NET Community Starter Kit" illustrates how to build a new module on top of the existing code in the ASP.NET Community Starter Kit (CSK). Using a Frequently Asked Questions (FAQ) module as an example, it shows how creating a new module allows you to add entirely new features which integrate seamlessly with the rest of the framework.
    [Read This Article]  [Top]
    Oct 20, 2004 - Beyond the DataGrid: An Architectural View of the Data Source Model in ASP.NET 1.x and 2.0
    Dino Esposito discusses the differences between the DataGrid control in version 1.x and 2.0 of ASP.NET. In the process, he also builds an improved version of the 1.x control that can get you some of the new 2.0 features today.
    [Read This Article]  [Top]
    Aug 25, 2004 - Developing Web Parts with the ICellProvider Interface
    Most default SharePoint Server Web Parts can be connected across organizations. The second article in this series shows how to develop connectable Web Parts that provide information to other Web Parts.
    [Read This Article]  [Top]
    Aug 4, 2004 - Accessibility Improvements in ASP.NET 2.0 - Part 2
    Alex Homer continues to highlight some of the new ASP.NET 2.0 accessibility features. These features make it easier for visually impaired users to view and navigate Web sites and provide better support for alternative types of browsers and user agents.
    [Read This Article]  [Top]
    Jul 30, 2004 - Connectable Web Parts in SharePoint Portal Server 2003 - Part 1
    Most default SharePoint Server Web Parts can be connected across organizations. The first article in this series explains how to connect existing Web Parts using the connection Interface classes in the SharePoint architecture.
    [Read This Article]  [Top]
    Jul 27, 2004 - Accessibility Improvements in ASP.NET 2.0 - Part 1
    Alex Homer highlights some of the new ASP.NET 2.0 accessibility features. These features make it easier for visually impaired users to view and navigate Web sites and provide better support for alternative types of browsers and user agents.
    [Read This Article]  [Top]
    Jun 30, 2004 - Simplified and Extended Data Binding Syntax in ASP.NET 2.0
    Alex Homer discusses the simplification of, and extensions to, the ASP.NET 1.x data binding syntax, the new two-way data binding syntax for updating data sources, and the new syntax for binding to XML data in ASP.NET 2.0.
    [Read This Article]  [Top]
    May 18, 2004 - ASP.NET 2.0 Caching Features
    This article examines some of the new and exciting caching features in ASP.NET 2.0 and shows how to implement them in Web applications.
    [Read This Article]  [Top]
    May 11, 2004 - SharePoint Security and .NET Impersonation
    When implementing custom components that require access to restricted resources, implicit impersonation must be used. Jay Nathan shows how to create a class that makes using .NET Impersonation a snap.
    [Read This Article]  [Top]
    May 4, 2004 - Creating a Flexible Configuration Section Handler
    Jeff Gonzalez demonstrates how to create a flexible configuration section handler using C#. He provides a summary background of the .NET configuration system, explains why the system is useful, and shows how it can be extended.
    [Read This Article]  [Top]
    Mailing List
    Want to receive email when the next article is published? Just Click Here to sign up.

    Support the Active Server Industry

    internet.commediabistro.comJusttechjobs.comGraphics.com

    Search:

    WebMediaBrands Corporate Info

    Legal Notices, Licensing, Reprints, Permissions, Privacy Policy.
    Advertise | Newsletters | Shopping | E-mail Offers | Freelance Jobs