Pages

Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Monday, November 14, 2011

Log4NetDatabaseConfiguration Part2

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

Step 5 : add New Console project for POC (LoggingExample) and add 2 config files . app.config and log4net.config
appconfig; put the configuration and modified it for the databse connection string

 
  
 

 
log4net.config:put the configuration

  
    
      
      
      
      
      
        
        
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
          
        
      
      
        
        
        
        
      


    
    
      
      
    
  


You are almost done for POC . Just two Steps Remening
Step: 6 . Create Table in Database
DROP TABLE [dbo].[ApplicationLog]
CREATE TABLE [dbo].[ApplicationLog] 
(
 [Id] int IDENTITY (1, 1) NOT NULL,
 [Date] datetime NOT NULL,
 [Thread] varchar(255) NULL,
 [Level] varchar(50) NOT NULL,
 [Logger] varchar(255) NOT NULL,
 [Host] varchar(50) NOT NULL,
 [Message] varchar(4000) NOT NULL,
 [Exception] varchar(2000) NULL,
 [severity] varchar(255) NULL,
 [useranme] varchar(255) NULL,
 [applicationName] varchar(255) NULL

)

Step:7 In Console application
using System;
using Database;

namespace LoggingExample
{
    class Program
    {
        static void Main(string[] args)
        {
            
            
                ILogger logger = new Logger();

                logger.EnterMethod("Main");
                logger.LogInfoMessage("LogInfo");
                logger.LogError("ErrorLog");
                logger.LeaveMethod("Main");
                       
        }
    }
}
You are done now !! if you like it please put a comment.
 Hope this will help you  :)

Log4NetDatabaseConfiguration Part1

step 1. Create a New Solution  and a Class library project called 'DatabaseLogger'

step 2. Download Log4net from  here and    and after download ,find log4net-1.2.11\bin\net\2.0\release\log4net.dll and refer it to your project

step 3. create a class Called Logger and an Inerface ILogger
using System;
using System.Configuration;
using System.Globalization;
using log4net;
using System.Diagnostics;

namespace DatabaseLogger
{
    public class DbLogger : IDbLogger
    {
        #region Datamembers

        private static ILog log = null;
        private const string Log4netConnectionString = "Log4netConnectionString";

        #endregion

        #region Class Initializer        
        public Logger()
        {
            log = LogManager.GetLogger(typeof(DbLogger));
            log4net.GlobalContext.Properties["host"] = Environment.MachineName;
            log4net.GlobalContext.Properties["severity"] = "Low";
            log4net.GlobalContext.Properties["userName"] = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
            log4net.GlobalContext.Properties["applicationName"] = Process.GetCurrentProcess().ProcessName;
            
        }

        #endregion

        #region IDbLogger Members

        public void EnterMethod(string methodName)
        {
            if (log.IsInfoEnabled)
                
                log.Info(string.Format(CultureInfo.InvariantCulture, "Entering Method {0}", methodName));
        }

        public void LeaveMethod(string methodName)
        {
            if (log.IsInfoEnabled)
                log.Info(string.Format(CultureInfo.InvariantCulture, "Leaving Method {0}", methodName));
        }

        public void LogException(Exception exception)
        {
            if (log.IsErrorEnabled)
                log.Error(string.Format(CultureInfo.InvariantCulture, "{0}", exception.Message), exception);
        }

        public void LogError(string message)
        {
            if (log.IsErrorEnabled)
                
                log.Error(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }

        public void LogWarningMessage(string message)
        {
            if (log.IsWarnEnabled)
                log.Warn(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }

        public void LogInfoMessage(string message)
        {
            if (log.IsInfoEnabled)
                
                log.Info(string.Format(CultureInfo.InvariantCulture, "{0}", message));
        }

        #endregion 
    }
}


using System;

namespace DatabaseLogger
{
    public interface IDbLogger
    {
        /// 
        /// Writes a log entry when entering the method.
        /// 
        /// 



Name of the method.
void EnterMethod(string methodName);

        /// 
        /// Writes a log entry when leaving the method.
        /// 
        /// 



Name of the method.
void LeaveMethod(string methodName);

