ASP.NET Tutorial/Development/Trace

Материал из .Net Framework эксперт
Версия от 11:56, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Enable trace in Web.config

File: web.config
<configuration>
   <system.web>
      <trace enabled="true"/>
   </system.web>
</configuration>


Enabling Page Level Tracing

<%@ Page Language="C#" Trace="true" %>
<script runat="server">
    private void Page_Load(Object Source, EventArgs E)
    {
        Trace.Write("Page_Load", "Declaring and initializing variables.");
        int _A = 10;
        int _B = 20;
        
        Trace.Write("Page_Load", "Applying add operation.");
        _A += _B;
        
        Trace.Write("Page_Load", "Variable values changed.");
        Trace.Write("_A", _A.ToString());
        Trace.Write("_B", _B.ToString());
    }        
</script>
<html>
<head>
<title>Enabling Page Level Tracing</title>
</head>
<body>
    <form runat="server">
        <!-- Insert content here -->
    </form>
</body>
</html>


Set Page.Trace.IsEnabled to true (C#)

File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="SimpleTrace" %>
<!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">
</head>
<body>
    <form id="form1" runat="server">
    <div>
        A Simple Tracing Example<br />
        <br />
        <asp:Button ID="cmdTrace" runat="server" OnClick="cmdTrace_Click" Text="Trace" /></div>
    </form>
</body>
</html>

File: Default.aspx.cs
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;
public partial class SimpleTrace : System.Web.UI.Page
{
    protected void cmdTrace_Click(object sender, EventArgs e)
    {
        Page.Trace.IsEnabled = true;
        Session["TestString"] = "This is just a string.";
        Session["MyDataSet"] = new DataSet();
    }
}


Trace.IsEnabled

<%@ Page Language="vb" %>
<html>
   <head>
      <title></title>
      <script runat="server">
         Sub Page_Load()
            If Trace.IsEnabled = True Then
               Message.Text = "Tracing is enabled."
            Else
               Message.Text = "Tracing is not enabled."
            End If
         End Sub
      </script>
   </head>
<body>
   <asp:label id="Message" runat="server"/>
</body>
</html>


Trace to a file

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="Tracing" %>
<!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">
    <div>
    <h2>Logging trace output to <asp:Literal runat="server" Text="<%$ appSettings:traceFile %>" /></h2>
    </div>
    </form>
</body>
</html>
File: Default.aspx.cs
using System;
using System.IO;
using System.Web;
using System.Configuration;
public partial class Tracing : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Trace.TraceFinished += Trace_Finished;
        Trace.Write("Using Page Trace", "Subscribed to TraceFinished event");
    }
    void Trace_Finished(Object sender, TraceContextEventArgs e)
    {
        string traceFile = ConfigurationManager.AppSettings["traceFile"];
        using (StreamWriter w = File.AppendText(traceFile))
        {
            int i = 0;
            foreach (TraceContextRecord r in e.TraceRecords)
                w.WriteLine("{0}) {1}:{2}", ++i, r.Category, r.Message);
        }
    }
}
File: Web.config
<?xml version="1.0"?>
<configuration>
  <appSettings>
    <add key="traceFile" value="c:\temp\trace_log.txt"/>
  </appSettings>
  <system.web>
    <compilation debug="true"/>
    <trace enabled="true" pageOutput="false" localOnly="true" />
  </system.web>
</configuration>


Use Trace.Write to write message (C#)

File: Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="TraceExample" Trace="true" %>
<!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">
    <div>
        <asp:Button ID="cmdWrite" runat="server" OnClick="cmdWrite_Click" Text="Write" />
        <asp:Button ID="cmdWriteCategory" runat="server" OnClick="cmdWriteCategory_Click"
            Text="Write Category" />
        <asp:Button ID="cmdError" runat="server" OnClick="cmdError_Click" Text="Write Error" />
    
    </div>
    </form>
</body>
</html>

File: Default.aspx.cs
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;
public partial class TraceExample : System.Web.UI.Page
{
    protected void cmdError_Click(object sender, EventArgs e)
    {
        try
        {
            DivideNumbers(5, 0);
        }
        catch (Exception err)
        {
            Trace.Warn("cmdError_Click", "Caught Error", err);
        }
    }
    protected void cmdWrite_Click(object sender, EventArgs e)
    {
        Trace.Write("About to place an item in session state.");
        Session["Test"] = "Contents";
        Trace.Write("Placed item in session state.");
    }
    protected void cmdWriteCategory_Click(object sender, EventArgs e)
    {
        Trace.Write("Page_Load", "About to place an item in session state.");
        Session["Test"] = "Contents";
        Trace.Write("Page_Load", "Placed item in session state.");
    }
    private decimal DivideNumbers(decimal number, decimal divisor)
    {
        return number / divisor;
    }
}


Write warning message with Trace.Warn

<%@ Page Language="VB" Trace="true"%>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.OleDb" %>
<script language="VB" runat="server">
   sub Page_Load(Sender as Object, e as EventArgs) 
      Trace.Warn("Custom", "Page loading...")
      if not Page.IsPostBack then
         Trace.Warn("Custom", "No post")
         CreateData()
      end if
   end sub
   
   sub CreateData
      dim source as DataView
      source = Cache("DataView")
      
      if source is nothing then
         dim strConnString as string = "PROVIDER=Microsoft.Jet.OLEDB.4.0;" _
            & "DATA SOURCE=" _
            & Server.MapPath("EmployeeDatabase.mdb;")
      
         Trace.Warn("Custom", "Creating OleDbDataAdapter...")
         dim objCmd as OleDbDataAdapter = new _
            OleDbDataAdapter("select * from employee", _
            strConnString)
         Trace.Warn("Custom", "SQL value: " & _
            objCmd.SelectCommand.rumandText)
         dim ds as DataSet = new DataSet()
         objCmd.Fill(ds, "employee")
         
         source = new DataView(ds.Tables(0))
         Trace.Warn("Custom", "Inserting into cache...")
         Cache.Insert("DataView", source)
      
         lblMessage.Text = "Data set created explicitly"
      else
         lblMessage.Text = "Data set retrieved from " & _
            "cache<br>"
      end if
      Trace.Warn("Custom", "Binding data...")
      dgData.DataSource = source
      dgData.DataBind()
   end sub
   
   sub ExpireCache(Sender as Object, e as EventArgs)
      Trace.Warn("Custom", _
         "Removing from cache, call CreateData")
      dim dv as dataview = Cache.Remove("DataView")
      CreateData()
   end sub
</script>
<html><body>
   <form runat="server">
      <asp:Label id="lblMessage" runat="server"
         maintainState=false/>
      <asp:Button id="btSubmit" runat="server"
         text="Expire Cache"
         OnClick="ExpireCache"/>
      <asp:DataGrid id="dgData" runat="server" 
         BorderColor="black" GridLines="Vertical" 
         cellpadding="4" cellspacing="0" 
         width="450" Font-Name="Arial" 
         Font-Size="8pt" 
         />
   </form>
</body></html>
File: web.config
<configuration>
   <system.web>
      <trace enabled="true"/>
   </system.web>
</configuration>