Sadi02’s Weblog

March 16, 2009

Building Blocks of .Net Platforms (CLR, CTS, CLS)

Filed under: Asp.Net, Computer Science — Md. Shaik Sadi @ 12:19 pm

CLR (Common Language Runtime): Programmatically speaking, the term runtime can be understood as a collection of external services that are required to execute a given compiled unit of code. The CLR is the layer of the .NET Framework that makes the source code into an intermediate language which is language independent. This language is called the Microsoft Intermediate Language. 

The key difference between the .NET runtime and the various other runtimes I just mentioned is the fact that the .NET runtime provides a single well-defined runtime layer that is shared by all languages and platforms that are .NET-know. 

The primary role of the CLR is to locate, load, and manage .NET types on your behalf. The CLR also takes care of a number of low-level details such as memory management and performing security checks. 

CTS (Common Type System): In the world of .NET, “type” is simply a generic term used to refer to a member from the set {class, structure, interface, enumeration, delegate}. When you build solutions using a .NET-aware language, you will most likely interact with each of these types. The Common Type System (CTS) is a formal specification that documents how types must be defined in order to be hosted by the CLR. 

Every language running on the .NET platform has a base set of data types provided by CTS.  CTS is responsible for defining type of .NET languages. Most of the languages running on .NET platform use aliases for using those CTS types. For example, a four-byte integer value is represented by the CTS type System.Int32. C# defines an alias for this called type called int and in VB.NET called Integer. 

CLS (Common Language System): The Common Language Specification (CLS), which is a set of basic language features needed by many .Net applications to fully interact with other objects regardless of the language in which they were implemented. The CLS represents the guidelines defined by for the .NET Framework. These specifications are normally used by the compiler developers and are available for all languages, which target the .NET Framework.

September 15, 2008

How to store log in database using log4net

Filed under: Computer Science — Tags: , , , , — Md. Shaik Sadi @ 10:00 am

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.

 

 

 
 
 
 
 
 
 
 

 

 


July 6, 2008

.Net Remoting with a simple example

Filed under: Computer Science — Tags: , , , , , — Md. Shaik Sadi @ 10:46 am

Introduction: .NET remoting enables you to build widely distributed applications easily, whether the application components are all on one computer or spread out across the entire world. You can build client applications that use objects in other processes on the same computer or on any other computer that is reachable over its network. You can also use .NET remoting to communicate with other application domains in the same process.

 

To use .NET remoting to build an application in which two components communicate directly across an application domain boundary, you need to build only the following:

 

  • A remotable object.
  • A host application domain to listen for requests for that object.
  • A client application domain that makes requests for that object.

 

Complete Remoting System Design

Suppose you have an application running on one computer, and you want to use the functionality exposed by a type that is stored on another computer. The following illustration shows the general remoting process.

Remoting process

 

If both sides of the relationship are configured properly, a client merely creates a new instance of the server class. The remoting system creates a proxy object that represents the class and returns to the client object a reference to the proxy. When a client calls a method, the remoting infrastructure handles the call, checks the type information, and sends the call over the channel to the server process. A listening channel picks up the request and forwards it to the server remoting system, which locates (or creates, if necessary) and calls the requested object. The process is then reversed, as the server remoting system bundles the response into a message that the server channel sends to the client channel. Finally, the client remoting system returns the result of the call to the client object through the proxy.

Very little actual code is required to make this work, but some thought should be given to the design and the configuration of the relationship. The code can be absolutely correct and yet fail because a URL or port number is incorrect.

Channels

Channels are objects that transport messages between applications across remoting boundaries, whether between application domains, processes, or computers. A channel can listen on an endpoint for inbound messages, send outbound messages to another endpoint, or both. This enables you to plug in a wide range of protocols, even if the common language runtime is not at the other end of the channel.

Channels must implement the IChannel interface, which provides informational properties such as ChannelName and ChannelPriority. Channels designed to listen for a particular protocol on a particular port implement IChannelReceiver and channels designed to send information implement IChannelSender. Both the TcpChannel and HttpChannel objects implement both of these interfaces, so they can be used to send or receive information.

