Archive for the ‘SQL’ Category

Hello All

Today I will go through logging with Log4net. Log4Net is a logging framework ( a rich library) for .NET. Log4Net is popular for its simplicity and robustness. We can write log in various way though we generally write log only in file we we can also mail log, show in console,save in datatbase as well as write in file in different ways.

First we have to download the Log4Net and add the log4net.dll in our implementation project. In the example I have take 2 projects named LogWriter and LogRunner accordingly, In one project I have implemented the logging and in another I execute that logging method.

My project structure is as image bellow :

In the LogWriter I have take two class as bellow :

LogLevel.cs: In this class I simply define a enum which basically helps to define my log level in my LogUtil class.

namespace LogWriter
{
    public enum LogLevel
    {
        DEBUG,
        ERROR,
        FATAL,
        INFO,
        WARN
    }
}

LogUtil.cs: In this class I have a static method named WriteLog which take 2 parameters one define log level and another take log message as string.

using log4net;
using log4net.Config;

namespace LogWriter
{
    public static class LogUtil
    {
        private static ILog logger = LogManager.GetLogger(typeof(LogUtil));

        static LogUtil()
        {
            XmlConfigurator.Configure();
        }

        public static void WriteLog(LogLevel logLevel,string log)
        {
            if (logLevel.Equals(LogLevel.DEBUG))
            {
                logger.Debug(log);
            }
            else if (logLevel.Equals(LogLevel.ERROR))
            {
                logger.Error(log);
            }
            else if (logLevel.Equals(LogLevel.FATAL))
            {
                logger.Fatal(log);
            }
            else if (logLevel.Equals(LogLevel.INFO))
            {
                logger.Info(log);
            }
            else if (logLevel.Equals(LogLevel.WARN))
            {
                logger.Warn(log);
            }             

        }
    }
}

As I am writing a  console application so my mail runner file is Program.cs which is as bellow but you can follow the same procedure in different place as per you requirement.

using System;
using LogWriter;

namespace LogRunner
{
    class Program
    {
        static void Main(string[] args)
        {
            try {
                throw new Exception();
            }

            catch (Exception exc)
            {
                    LogUtil.WriteLog(LogLevel.DEBUG, "Debug mode logging");
                    LogUtil.WriteLog(LogLevel.ERROR, "Error mode logging");
                    LogUtil.WriteLog(LogLevel.FATAL, "Fatal mode logging");
                    LogUtil.WriteLog(LogLevel.INFO, "Info mode logging");
                    LogUtil.WriteLog(LogLevel.WARN, "Warn mode logging");

                    Console.ReadKey();
            }
        }
    }
}

Now one of the most important thing I will focus is log4net configuration. We can configure it from web.config or app.config . In my example I have configured it app.config file in my LogRunner project. In the app.config file follow the commented section.

My configuration file is as bellow , please go through the commented line to get know in detail such as log file rolling, max log file number & size, Log level etc.

<?xml version="1.0" encoding="utf-8" ?>

<configuration>

    <configSections>

        <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

    </configSections>

    <log4net>

        <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">

            <!-- Log file locaation -->
            
            <param name="File" value="C:\Users\sanzeeb\Documents\Visual Studio 2008\Projects\Solution1\LogWriter\Log\" />

            <param name="AppendToFile" value="true" />

            <!-- Maximum size of a log file -->
            <maximumFileSize value="2KB" />

            <!--Maximum number of log file -->
            <maxSizeRollBackups value="8" />

            <!--Set rolling style of log file -->
            <param name="RollingStyle" value="Composite" />

            <param name="StaticLogFileName" value="false" />

            <param name="DatePattern" value=".yyyy-MM-dd.lo\g" />

            <layout type="log4net.Layout.PatternLayout">

                <param name="ConversionPattern" value="%d [%t] %-5p  %m%n" />

            </layout>

        </appender>

        <!-- Appender layout fix to view in console-->
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >

            <layout type="log4net.Layout.PatternLayout">

                <param name="Header" value="[Header]\r\n" />

                <param name="Footer" value="[Footer]\r\n" />

                <param name="ConversionPattern" value="%d [%t] %-5p  %m%n" />

            </layout>

        </appender>

      
        <!-- Database appender -->

        <!--
        You need to create a table as bellow to insert log in database for MSSQL server.

        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
        )
        -->

        <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">
            <bufferSize value="100" />
            <connectionType value="System.Data.SqlClient.SqlConnection, System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
            <connectionString value="Data Source=SANZEEB-PC\SQLEXPRESS;Initial Catalog=AppTesterDB;Integrated Security=True" />
            <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>

        <root>

            <level value="DEBUG" />

            <!--
            Log level priority in descending order:

            FATAL = 1 show  log -> FATAL
            ERROR = 2 show  log -> FATAL ERROR
            WARN =  3 show  log -> FATAL ERROR WARN
            INFO =  4 show  log -> FATAL ERROR WARN INFO
            DEBUG = 5 show  log -> FATAL ERROR WARN INFO DEBUG
            -->

            <!—To write log in file -->
            <appender-ref ref="LogFileAppender" />

            <!--To view log in console -->
            <appender-ref ref="ConsoleAppender" />
            
            <!--To write log in file batabase -->
            <appender-ref ref="AdoNetAppender" />

        </root>

    </log4net>

