You are on page 1of 41

Module 9: Developing

Components in Visual
Basic .NET
Overview

 Components Overview
 Creating Serviced Components
 Creating Component Classes
 Creating Windows Forms Controls
 Creating Web Forms User Controls
 Threading
 Components Overview

 Types of Components
 Using Modules As Components
 Using Classes As Components
 Using Components in Unmanaged Client Applications
 .NET Remoting Overview
Types of Components

 Structures
 Modules
 Classes
 Component classes
 Serviced components
 User controls
 Windows Forms user controls
 Web Forms user controls
Using Modules As Components

 Declare the module as public


 Reference and import the assembly into client code
Public
Public Module
Module MyMathFunctions
MyMathFunctions
Public
Public Function Square(ByVal
Function Square(ByVal lng
lng As
As Integer)
Integer) As
As Long
Long
Return
Return (lng
(lng ** lng)
lng)
End Function
End Function
...
...
End
End Module
Module

'Client
'Client code
code
Imports MyAssembly
Imports MyAssembly
...
...
Dim
Dim xx As
As Long
Long == Square(20)
Square(20)
Using Classes As Components

 Declare the class as public


 Reference and import the assembly into client code
Public
Public Class
Class Account
Account
Public
Public Sub Debit(ByVal
Sub Debit(ByVal AccountId
AccountId As
As Long,
Long, Amount
Amount As
As Double)
Double)
'Perform debit action
'Perform debit action
End
End Sub
Sub
Public
Public Sub
Sub Credit(ByVal
Credit(ByVal AccountId
AccountId As
As Long,
Long, Amount
Amount As
As Double)
Double)
'Perform credit action
'Perform credit action
End
End Sub
Sub
End Class
End Class

'Client
'Client code
code
Imports
Imports MyAssembly
MyAssembly
Dim
Dim xx As
As New
New Account(
Account( ))
x.Debit(1021,
x.Debit(1021, 1000)
1000)
Using Components in Unmanaged Client Applications

 Setting assembly properties


 Generate a strong name
 Select Register for COM Interop in Build options
 Exposing class members to COM and Component Services
 Define and implement interfaces
 Use the ClassInterface attribute with AutoDual value
 Use the COMClass attribute
.NET Remoting Overview
Client AppDomain Server AppDomain
Marshal By Reference

Client Code
Formatter
Formatter
Server
Proxy Channel
Server
Object
Marshal By Value
Client Code
Formatter Channel
Server Channel
Object
Copy

Remoting Boundary
 Creating Serviced Components

 Hosting Components in Component Services


 Using Transactions
 Using Object Pooling
 Using Constructor Strings
 Using Security
 Using Other Component Services
 Configuring Assemblies for Component Services
Hosting Components in Component Services

 Add a reference to System.EnterpriseServices in your


assembly
 The System.EnterpriseServices namespace provides:
 ContextUtil class
 ServicedComponent class
 Assembly, class, and method attributes
Using Transactions

 Transaction attribute specifies how a class participates in


transactions
 ContextUtil class provides transaction voting
 AutoComplete attribute avoids using the SetAbort, SetComplete,
and ContextUtil methods
<Transaction(TransactionOption.Required)>
<Transaction(TransactionOption.Required)> Public
Public Class
Class Account
Account
Inherits ServicedComponent
Inherits ServicedComponent
Public
Public Sub
Sub Debit(...)
Debit(...)
'Perform
'Perform debit
debit action
action
ContextUtil.SetComplete(
ContextUtil.SetComplete( ))
End
End Sub
Sub
<AutoComplete(
<AutoComplete( )>
)> Public
Public Sub
Sub Credit(...)
Credit(...)
'Perform credit action
'Perform credit action
'No
'No SetComplete
SetComplete because
because AutoComplete
AutoComplete is
is on
on
End
End Sub
Sub
End
End Class
Class
Using Object Pooling

 Object pooling allows objects to be created in advance


 ObjectPooling attribute specifies MinPoolSize and
MaxPoolSize
 ServicedComponent provides CanBePooled method

<ObjectPooling(Enabled:=True,
<ObjectPooling(Enabled:=True, MinPoolSize:=5,
MinPoolSize:=5, __
MaxPoolSize:=50)>
MaxPoolSize:=50)> __
Public
Public Class
Class Account
Account
Inherits
Inherits ServicedComponent
ServicedComponent
...
...
Protected
Protected Overrides
Overrides Function
Function CanBePooled(
CanBePooled( )) As
As Boolean
Boolean
Return
Return True
True
End
End Function
Function
End
End Class
Class
Using Constructor Strings

 Specify the ConstructionEnabled attribute to indicate that a