        /// 
        /// Logs the exception.
        /// 
        /// 



The exception.
void LogException(Exception exception);

        /// 
        /// Logs the error.
        /// 
        /// 



The message.
void LogError(string message);

        /// 
        /// Logs the warning message.
        /// 
        /// 



The message.
void LogWarningMessage(string message);

        /// 
        /// Logs the info message.
        /// 
        /// 



The message.
void LogInfoMessage(string message);
    }
}
Step 4: Now We Need to add One more Class Call SqlServerAppender for Log4Net Connection string

using System;
using System.Configuration;
using log4net.Appender;

namespace Database
{
    public class SqlServerAppender : AdoNetAppender
    {
        private const string Log4netConnectionString = "Log4netConnectionString";

        public new string ConnectionString 
        {
            get { return base.ConnectionString; }
            set { base.ConnectionString = ConfigurationManager.ConnectionStrings[Log4netConnectionString].ConnectionString; }
        }
    }
}

after that Your Dll is ready for Refernceing for your Project where you want to implement it .
Now You need Some Configuration for Log4net and what database field you want in the table
I put  four custom fileds alogin with the other filed provieded by Log4net.
I seperated my appconfig file and log4net config file for better understatding.
for seprating you need to add a line of code  in AssembblyInfo.cs continue with part2

Wednesday, October 19, 2011

Invoke Webservice Dyanamicly

Hi Friends this time I want to share , How to Invoke Webservice Dyanamicly and get Response
I Created a Class and Create a method to get all the webmethods in the given serivce Url
using System.Net;
using System;
using System.Web.Services.Description;
using System.CodeDom;
using System.IO;
using System.CodeDom.Compiler;
using System.Reflection;
using System.Xml.Serialization;

public class DyanamicProxyGeneration
{
 #region Members
 List _serviceMethods;
 Uri uri;
 String Url;
 WebRequest webRequest;
 Stream requestStream;
 ServiceDescription sd;
 ServiceDescriptionImporter servImport;
 MethodInfo[] methodInfo;        
 CodeCompileUnit codeCompileUnit;
 StringWriter stringWriter;
 CodeNamespace nameSpace;
 Type service;
 CSharpCodeProvider prov;
 Assembly assembly;
 CompilerResults results;
 CompilerParameters param;
 String[] assemblyReferences;                        
 #endregion
 public void DynamicInvocation(string Url)
 {
  try
  {
   uri = new Uri(Url + "?WSDL");
   webRequest = WebRequest.Create(uri);
   requestStream = webRequest.GetResponse().GetResponseStream();
   // Get a WSDL file describing a service
   sd = ServiceDescription.Read(requestStream);
   string sdName = sd.Services[0].Name;

   // Initialize a service description servImport
   servImport = new ServiceDescriptionImporter();
   servImport.AddServiceDescription(sd, String.Empty, String.Empty);
   servImport.ProtocolName = "Soap";
   servImport.CodeGenerationOptions = CodeGenerationOptions.GenerateProperties;


   nameSpace = new CodeNamespace();
   codeCompileUnit = new CodeCompileUnit();
   codeCompileUnit.Namespaces.Add(nameSpace);
   // Set Warnings
   ServiceDescriptionImportWarnings warnings = servImport.Import(nameSpace, codeCompileUnit);

   if (warnings == 0)
   {
    stringWriter = new StringWriter(System.Globalization.CultureInfo.CurrentCulture);
    prov = new Microsoft.CSharp.CSharpCodeProvider();
    prov.GenerateCodeFromNamespace(nameSpace, stringWriter, new CodeGeneratorOptions());
    
    // Compile the assembly with the appropriate references
    assemblyReferences = new string[2] { "System.Web.Services.dll", "System.Xml.dll" };
    param = new CompilerParameters(assemblyReferences);
    param.GenerateExecutable = false;
    param.GenerateInMemory = true;
    param.TreatWarningsAsErrors = false;
    param.WarningLevel = 4;
    results = new CompilerResults(new TempFileCollection());
    results = prov.CompileAssemblyFromDom(param, codeCompileUnit);
    assembly = results.CompiledAssembly;
    service = assembly.GetType(sdName);
    methodInfo = service.GetMethods();
    
    foreach (MethodInfo t in methodInfo)
    {
     if (t.Name == "Discover")
      break;
     _serviceMethods.Add(t.Name);
    }
   }
  }
  catch (Exception ex)
  {
  }
 }
}


public object GetResponse(MethodInfo[] methodInfoList)
        {
            Object response = null;
            ParameterInfo [] paramters;

