Component Programming in Dotnet


Èñòî÷íèê: http://www.csharphelp.com/2006/07/component-programming-in-dotnet/


What is Component?

    Component is the reusable piece of software in binary form, which can be used by another components. COM is a specification for the construction of binary-compatible software components. COM is not a programming language, an API or a compiler. COM allows developers to build components that can communicate with each other, no matter which is the programming language you choose to build it. COM is Microsoft's binary specification for what an object is and how it can be used. ActiveX Components, Beans, EJB's are the examples of COM (Component Object Model) Technologies implemented by Microsoft and Sun Microsystem.

    We have been developing components using Visual Basic and Visual C++. we are all familiar with COM and each one of us must have developed .DLL, .OCX or at least .EXE. These components were great for the functionality, they take huge amount of time and resource to develop and every Visual Basic developer knows about the DLL Hell.

Microsoft's COM

    In traditional COM (before .NET), we must register our COM objects within the window registry so client programs can access the objects.

    Advantages of COM

    Using COM, you don't need to build and update the whole application every time. You can rebuild a single component.

    In typically COM development, you have to develop the component interfaces first, to make sure that everything will work together. Once the interfaces are designed, you can distribute them to several programmers, and the implementation of the components can proceed in parallel.

    For example, you are developing one project, using different components, like String-handling component, a calculation component and a database component. All of them can be built at the same time, with the different languages and programmers, if the interfaces are designed properly.

Limitation of COM

    Every component must get unique ID(GUID=Globally Unique Identifier), for the identify component by the operating system. These GUIDs are stored in the Registry. The problem is, every time you change your component's interface, a new GUID is assigned to it. You have to be careful during development of COM, about the versions of the component you are using. And if component version got out of the control, it will be real debugging problem for your application.

    COM's problems are component versioning, language interoperability and application deployment. For example, there are lots of components from C++ are unusable for Visual Basic. C++ built-in types (strings, pointers) are impractical (sometimes impossible) to use from other languages.

   .NET simplifies these issues.

    .NET was specifically created for these some of the reasons. In the early 1990, Microsoft developed OLE (Object Linking and Embedding) technology. For example, MS Word and Excel were great products individually, but users sometimes wanted to incorporate spreadsheet within word document. Using OLE technology, users can insert a document from one application into another.

CLR

    The programming model of the CLR is based on the universal type system. The CLR translate any CLR-compliant application to MS Intermediate Language. This IL code is then complied for the platform where it will be executed. Exactly this process allows you to create an application or component in one language that can be used on any other language or operating system using CLR. Right now Microsoft is releasing four different languages that supports CLR. These are Visual Basic.NET, C#, C++.NET and JScript.NET. Third-party languages are also being developed, such as Perl, Cobol and SmallTalk. In the near future it is possible that .NET will be ported to other non windows operating system viz. Linux, FreeBSD.

    The CLR standardizing on a universal set of types that are shared across all managed languages. Visual Basic.NET provides the Integer keyword, which is the equivalent of the int keyword in C#. Both types map directly to the CLR's System.Int32 type.

What is Csharp?

    C# is a brand new language developed by Microsoft for its new .NET Framework. After Windows DNA, .NET Framework is Microsoft's development platform for building component-based applications. C#, created by Andres Hejlsberg one of distinguished developer of Microsoft, who was also responsible for creating Delphi and Turbo Pascal.

    I think you might have got an overview of COM, C# and its capability. Now will make on component in Csharp and will use in another application. So we can learn how to make component in .NET environment.

    We will create dll component using notepad(or your fav. Text editor) and also I will show you how to create the dll using Visual Studio Beta 2 IDE.

   A component contains a public interface, which is used by Client application.
Code Listing 1.0
using System;
namespace BankAccount
{
public class Account
{
public int Balance = 100;
public Account()
{
}
public int CheckBalance()
{
return Balance;
}
public int Deposite(int amt)
{
Balance = Balance + amt;
return Balance;
}
public int WithDraw(int amt)
{
Balance = Balance – amt;
return Balance;
}
}
}
Save this file as BankAccount.cs
From the commandLine you can compile this as
csc /t:library BankAccount.cs

    The "/t:library" in compilation code says that c# compiler to create a library and also tells to not to look for a static Main() method.

    The code is fairly simple. We create one Class Account with three methods checkBalance(), Deposite() and WithDraw(). My Initial Balance is 100;

    If you want to create dll component using VS.NET IDE create new C# ClassLibrary from New Project Wizard. It will automatically create the .dll in your debug folder of the project's folder.

    Our DLL component is complete now. Lets call this component in our another csharp application.

    Call methods and properties of the dll from a C# client is also an easy task. Just follow these few simple steps and see how to use component in C#.

    Now start the C# Windows application.

    Add Reference of the Namespace, Go to Projects menu and Add reference. Browse your dll component. And click OK.

    Now you can use your Component in your application.

    Use namespace using BankAccount;

    Now you have to create an Object of BankAccount.Account.