You can register channels with the remoting infrastructure in the following ways:

  • If you are publishing a remotable object, call ChannelServices.RegisterChannel prior to registering your server object.
  • If you are consuming a remotable object’s functionality, call RegisterChannel prior to creating an instance of your server object.

Types of Remoting

There are two very different types of remote interaction between components

  • Marshal by value (Uses Serializable objects passed as a copy)
  • Marshal by Ref (Sends Objects implemented the MarshalByRefObject)

What is Marshaling?

Passing an object between process or machines are called marshaling.

Marshal by value objects

Marshaling by value means to serialize the objects in a persistent form from which they can be deserialized in a different context. Only a state of the object will be marshal.

[Serializable]

public class CCustomer

{

public int Id;

public string name;

 

public CCustomer()

{

Console.WriteLine(“New CCustomer is Created…”);

}

}

an instance of CCustomer is objCustomer

where, objCustomer.Id=5;objCustomer.name=”ABC”;

 

if you get this object remotely then you will get like this

 

<CCustomer>

<id>5</id>

<name>”ABC”</name>

</CCustomer>

Marshal by Ref Objects

Marshal by ref objects are objects that created and run on the client machine when using by a remote client. All of its data is stored in the server memory. These objects are identify by a pointer like ObjRef which actually contains the server name/IP and Identity that identify one from a set of objects running on the server.

To expose a object as marshal by ref extend it with MarshalByRefObject.

public class CCustomer:MarshalByRefObject

{

public int Id;

public string name;

 

public CCustomer()

{

Console.WriteLine(“New CCustomer is Created…”);

}

}

Activation of Remote Objects

There are two types of activation for marshal-by-reference objects:

  • Server activation.

Server-activated objects are created by the server only when they are needed. They are not created when the client proxy is created by calling new or Activator.GetObject, but rather when the client invokes the first method on that proxy. For details, see Server Activation.

Server Activation Modes

There are two activation modes (or WellKnownObjectMode values) for server-activated objects: Singleton and SingleCall.

  • Singleton types never have more than one instance at any one time. If an instance exists, all client requests are serviced by that instance. If an instance does not exist, the server creates an instance and all subsequent client requests will be serviced by that instance. Because Singleton types have an associated default lifetime, clients will not always receive a reference to the same instance of the remotable class, even if there is never more than one instance available at any one time.

 

  • SingleCall types always have one instance per client request. The next method invocation will be serviced by a different server instance, even if the previous instance has not yet been recycled by the system. SingleCall types do not participate in the lifetime lease system.
  • Client activation.

Client-activated objects are created on the server when the client calls new or Activator.CreateInstance. The client itself, using the lifetime lease system, can participate in the lifetime of these instances. For details, see Client Activation and Lifetime Leases.

A Simple Example of .Net Remoting

 

SERVER

 

  1. At first create a solution name “server” in visual studio
  2. Add a library project Name ‘”SharedLibrary” in the solution.
  3. Add a class name “CCustomer” and put this code given below

 

using System;

using System.Collections.Generic;

using System.Text;

 

namespace SharedLibrary

{

/// <summary>

/// this is a interface of customer manager

/// </summary>

public interface ICustomerMgr

{

CCustomer GetCustomer();

int Number

{

get;

set;

}

}

/// <summary>

/// This is customer class

/// </summary>

public class CCustomer

{

public CCustomer()

{

Console.WriteLine(“New Customer is created…….”);

}

public int Id;

}

}

4. Build this project.

    5. Add a console project Name “server” in the solution

    6. Add the reference of “SharedLibrary.dll” from project.

    7. Add a class Name “CCustomerMgr” and put the code in the class.

 

using System;

using System.Collections.Generic;

using System.Text;

using SharedLibrary;

 

namespace Server

{

[Serializable]

public class CCustomerMgr : MarshalByRefObject, ICustomerMgr

{

CCustomer oCustomer;

private int _iNumber;

 

/// <summary>

///

/// </summary>

public int Number

{

get { return _iNumber; }

set { _iNumber = value; }

}

/// <summary>

///

/// </summary>

public CCustomerMgr()

{

oCustomer = new CCustomer();

oCustomer.Id = 99340;

Number = 100;

 

Console.WriteLine(“New CustomerMgr is Created…”);

}

/// <summary>

///

/// </summary>

/// <returns></returns>

public CCustomer GetCustomer()

{

return oCustomer;

}

}

}

 

 

  8. The main method will be like this and compile

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.Remoting.Channels.Http;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Services;