            foreach (MethodInfo t in methodInfo)
            {
                //Invoke Method
                paramters  = new ParameterInfo []{};
                paramters = t.GetParameters();
                object[] param1 = paramters;
                Object obj = Activator.CreateInstance(service);
                response = t.Invoke(obj, param1);
                break;
            }
            if (response != null)
            {
                return response;
            }
            else
                return null;
        }

Monday, October 17, 2011

Return ObjectId From the Stored Procrdure & C#.

Hi Frineds, this time i want to share ,How to Get ObjectId From the Stored Procrdure in C#.
Here i have Written Both Stored Procedure and CSharp Code . Please look it and if you like this post. just comment it .


public class DataAccess
{
 private SqlConnection conn;
 public DataAccess()
 {
  string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
  // I used for SQLServer2005 .For other Databases check with "http://www.connectionstrings.com"
  conn = new SQLConnection(connectionString);
 }
// To Get Saved object Id 
 public int Save_Details(string parameter1, string paramter2,....., string parameterN)
   {
            int returnObjectId;
            conn.Open();            
            SqlCommand cmd = new SqlCommand("SP_Insert", conn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@parameter1", parameter1);
            cmd.Parameters.AddWithValue("@parameter2", parameter2);
   //.
   //.
   //.
   //.
            cmd.Parameters.AddWithValue("@parameterN", parameterN);
            cmd.Parameters.Add("@ObjectId", SqlDbType.Int, 0, "Id");
            cmd.Parameters["@ObjectId"].Direction = ParameterDirection.Output;
            cmd.ExecuteNonQuery();

            returnObjectId = (int)cmd.Parameters["@ObjectId"].Value;
            conn.Close();
            if (returnObjectId > 0)
            { return returnObjectId;}
            else
   {return 0;}
        }

}


--Stored Procedure code
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE PROCEDURE [dbo].[SP_Insert] 

 @parameter1 nvarchar(50),
 @parameter2 nvarchar(50),
 -- .
 -- .
 -- .
 @parametern nvarchar(50),
 @Object_Id int OUTPUT
 

AS
BEGIN
   INSERT INTO [dbo].[TableName]
           ([Parameter1]
           ,[Parameter2]
           ,[ParameterN])
     VALUES
     (@parameter1,
  @parameter2,
     @parametern)   
     
END

select @Object_Id =@@Identity

Wednesday, September 21, 2011

Constructor Chaining in CSharp


We starts with basics....
Basically ,it is a mehtod in the calss which executed when its object is created. We put the initialization code in the constructor. Creating a constructor in the class is pretty simple.
look at the following sample :

public class mySampleClass
{

    public mySampleClass()
    {

    // This is the constructor method.
    }
// rest of the class members goes here.
}

When the object of this class is instantiated this constructor will be executed automatically .

Like this :

// At this time the code in the constructor will // be executed
mySampleClass obj = new mySampleClass()


Constructor Overloading :


C# supports overloading of constructors, that means we can have constructors with different set of parameters. So our class can be like this :

public class mySampleClass
{

    public mySampleClass()
    {

    // no parameter constructor method.// First Constructor
    }
    public mySampleClass(int Age)
    {

    // constructor with one parameter.// Second Constructor
    }

    public mySampleClass(int Age, string Name)
    {

    // constructor with two parameters.// Third Constructor
    }

// rest of the class members goes here.
}

Well, note here that call to the constructor now depends on the way you instantiate the object.

For example :

mySampleClass obj = new mySampleClass()
// At this time the code of no parameter // constructor (First Constructor) will be executed

mySampleClass obj = new mySampleClass(12)
// At this time the code of one parameter // constructor(Second Constructor) will be // executed.
The call to the constructors is completely governed by the rules of the overloading here.

Calling Constructor from another Constructor:
You can always make the call to one constructor from within the other.
Say for example :
public
class mySampleClass
{