Account sachinac = new BankAccount.Account();

Now call the Methods and properties.
Make one Form with one TextBox and three Buttons.

Control Name
******* *****
TextBox Amount
CommandButton CheckBalance
CommandButton Deposite
CommandButton WithDraw
Form of application in Designer
Now double click on CheckBalance Button and write the code.

MessageBox.Show("Your Balance is " + sachinAc.Balance);

We will keep our coding simple, So we can understand how to use object. Repeat same thing for other buttons.

For Deposite Button :
sachinAc.Deposite(Convert.ToInt32(Amount.Text));

For WithDraw Button :
sachinAc.WithDraw(Convert.ToInt32(Amount.Text));

    Now compile your Application. And Check everything is going perfect.

    Here we used Convert.ToInt32 to convert String object into Int, because Amount. Text is String and We have defined method parameter amt as int.

    Check Balance will show you the current balance. Enter some amount in TextBox and click on any of the button then check your current balance.

    Great, So we have just created on component, basic simple but it is a component. C# provides full supports for properties, Events, Interfaces for components.

    We will take a detailed look about interfaces and events in the next week with one big example. And will explore some more about CLS. Also we will see how to use C# component in VB.NET.

Versioning

    Your component no longer need to be registered with the registry. Here, a developer can guarantee that his component will retain binary compatibility with existing client applications, as you can use different versions of a library in the same context because the libraries are referenced not by the Registry, but by the metadata contained in the executable code.

    Regards

Code Listing 1.0

using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using BankAccount;

namespace SachinAccount
{
public class Form1 : System.Windows.Forms.Form
{
private System.Windows.Forms.Button button1;
Account sachinAc = new Account();
private System.Windows.Forms.Button button2;
private System.Windows.Forms.Button button3;
public System.Windows.Forms.TextBox Amount;

private System.ComponentModel.Container components = null;

public Form1()
{
InitializeComponent();

//
// TODO: Add any constructor code after InitializeComponent call
//
}

/// <summary>
/// Clean up any resources being used.
/// </summary>
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}

public void InitializeComponent()
{
this.button1 = new System.Windows.Forms.Button();
this.button2 = new System.Windows.Forms.Button();
this.button3 = new System.Windows.Forms.Button();
this.Amount = new System.Windows.Forms.TextBox();
this.SuspendLayout();

this.button1.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.button1.Location = new System.Drawing.Point(8, 120);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 24);
this.button1.TabIndex = 0;
this.button1.Text = "Check Balance";
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// button2
//
this.button2.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.button2.Location = new System.Drawing.Point(120, 120);
this.button2.Name = "button2";
this.button2.Size = new System.Drawing.Size(96, 24);
this.button2.TabIndex = 0;
this.button2.Text = "Deposite";
this.button2.Click += new System.EventHandler(this.button2_Click);
//
// button3
//
this.button3.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Bold,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.button3.Location = new System.Drawing.Point(232, 120);
this.button3.Name = "button3";
this.button3.Size = new System.Drawing.Size(96, 24);
this.button3.TabIndex = 2;
this.button3.Text = "WithDraw";
this.button3.Click += new System.EventHandler(this.button3_Click);

this.Amount.Font = new System.Drawing.Font("Trebuchet MS", 8.25F, System.Drawing.FontStyle.Regular,
System.Drawing.GraphicsUnit.Point, ((System.Byte)(0)));
this.Amount.Location = new System.Drawing.Point(72, 48);
this.Amount.Name = "Amount";
this.Amount.Size = new System.Drawing.Size(192, 20);
this.Amount.TabIndex = 3;
this.Amount.Text = "Enter your Amount";

this.AutoScaleBaseSize = new System.Drawing.Size(5, 13);
this.ClientSize = new System.Drawing.Size(336, 157);
this.Controls.AddRange(new System.Windows.Forms.Control[] {

this.Amount,

this.button3,

this.button2,

this.button1});
this.Name = "Form1";
this.Text = "Form1";

this.ResumeLayout(false);

}

[STAThread]
static void Main()
{
Application.Run(new Form1());
}

private void button1_Click(object sender, System.EventArgs e)
{

MessageBox.Show("Your Balance is " + sachinAc.Balance);

}

private void button2_Click(object sender, System.EventArgs e)
{

sachinAc.Deposite(Convert.ToInt32(Amount.Text));

}

private void button3_Click(object sender, System.EventArgs e)
{
sachinAc.WithDraw(Convert.ToInt32(Amount.Text));
}
}
}