construction string is required
 Override the Construct method to retrieve information

<ConstructionEnabled(True)>Public
<ConstructionEnabled(True)>Public Class
Class Account
Account
Inherits
Inherits ServicedComponent
ServicedComponent
Protected
Protected Overrides
Overrides Sub
Sub Construct(ByVal
Construct(ByVal ss As
As String)
String)
''Called
Called after
after class
class constructor
constructor
''Use
Use passed
passed in
in string
string
End
End Sub
Sub
End
End Class
Class
Using Security

 Security configuration attributes enable security and role


configuration
 SecurityCallContext class provides role checking and caller
information
<ComponentAccessControl(True),
<ComponentAccessControl(True), SecurityRole("Manager")>
SecurityRole("Manager")> __
Public
Public Class
Class Account
Account
Inherits ServicedComponent
Inherits ServicedComponent
Public
Public Function
Function GetDetails(
GetDetails( )) As
As String
String
With SecurityCallContext.CurrentCall
With SecurityCallContext.CurrentCall
If
If .IsCallerInRole("Manager")
.IsCallerInRole("Manager") Then
Then
Return
Return .OriginalCaller.AccountName
.OriginalCaller.AccountName
End If
End If
End With
End With
End Function
End Function
End Class
End Class
Using Other Component Services

 Other Component Services include:


 Just-in-time activation
 Queued components
 Shared properties
 Synchronization
Configuring Assemblies for Component Services

 Setting assembly attributes


 ApplicationName
 Description
 ApplicationActivation: library or server application
 AssemblyKeyFile
 Using Regsvcs to register and create Component Services applications
 Regsvcs.exe myApplication.dll
 Using Lazy Registration
 Application registered on first use by client
Demonstration: Creating a Serviced Component
Lab 9.1: Creating a Serviced Component
 Creating Component Classes

 Architecture of a Component Class


 Creating a Component Class
Architecture of a Component Class

s s
C la
a s e System.ComponentModel.Component
B

IComponent
Interface
ed
r i v s Component Classes
D e l as s e Predefined Classes
C Custom Classes
Creating a Component Class

1. Inherit the System.ComponentModel.Component


 Perform any initialization in constructor
 Override Dispose method
2. Add any sited components
 Use Server Explorer or Toolbox items
3. Create required functionality
 Properties, methods, and events
4. Build the assembly
Demonstration: Creating a Stopwatch Component
 Creating Windows Forms Controls

 Inheriting from the UserControl Class


 Inheriting from a Windows Forms Control
 Providing Control Attributes
Inheriting from the UserControl Class

 Inherit from System.Windows.Forms.UserControl


 Add required controls to designer
 Add properties and methods that correspond to those of
constituent controls
 Add any additional properties and methods
 No InitProperties, ReadProperties, or WriteProperties
 Property storage is automatic
Inheriting from a Windows Forms Control

 Allows enhanced version of a single control


 Inherit from any System.Windows.Forms control
Public
Public Class
Class MyTextBox
MyTextBox
Inherits System.Windows.Forms.TextBox
Inherits System.Windows.Forms.TextBox
Private
Private strData
strData As
As String
String
Public
Public Property
Property HiddenData(
HiddenData( )) As
As String
String
Get
Get
Return
Return strData
strData
End Get
End Get
Set(ByVal
Set(ByVal Value
Value AsAs String)
String)
strData = Value
strData = Value
End Set
End Set
End Property
End Property
...
...
End
End Class
Class
Providing Control Attributes

 System.ComponentModel provides control attributes


 Class level – DefaultProperty, DefaultEvent, ToolboxBitmap
 Property level – Category, Description, DefaultValue

