SQL XML output to populate a treeview

In this post I will show how to populate an asp.net tree view from the output of sql stored procedure. The table looks like this:

pageid pagename parentid

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

1 N1 0

3 N4 1

4 N10 3

5 N7 3

SET ANSI_NULLS ON 
SET QUOTED_IDENTIFIER ON 
GO
ALTER PROCEDURE [DBO].[gentree]
AS
  BEGIN
    SET NOCOUNT ON;
    WITH TREE
         AS (SELECT CAST(1 AS INT) AS LEVEL,
                    PAGEID,
                    PAGENAME,
                    CAST(RIGHT(' '
                                 + CONVERT(VARCHAR(11),PAGEID),11) AS VARCHAR(120)) AS HIERARCHY
             FROM   PAGE
             WHERE  PARENTID = '0'
             UNION ALL
             SELECT LEVEL
                      + 1,
                    B.PAGEID,
                    B.PAGENAME,
                    CAST(A.HIERARCHY
                           + '/'
                           + RIGHT(' '
                                     + CONVERT(VARCHAR(11),B.PAGEID),11) AS VARCHAR(120))
             FROM   TREE A
                    JOIN PAGE B
                      ON A.PAGEID = B.PARENTID),
         SEQTREE
         AS (SELECT LEVEL,
                    Row_number()
                      OVER(ORDER BY HIERARCHY) AS SEQ,
                    PAGEID,
                    PAGENAME,
                    HIERARCHY
             FROM   TREE)
    SELECT '<Root>'
             + REPLACE(REPLACE((SELECT   '`tree id="'
                                           + CONVERT(VARCHAR(11),A.PAGEID)
                                           + '" PageName="'
                                           + A.PAGENAME
                                           + '" ~'
                                           + CASE
                                               WHEN A.LEVEL < Isnull(B.LEVEL,1) THEN ''
                                               ELSE Replicate('`/tree~',1
                                                                          + A.LEVEL
                                                                          - Isnull(B.LEVEL,1))
                                             END
                                FROM     SEQTREE A
                                         LEFT JOIN SEQTREE B
                                           ON A.SEQ
                                                + 1 = B.SEQ
                                ORDER BY A.SEQ
                                for xml path('')
                                                               
                               ),'`','<'),'~','>')
             + '</Root>' AS MYXML
  END
  --exec [GenTree]

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <div>
           <asp:TreeView ID="TreeView1" runat="server" DataSourceID="XmlDataSource1" ExpandDepth="0">
               <DataBindings>
                   <asp:TreeNodeBinding DataMember="tree" TextField="PageName" ValueField="id" />
               </DataBindings>
           </asp:TreeView>
           <asp:XmlDataSource ID="XmlDataSource1" runat="server" OnLoad="XmlDataSource1_Load"
               XPath="Root/tree"></asp:XmlDataSource>
       </div>
   </form>


</body>
</html>

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;
using System.Data.SqlClient;

public partial class Default2 : System.Web.UI.Page
{
   protected void Page_Load(object sender, EventArgs e)
   {

   }
   protected void XmlDataSource1_Load(object sender, EventArgs e)
   {
       if (!Page.IsPostBack)
       {

           SqlConnection SqlCon = new SqlConnection("server=(local);database=CMMForStarters;uid=sa;pwd=12345");

           SqlCon.Open();

           SqlCommand SqlCmd = new SqlCommand("GenTree", SqlCon);

           SqlCmd.CommandType = CommandType.StoredProcedure;

           SqlDataReader SqlDrr = SqlCmd.ExecuteReader();

           if (SqlDrr.Read())
           {

               XmlDataSource1.Data = SqlDrr.GetString(0);

           }

           SqlDrr.Close();

           SqlCon.Close();

           SqlCmd.Dispose();

           SqlCon.Dispose();
       }

   }

}

How To Add Session Timeout Popup in asp.net