</configuration>

Hope this will help to improve your logging in your .NET application.

Thanks

That’s all for today.

BYE

Hello all

Though its a very simple process but we usually don’t do this stuff too much unless we are bound to do that.In this article I will show how to update a table data with another table depending on another table & another will be a simple regular expression in MySQL query.

In the example I have ‘new_users’ table to update with the data of ‘listings’ table depending on the condition or ‘users’ table. and the table structure is as bellow.

‘new_users’ :
userID,phone,user_state
‘listings’ :
listID,userID,phone
‘users’:
countID,userID,category

Now the scenario is I have to update the phone of new_users from the listings tables phone of same userID but only who are only ‘Admin’ which we may found in users table’s  category field. So the query will be as following

-- Update from listings for 'Admin'
update listings, new_users, users
set
new_users.phone = listings.phone
where
users.category = 'Admin' &&
listings.userID = users.userID &&
users.userID = new_users.userID

Now come to the second part, we can apply regular expression in our MySQL query as follow:

-- Update all user_state to null which contains invalid character
update new_users
set
new_users.user_state = null
where
new_users.user_state REGEXP '[1234567890~!@#$%^&*()_+|}{":?><,./;]'

The query will set null to user_state field if user_state field contains none but a-z & A-Z previously.

I have also some collection or regular expression for MySQL which i have collected from different site.

A very simple example illustrating this is to select all the records from MyTable for which MyField starts with "A"

SELECT * FROM  MyTable WHERE MyField REGEXP ‘^a’;

Please take a look to the list below in order to find more information for the available options MySQL Regular Expressions

Matches zero or more instances of the string preceding it

Matches one or more instances of the string preceding it

Matches zero or one instances of the string preceding it

Matches any single character
[xyz] 
Matches any of x, y, or z (the characters within the brackets)
[A-Z] 
Matches any uppercase letter
[a-z] 
Matches any lowercase letter
[0-9] 
Matches any digit 

Anchors the match from the beginning 

Anchors the match to the end

Separates strings in the regular expression
{n,m} 
String must occur at least n times, but no more than n  
{n} 
String must occur exactly n times
{n,| 
String must occur at least n times

[Source]

 

That’s all for the day.
BYE

User ScrumPad for your Agile based projects.

Its pretty much needed to work with a existing relational database to test any new features of a language,but its really tough to get it at the right moment. We can easily get one from Microsoft’s Northwind database.First we have to install SQL Server Management Studio and then download the sample database form here . After installing the SampleDB, it will create a directory named “C:\SQL Server 2000 Sample Databases” . In this Database we will get some files including NORTHWND.MDF.To use it, first we have some inital tasks to do …

1. In the first step we have to double click on “instnwnd.sql” which is in the “C:\SQL Server 2000 Sample Databases” folder , after click SQL Server Management Studio will automaticly open then we have to press the “Execute” button.

2. In the similar way we also wave to double click on “instpubs.sql” and do the same thing.

after that when we connect our SQL server we foud our desired NORTHWIND database .

in the above topic i have escaped many vital technical issues just to make the article simple any easy to read as well as easy to impliment. hope it will work.

have a nice day.