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

Polymorphism, Method Hiding and Overriding in C#

Overview

One of the fundamental concepts of object oriented software development is polymorphism. The term polymorphism (from the Greek meaning “having multiple forms”) in OO is the characteristic of being able to assign a different meaning or usage to something in different contexts – specifically, to allow a variable to refer to more than one type of object.

Inherited Methods

A method Sadi() which is declared in the base class A and not redeclared in classes B or C is inherited in the two subclasses

    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Sadi() { Console.WriteLine("A::Sadi()"); }
        }

        class B : A {}

        class Test
        {
            static void Main(string[] args)
            {
                A a = new A();
                a.Sadi();  // output --> "A::Sadi()"

                B b = new B();
                b.Sadi();  // output --> "A::Sadi()"
            }
        }
    }
      

The method Sadi() can be overridden in classes B and C:

    using System;
    namespace Polymorphism
    {
        class A
        {
              public void Sadi() { Console.WriteLine("A::Sadi()"); }
        }

        class B : A
        {
              public void Sadi() { Console.WriteLine("B::Sadi()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Sadi();  // output --> "A::Sadi()"
                b.Sadi();  // output --> "B::Sadi()"

                a = new B();
                a.Sadi();  // output --> "A::Sadi()"
            }
        }
    } 

This issue will be discussed in section Hiding and Overriding Methods.

Methods (Use of override keyword)Virtual and Overridden

Only if a method is declared virtual, derived classes can override this method if they are explicitly declared to override the virtual base class method with the override keyword.

    using System;
    namespace Polymorphism
    {
        class A
        {
            public virtual void Sadi() { Console.WriteLine("A::Sadi()"); }
        }

        class B : A
        {
            public override void Sadi() { Console.WriteLine("B::Sadi()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Sadi();  // output --> "A::Sadi()"
                b.Sadi();  // output --> "B::Sadi()"

                a = new B();
                a.Sadi();  // output --> "B::Sadi()"
            }
        }
     } 

Method Hiding (Use of new keyword)

Why did the compiler in the second listing generate a warning? Because C# not only supports method overriding, but also method hiding. Simply put, if a method is not overriding the derived method, it is hiding it. A hiding method has to be declared using the new keyword. The correct class definition in the second listing is thus:

    using System;
    namespace Polymorphism
    {
        class A
        {
            public void Sadi() { Console.WriteLine("A::Sadi()"); }
        }

        class B : A
        {
            public new void Sadi() { Console.WriteLine("B::Sadi()"); }
        }

        class Test
        {
            static void Main(string[] args)
            {
                A a;
                B b;

                a = new A();
                b = new B();
                a.Sadi();  // output --> "A::Sadi()"
                b.Sadi();  // output --> "B::Sadi()"

                a = new B();
                a.Sadi();  // output --> "A::Sadi()"
            }
        }
    } 

C# Access Modifier

C# Access Modifier

Meaning in Life

public

Marks amember as accessible from an object variable as well as any derived classes.

private

Marks a method as accessible only by the class that has defined the

method. In C#, all members are private by default.

protected

Marks a method as usable by the defining class, as well as any derived

classes. Protected methods, however, are not accessible from an object

variable.

internal

Defines a method that is accessible by any type in the same assembly,

but not outside the assembly.

protected internal

Defines a method whose access is limited to the current assembly or

types derived from the defining class in the current assembly.

Class Modifiers and their uses in C# .Net

Class/Interface (Base class)

Inheritance (Inherited class)

Implementation (Interface)

(Child)

(Instance)

Is initiated??

General

Abstract

Sealed

Static*

General

Yes

Yes

Yes

No

No

Yes

Abstract

Yes

Yes

Yes

No

No

No

Sealed

No

No

No

No

No

Yes

Static

No

No

No

No

No

No

Interface

Yes

Yes

Yes

No

Yes

No

 

 

 


 

 

 

 

 

This table is for showing relationship between a base class and child class

In this table I want to show the accessibility among the various types of classes and interface. From this table you also can know what type of class can be initiated. This is one example that helps you to understand the table.

If you use Abstract class as base class and take a general class as child and want to inherit, this will possible …here you can see..

Base: Abstract (ASadi)

Child: Interface (Sadi)

Accessibility: Yes

abstract class Sadi : ASadi

{

#region ASadi Members

public int getint() {

throw new Exception(“The method or operation is not implemented.”); }

#endregion

}

If you execute this code, it executes properly

From the first column of the table we can say that general class inherites both general and abstract class and also implements an interface. These classes cannot inherites sealed as well as static class. Only General and Sealed classes can be initiated.

From the table and above discussion we can conclude that,

Abstract Class

A class defined as abstract is used as a base class. Such a class is used for the purpose of inheritance only i.e. other classes are derived from this class. We cannot create an object of an abstract class. An abstract class may contain methods and properties. The classes derived from the abstract class inherit these methods and properties. The abstract class may also contain abstract methods and properties. Abstract method and properties do not have any functionality. The derived class defines their full functionality.

Here is an example of an abstract class:

abstract class MyAbstract { public abstract void AbMethod(); }

Sealed Class

Classes can be declared as sealed. This is accomplished by putting the sealed keyword before the keyword class in the class definition. For example:

public sealed class classSealed { // Class members here. public string ID; public double Price; }

A sealed class cannot be used as a base class. For this reason, it cannot also be an abstract class. Sealed classes are primarily used to prevent derivation. Because they can never be used as a base class, some run-time optimizations can make calling sealed class members slightly faster. Sealing a class means one cannot derive from it. Sealing a method means one cannot override it. In C# structs are implicitly sealed; therefore, they cannot be inherited. If we try to inherit from a sealed class in another class we will get compile time error about Inconsistent accessibility (code is shown in following code listing). In C# a method cannot be declared as sealed. However when we override a method in a derived class, we can declare the overridden method as sealed as shown below. By declaring it as sealed, we can avoid further overriding of this method.

Static Class

Static classes are classes that contain only static members. Following is an example of static class. public static MyClass { …..}

A class can be declared static, which indicates that it contains only static members. It is not possible to use the new keyword to create instances of a static class. Static classes are loaded automatically by the .NET Framework common language runtime (CLR) when the program or namespace that contains the class is loaded.

Use a static class to contain methods that are not associated with a particular object. For example, it is a common requirement to create a set of methods that do not act on instance data and are not associated to a specific object in your code. You could use a static class to hold those methods.

Following are the main features of a static class:

·         They only contain static members.

·         They cannot be instantiated.

·         They are sealed.

·         They cannot contain Instance Constructors (C# Programming Guide).

Creating a static class is therefore basically the same as creating a class that contains only static members and a private constructor. A private constructor prevents the class from being instantiated.

The advantage of using a static class is that the compiler can check to make sure that no instance members are accidentally added. The compiler will guarantee that instances of this class cannot be created.

Static classes are sealed and therefore cannot be inherited. They cannot inherit from any class except Object. Static classes cannot contain an instance constructor; however, they can have a static constructor. For more information, see Static Constructors (C# Programming Guide).

 

Difference between Namespace and Assembly in C# .Net

Assembly will contain Namespaces, Classes, Data types it’s a small unit of code for deployment. Assembly defines the name of the .dll file.
Namespace is used in order to avoid conflict of user defined classes

Namespace:
1) it is a Collection of names wherein each name is Unique.
2) They form the logical boundary for a Group of classes.
3) Namespace must be specified in Project-Properties.

Assembly:
1) It is an Output Unit.
2) It is a unit of Deployment & a unit of versioning.
3) Assemblies contain MSIL code.
4) Assemblies are Self-Describing. [e.g. metadata,manifest]
5)An assembly is the primary building block of a .NET Framework application.
6) It is a collection of functionality that is built, versioned, and deployed as a single implementation unit (as one or more files).
7) All managed types and resources are marked either as accessible only within their implementation unit, or by code outside that unit.

