Monday, August 3, 2009

Tree View With Check Box

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">

    protected void btnSubscribe_Click(object sender, EventArgs e)
    {
        foreach (TreeNode node in TreeView1.CheckedNodes)
            bltSubscribed.Items.Add(node.Text);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>TreeView CheckBoxes</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    Select the Newsgroups which you 
    would like to join: 
    
    <br />
    
    <asp:TreeView
        id="TreeView1"
        ShowCheckBoxes="Root"
        Runat="server">
        <Nodes>
        <asp:TreeNode
            Text="Programming">
            <asp:TreeNode Text="ASP.NET" />
            <asp:TreeNode Text="JAVA" />
            <asp:TreeNode Text="Cold Fusion" />
        </asp:TreeNode>
        <asp:TreeNode
            Text="Sports">
            <asp:TreeNode Text="Baseball" />
            <asp:TreeNode Text="Hockey" />
            <asp:TreeNode Text="Football" />
        </asp:TreeNode>        
        </Nodes>
    </asp:TreeView>    
    
    <br />
    
    <asp:Button
        id="btnSubscribe"
        Text="Subscribe"
        OnClick="btnSubscribe_Click"
        Runat="server" />
    
    <hr />
    
    You selected:
    
    <asp:BulletedList
        id="bltSubscribed"
        EnableViewState="false"
        Runat="server" />
    
    </div>
    </form>
</body>
</html>


Source ASP.NET Unleased 3.5 Book

TreeView Sample

TreeView Sample

<%@ Page Language="C#" %>
<!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 id="Head1" runat="server">
    <title>TreeView Declare</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:TreeView
        id="TreeView1"
        Runat="server">
        <Nodes>
        <asp:TreeNode
            Text="Home"
            NavigateUrl="~/Default.aspx">
            <asp:TreeNode
                Text="Products">
                <asp:TreeNode
                    Text="First Product"
                    NavigateUrl="~/Products/FirstProduct.aspx" />
                <asp:TreeNode
                    Text="Second Product"
                    NavigateUrl="~/Products/SecondProduct.aspx" />
            </asp:TreeNode>
            <asp:TreeNode
                Text="Services">
                <asp:TreeNode
                    Text="First Service"
                    NavigateUrl="~/Services/FirstService.aspx" />
                <asp:TreeNode
                    Text="Second Service"
                    NavigateUrl="~/Services/SecondService.aspx" />
            </asp:TreeNode>    
        </asp:TreeNode>    
        </Nodes>
    </asp:TreeView>    
    
    
    </div>
    </form>
</body>
</html>


Source ASP.NET Unleased 3.5 Book

Menu From Database

Menu From Database

Tabel Categories

CategoryIDparentIDname
1NULLBeverages
2NULLFruit
31Milk
41Juice
54Applice Juice
64orage Juice
72Apples
82pears




<%@ Page Language="C#" %>
<%@ Import Namespace="System.Web.Configuration" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">
   

    /// <summary>
    /// Only populate the menu when the page first loads
    /// </summary>
    void Page_Load()
    {
        if (!Page.IsPostBack)
            PopulateMenu();
    }

    /// <summary>
    /// Get the data from the database and create the top-level
    /// menu items
    /// </summary>
    private void PopulateMenu()
    {
        DataTable menuData = GetMenuData();
        AddTopMenuItems(menuData);
    }
    
    /// <summary>
    /// Use a DataAdapter and DataTable to grab the database data
    /// </summary>
    /// <returns></returns>
    private DataTable GetMenuData()    
    {
        // Get Categories table
        string selectCommand = "SELECT CategoryId,ParentId,Name FROM Categories";
        string conString = WebConfigurationManager.ConnectionStrings["Categories"].ConnectionString;
        SqlDataAdapter dad = new SqlDataAdapter(selectCommand, conString);
        DataTable dtblCategories = new DataTable();
        dad.Fill(dtblCategories);
        return dtblCategories;
    }

    /// <summary>
    /// Filter the data to get only the rows that have a
    /// null ParentID (these are the top-level menu items)
    /// </summary>
    private void AddTopMenuItems(DataTable menuData)
    {
        DataView view = new DataView(menuData);
        view.RowFilter = "ParentID IS NULL";
        foreach (DataRowView row in view)
        {
            MenuItem newMenuItem = new MenuItem(row["Name"].ToString(), row["CategoryId"].ToString());
            Menu1.Items.Add(newMenuItem);
            AddChildMenuItems(menuData, newMenuItem);
        }

    }

    /// <summary>
    /// Recursively add child menu items by filtering by ParentID
    /// </summary>
    private void AddChildMenuItems(DataTable menuData, MenuItem parentMenuItem)
    {
        DataView view = new DataView(menuData);
        view.RowFilter = "ParentID=" + parentMenuItem.Value;
        foreach (DataRowView row in view)
        {
            MenuItem newMenuItem = new MenuItem(row["Name"].ToString(), row["CategoryId"].ToString());
            parentMenuItem.ChildItems.Add(newMenuItem);
            AddChildMenuItems(menuData, newMenuItem);
        }
    }
    
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
        .menuItem
        {
            border:Solid 1px black;
            width:100px;
            padding:2px;
            background-color:#eeeeee;
        }
        .menuItem a
        {
            color:blue;
        }
        .grid
        {
            margin-top:10px;
        }
        
        .grid td, .grid th
        {
            padding:10px;
        }
    </style>
    <title>Menu Database</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:Menu
        id="Menu1"
        Orientation="horizontal"
        StaticMenuItemStyle-CssClass="menuItem"
        DynamicMenuItemStyle-CssClass="menuItem"
        Runat="server" />

          
    
    
    </div>
    </form>
</body>
</html>

Source ASP.NET Unleased 3.5 Book


Menu with MultiView

Menu with MultiView

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<script runat="server">

    protected void menuTabs_MenuItemClick(object sender, MenuEventArgs e)
    {
        multiTabs.ActiveViewIndex = Int32.Parse(menuTabs.SelectedValue);
    }
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <style type="text/css">
        html
        {
            background-color:silver;
        }
        .menuTabs
        {
            position:relative;
            top:1px;
            left:10px;
        }
        .tab
        {
            border:Solid 1px black;
            border-bottom:none;
            padding:0px 10px;
            background-color:#eeeeee;
        }
        .selectedTab
        {
            border:Solid 1px black;
            border-bottom:Solid 1px white;
            padding:0px 10px;
            background-color:white;
        }
        .tabBody
        {
            border:Solid 1px black;
            padding:20px;
            background-color:white;
        }
    </style>
    <title>Menu Tab Strip</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
    <asp:Menu
        id="menuTabs"
        CssClass="menuTabs"
        StaticMenuItemStyle-CssClass="tab"
        StaticSelectedStyle-CssClass="selectedTab"
        Orientation="Horizontal"
        OnMenuItemClick="menuTabs_MenuItemClick"
        Runat="server">
        <Items>
        <asp:MenuItem
            Text="Tab 1"
            Value="0" 
            Selected="true" />
        <asp:MenuItem
            Text="Tab 2" 
            Value="1"/>
        <asp:MenuItem
            Text="Tab 3"
            Value="2" />
            
        </Items>
    </asp:Menu>    
    
    
    <div class="tabBody">
    <asp:MultiView
        id="multiTabs"
        ActiveViewIndex="0"
        Runat="server">
        <asp:View ID="view1" runat="server">
        
        Contents of first tab
        
        </asp:View>
        <asp:View ID="view2" runat="server">
        
        Contents of second tab
        
        </asp:View>
        <asp:View ID="view3" runat="server">
        
        Contents of third tab
        
        </asp:View>
    </asp:MultiView>    
    </div>
    
    </div>
    </form>
</body>
</html>

Source ASP.NET Unlease 3.5 Book

Simple Menu Example

A Simple Menu EG :-
<%@ Page Language="C#" %>
<!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 id="Head1" runat="server">
<title>Menu SiteMap</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Menu
id="Menu1"
DataSourceID="srcSiteMap"
Runat="server" />
<asp:SiteMapDataSource
id="srcSiteMap"
Runat="server" />
</div>
</form>
</body>
</html>


Config for above SiteMap
Create an web.sitemap as give below

<?xml version="1.0" encoding="utf-8" ?>
<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode
url="~/Default.aspx"
title="Home"
description="The home page of the Website">

<!-- SiteMapPath Nodes -->
<siteMapNode
title="Using the SiteMapPath Control"
description="Sample code for the SiteMapPath Control">
<siteMapNode
url="~/UsingSiteMapPath/DisplaySiteMapPath.aspx"
title="Displaying a SiteMapPath"
description="Sample code for displaying a SiteMapPath" />
<siteMapNode
url="~/UsingSiteMapPath/SiteMapPathStyle.aspx"
title="Using SiteMapPath Styles"
description="Sample code for using styles with SiteMapPath" />
<siteMapNode
url="~/UsingSiteMapPath/SiteMapPathTemplates.aspx"
title="Using SiteMapPath Templates"
description="Sample code for using templates with SiteMapPath" />
</siteMapNode>

<!-- Menu Nodes -->
<siteMapNode
title="Using the Menu Control"
description="Sample code for the Menu control">
<siteMapNode
url="~/UsingMenu/MenuSiteMap.aspx"
title="Displaying a Menu"
description="Sample code for displaying a Menu" />
</siteMapNode>

<!-- TreeView Nodes -->
<siteMapNode
title="Using the TreeView Control"
description="Sample code for the TreeView control">
<siteMapNode
url="~/UsingTreeView/TreeViewSiteMap.aspx"
title="Displaying a TreeView"
description="Sample code for displaying a TreeView" />
</siteMapNode>

</siteMapNode>

</siteMap>



Source ASP.NET Unleashed book 3.5

Wednesday, July 15, 2009

Log File


In this article, we will adopt a simple mechanism to log errors and exceptions in website,
The error will get logged in a text file on the server.
The error file will be created on a daily basis, whenever the error is encountered

Public Shared Sub WriteErrorLog(ByVal errorMessage As String, ByVal errorStack As String, ByVal methodName As String)
Dim path As String = "~/LOG/" & DateTime.Today.ToString("dd-MM-yy") & ".txt"
If (Not File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) Then
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close()
End If
Using w As StreamWriter = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))
w.WriteLine(Constants.vbCrLf & "Log DateTime : " & DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture))
w.WriteLine("Page :- " & System.Web.HttpContext.Current.Request.Url.AbsolutePath.ToString.Trim)
w.WriteLine("Function Name :- " & methodName)
w.WriteLine("Message :- " & errorMessage)
w.WriteLine("Stack Trace :- " & errorStack)
w.WriteLine("__________________________")
w.Flush()
w.Close()
End Using
End Sub
Protected Sub btnTest_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Try
Dim i As Integer = 1
Dim j As Integer = 0
Response.Write(i \ j)
Catch ex As Exception
WriteErrorLog(ex.Message, ex.StackTrace.ToString.Trim, ex.TargetSite.Name)
End Try
End Sub

