Component Programming with C# and.NET. C# components The most commonly used components in.NET are...
-
Upload
bruno-tyler-matthews -
Category
Documents
-
view
224 -
download
2
Transcript of Component Programming with C# and.NET. C# components The most commonly used components in.NET are...
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 the Button Control (Windows Forms), ComboBox Control
(Windows Forms), and so on .
•Non-visual components include the Timer Control, SerialPort,
and ServiceController among others.
What defines a component?
•What defines a component?– Properties, methods, events– Design-time and runtime information– Integrated help and documentation
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;;
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]);;
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");} }
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.
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.) (
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
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
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.
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
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.
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
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,
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}}} ;
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.
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
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 .
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
Apply attributes
•Define a new attribute or use an existing attribute by importing its namespace from the
.NET Framework.
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 ;) (} }
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.
Attribute Fundamentals
•Attributes are classes! Completely generic
class HelpUrl : System.Attribute { public HelpUrl(string url)} … {
… }
[HelpUrl(“http://SomeUrl/APIDocs/SomeClass”)]class SomeClass} … {
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);
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.
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} .
COM Support
•.NET Framework provides great COM support –TLBIMP imports existing COM classes–TLBEXP exports .NET types
•Most users will have a seamless experience
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
Configure your Project Property Pages with the right information
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"(]
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 );