Component Programming with C# and.NET. C# components The most commonly used components in.NET are...

35
Component Programming with C# and .NET

Transcript of Component Programming with C# and.NET. C# components The most commonly used components in.NET are...

Page 1: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Component Programming with C# and .NET

Page 2: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

C# components

•The most commonly used components in .NET are the visual controls that you add to

Windows Forms such as the Button Control (Windows Forms), ComboBox Control

(Windows Forms), and so on .

•Non-visual components include the Timer Control, SerialPort,

and ServiceController among others.

Page 3: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

What defines a component?

•What defines a component?– Properties, methods, events– Design-time and runtime information– Integrated help and documentation

Page 4: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

AP 08/01

public class Button: Controlpublic class Button: Control{{

private string captionprivate string caption;;

public string Captionpublic string Caption{ { getget{ {

return captionreturn caption;;} } setset{ {

caption = valuecaption = value;; RepaintRepaint;)(;)(} }

} } }}

Properties•Properties are “smart fields”

–Natural syntax, accessors, inlining

Button b = new ButtonButton b = new Button;)(;)(b.Caption = "OKb.Caption = "OK;";"

String s = b.CaptionString s = b.Caption;;

Page 5: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

AP 08/01

Indexers•Indexers are “smart arrays”

–Can be overloaded

public class ListBox: Control{

private string[] items;

public string this[int index]{ get{

return items[index];} set {

items[index] = value; Repaint;)(}

} }

ListBox listBox = new ListBoxListBox listBox = new ListBox;)(;)(listBox[0] = "hellolistBox[0] = "hello;";"

Console.WriteLine(listBox[0])Console.WriteLine(listBox[0]);;

Page 6: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

AP 08/01

Events•Efficient, type-safe and customizable

–Built on delegates

public class MyForm: Form{ public MyForm )(

{ Button okButton = new Button;)...(

okButton.Click += new EventHandler(OkButtonClick);}

void OkButtonClick )…({

ShowMessage("You clicked OK");} }

Page 7: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Events

•Events enable a class or object to notify other classes or objects when something of interest

occurs•The class that sends (or raises) the event is

called the publisherand the classes that receive (or handle) the event are

called subscribers.

Page 8: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Example

•Arithmetic component which does addition•We will create a component called

csAddComp1 and package it into a dll (Dynamic Linked Library) .

•This component has two properties and a method .

•Properties take input for the addition and method called Sum.) (

Page 9: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Example•To create properties in C# you

use the get and set accessors .•The get accessor is used for

getting (reading) .•The set accessor for setting

(writing) the property

Page 10: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Component Programusing System ;

namespace CompCS { public class csAddComp1 {

private int i=0,j=0 ;public int varI { get { return i; } //this is property get for varI set { i=value; } //this is property set for varI

}public int varJ {

get { return j; } // this is property get for varJ set { j=value; } // this is property set for varJ

}public int Sum { )(

return i+j; //this returns the sum of two variables// } } end of class

// } end of namespace

Page 11: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

DLL package •To package the component as dll there is slight change

in usual compilation process .•Its little complicated process when compared to normal

stand-alone program compilation.csc /out:csAddComp1.dll /target:library csAddComp1.cs

•Here the /out switch to put the compiled component in the relative subdirectory and file for convenience .

•Likewise, we need the /target:library switch to actually create a DLL rather than an executable with a .dll file

extension.

Page 12: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

 client programusing System ;

using CompCS ;

class clAddComp1 {

public static void Main { )(

csAddComp1 addComp= new csAddComp1 ;)(

addComp.varI=10; //property set for varI

addComp.varJ=20; //property set for varJ //below property get for varI

Console.WriteLine("variable I value : {0}",addComp.varI); //below property get for varJ

Console.WriteLine("variable J value : {0}",addComp.varJ); // calling Sum(..) method

Console.WriteLine("The Sum : {0}",addComp.Sum()) ;

// }end of Main

// }end of Class

Page 13: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Component Designer in C#•Allows to add subcomponents to a class, configure

them, and code their events .•Add components and items from the Toolbox or

from Server Explorer.•Group together a set of subcomponents into a

single class.•Double-click the designer and write code in the

general declarations section of the class, or double-click an element on the designer to write code for

that element.

Page 14: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Component Designer in C#

•To display the designer, from the Project menu, select Add Component .

•The Add New Item dialog box appears .•By default, the Component Class item is selected .•Click OK to add a new component to project and open

the Component Designer.•http://www.youtube.com/watch?v=DgAqyYO20nY

Page 15: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

As an example, to package the alarm functionality we built earlier around the Timer component, let's build anAlarmComponent class. To create a new component class, right-click on the project and choose Add | Add Component, enter the name of your component class, and press OK. You'll be greeted with a blank design surface,

Page 16: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.
Page 17: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

using System ;using System.ComponentModel ;

using System.Collections ;using System.Diagnostics   ;namespace Components{

public class AlarmComponent : System.ComponentModel.Component { private Timer timer1 ;

private System.ComponentModel.IContainer components   ;public AlarmComponent(System.ComponentModel.IContainer container) {

container.Add(this) ;InitializeComponent   ;)(

  } public AlarmComponent{ )(

InitializeComponent   }   ;)(private void InitializeComponent { )(

this.components = new System.ComponentModel.Container ;)(this.timer1 = new System.Windows.Forms.Timer(this.components) ;

this.timer1.Enabled = true}}} ;

Page 18: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Attributes•C# declarations contain keywords, such as public and private, that

provide additional information about class members .•These keywords further define the behavior of class members by

describing their accessibility to other classes .•Because compilers are explicitly designed to recognize predefined

keywords, you do not traditionally have the opportunity to create your own .

•keyword-like descriptive declarations, called attributes, annotate programming elements such as types, fields, methods, and

properties.

Page 19: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Attributes•How do you associate information with types

and members?–Documentation URL for a class–Transaction context for a method–XML persistence mapping

•Traditional solutions–Add keywords or pragmas to language–Use external files, e.g., .IDL, .DEF

•C# solution: Attributes

Page 20: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Attributes

•We can use attributes to define both design-level information (such as help file,

URL for documentation) and run-time information (such as associating XML field

with class field) .

•We can also create "self-describing" components using attributes .

Page 21: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Attributes

[[HelpUrl(“http://SomeUrl/Docs/SomeClass”)HelpUrl(“http://SomeUrl/Docs/SomeClass”)]]class SomeClassclass SomeClass{{

[ [ WebMethodWebMethod]] void GetCustomersvoid GetCustomers} … { )(} … { )(

string Test([SomeAttr] string param1)string Test([SomeAttr] string param1)}…{ }…{ }}

•Appear in square brackets•Attached to code elements

Page 22: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Apply attributes

•Define a new attribute or use an existing attribute by importing its namespace from the

.NET Framework.

Page 23: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Exampleusing System ;

public class AnyClass { [Obsolete("Don't use Old method, use New method", true) ]

static void Old } { ) (static void New } { ) (

public static void Main ) ( {

Old ;) (} }

Page 24: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Example•we use attribute Obsolete, which marks a

program entity that should not be used .

•The first parameter is the string that can be any text .

•The second parameter tells the compiler to treat the use of the item as an error .

•Default value is false, which means compiler generates a warning for this.

Page 25: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Attribute Fundamentals

•Attributes are classes! Completely generic

class HelpUrl : System.Attribute { public HelpUrl(string url)} … {

… }

[HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)]class SomeClass} … {

Page 26: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Attributes to specify DLL Imports

[DllImport("gdi32.dll",CharSet=CharSet.Auto)]public static extern

int GetObject( int hObject , int nSize ,

[ In, Out ]ref LOGFONT lf;)

[DllImport("gdi32.dll")]public static extern

int CreatePen(int style, int width, int color);

Page 27: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Component & attributes•components can be displayed in a designer, such as Visual

Studio .NET, but required attributes that provide metadata to design-time tools.

•A DesignerAttribute attribute is applied at the class level and informs the forms designer which designer class to use to

display the control .

•Components are associated with a default designer (System.ComponentModel.Design.ComponentDesigner),

and Windows Forms and ASP.NET server controls are associated with their own default designers .

•Apply DesignerAttribute only if you define a custom designer for your component or control.

Page 28: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

To add a security attribute to a code member of your component

using System.Security.Permissions;

[FileIOPermission(SecurityAction.Demand)]

public void FileDeleter )(

// {Insert code to delete files} .

Page 29: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

COM Support

•.NET Framework provides great COM support –TLBIMP imports existing COM classes–TLBEXP exports .NET types

•Most users will have a seamless experience

Page 30: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Building COM components using.NET Framework

•Create C# - Class Library project•Configure Project Property Pages with the right

information•Develop the AccountManager.cs library•Modify the generated AssemblyInfo.cs to add the right

assembly information•Build the Project Files•Deploy the component as a Shared Assembly, and

Configure the Assembly in the COM+ Catalog

Page 31: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.
Page 32: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Configure your Project Property Pages with the right information

Page 33: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.
Page 34: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

add the right assembly information

[assembly: AssemblyTitle("AccountManager for Bank")][assembly: AssemblyDescription)"Creates and Deletes

Accounts for the Bank"(][assembly: AssemblyConfiguration(""])[assembly: AssemblyCompany)"eCommWare

Corporation"(][assembly: AssemblyProduct)"COM+ Bank Server"(][assembly: AssemblyCopyright)"(c) 2001, Gopalan

Suresh Raj. All Rights Reserved."(][assembly: AssemblyTrademark)"Web Cornucopia"(][assembly: AssemblyCulture)"en-US"(]

Page 35: Component Programming with C# and.NET. C# components The most commonly used components in.NET are the visual controls that you add to Windows Forms such.

Calling into a COM component

•Create .NET assembly from COM component via tlbimp•Client apps may access the newly created assembly

using System;using System.Runtime.InteropServices;

using CONVERTERLib;

class Convert{ public static void Main(string [] args){ CFConvert conv = new CFConvert;)(

...fahrenheit = conv.CelsiusToFahrenheit( celsius );