E:\web\learnaspcom\htdocs\freebook\learn\ubtoc.xml LearnAsp.com - ASP ASP.net Free Lessons
Search Search

#1 worldwide
FREE Coding Lessons

since 1996
   THE BEST WAY to learn ASP & Asp.net!
Advertise Here!
click for details
Credits Host:
DiscountASP.net
Server Admin:
The "Team"
Contact Info.
Charles M. Carroll
<Asp.net blog>
<personal site>
xxx

C# Log4Net Sample
by Charles M. Carroll

Log4Net is a great logging library that is multi-platform (Java, PHP, C++, plSQL, etc). It has many conveniences but the ones that caught my attention are:

  • The ability to change the logging destination with a configuration change at runtime, and for multiple logging destinations.
  • The well behaved fact that errors in the logging library/configuration never bubble to the application.
  • The extensibility by design of Log4net

Here are the core links:
This page demonstrates Log4Net in action

   filename=/experiments/log4net/writefilesfromdb.aspx

<Test Script Below>


<%@ trace="true" tracemode="SortByTime"%>
<%@ import namespace = "System.Data.OleDb" %> 
<%@ Import Namespace="System.Configuration" %> 
<%@ Import Namespace="log4net" %> 
<%@ Import Namespace="log4net.Config" %>
<script language="C#" runat="server"> 

protected void Page_Load(Object S,EventArgs E)
{

    log4net.ILog Log = log4net.LogManager.GetLogger("WriteFilesFromDB.aspx");
    /*
        log4net.Config.BasicConfigurator.Configure();
        the ABOVE line does not work so had to replace with
        log4net.Config.DOMConfigurator.Configure();
    */
    log4net.Config.DOMConfigurator.Configure();

    OleDbDataReader reader1=null;
    OleDbConnection conn=null;
    string strSQL="";
    StringBuilder sbTemp=null;
    string strExportFileName="/experiments/data/";
    ArrayList arylstFilesCreated=new ArrayList();

    try
    {
    errormsg.Text="";
    strSQL="select * from publishers where state='NY' order by zip";
    string strConn=ConfigurationSettings.AppSettings["Biblio"];
    conn=new OleDbConnection(strConn);
    OleDbCommand cmd=new OleDbCommand(strSQL,conn);

    conn.Open();
    reader1=cmd.ExecuteReader();

    // Variables to Gather Data
    string fieldPubID,fieldName,fieldCompanyName,fieldAddress;
    string fieldCity, fieldState; string fieldZip="";
    string fieldTelephone,fieldFax,fieldComments;
    
    sbTemp=new StringBuilder();
    ArrayList arylstLineConverted=new ArrayList();
    
    int intFieldPubIDPos=reader1.GetOrdinal("PubID");
    int intFieldNamePos=reader1.GetOrdinal("Name");
    int intFieldCompanyNamePos=reader1.GetOrdinal("Company Name");
    int intFieldAddressPos=reader1.GetOrdinal("Address");
    int intFieldCityPos=reader1.GetOrdinal("city");
    int intFieldStatePos=reader1.GetOrdinal("state");
    int intFieldZipPos=reader1.GetOrdinal("zip");
    int intFieldTelephonePos=reader1.GetOrdinal("Telephone");
    int intFieldFaxPos=reader1.GetOrdinal("Fax");
    int intFieldCommentsPos=reader1.GetOrdinal("Comments");
    
    int intLoopCounter=0;
    int intRecordCountForGroup=0;
    bool NewZipCodeGroup=false;
    string strTempLine;
    string strZipCurrentGroup="";
    
        if(reader1.HasRows==false)
            {
            output.Text="No Records found!";
            return;
            } // if
    while (reader1.Read())
        {
            strZipPrev=fieldZip;

            fieldName=ReaderGrab(reader1,intFieldNamePos);
            Log.Info("fieldName=" + fieldName);
            
            fieldCompanyName=ReaderGrab(reader1,intFieldCompanyNamePos);
            Log.Info("fieldCompanyName=" + fieldCompanyName);
            
            fieldAddress=ReaderGrab(reader1,intFieldAddressPos);
            Log.Info("fieldAddress=" + fieldAddress);
            
            fieldCity=ReaderGrab(reader1,intFieldCityPos);
            Log.Info("fieldCity=" + fieldCity);
            
            fieldState=ReaderGrab(reader1,intFieldStatePos);
            Log.Info("fieldState="+ fieldState);
            
            fieldZip=ReaderGrab(reader1,intFieldZipPos);
            Log.Info("fieldZip="+ fieldZip);
            
            fieldFax=ReaderGrab(reader1,intFieldFaxPos);
            Log.Info("fieldFax="+ fieldFax);
            
            fieldTelephone=ReaderGrab(reader1,intFieldTelephonePos);
            Log.Info("fieldTelephone="+ fieldTelephone);
            
            fieldComments=ReaderGrab(reader1,intFieldCommentsPos);
            Log.Info("fieldComments="+ fieldComments);

            sbTemp.Append(fieldName);
            sbTemp.Append(",");
            sbTemp.Append(fieldCompanyName);
            sbTemp.Append(",");
            sbTemp.Append(fieldAddress);
            sbTemp.Append(",");
            sbTemp.Append(fieldCity);
            sbTemp.Append(",");
            sbTemp.Append(fieldState);
            sbTemp.Append(",");
            sbTemp.Append(fieldZip);
            sbTemp.Append(",");
            sbTemp.Append(fieldTelephone);
            sbTemp.Append(",");
            sbTemp.Append(fieldFax);
            sbTemp.Append(",");
            sbTemp.Append(fieldComments);
            
            strTempLine=sbTemp.ToString();
            NewZipCodeGroup=GroupByZip(fieldZip);
            if (NewZipCodeGroup==false)
                {
                arylstLineConverted.Add(strTempLine);
                intRecordCountForGroup++;
                }
            sbTemp.Length=0;

            
            if (NewZipCodeGroup==true)
                {
                if (strZipPrev=="") {strZipPrev=fieldZip;}
                string strFileCreated=strExportFileName + "zip_" + strZipPrev + ".txt";
                Trace.Write("strFileCreated",strFileCreated);
                FileWrite(strFileCreated,arylstLineConverted);
                arylstFilesCreated.Add(strFileCreated);
                arylstLineConverted.Clear();
                arylstLineConverted.Add(strTempLine);
                intRecordCountForGroup=1;
                }
            intLoopCounter++;
        } // while
    } // try
    
    catch (OleDbException oleExc1)
        {
        errormsg.Text += "<br>Error with Reader!<br>" + strSQL + "<br>" + oleExc1.ToString() + "<br>";
        } // OleDBexception catch

    catch (Exception exc1)
        {
        errormsg.Text += "<br>Error with Reader!<br>" + strSQL + "<br>" + exc1.ToString() + "<br>";
        } // catch


    finally
        {            
            if (reader1 != null)
                {
                if (!reader1.IsClosed) reader1.Close();
                }
            if (conn != null)
                {
                if (conn.State==System.Data.ConnectionState.Open) conn.Close();
                }
        } // end finally

    output.Text="<h1>Done exporting</h1>";
    StringBuilder sbFileHrefs=new StringBuilder();

    foreach (String item in arylstFilesCreated)
            {    
                sbFileHrefs.Append("<a href='" + item + "'>" + item + "</a><br>");
            }
    output.Text +="<h2>See Results:</h2>" + sbFileHrefs.ToString();
    
} // Page_Load