OutPut
__________________________

Log DateTime : 07/15/2009 15:25:20
Page :- /Default.aspx
Function Name :- btnTest_Click
Message :- Attempted to divide by zero.
Stack Trace :- at Default.aspx.btnTest_Click(Object sender, EventArgs e) in D:\Test\Default.aspx.vb:line 107
__________________________


Same thing you can do in Globa.asax, at Application_Error event. You can get an Server last error by Server.GetLastError()

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs when an unhandled error occurs
Dim objErr As Exception = Server.GetLastError().GetBaseException()

'Function Name not be correct at application level error
WriteErrorLog(objErr .Message, objErr .StackTrace.ToString.Trim, "")

'IF you want you can redirect to user after log into log file here
' Response.Redirect("Error.aspx")
End Sub

Tuesday, July 14, 2009

Showing Total in GridView

'Declare Variable
Dim Total As Double


Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As GridViewRowEventArgs)
Select Case e.Row.RowType
Case DataControlRowType.DataRow, ListItemType.Item
'Calculate total for the field of each row and alternating row, Cell number change according to your field place
Total += CDbl(e.Row.Cells(0).Text)
Case DataControlRowType.Footer
'Use the footer to display the summary row.
e.Row.Cells(0).Text = Total.ToString("#,###.00")
End Select
End Sub