Archive for the ‘Visual Studio’ 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

Today I will show you how to fire  Link Button’s event with argument and initialize a label inside of a repeater. To do that first we have to take LinkButton and a Label control inside the ItemTemplate of the repeater. Then we have to initialize the the Label from OnItemDataBound event of the repeater. In the following code blocks its shown how to perform the job.

Following is my Default.aspx file:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="TestProject._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Selected ID:<asp:Label ID="lblSelectedID" runat="server" Text=""></asp:Label>
        <br />
        <asp:Repeater ID="rptContent" runat="server" OnItemDataBound="rptContent_ItemDataBound">
            <ItemTemplate>
                <asp:Label ID="lblName" runat="server">
                </asp:Label>
                <asp:LinkButton ID="lnkShowData" runat="server" OnCommand="LinkButton_Command" CommandArgument='<%# Eval("key") %>'
                    Text="[Show]" CommandName="Show"></asp:LinkButton>
                <br />
            </ItemTemplate>
        </asp:Repeater>
    </div>
    </form>
</body>
</html>

In the above code I have bind the "key" as CommandArgument in LinkButton which will be initialize form the code behind file.

My code behind is as following:

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace TestProject
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            rptContent.DataSource = this.userInformation();
            rptContent.DataBind();
        }

       // Fire the link button event from inside repeater.
       protected void LinkButton_Command(object sender, CommandEventArgs e)
        {
           lblSelectedID.Text = e.CommandArgument.ToString();
        }

        protected void rptContent_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            // find the label control by id
            Label lblDynaLabel = (Label)(e.Item.FindControl("lblName"));

            // bind the data from repeater data source (value from the dictionary)with the label control.
            lblDynaLabel.Text = DataBinder.Eval(e.Item.DataItem,"value").ToString();
        }

        #region Private method

        private Dictionary<int, string> userInformation()
        {
            Dictionary<int, string> userData = new Dictionary<int, string>();

            userData.Add(1, "Max");
            userData.Add(2, "Top");
            userData.Add(3, "Avg");

            return userData;
        }
        #endregion
    }
}

The output will be as bellow:

Selected ID:1
Max [Show]
Top [Show]
Avg [Show]

In the private method section I have created a simple mathod named userInformation, which contains dictionary data collection to bind it with repeater.Hope that above code blocks will help.

Thanks

That’s all for the day.

BYE

User ScrumPad for your Agile based projects.

Hello all

Today I will try to demonstrate how to create simple web service through WCF. To get into WCF first we have to know some basic principal of WCF and its "ABC".

Address : the location of the service.

Bind: how to get service.

Contract: service action.

In this tutorial I will not describe details about WCF.My basic focus will be on creating a WCF service through Visual Studio 2008

First open a new WCF project:

In my sample project I have named "TestWCFService" for creating the service.

In the solution explorer you will found IService1.cs interface , Service1.svc file and a code behind file Service1.svc.cs

In my project I have renamed those as IDataService.cs, DataService.svc and DataService.svc.cs accordingly. To change the markup file of DataService.svc right click on the DataService.svc file in solution explorer and press "View Markup" as bellow

and change the Service according to you code as bellow.

<%@ ServiceHost Language="C#" Debug="true" Service="TestWCFService.DataService" CodeBehind="DataService.svc.cs" %>

In the solution my IDataSevice.cs is as bellow:

using System.Runtime.Serialization;
using System.ServiceModel;

namespace TestWCFService
{

    [ServiceContract]
    public interface IDataService
    {

        [OperationContract]
        UserInformation GetUserDataFromService();

        [OperationContract]
        string GetUserRestrictionFromService(string userID);

        // TODO: Add your service operations here
    }

    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class UserInformation
    {

        [DataMember]
        public string UserName { get; set; }

        [DataMember]
        public string UserLocation { get; set; }

        public string UserRestriction(int userID)
        {
            if (userID.Equals(1))
                return "approve";
            else
                return "rejected";
        }

    }
}

My DataService.svc.cs file is as bellow :

using System;

namespace TestWCFService
{
    // NOTE: If you change the class name "Service1" here, you must also update the reference to "Service1" in Web.config and in the associated .svc file.
    public class DataService : IDataService
    {
        #region IDataService Members

        public UserInformation GetUserDataFromService()
        {
            return new UserInformation() { UserName = "Tanvir", UserLocation = "Dhaka" };
        }

        public string GetUserRestrictionFromService(string userID)
        {

            UserInformation userInformation = new UserInformation();

            if (userInformation.UserRestriction(Int32.Parse(userID)).Equals("approve"))
                return String.Format("your user id is {0} and you are approved", userID);
            else
                return String.Format("your user id is {0} and you are not approved", userID);

        }

        #endregion
    }
}

And the most important thing is to change in system.servieModel section in Web.config file as bellow :

<system.serviceModel>
        <services>
            <service name="TestWCFService.DataService" behaviorConfiguration="TestWCFService.Service1Behavior">
                <!-- Service Endpoints -->
                <endpoint address="" binding="wsHttpBinding" contract="TestWCFService.IDataService">
                    <!--
              Upon deployment, the following identity element should be removed or replaced to reflect the
              identity under which the deployed service runs.  If removed, WCF will infer an appropriate identity
              automatically.
          -->
                    <identity>
                        <dns value="localhost"/>
                    </identity>
                </endpoint>
                <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
            </service>
        </services>
        <behaviors>
            <serviceBehaviors>
                <behavior name="TestWCFService.Service1Behavior">
                    <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
                    <serviceMetadata httpGetEnabled="true"/>
                    <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
                    <serviceDebug includeExceptionDetailInFaults="false"/>
                </behavior>
            </serviceBehaviors>
        </behaviors>
    </system.serviceModel>

We have to change the underline and bold section up above according to you code and naming in our solution.

Thanks

That’s all for the day.

BYE

User ScrumPad for your Agile based projects.