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

Advertisements

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.

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()"
            }
        }
    } 

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