If you need to alert a user that his session will time out. This is how to do it. Add the following code snippet to the OnInit method on the base page of your application.
protected override void OnInit(EventArgs e)
   {
       base.OnInit(e);
       string script = "window.setTimeout(\"alert('Your session expired!');\", " + (Session.Timeout - 1) * 60000 + ")";
       this.Page.ClientScript.RegisterStartupScript(this.GetType(), "SessionManager", "<script language=\"javascript\">" + script + "</script>");
   }

AdRotator control and Database


The AdRotator control reads advertisement information from a data source, which contains one or more ad records. You can store ad information in a database table with a specific schema, and then use a data source control to read the ad records at run time. If you have an existing table with ad information, you can map the schema of your table to the fields that are required by the AdRotator control.
You can store ad information in any type of database, as long as you have the corresponding data source control for that database.

To create the database table for ads

1. If you do not already have a database table that contains the ad information, create a table with the following schema. All columns except ID are optional.
Data types are provided as SQL Server types. If you are using a different database, substitute the appropriate corresponding type.
Column name
Data type
Description
ID int Primary key. This column can have any name.
ImageUrl nvarchar(length) The relative or absolute URL of the image to display for the ad.
NavigateUrl nvarchar(length) The target URL for the ad. If you do not provide a value, the ad is not a hyperlink.
AlternateText nvarchar(length) The text displayed if the image cannot be found. In some browsers, the text is displayed as a ToolTip. Alternate text is also used for accessibility so that users who cannot see the graphic can hear its description read out loud.
Keyword nvarchar(length) A category for the ad on which the page can filter.
Impressions int(4) A number that indicates the likelihood of how often the ad is displayed. The larger the number, the more often the ad will be displayed. The total of all impressions values in the XML file may not exceed 2,048,000,000 - 1.
Width int(4) The width of the image in pixels.
Height int(4) The height of the image in pixels.
2. If you have an existing database table with ad information in it, set the following properties of the AdRotator control to map your database table schema to the fields required by the control:
3. Insert new records into the table with ad information.



<%@ Page Language="C#" AutoEventWireup="true" CodeFile="AddRotator.aspx.cs" Inherits="AddRotator" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManger1" runat="Server">
    </asp:ScriptManager>
    <div>
        <asp:Timer runat="server" Interval="10000" ID="SlideShowTimer" OnTick="SlideShowTimer_Tick" />
        <asp:UpdatePanel runat="server" ID="SlideShow" UpdateMode="Conditional">
            <ContentTemplate>
                <asp:Image runat="Server" ID="SlideShowImage1" ImageUrl="" Width="100%" Height="150px" />
                <asp:AdRotator ID="AdRotator1" runat="Server" />
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="SlideShowTimer" EventName="Tick" />
            </Triggers>
        </asp:UpdatePanel>
        <cc1:UpdatePanelAnimationExtender runat="server" ID="UPextender" TargetControlID="SlideShow"
            BehaviorID="animation">
            <Animations>
      <OnUpdating>
           <%-- It should take 1/2 of a second to fade out --%>
           <FadeOut Duration=".5" Fps="20" minimumOpacity=".1" />
       </OnUpdating>
       <OnUpdated>
           <%-- It should take 1 and 1/2 of a second to fade back in --%>
           <FadeIn Duration="1.5" Fps="20" minimumOpacity=".1" />
       </OnUpdated>
            </Animations>
        </cc1:UpdatePanelAnimationExtender>
    </div>
    </form>
</body>
</html>


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;
using System.Data.SqlClient;
public partial class AddRotator : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {

            AdRotator1.DataSource = FetchAdsFromDB();
            AdRotator1.DataBind();

        }
    }
    protected void SlideShowTimer_Tick(object sender, EventArgs e)
    {
        AdRotator1.DataSource = FetchAdsFromDB();
        AdRotator1.DataBind();

    }
    private DataTable FetchAdsFromDB()
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection("Your Connection String");
        SqlDataAdapter da = new SqlDataAdapter("select AlternateText,ImageUrl,NavigateUrl,Impressions  from [add]", con);
        da.Fill(dt);
        return dt;
    }
}

