How to store log in database using log4net

One of the best ways to store log in the database using log4net coz it is easy to use and its world wide popularity. For storing log in the database all task are manage by log4net internally.

At first you need to create a table for Storing log in the SqlServer database

The table should be like as

CREATE TABLE [dbo].[Log] (

[Id] [int] IDENTITY (1, 1) NOT NULL,

[Date] [datetime] NOT NULL,

[Thread] [varchar] (255) NOT NULL,

[Level] [varchar] (50) NOT NULL,

[Logger] [varchar] (255) NOT NULL,

[Message] [varchar] (4000) NOT NULL,

[Exception] [varchar] (2000) NULL

)

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create an application.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. Now put this web.config/app.config file in configuration tag.

<configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/> </configSections> <log4net> <root> <level value="DEBUG" /> <appender-ref ref="ADONetAppender" /> </root> <appender name="ADONetAppender" type="log4net.Appender.ADONetAppender"> <bufferSize value="100" /> <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" /> <connectionString value="server=servername; uid=Lion; pwd=Lionman; database=databasename" /> <commandText value="INSERT INTO Log ([Date],[Thread],[Level],[Logger],[Message],[Exception]) VALUES (@log_date, @thread, @log_level, @logger, @message, @exception)" />
<parameter>
<parameterName value="@log_date"/> <dbType value="DateTime"/> <layout type="log4net.Layout.RawTimeStampLayout"/> </parameter>
<parameter>
<parameterName value="@thread"/> <dbType value="String"/> <size value="255"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%thread"/> </layout> </parameter>
<parameter>
<parameterName value="@log_level"/> <dbType value="String"/> <size value="50"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%level"/> </layout> </parameter>
<parameter>
<parameterName value="@logger"/> <dbType value="String"/> <size value="255"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%logger"/> </layout> </parameter>
<parameter>
<parameterName value="@message"/> <dbType value="String"/> <size value="4000"/> <layout type="log4net.Layout.PatternLayout"> <conversionPattern value="%message"/> </layout> </parameter>
<parameter>
<parameterName value="@exception"/> <dbType value="String"/> <size value="2000"/> <layout type="log4net.Layout.ExceptionLayout"/> </parameter> </appender> </log4net> 

In the connection string tag you need to change server name and database. You also can decide how to define the security part of the connection string.

There are two way to define the security part

· Use integrated Security

· State the username and the password in the connection string.

In both cases you need to make sure that the user has access to the, SQL server, the database and the databasetable that Log4Net is going to use.

If you use integrated security then the connection string should be like as

<connectionString value=”Data Source=servername;initial Catalog=databasename; Integrated Security=True;”/>

5. To use log4net put this as a local class variable:    private static readonly log4net.ILog log =log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

6. And do this to write messages in the log file.   log.Debug(”this text will be in log file”);

For Example,

using System;
using System.Collections.Generic;
using System.Text; using log4net;
using log4net.Config; using log4net.Core;
using log4net.Repository.Hierarchy;
using log4net.Appender;

namespace LogPractice
{
    class Program
    {
        private static readonly log4net.ILog log =log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Debug("log Debug");
            log.Info("log Info");
            log.Warn("log Warn");
            log.Error("log Error");
            log.Fatal("log Fatal");
        }
    }
}

Now run the code then you can see the log stored in the database table.

.Net Remoting with a simple example

Hi Dear,
I have moved my content to my own hosting. To see the existing content please go the following url

http://techboom.xyz/2008/07/06/58/

From now you will get blog post regularly. To see my new blog site please Click here. Feel free to leave comments I will try to reach you as soon as I can. Hope you will enjoy all the article.

ADO.NET – DataReader(Connected) and DataSet(Disconnected) in C# .Net with Examples

ADO.NET provides a relatively common way to interact with data sources, but comes in different sets of libraries for each way you can talk to a data source. 

Core Objects of .NET Framework Data Providers

The following table outlines the four core objects that make up a .NET Framework data provider.

Object

Description

