Thursday, August 18, 2016

Log4Net


log4net step by step


1. Install Log4Net either by adding log4Net.dll or by running below command,
  • PM> Install-Package log4net

2. Create XML file inside web application project as below

<? xml version = " 1.0 " ?>
< log4net >
< appender name = " FileAppender " type = " log4net.Appender.RollingFileAppender " >
< param name = " File " value = " D:\LogFile.log " />
< param name = " DatePattern " value = " yyyy.MM.dd " />
< param name = " RollingStyle " value = " Size " />
< param name = " maxSizeRollBackups " value = " 10 " />
< param name = " maximumFileSize " value = " 100KB " />
< layout type = " log4net.Layout.PatternLayout " >
< param name = " ConversionPattern " value = " %date{yyyy-MM-dd HH:mm:ss ffff} [%-3t] %-5p %logger{1}.%method: %message%newline " />
</ layout >
</ appender >
< root >
<!-- OFF, FATAL, ERROR, WARN, DEBUG, INFO, ALL -->
< level value = " ALL " />
< appender-ref ref = " FileAppender " />
</ root >
</ log4net >

Assume that "log4net.xml" is the file name of the above created xml file

3.  Configure above created xml file in web.config
  • In <appsettings> section add below entry
  • <add key = "log4net.config" value = "log4net.xml" />
4. Create Logger.cs in project and add reference of log4net.dll in the project. Mostly this would be in the utility project as we can refer utility project in any of the layer/project.

Using System;

namespace yournamespacename;
public class logger
{
private static log4net.ILog Log {get; set;}
static Logger
{
Log = log4net.LogManager.GetLogger(typeof(Logger));
}

public static void Error (Object message)
{
Log.Error(message);
}

public static void Error (Object message, Exception Ex)
{
Log.Error(message, Ex);
}

public static void Error (Exception Ex)
{
Log.Error(Ex);
bool x = Log.IsErrorEnabled;
}

public static void Info (Object message)
{
Log.Info(message);
}

}

5. Make sure the user (generally Iuser) configured in IIS to access the website has read write access to the Log file. This can be done by right click -> properties -> Security -> Edit -> Add -> select the user and give the permissions.

6. Below is the sample which can be used in catch block
  • Add reference of above project where log4net has to be used
  • Catch block can be as below
Catch (exception ex)
{
Logger.Error(ex);
}

 ====================================================================
If it is not working, follow below changes,

1. Add below line in AssemblyInfo.cs file,
[assembly: log4net.Config.XmlConfigurator(Watch = true)]

2. Add below section in App.config file,

<configSections>

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

</configSections>

<log4net>

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

<param name="File" value="D:\\PUDLog.log" />

<AppendToFile value="true" />

<param name="DatePattern" value="yyyy.MM.dd" />

<param name="RollingStyle" value="Size" />

<param name="maxSizeRollBackups" value="10" />

<param name="maximumFileSize" value="100KB" />

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

<param name="ConversionPattern" value="%date{yyyy-MM-dd HH:mm:ss ffff} [%-3t] %-5p %logger{1}.%method: %message%newline" />

</layout>

</appender>

<root>

<!-- OFF, FATAL, ERROR, WARN, DEBUG, INFO, ALL -->

<level value="DEBUG" />

<appender-ref ref="FileAppender" />

</root>

</log4net>

Wednesday, August 3, 2016

Anonymous method in c#

Anonymous method


When to use anonymous methods

  • If we want to use the delegate only inside the same function
  • Reduce overhead of instantiating delegate i.e. performance improvement
E.g.

class program
{
delegate int pointToAddFunction(int n1,int n2);

static void Main (string[] args)
{
//Anonymous method is below
pointToAddFunction ptrObj = delegate
(int n1,int n2)
{
return n1 +n2;
};     //Note semicolon
//Anonymous method ended

int x = ptrObje.Invoice(2,2);
console.writeline(x);
}
}
 

Design patterns c# examples

Singleton Pattern

When we want only one instance of the object to be created and shared between clients (global variables of project)

To achieved/implement Singleton pattern
1. Define the constructor as private. So no instance/object can be created
2. Define instance (variables) & methods as static. This will cause one global instance to be created and shared across.

E.g.

public class clsSingleton
{
public static int intCounter;
private clsSingleTon()
{
//This is private constructor
}
private static void Hits()
{
intCounter++;
}
public static int getTotalHits()
{
return intCounter;
}
}

Client code

clsSingleTon.Hit();  // Everytime counter increments tag by 1

=========================================================================

Factory Pattern

public class clsFactoryInvoice
{
public static IInvoice getInvoice(int intInvoiceType)
{
IInvoice objinv;
if(intInvoiceType == 1)
{
objinv = new clsInvoiceWithHeaders();
}
else if (intInvoiceType == 2)
{
objinv = new clsInvoiceWithoutHeaders();
}
else
{
return null;
}
return objinv;
}
}

public Interface IInvoice
{
void print();
}

public class clsInvoiceWithHeader : IInvoice
{
public void print()
{
console.writeline("Invoice will be printed with Header");
}
}

public class clsInvoiceWithoutHeader : IInvoice
{
public void print()
{
console.writeline("Invoice will be printed without Header");
}
}

client code

class program
{
static void Main (string [] args)
{
int intInvoiceType = 0;
IInvoice objInvoice;
console.writeline("Enter Invoice Type");
intInvoiceType = console.readline();
objInvoice = clsFactoryInvoice.getInvoice(intInvoiceType );
objInvoice .print();
console.Readline();
}
}

Benefits : Client no need to know which all concrete classes available (loosely coupling) client will have object created just by passing parameter