How To Create Slideshow using UpdatePanel and Timer

In this Post i will show how to create Slideshow using UpdatePanel and Timer Control
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
       <asp:ScriptManager ID="ScriptManager1" runat="server" />
       <div>
           <asp:Timer runat="server" Interval="10000" ID="SlideShowTimer" OnTick="SlideShowTimer_Tick" />
           <br />
           <h2 style="text-transform: uppercase; margin: 10px 0px 0px 8px; display: inline;">
               Welcome to My Photo Gallery
           </h2>
           <br />
           <asp:UpdatePanel runat="server" ID="SlideShow" UpdateMode="Always">
               <ContentTemplate>
                   <%-- This is the main slideshow image control --%>
                   <img runat="server" id="SlideShowImage1" src="~/Images/1.jpg" alt="First Image" />
                   <asp:Label runat="server" ID="SlideShowText" Text="First Slide" />
               </ContentTemplate>
               <Triggers>
                   <%-- The update panel will postback when the timer 'tick' event fires --%>
                   <asp:AsyncPostBackTrigger ControlID="SlideShowTimer" EventName="Tick" />
               </Triggers>
           </asp:UpdatePanel>
           <cc1:UpdatePanelAnimationExtender runat="server" ID="UPextender" TargetControlID="SlideShow"
               BehaviorID="animation">
               <Animations>

      <OnUpdating>

           <%-- It should take 1/2 of a second to fade out --%>

           <FadeOut Duration=".5" Fps="20" minimumOpacity=".1" />

       </OnUpdating>

       <OnUpdated>

           <%-- It should take 1 and 1/2 of a second to fade back in --%>

           <FadeIn Duration="1.5" Fps="20" minimumOpacity=".1" />

       </OnUpdated>

               </Animations>
           </cc1:UpdatePanelAnimationExtender>
       </div>
   </form>
</body>
</html>
• The script manager is required on the page for the AJAX extensions to work correctly. • The timer control raises the "tick" event every 10 seconds. • The Update panel updateMode is set to always. This means that anytime any item on the page raises a postback event, the update panel will update itself. The Update panel also contains an img and label in its content template. There is also a Trigger section that registers the timers "tick" event as a trigger for the update panel to update. • The Update panel animation extender exists to handle the desired fade out / fade in effect. The update panel animation extender section contains animation specific xml. Read the animation reference and walkthrough. My specific animation is set to fade to an opacity of .1 over a period of .5 seconds. And then when it fades back in, it will start at .1 opacity, and take 1.5 seconds to return to full opcaity. SlideShowTimer_Tick event handler: The timer control fires this event every 10 seconds. As you can see, the event handler creates a DateTime stamp 1/2 second from when the event is fired. This is use to create a delay of half a second, so that the update panel animation can finish it's FadeOut animation before we change the image. After the .5 second delay is completed, we get a random image name from the RandomImageName() method. We then set the text of the image caption to be the name of the new image file. RandomImageName() method: This is a private method that returns a string value. We create an instance of the System.Random class. We then limit the random integer to be a number between 1 and 5, since we are only working with 6 images in the slideshow.
using System;
using System.Data;
using System.Configuration;
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 _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void SlideShowTimer_Tick(object sender, EventArgs e)
    {
        DateTime later = DateTime.Now.AddSeconds(.5);
        while (DateTime.Now < later)
        {

        }

        this.SlideShowImage1.Src = RandomImageName();
        this.SlideShowText.Text = this.SlideShowImage1.Src.ToString();

    }
    private string RandomImageName()
    {

        Random rand = new Random();

        int RandomInt = rand.Next(0, 5);

        switch (RandomInt)
        {

            case 0:
                return "~/Images/1.jpg";
                break;
            case 1:
                return "~/Images/2.jpg";
                break;
            case 2:
                return "~/Images/3.jpg";
                break;
            default:
                return "~/Images/1.jpg";
                break;

        }


    }
}