    public mySampleClass(): this(10)
    {

    // No parameter constructor method.// First Constructor
    }

    public mySampleClass(int Age)
    {

    // Constructor with one parameter.// Second Constructor}
    }

}

Very first of all let us see what is this syntax :
    

public mySampleClass(): this(10)

Here this refers to same class, so when we say this(10), we actually mean execute the public SampleClass(int Age) method.The above way of calling the method is called initializer. We can have at the most one initializer in this way in the method.
Another thing which we must know is the execution sequence i.e., which method will be executed when. Here if I instantiate the object as 

mySampleClass obj = new mySampleClass()
Then the code of public mySampleClass(int Age) will be executed before the code of mySampleClass(). So practically the definition of the method : 

public mySampleClass(): this(10)
{

    // This is the no parameter constructor method.// First Constructor
}

is equivalent to :
public mySampleClass()
{
    mySampleClass(10)

     // This is the no parameter constructor method.// First Constructor
}

This is sometimes called Constructor chaining.

Tuesday, September 20, 2011

Types of Design Patterns

Hi Frnds
There are 23 design patterns that are used in the application development.These are divied into thre sub groups: Creational,Structural and Behavioral.

Creational

Creational patterns is used when object construction and referencing are the concerns.In short,the responsibility of instantiating instances of objects from the client, by which keeping the code loosely coupled and the responsibility of creating complex objects in one place having the Single Responsibility and
Separation of Concerns principles.
The patterns which comes  in the Creational group:
Abstract Factory: Provides an interface to create families of related objects.
Factory: Enables a class to delegate the responsibility of creating a valid object.
Builder: Enables various versions of an object to be constructed by separating the construction
for the object itself.
Prototype: Allows classes to be copied or cloned from a prototype instance rather than creating
new instances.
Singleton: Enables a class to be instantiated once with a single global point of access to it.

Structural

Structural patterns is used when the composition and relationships of objects to fulfill the needs of
larger systems.
The patterns which comes  in the Structural group:
Adapter: Enables classes of incompatible interfaces to be used together.
Bridge: Separates an abstraction from its implementation, allowing implementations and
abstractions to vary independently of one another.
Composite: Allows a group of objects representing hierarchies to be treated in the same way
as a single instance of an object.
Decorator: Can dynamically surround a class and extend its behavior.
Facade: Provides a simple interface and controls access to a series of complicated interfaces
and subsystems.
Flyweight: Provides a way to share data among many small classes in an efficient manner.
Proxy: Provides a placeholder to a more complex class that is costly to instantiate.

Behavioral

Behavioral patterns is used when the communication between objects in terms of responsibility and
algorithms. The patterns in this group encapsulate complex behavior and abstract it away from the
flow of control of a system, thus enabling complex systems to be easily understood and maintained.
The patterns which comes  in the Behavioral group:
Chain of Responsibility: Allows commands to be chained together dynamically to handle a
request.
Command: Encapsulates a method as an object and separates the execution of a command
from its invoker.
Interpreter: Specifies how to evaluate sentences in a language.
Iterator: Provides a way to navigate a collection in a formalized manner.
Mediator: Defines an object that allows communication between two other objects without
them knowing about one another.
Memento: Allows you to restore an object to its previous state.
Observer: Defines the way one or more classes can be alerted to a change in another class.
State: Allows an object to alter its behavior by delegating to a separate and changeable state
object.
Strategy: Enables an algorithm to be encapsulated within a class and switched at run time to
alter an object’s behavior.
Template Method: Defines the control of flow of an algorithm but allows subclasses to override
or implement execution steps.
Visitor: Enables new functionality to be performed on a class without affecting its structure.

These all are the patterns which are used in the aplication development.
Happy Coding :)

Wednesday, September 14, 2011

Unmanaged vs. Managed Code

Unmanaged executable files are binary images of x86 code loaded into memory. The role of the operating system in this case is to load the application into memory and let it run. Although there are some protections regarding memory management and I/O ports, the operating system does not have any idea what the application is doing.

By contrast, managed code is under full control of the operating system. At any point in time, the operating system can stop running the CPU and investigate the runtime state. It can also insert exception handling, array bounds and indexes, traps, garbage collection hooks, and other things. In this way, it mitigates a whole class of security concerns and typical programming errors. All programming languages that support the .NET Framework produce managed code. There are currently over 30 such languages. Several are provided by Microsoft (C#, Visual Basic .NET, managed C++, J#, JScript .NET), while others are developed by third parties (everything from COBOL to Pascal).

Sunday, September 11, 2011

Basic Simple Programs for Interview

Hi Friends this time I am sharing you a very simple basic programs that generally asked at the time of interview. I used to asked it some times a very very simple programs ..we know that we can make it out those program but in interview time if you know how to do that then you can make it out very easyly and make a face that you are thinking about it ;) .. but you know already . and write it after some moments . ;) So just take a look before the interview ..!! All the best friends..!! Prog1:Retrun Vowel of Not. Solution: ======
public bool CheckVowel(object sender,KeyEventArgs e)
{
    if(e.KeyCode ==Keys.A||e.KeyCode ==Keys.E||e.KeyCode ==Keys.I||e.KeyCode ==Keys.O||e.KeyCode ==Keys.U)
    {    
    return true;
    }
    else
    return false;
}
Prog 2: Even Or Odd Solution: ======
public string EvenOrOdd( int Num)
{
    if(num%2 ==0)
    retrun "evenNumber";
    else
    return "OddNumber"
}
Prog3:PrimeNumber Soultion: ======
public string PrimeOrNot(int num)
{
    int i = 0;
    for (i = 3; i < num; i++)
    {
        if (num % i == 0)
        {
            Console.WriteLine("{0} is not a prime number", num);
            break;
        }
    }
    if (i == num)
    {
        Console.Writeline("{0} is a prime Number", num);
    }
}
Prog4:Fibonacci Series Solution: =======
public void FibonacciSeries(int number)
{
    int f_0 = 0;
    int f_1 = 1;
    int sum;
    Console.Write("{0} {1} ", f_0, f_1);
    for (int i = 2; i < number; i++)
    {
        sum = f_0 + f_1;
        f_0 = f_1;
        f_1 = sum;
        int value = f_0 + f_1;
        Console.Write("{0} ", value);
    }
}
Prog5: Factorial Solution: =======
public int Factorial(int number)
{
    int value = 1;
    for (int i = 1; i <= number; i++)
    {
        value = value * i;
    }
    return value;
}
Prog:6 Permutation (nPr) Solution: ====== Refrence Solution 5;
public double Permutation(int n, int r)
{
    double nPr = Factorial(n) / Factorial(n - r);
    return nPr;
}
 
Prog:7 Combination(nCr) Solution: ====== Refrence Solution 5;
public double Combination(int n , int r)
{
double nCr = Factorial(n)/Factorial(r)*(Factorial(n-r);
return nCr;
}
Prog8 : Add two numbers without using the plus operator Solution: ======
public int Add (int x , int y )
{
    return x-(-y);
}    
Prog9: Multiply two numbers without usering * operator Solution: =======
public int MulWithOutStarOperator( int x ,int y)
{
    for(int z= 1 ; z<=y ; z++)
    {
        int value = value +x;
    }
    return value;
} 
Prog:10 String Reverse Solution: =======
public string ReverseString(string str)
{
    int strLenght = str.Lenght;
    char strArray[] = new char[strLength];
    for ( int i = 0 ; i

Prog:11 Return multiple values from a function

Solution:
========

public int Add(int a,int b,out int c)
{
     c=a+1;
     return a+b;
}
Description : --------------- when we call the Add method we will get the sum of the a and b and can also use the value of c like int d=0; int e= Add(2,3,d) ; then the value of e will be 5 and the value of d will be 3.