using System.Runtime.Remoting.Channels;

 

 

namespace Server

{

public class Program

{

static void Main(string[] args)

{

HttpChannel Chn = new HttpChannel(1234);

ChannelServices.RegisterChannel(Chn);

RemotingConfiguration.RegisterWellKnownServiceType(typeof(CCustomerMgr), “sadi.com”, WellKnownObjectMode.Singleton);//put the type of object, Url name and mode.

 

Console.WriteLine(“Enter any key to stop the server…”);

Console.ReadLine();

}

}

}

 

CLIENT

  1. At first create a solution name “Client” in visual studio
  2. Add a console project Name “Client” in the solution.
  3. Add the reference of “SharedLibrary.dll”.
  4. The main method will be like this(if the client is in your local machine then it will “localhost”. If the client is in another machine then put the machine name in the “localhost”)

 

using System;

using System.Collections.Generic;

using System.Text;

using System.Runtime.Remoting;

using System.Runtime.Remoting.Channels.Http;

using System.Runtime.Remoting.Services;

using System.Runtime.Remoting.Channels;

using SharedLibrary;

 

namespace Client

{

public class Program

{

static void Main(string[] args)

{

HttpChannel Chn = new HttpChannel();

ChannelServices.RegisterChannel(Chn);

ICustomerMgr oCustomerMgr = (ICustomerMgr) Activator.GetObject(typeof(ICustomerMgr),“http://localhost:1234/sadi.com”);//if the client is in your local machine then it will //“localhost”. If the client is in another machine then put the //machine name in the “localhost”

 

Console.WriteLine(“Before Change :” + oCustomerMgr.Number);

oCustomerMgr.Number += 100;

Console.WriteLine(“After Change :” + oCustomerMgr.Number);

Console.ReadLine();

}

}

}

 5. Build the programe.

 

Execute The Remoting Process

  1. At first run the surver ..the output will show in console—

Enter any key to stop the server…

    2.  Then open the client and run the output will be—

Before Change :100

After Change :200

June 30, 2008

ADO.NET – DataReader(Connected) and DataSet(Disconnected) in C# .Net with Examples

Filed under: Computer Science — Tags: , , , — Md. Shaik Sadi @ 9:07 am

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();

                }

            }

        }

June 29, 2008

Log4Net Tutorial in C# .net (How can I show log in a file?)

Filed under: Computer Science — Tags: , , , — Md. Shaik Sadi @ 7:32 am

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

    {       

        static void Main(string[] args)

        {

             log4net.Config.BasicConfigurator.Configure();

             log4net.ILog log = log4net.LogManager.GetLogger(typeof(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:\temp\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: 

1.  using System;

2.  using System.Collections.Generic;

3.  using System.Text;

4.  using log4net;

5.  using log4net.Config;

6.   

7.  namespace LogPractice

8.  {

9.      class Program

10.    {

11.        protected static readonly ILog log = LogManager.GetLogger(typeof(Program));

12.        static void Main(string[] args)

13.        {

14.            log4net.Config.XmlConfigurator.Configure();

15. 

16.            //————————–

17.            log.Warn(“sadi the great”);

18.   

19.        }

20.    }

21.}

 

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. 

 

 

June 25, 2008

What is the main difference between process and procedure in Software Engineering?

Filed under: Computer Science — Tags: , — Md. Shaik Sadi @ 5:43 am

 

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.

June 23, 2008

Find data from a data structure(List, Dictionary) using delegate in c# .Net

Filed under: Computer Science — Tags: , , , — Md. Shaik Sadi @ 4:23 am
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
        }
    }
}

June 4, 2008

What’s the difference between override and new in C#? (Use of override and new modifier)

Filed under: Computer Science — Tags: , , , — Md. Shaik Sadi @ 9:57 am

 

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#

Filed under: Computer Science — Tags: , , — Md. Shaik Sadi @ 8:49 am

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

June 1, 2008

C# Access Modifier

Filed under: Computer Science — Tags: , — Md. Shaik Sadi @ 9:39 am

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.

Older Posts »

Blog at WordPress.com.