Connection Establishes a connection to a specific data source. The base class for all Connection objects is the DbConnection class.
Command Executes a command against a data source. Exposes Parameters and can execute within the scope of a Transaction from a Connection. The base class for all Command objects is the DbCommand class.
DataReader Reads a forward-only, read-only stream of data from a data source. The base class for all DataReader objects is the DbDataReader class.
DataAdapter Populates a DataSet and resolves updates with the data source. The base class for all DataAdapter objects is the DbDataAdapter class.

 

In addition to the core classes listed in the table above, a .NET Framework data provider also contains the classes listed in the following table.

Object

Description

Transaction Enables you to enlist commands in transactions at the data source. The base class for all Transaction objects is the DbTransaction class.
Parameter Defines input, output, and return value parameters for commands and stored procedures. The base class for all Parameter objects is the DbParameter class.

 

SqlConnection Object

The first thing you will need to do when interacting with a data base is to create a connection.  The connection tells the rest of the ADO.NET code which data base it is talking to.

Creating a SqlConnection Object:

 SqlConnection conn = new SqlConnection(“Server=sadi;database=test;uid=Tiger;pwd=lion);  

Table below describes common parts of a connection string.

table 1.  ADO.NET Connection Strings contain certain key/value pairs for specifying how to make a data base connection.  They include the location, name of the database, and security credentials.

 

Connection String Parameter Name

Description

Data Source

Identifies the server.  Could be local machine, machine domain name, or IP Address.

Initial Catalog

Data base name.

Integrated Security

Set to SSPI to make connection with user’s Windows login

User ID

Name of user configured in SQL Server.

Password

Password matching SQL Server User ID.

Integrated Security is secure when you are on a single machine doing development.  However, you will often want to specify security based on a SQL Server User ID with permissions set specifically for the application you are using.  The following shows a connection string, using the User ID and Password parameters:

SqlConnection conn = new SqlConnection(“Data Source=DatabaseServer;Initial Catalog=sadi;User ID=YourUserID;Password=YourPassword”);

Notice how the Data Source is set to DatabaseServer to indicate that you can identify a data base located on a different machine, over a LAN, or over the Internet.  Additionally, User ID and Password replace the Integrated Security parameter.

The sequence of operations occurring in the lifetime of a SqlConnection are as follows:

  1. Instantiate the SqlConnection.
  2. Open the connection.
  3. Pass the connection to other ADO.NET objects.
  4. Perform data base operations with the other ADO.NET objects.
  5. Close the connection.

SqlCommand Object

A SqlCommand object allows you to specify what type of interaction you want to perform with a data base.  For example, you can do select, insert, modify, and delete commands on rows of data in a data base table.

SqlDataReader Object

A SqlDataReader is a type that is good for reading data in the most efficient manner possible.  You can *not* use it for writing data.  SqlDataReaders are often described as fast-forward firehose-like streams of data.

You can read from SqlDataReader objects in a forward-only sequential manner.  Once you’ve read some data, you must save it because you will not be able to go back and read it again.

 

Example on the use of these ADO.NET objects…

Getting Data from database :

string sConnectionString = “Server=sadi;database=test;uid=Tiger;pwd=Lion”;

            SqlConnection oConn = new SqlConnection(sConnectionString);

            string sQueryString = “select * from tblUser”;

            SqlCommand oCommand = new SqlCommand(sQueryString);

            oCommand.Connection = oConn;

            oConn.Open();

            SqlDataReader oReader = oCommand.ExecuteReader();

            ArrayList oList = new ArrayList();

            if (oReader.HasRows)

            {

                while (oReader.Read())

                {

                    oList.Add(oReader[0].ToString());

                    oList.Add(oReader[1].ToString());                   

                }

            }

            oReader.Close();

            oConn.Close();

Getting single data from database:

 SqlCommand cmd = new SqlCommand(“select count(*) from Categories”, connection); 
 
int count = (int)cmd.ExecuteScalar();

Inserting data to database:

string conectionstring = “Server=sadi;database=test_db;uid=Tiger;pwd=Lion”;            SqlConnection connection = new SqlConnection(conectionstring);

            string querystring = “insert into customer values(‘”+ Guid.NewGuid() + “‘,'”+ txtCustName.Text+ “‘)”;

            SqlCommand oSqlCommand = new SqlCommand(querystring);

            connection.Open();

            oSqlCommand.Connection = connection;

            oSqlCommand.ExecuteNonQuery();

Working with Disconnected Data – The DataSet and SqlDataAdapter

A DataSet is an in-memory data store that can hold numerous tables.  DataSets only hold data and do not interact with a data source.  It is the SqlDataAdapter that manages connections with the data source and gives us disconnected behavior.  The SqlDataAdapter opens a connection only when required and closes it as soon as it has performed its task.  For example, the SqlDataAdapter performs the following tasks when filling a DataSet with data:

  1. Open connection
  2. Retrieve data into DataSet
  3. Close connection

and performs the following actions when updating data source with DataSet changes:

  1. Open connection
  2. Write changes from DataSet to data source
  3. Close connection

In between the Fill and Update operations, data source connections are closed and you are free to read and write data with the DataSet as you need.  These are the mechanics of working with disconnected data.

Creating a DataSet Object

There isn’t anything special about instantiating a DataSet.  You just create a new instance, just like any other object:

DataSet dsCustomers = new DataSet();

The DataSet constructor doesn’t require parameters.  However there is one overload that accepts a string for the name of the DataSet

Creating A SqlDataAdapter

The SqlDataAdapter holds the SQL commands and connection object for reading and writing data.  You initialize it with a SQL select statement and connection object:

SqlDataAdapter daCustomers = new SqlDataAdapter(
“select CustomerID, CompanyName from Customers”, conn);

As indicated earlier, the SqlDataAdapter contains all of the commands necessary to interact with the data source. 

The Example of DataSet of select query is given below-

using System;

using System.Collections.Generic;

using System.Text;

using System.Data.SqlClient;

using System.Data;

 

namespace ConsoleApplication1

{

    class Program

    {

        DataSet dataset = new DataSet();

        static void Main(string[] args)

        {

 

            Program p = new Program();

            p.TestRead();

            p.printTest();

            Console.ReadKey();

        }

 

        private void TestRead()

        {

            SqlConnection oConnection = new SqlConnection(“Server=sadi;database=test;uid=Tiger;pwd=Lion”);

 

            try

            {

                oConnection.Open();              

                SqlDataAdapter adapter = new SqlDataAdapter();

                adapter.SelectCommand = new SqlCommand(“select * from tblUser”, oConnection);

                adapter.Fill(dataset,“TEST”);

                oConnection.Close();

               

            }

            catch (SqlException oSqlExp)

            {

                Console.WriteLine(“” + oSqlExp.Message);

            }

            catch (Exception oEx)

            {

                Console.WriteLine(“” + oEx.Message);

            }

            finally

            {

                if (oConnection != null)

                {

                    oConnection.Close();

                }

            }

        }

Log4Net Tutorial in C# .net (How can I show log in a file?)

For logging service my choice is log4net from Apache Software Foundation. It is easy to use, open source and well documented. There are also so many logging services but they are not open source. So it is an easy and best solution for you.

Write Log in Console procedures are given below-

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create a new console application.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. write the main method like this

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;

namespace LogPractice
{
  class Program
  {
    void Main(string[] args)
    {
     log4net.Config.BasicConfigurator.Configure();
     log4net.ILog log = log4net.LogManager.GetLogger(Program);
log.Debug("THis is sadi's world!");
     log.Info("How beautyful the console looks like");
     log.Warn("You are great you did this");
     log.Error("Who make you know is the best");
     log.Fatal("sadi the great");
     Console.ReadLine();  // Hold the output
     }
   }
 }

Using Log4net Write log in a file, Procedures are given below-

1. Download log4net from http://logging.apache.org/log4net/download.html

2. Open visual studio and create an application.

3. Add to the project a reference to the \bin\net\2.0\release\log4net.dll assembly in the log4net distribution.

4. Now put this web.config/app.config file in configuration tag.

 <configSections>
   <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
 </configSections>
 <log4net>
 <root>
  <level value="DEBUG" />
  <appender-ref ref="LogFileAppender" />
 </root>
 <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
  <param name="File" value="C:\Try\logger\logger\bin\Debug\log.txt" />
  <param name="AppendToFile" value="true" />
  <rollingStyle value="Size" />
  <maxSizeRollBackups value="10" />
  <maximumFileSize value="10MB" />
  <staticLogFileName value="true" />
  <layout type="log4net.Layout.PatternLayout">
  <param name="ConversionPattern" value="%-5p%d{yyyy-MM-dd hh:mm:ss} – %m%n" />
  </layout>
 </appender>
 </log4net>

this configuration creates a log file in C:\temp\log.txt.

5. To use log4net put this as a local class variable:   protected static readonly ILog log =
LogManager.GetLogger(Program);

6.    And do this to write messages in the log file.   log.Debug(“this text will be in log file”);

For Example:

using System;
using System.Collections.Generic;
using System.Text;
using log4net;
using log4net.Config;

namespace <code>LogPractice</code>
{
 class Program
 {
 protected static readonly ILog log = LogManager.GetLogger(typeof(Program));
 static void Main(string[] args)
 {

 log4net.Config.XmlConfigurator.Configure();
 //————————–
 log.Warn("sadi the great");
 }
 }
}

7. Compile and run the application, and you’ll see output to the console

N.B : if you run this code log will show in the c:/temp/log.txt file.

What is the main difference between process and procedure in Software Engineering?

 

What is the best and easiest way to explain the difference? I usually say process is “what to do” and the procedure is “how to do”. A process is any series of actions or operations viewed as a whole, with a start and finish. A procedure is a series of actions or operations viewed as discrete steps. A process may not even have steps but may simply be a continuum (the process of fermentation, etc.). Additionally, a process is often something one observes, whereas a procedure is something one executes. And I usually say procedure is the steps you take to reach a goal.

Find data from a data structure(List, Dictionary) using delegate in c# .Net

using System;
using System.Collections.Generic;
using System.Text; 
namespace MyDelegate
{
    class Program
    {
        static void Main(string[] args)
        {
            List<string> m_liName=new List<string>();
            m_liName.Add("sadi");
            m_liName.Add("pothik");
            m_liName.Add("shiman");
            m_liName.Add("shuvro");
            m_liName.Add("arif");
 
            //**************Find a single data
            string sName = m_liName.Find(delegate(string s) 
            { return s.Equals("sadi"); });

            //**************Find multiple data
            List<string> liName1 = m_liName.FindAll(delegate(string s) 
            { return s.Equals("sh"); });

            //*************If contains the data**********
            bool bIsSuccess = m_liName.Contains("sadi"); 
            // output: true
        }
    }
}

What’s the difference between override and new in C#? (Use of override and new modifier)

 

new is used for method hiding and override is used for method overriding…

This is all to do with polymorphism. When a virtual method is called on a reference, the actual type of the object that the reference refers to is used to decide which method implementation to use. When a method of a base class is overridden in a derived class, the version in the derived class is used, even if the calling code didn’t “know” that the object was an instance of the derived class. For instance:

public class Base

 

{

public virtual void SomeMethod()

{

Console.WriteLine(“Base:: SomeMethod”);

}

}

 

public class Derived : Base

{

public override void SomeMethod()

{

Console.WriteLine(“Derived:: SomeMethod”);

}

}

 

 

Base b = new Derived();

b.SomeMethod();//output : Derived:: SomeMethod

 

will end up calling Derived.SomeMethod if that overrides Base.SomeMethod.


Now, if you use the new keyword instead of override, the method in the derived class doesn’t override the method in the base class, it merely hides it. In that case, code like this:

public class Base

{

public virtual void SomeOtherMethod()

{

Console.WriteLine(“Base:: SomeMethod”);

}

}

 

public class Derived : Base

{

public new void SomeOtherMethod()

{

Console.WriteLine(“Derived:: SomeMethod”);

}

}

 

 

 

Base b = new Derived();

Derived d = new Derived();

b.SomeOtherMethod();//output: Base::SomeMethod

d.SomeOtherMethod();//output: Derived::SomeMethod

 

Will first call Base.SomeOtherMethod , then Derived.SomeOtherMethod . They’re effectively two entirely separate methods which happen to have the same name, rather than the derived method overriding the base method.If you don’t specify either new or overrides, the resulting output is the same as if you specified new, but you’ll also get a compiler warning (as you may not be aware that you’re hiding a method in the base class method, or indeed you may have wanted to override it, and merely forgot to include the keyword).