Imports
Imports System.ComponentModel
System.ComponentModel
<ToolboxBitmap("C:\txticon.ico"),
<ToolboxBitmap("C:\txticon.ico"), DefaultEvent("Click")>
DefaultEvent("Click")> __
Public
Public Class
Class MyTextBox
MyTextBox
Inherits System.Windows.Forms.UserControl
Inherits System.Windows.Forms.UserControl
<Category("Appearance"),
<Category("Appearance"), __
Description("Stores
Description("Stores extra
extra data"),
data"), __
DefaultValue("Empty")>
DefaultValue("Empty")> __
Public
Public Property
Property HiddenData(
HiddenData( )) As
As String
String
...
...
End Property
End Property
...
...
End Class
End Class
Demonstration: Creating an Enhanced TextBox
 Creating Web Forms User Controls

 Extending Existing Controls


 Creating Web User Controls
Extending Existing Controls

1. Add a Web user control to an ASP.NET Web project


2. Use the Toolbox to drag existing controls to the Web user
control designer
3. Add properties and methods
4. Save the .ascx file
5. Drag the .ascx file from Solution Explorer to the Web
Forms Designer
6. Create Web Form code as usual
Creating Web User Controls

<%@
<%@ Control
Control Language="vb"
Language="vb" AutoEventWireup="false"
AutoEventWireup="false"
Codebehind="SimpleControl.ascx.vb"
Codebehind="SimpleControl.ascx.vb"
Inherits="MyApp.SimpleControl"%>
Inherits="MyApp.SimpleControl"%>
<asp:TextBox
<asp:TextBox id="TextBox1"
id="TextBox1" runat="server"></asp:TextBox>
runat="server"></asp:TextBox>

Public
Public MustInherit
MustInherit Class
Class SimpleControl
SimpleControl
Inherits System.Web.UI.UserControl
Inherits System.Web.UI.UserControl
Protected
Protected WithEvents
WithEvents TextBox1
TextBox1 AsAs System.Web.UI.WebControls.TextBox
System.Web.UI.WebControls.TextBox
Public
Public Property
Property TextValue(
TextValue( )) As
As String
String
Get
Get
Return
Return TextBox1.Text
TextBox1.Text
End Get
End Get
Set(ByVal
Set(ByVal Value
Value As
As String)
String)
TextBox1.Text
TextBox1.Text = Value
= Value
End
End Set
Set
End Property
End Property
End
End Class
Class
Demonstration: Creating a Simple Web Forms User
Control
Lab 9.2: Creating a Web Forms User Control
 Threading

 What Is a Thread?
 Advantages of Multithreading
 Creating Threads
 Using Threading
 When to Use Threading
What Is a Thread?

 The unit of execution that the CPU processes


 All application processes contain at least one thread
 Threads are scheduled
 The computer appears to perform multiple tasks at one time
Every thread contains its own call stack and storage
Thread Scheduler
Thread 1
Process 1 Thread 321
CPU
Thread 2
Process 2
Thread 3
Advantages of Multithreading

 Improved user interface responsiveness


 Example: a status bar
 No blocking
 Asynchronous communication
 No thread affinity
 Objects are not tied to one thread
Creating Threads

 Use the System.Threading.Thread class


 Constructor specifies delegate method
 Methods provide control of thread processing
 Properties provide state and priority information
 Use a class if parameters are required
 Allow public access to class variables
 Raise an event when finished
Using Threading
Class
Class Calculate
Calculate
Public
Public iValue
iValue As
As Integer
Integer
Public
Public Event Complete(ByVal Result
Event Complete(ByVal Result As
As Integer)
Integer)
Public Sub LongCalculation(
Public Sub LongCalculation( ) )
'Perform
'Perform aa long
long calculation
calculation based
based on
on iValue
iValue
...
...
RaiseEvent
RaiseEvent Complete(iResult)
Complete(iResult) 'Raise
'Raise event
event to
to signal
signal finish
finish
End Sub
End Sub
End
End Class
Class

Sub
Sub Test(
Test( ))
Dim
Dim calc
calc AsAs New
New Calculate(
Calculate( ))
Dim
Dim th
th As
As New
New Threading.Thread(AddressOf
Threading.Thread(AddressOf calc.LongCalculation)
calc.LongCalculation)
calc.iValue
calc.iValue == 10
10
AddHandler
AddHandler calc.Complete, AddressOf
calc.Complete, AddressOf CalcResult
CalcResult
th.Start(
th.Start( ))
End
End Sub
Sub
Sub
Sub CalcResult(ByVal
CalcResult(ByVal Result
Result As
As Integer)
Integer)
...
...
End
End Sub
Sub
When to Use Threading

 Use threads carefully


 Using more threads requires more system resources
 Synchronize access to shared resources
 Prevent two threads from accessing shared data
simultaneously
 Use SyncLock statement to block sections of code
Sub
Sub Worker(
Worker( ))
SyncLock(theData)
SyncLock(theData) 'Lock
'Lock this
this object
object variable
variable
theData.id = iValue
theData.id = iValue
'Perform
'Perform some
some lengthy
lengthy action
action
iValue
iValue == theData.id
theData.id
End SyncLock
End SyncLock 'Unlock
'Unlock the
the object
object variable
variable
End Sub
End Sub
Demonstration: Using the SyncLock Statement
Review

 Components Overview
 Creating Serviced Components
 Creating Component Classes
 Creating Windows Forms Controls
 Creating Web Forms User Controls
 Threading
Course Evaluation

You might also like