Simple Example of Inheritance and Interface (why do we use Inheritance and interface) in c# .Net

using System;
using System.Collections.Generic;
using System.Text;
interface Talkable
{
string Table();
}
class Animal { }
class Cat : Animal, Talkable
{
string Talkable.Table() { 
return "miao"; 
}
}
class Dog : Animal, Talkable
{
string Talkable.Table(){
return "bulk"; 
}
}
class Elephant : Animal
{
}
class MainClass
{
static void Main()
{
Animal[] AnimalArray = new Animal[3];
AnimalArray[0] = new Cat();
AnimalArray[1] = new Elephant();
AnimalArray[2] = new Dog();
foreach (Animal a in AnimalArray)
{
Talkable b = a as Talkable;
if (b != null)
Console.WriteLine("Baby
is called: {0}", b.Table());
}
}
}
output:
Baby is called: miao
Baby is called: bulk

Difference between class and struct in C# .Net

1. Classes are reference types and structs are value types.
Since classes are reference type, a class variable can be assigned null.But we cannot assign null to
a struct variable, since structs are value type.
2. When you instantiate a class, it will be allocated on the heap.When you instantiate a struct, it gets created on the stack.
3. You will always be dealing with reference to an object ( instance ) of a class. But you will not be dealing with references to an instance of a struct ( but dealing directly with them ).
4. When passing a class to a method, it is passed by reference. When passing a struct to a method, it’s passed by value instead of as a reference.
5. You cannot have instance Field initializers in structs.But classes can have
example:
class MyClass
{
int myVar =10; // no syntax error.
public void MyFun( )
{
// statements
}
}
struct MyStruct
{
int myVar = 10; // syntax error.
public void MyFun( )
{
// statements
}
}
6. Classes can have explicit parameterless constructors. But structs cannot have
7. Classes must be instantiated using the new operator. But structs can be
8. Classes support inheritance.But there is no inheritance for structs.
( structs don’t support inheritance polymorphism )
9. Since struct does not support inheritance, access modifier of a member of a struct cannot be protected or protected internal.11. A class is permitted to declare a destructor.But a struct is not
12. classes are used for complex and large set data. structs are simple to use.

Dynamic Method Invocation in C# .Net (Static Method and Non Static Method)

Create a solution in visual studio and add two project. First project name is  “FirstProject” and second one is “DynamicInvoke”. In the first project add Class1.cs class and compile.

Class1.cs

using System;
public class Class1{
public static String method1()
{
return "I am Static method (method1) in class1";
}
public String method2()
{
return "I am a Instance Method (method2) in Class1";
}
public String method3(String s)
{
return "Hello " + s;
}
}

DynaInvoke.cs

using System;
using System.Reflection;
class DynamicInvoke
{
public static void Main(String[] args)
{
Assembly MyAssembly = Assembly.Load("FirstProject");
//For getting the assembly click the right mouse on the class1 oject then go to the property
Type MyType = MyAssembly.GetType("FirstProject.Class1");
//class name should be added with assembly like (assemblyName.className) (NameSpace with classname)
object MyObj = Activator.CreateInstance(MyType);

//Invoking a static method (How to invoke a static method??)
String str = (String)MyType.InvokeMember("method1", BindingFlags.Default | BindingFlags.InvokeMethod, null, null, new object[] { });
Console.WriteLine(str);

//Invoking a non-static method (How to invoke a non static method??)
str = (String)MyType.InvokeMember("method2", BindingFlags.Default | BindingFlags.InvokeMethod, null, MyObj, new object[] { });
Console.WriteLine(str);

//Invoking a non-static method with parameters (How to invoke a non static method with parametres??)
object[] MyParameter = new object[] { "Sadi" };
str = (String)MyType.InvokeMember("method3", BindingFlags.Default | BindingFlags.InvokeMethod, null, MyObj, MyParameter);
Console.WriteLine(str);
}
}

In the second project add this code and run..

Difference between Abstract class and Interface in C# .Net

Interfaces are essentially having all method prototypes no definition but Abstract class can contain method definations also.

In short Interface is a abstract class having all methods abstract.

Both abstract classes and interfaces are used when there is a difference in behaviour among the sub-types extending the abstract class or implementing the interface.

When the sub-types behaviour is totally different then you use an interface, when the sub-types behaviour is partially common and different with respect to the supertype an abstract class is used. In an abstract class the partially common behaviour is given a concrete implementation. Since there is no common behaviour between an interface and a sub-type an interface does not have an implementation for any of its behaviour.

If you create a abstract class writing the abstract keyword in the declaration part then You only can inherit the class. You can not create an instance of this abstract class but can inherit the class and with creating the instance of the derived class you can access the method of the abstract class.

If you use a virtual keyword in a method then you can override this method in the subclass if you wish..

If you create a abstract method then you must override this method in the subclass other wise it shows error in the program.

what’s the difference between architecture and framework? in C# .Net

as far as i know, the architecture is the first design result which
should consider some functions and properties of quality,sometimes
environment of the software,while framework is focus on domain-specificated
application which is something general to a certain domain.

could i have such a conclusion,if i do something first,it’s
architecture,if i do it again it called repeated labor,if i do it thirdly
then i could consider to make it a common framework?

Alas, both words are heavily overloaded in the software industry.
Basically the definition depends on which tool vendor one is talking to.
for example, the Computer Desktop Encyclopedia defines the terms as:

architecture: The set of protocols for communicating with another
application.

framework: the set of building blocks for constructing an application.

I don’t like either of those definitions because they don’t agree with
what Daddy told me many moons ago as I sat on his knee. FWIW, I prefer
the definitions:

architecture: The strategy and/or infrastructure for accomplishing some
specific goal that defines or supports cooperation among multiple
distinct software elements.

framework: An infrastructure that acts as a generic skeleton for
combining customized software elements. Generally a framework can be
reused for multiple applications or systems of applications.

Since both can be infrastructures, in my view the distinction is
primarily about reuse. Architectures are usually focused on specific
problem contexts while frameworks are designed to be used in entirely
different problem contexts.