protected string ReaderGrab(OleDbDataReader parmRdr1,int parmIntField)
{
   Object objTemp=null;
   string strTemp="";
   try
   {
    objTemp=parmRdr1.GetValue(parmIntField);
    strTemp=(string) objTemp;
   } // try
   catch
   {
    strTemp="type=" + objTemp.GetType().ToString();
   } // catch

   return(strTemp);
} // ReaderGrab

public static string strZipCurrent="";
public static string strZipPrev="";
protected bool GroupByZip(string parmstrZip)
{
    strZipPrev=strZipCurrent;
    strZipCurrent=parmstrZip;
    return(strZipCurrent==strZipPrev ? false:true);
} // GroupByZip

protected bool FileWrite(string parmStrFileName,ArrayList parmArylst)    
{
    System.IO.StreamWriter file=null;
    try
    {
    file=new System.IO.StreamWriter(Server.MapPath(parmStrFileName));
    
    for (int intLineCounter=0;intLineCounter<parmArylst.Count;intLineCounter++)
        {
        file.WriteLine(parmArylst[intLineCounter]);
        }
    } // try
        
    catch (Exception exc1)
    {
    errormsg.Text += "<br>Error with WriteFile!<br>" + parmStrFileName + "<br>" + exc1.ToString() + "<br>";
    } // catch
    
    finally
    {
    if (file!=null) file.Close();
    }

    return(true);
} // FileWrite

</script> 
<html><head> 
<title>WriteFilesFromDB</title> 
</head> 
<body bgcolor="#FFFFFF"> 
<asp:literal id="errormsg" runat="server" /><br>
<form runat="server">
<asp:literal id="output" runat="server" />
</form>
</body><html>

Web.Config file:

filename=/experiments/web.config


<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
    <configSections>
        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
    </configSections>
    
    <appSettings>
        <add key="log4net.Internal.Debug" value="true"/>
    </appSettings>

    <system.web>
        <customErrors mode="Off" />
    </system.web>

    <log4net>

        <!-- Not needed: the logger name does this
        <root>
            <level value="INFO" />
            <appender-ref ref="AspNetTraceAppender" />
        </root>
            

        <logger name="WriteFilesFromDB.aspx">
            <level value="INFO" />
            <appender-ref ref="AspNetTraceAppender" />
        </logger>
        
        -->

        <root>
            <level value="ALL" />
            <appender-ref ref="AspNetTraceAppender" />
        </root>
        
        <appender name="AspNetTraceAppender" type="log4net.Appender.AspNetTraceAppender" >
            <layout type="log4net.Layout.PatternLayout">
                <conversionPattern value="%m%ndate=%d%nthread=%t%n%-5l %l%npriority=%p" />
            </layout>
        </appender>
        
    </log4net>
</configuration>
--%>
Chaz Wish List
Tall Tip $5
Grande Tip $20
Venti Tip $39
Tip Jar Thanks
2004 Thanks
2005 Thanks
HUGE Tip -love site