You are on page 1of 219

C# COM+

[] Derek Beyer


.NET Microsoft Internet C#
Microsoft .NET .NET
.NET COM+ (
) COM+.NET .NET
COM+ C#.NET COM+

C#

Microsoft .NET
Original English language edition Copyright by Hungry Minds,Inc. All rights reserved including
the right of reproduction in whole or in part in any form. This translation published by
arrangement with Hungry Minds,Inc.
01-2001-4560
(CIP)
C# COM+ / ()(Beyer,D.) .
2002
()
C# COM+ Programming
ISBN 7-5084-1O05-X

IC II III. C - -
IVTP312 TP393.4
CIP (2002) 013334

C# COM+
[] Derek Beyer

( 6 100044)
:www.waterpub.com.cn
E-mail:mohannel@public3.bta.net.cn()
sale@waterpub.com.cn
:(010)68359286() 63202266() 68331835()

787 * 1092
16 15 327
2002 3 2002 3
0001 5000
30.00 ( 1CD)


2000 .NETMicrosoft .NET
.NET Microsoft XML Web (.NET is Microsofts platform for XML
Web services.) Microsoft Intenet .NET
Microsoft Microsoft .NET XML
Internet XML Web
XML Web Microsoft
XML Web Internet

XML(eXtended Markup Language)C# Microsoft C++ Java


.NET .NET
C# C#
COM+
Microsoft 1997 Microsoft San Diego
COM+(Component Object ModelCOM)
COM+.NET
COM+.NET COM+
?.NET Michael Lane
Thomas COM+ C#

.NET C#
()

1 5 6 8 9
10 (
)

2001 11 20


Derek Beyer Web Grand Rapids Meijer Stores
Derek
Web Derek MTSCOM+Visual
Basic Active Server Pagers
Derek March First
Internet SAP R3 Web Derek
COM+.Net
Derek

Matt Lusher Eric Newman


Matt Chris Jones

Sharon Cox Sharon


Sharon! Hungry Minds
Rolf Crozier
Rolf Hungry Minds
Steve
Schofield .NET
Steve Hungy Minds
Nick McCollum
Microsoft Mike Swanson Shannon PaulMike

Shannon COM+
Shannon


JacqueJacque

C# COM+
COM+ ?COM+ NET
?!Microsoft Windows 2000
COM+.NET C++
COM+ Visual Basic .NET C#
COM+
COM+ COM+
? COM+
COM+
C#C#.NET
.NET C#
COM+ C# C#
C++

COM+
COM+
Web
.NET COM+.NET
COM .NET
COM 1
1 .NET

C# C C

COM+ COM+
COM+ COM+


.NET
COM+ COM+
COM+
(Common Language Runtime).NET
.NET C# COM+
COM
C# COM COM C#
COM COM COM .NET

COM+
COM+

()

COM+

COM+.NET
.NET
C# COM+
Windows XP COM+Internet (Iternet Information Server) Microsoft
(Microsoft Message Queue)() COM+
COM+

()

5
using System;
using Microsoft.Comservices;
[assembly: ApplicationAccessControl{
AccessChecksLevel = AccessCheckLevelOption.ApplicationComponent
}
]
public class SecuredComponent {
// Some method implementations
}
assembly C#
AccessChecksLevelOption AccessChecksLevel

( using System )
assembly AccessChecksLevel
AccessChecksLevelOption

.NET Pascal
Pascal
CustomerOrders Pascal Customer
C Orders O

C# COM+

COM
1 .NET
2 .NET COM
3 COM .NET

1 .NET

*
*
*
*
*

(Common Language Runtime)

(Common Type System)

.NET (.NET Framework) Microsoft Windows


Visual Studio 6 C++ Visual
Basic COM
COM COM
.NET (reflection)
API API

Framework
C++Windows COM+ Object Pooling (COM+
) HTTPSMTP FTP Internet Visual Basic .NET
C#
.NET
.NET ( C# COM+)
(Common Language Runtime,CLR) CLR
CLR (Garbage Collection),

CLR CLR C# COM+

1.1
CLR CLR
(Virtual Execution System,VES)
CLR
VES
class() dll()

COM+(exe dll )

1.1.1

Microsoft

C# Microsoft
(Microsoft Intermediate LanguageMSIL)(Portable
ExecutablePE)MSIL CLR MSIL CLR
CLR
(Just In Time CompilerJIT) MSIL
MSIL Microsoft
MSIL CLR Visual Studio .NET Windows 2000
CLR CLR
MSIL COM+

C#?
COM+ Microsoft

System.Net.Sockets TCP/IP
TCP/IP
MSIL
CLR CLR

dll(Dynamic Link Library) MSIL


CLR NET
CLR ( COM+)
COM+ CLR COM+

COM+ Catalog(COM+)
.NET
Visual
Studio COM+
Windows COM+ Catalog dll COM+

Visual Studio .NET

dll dll
Class Loader () JIT

1.1.2
? CLR
A C
A XML

C (
) dll dll
dll

*
autolayout
*
layoutsequential
*
explicitlayout
MSIL
Microsoft Tool Developer Guide()
Tool Developers Guide Visual Studio .NET COM+

JIT

1.1.3
(Just In Time Compiler) MSIL
JIT MSIL

JIT JIT
A
Cfoo Cfoo ToString()JITer Cfoo.ToString()
CFoo JIT JIT

JIT MSIL
CPU JIT
.NET

1.1.4
C++
C++ Visual Basic
CLR
CLR CLR
11

C# new CIR
1-2 new

CLR Winn32
Win32 Win32

(Garbage Collection) (Garbage


Collection)

*
()
*
()
*
CPU
JIT

(Generational Garbage Collection)

0 (Generation 0)1 (Generation 1) 2


(Generation 2)0 1 1
2 2
0
0

0 1 2

.NET
(nondeterministic finalization)

( Visual Basic Class_Terminate)


.NET Class_Terminate C#
Visual Basic Class_Terminate Finalize
Finalize
Finalize
Microsoft Dispose
Close
Finalize
Finalize Garbage Collector Finalize
C#

Finalize
Finalize
*
*
*

()

base.Finalize() Finalize
Finalize
*
Finalize C#
new CLR
Finalize (Finalizeation Queue)

Finalize
Freachable Queue
Freachable Queue
Finalize
Finalize

CLR

SDK
JIT
(JIT Compilation Counters)(Loading Counters)(Memory Counters)

JIT Compilation Counters(JIT )


IL Bytes Jitted/sec: IL
# of IL Bytes Jitted: JIT IL
# of Methods Jitted: JIT
Loading Counters()
Current Classes Loaded: CLR
Total # of Failures:
Total Classes Loaded:
Memory Counters()
#Bytes in Heap:
Gen 0 Heap Size:0 1 2
#Gen 0 Collections: 0 1 2

1.2
CLR
() JPEG dll

.NET
Visual Basic COM

1.2.1
CLR

*
()
*

*
CLR
*

1-3

1.2.2
4
.NET SDK Beta 2 System.Windows.Forms 1.02411.0
1 0 2411 0 CLR
CLR
CLR
(Quick Fix EngineeringQFE)QFE

1.2.3

()


.NET SDK Visual Studio .NET
CLR

1.2.4

(Global Assembly Cache)

.NET Framework SDK gacutil.exe(Global Assembly Cache


Utilty)\winnt\assembly \winnt\assembly
Windows Shell Windows (Windows Explorer)
(My Computer) 1-4

Global Assembly Cache


Global
Assembly Cache
*
*
*
*

Global Assembly Cache

Global Assembly Cache


QFE

CLR

CLR

JIT
()

1.2.5
CLR
XML .cfg

c:\program files\Microsoft office\Word.exe c:\program


files\Microsoft office\Word.exe.cfg CLR
*
*
*
*

QFE
()
()
BindingPolicy
<BindingPolicy>
<BindingRedir Name=myAssembly
Originator=e407643ef63677f0
Version=1.0.0.0 VersionNew=2.1.0.0
UseLatestBuildRevision=no/>
</BindingPolicy>
BindingPolicy CLR
myAssembly 2.1.0.0 1.0.0.0
CLR
UseLatestBuildRevision CLR QFE
no CLR
yesCLR ()
Originator
CLR
CLR

<BindingMode>
<AppBindingMode Mode=safe/>
</BindingMode>
safe
Mode
normal
Assemblies
CodeBase
<Assemblies>
<CodeBaseHint Name=myAssembly
Originator=e407643ef63677f0
Version=2.1.0.0
CodeBase=c:\winnt\myNewDll.dll/>
</Assemblies>
CLR myAssembly 2.1.0.0 c:\winnt\myNewDll.dll
CLR
?CLR CLR


1. CLR .mcl.dll .exe
2. PrivatePaths
3.
4.
Originator
Originator QFE CLR

*
*
*
*
*

myapp.exe
c:\program files\myapp\
PrivatePaths <AppDomainPrivatePathcomplus>
myassembly
Originator
QFE

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.

C:\program files\myapp\myassembly.mcl
C:\program files\myapp\myassembly.dll
C:\program files\myapp\myassembly.exe
C:\program files\myapp\myassembly\myassembly.mcl
C:\program files\myapp\myassembly\myassembly.dll
C:\program files\myapp\myassembly\myassembly.exe
C:\program files\myapp\complus\myassembly.mcl
C:\program files\myapp\complus\myassembly.dll
C:\program files\myapp\complus\myassembly.exe
Global Assembly Cache

1.3
dll.exe Windows
Win32

*
Win32
CLR CLR
Win32 Win
Win32 CLR

1.4
(Common Type System)
.NET

.NET ( C++)

new CLR

C++ C++
C++(C#)

CLR 0
(boxed tyPe)

int iNum = 1;
Object oObj = iNum;
oObj = 2;
WriteLine(iNum);
WriteLine(oObj);
/* OUTPUT */
1
2

iNum 1 Object oObj


iNum iNum oObj

1.5
CLR ()
Visual Basic Visual C++ CLR

CLR
*
*

CLR COM+ COM+


COM+

*
*
*

C#

COM
.NET CLR CLR COM

2 .NET COM

*
*
*

.NET
(Runtime Callable Wrapper)
.NET COM

1 .NET
COM
COM .NET
COM .NET
COM
COM
Microsoft .NET
COM API
.NET COM ?
.NET COM (COM InteroperationCOM Interop)COM Interop
.NET COM

2.1 .NET
.NET .NET .NET
COM COM (TypeLib)
(Type Library Importer) (tlbimp.exe)
COM
COM

Visual Basic 6 HelloWorld COM tlbimp.exe


HelloWorld Hello

VB project name: prjHelloWorld


class name: CHelloWorld
Public Function Hello() as string
Hello = Hello World
End Function
prjHelloWorld CHelloWorld COM ProgID
prjHelloWorld.ChelloWorldCOM prjHelloWorld.dll

Library prjHelloWorld {
Interface _CHelloWorld {
HRESULT Hello([out, retval] BSTR* );
}

coclass CHelloWorld {

[default] interface _CHelloWorld;


}

Visual Basic Visual Basic

dll
AsmHelloWorld.dll
tlbimp.exe /out:AsmHelloWorld.dll prjHelloWorld.dll
/out:HelloWorld.dll
?
MSIL Disassembler(MSIL ,ildasm.exe)MSIL
(MSIL Disassembler)
MSIL
Ildasm.exe AsmHelloWorld.dll
2-1 MSIL
MSIL
*
*
*

.NET
COM
COM (COM CoClass) - CHelloWorld

MAINIFEST prjHelloWorld
COM prjHelloWorld
CHelloWorld COM .NET COM
.NET.NET
.NET _CHelloWorId implements
prjHelloWorld._CHelloWorld, Hello

HRESULT[out,retval]

.NET
.NET ? 1
.NET
Sn k AsmHelloWorld.snk
k (Shared Name Utility) keyfile

AsmHelloWorld.snk
keyfile /keyfile
Tlbimp /out:AsmHelloWorld.dll
/keyfile:AsmHelloWorld.snk prjHelloWorld.dll
.NET
COM CDog Breed
Breed
Library Animals {
interface IDog {
[propput] HRESULT Breed ([in] BSTR);
[propget] HRESULT Breed ([out, retval] BSTR*);
}
coclass CDog {

[default] interface IDog;


}
}

Namespace Animals {
Class CDog {
// private get accessor method called by runtime
private string get_Breed() { ... };
// private set accessor method called by runtime
private void set_Breed(string) { ... };
// public class field that you will Interop with
public string Breed; // public class property
}
}

Visual Stuid0 .NET Animals


Breed get_Breed() set_Breed() Breed

()
Visual Basic 5 6
COM Let/Set/Get C
C#

.NET
(enums)(typedefs)(
)
COM Visual Basic C++
COM typedefs typedef:
Library Animals {

Typedef [public] int AGE;


Interface _CDog {
HRESULT GetAgeInDogYears(
[in] AGE humanyears,
[out, retval] AGE dogyears
);
}
}

typedef

Namespace Animals {
Interface _CDog {
Int GetAgeInDogYears([ComAliasName(AGE)] int humanyears);
}
}

int ComAliasName
ComAliasName
Visual
Studio .NET
enum COM enum

Enum {
GoldenRetriever = 0,
Labrador = 1,

ChowChow = 2
} Breeds;
enum enum enum

typedefs enums
.NET
Security COM

Module Security {
Const long SIDToken = 0x009312;
[entry(ApplySidToThread)]
pascal void ApplySidToThread([in] long SID);
}

Security

Public class Security {


Public static const SIDToken = 0x009312;
Public static void ApplySidToThread(long SID);
}

2.2
COM .NET .NET COM
COM
(Runtime Callable WrapperRCW)RCW
*
*
*
*
*

COM
COM

IUnknown IDispatch

2.2.1
RCW COM
new RCW COM
RCW RCW COM
RCW IUnknown->QueryInterface() RCW

RCW
RCW IUnknown->QueryInterface
COM COM
RCW .NET COM

2.2.2 COM
1 .NET null
.NET
COM RCW
COM COM COM
IUnknown->AddRef()
IUnknown->Release() COM
RCW COM AddRef Release
Release RCW Finalize

RCW COM
COM

.NET
RCW Release RCW
System GC
RequestFinalizeOnShutdown WaitForPendingFinalizersRequestFinalizeOnShutdown

Finalize WaitForPendingFinalizers

.NET Release ()
System.Runtime.InteropServices Marshal Marshal.RelaseComObject
RCW 1
Using System.Runtime.InteropServices;
Class CMain {
Public void MakeDogBark() {
// RCW that maps to the CDog COM Class
CDog dog = new CDog();
dog.Bark();
Marshal.ReleaseComObject ((object)dog);
}
}

RCW Marshal.ReleaseComObject()
COM COM
RCW dog
RCW

2.2.3
RCW COM
RCW
COM RCW RCW

RCW .NET .NET


COM COM RCW
.NET 2-l RCW
2-l RCW
COM

Iunknown

.NET COM RCW


COM COM
.NET .NET

RCW
: RCW RCW
IUnknown->QueryInterface COM
IUnknown->AddRef

Idispatch

.NET COM
RCW COM
.NET (Reflection)

IsupportErrorInfo

COM COM

IerrorInfo

HRESULT RCW
RCW
.NET

IconnectionPoint

COM COM

IconnectionPointContainer

RCW COM .NET

2.2.4
RCW .NET COM RCW
.NET
*
*

HRESULT COM .NET HRESULT


HRESULT
COM retval .NET

*
*

COM .NET

2.3
COM . NET COM .NET
COM COM

(Single Threaded ApartmentSTA)


(Multi-Threaded ApartmentMTA) COM COM
COM Windows COM
STA Visual Basic 6

COM+ COM+
COM+

.NET COM .NET MTA


COM .NET

COM STA COM


.NET STA System.Threading
Thread .NET STA
System.Thread.CurrentThread.ApartmentState = ApartmentState.STA.
COM RCW COM

2.4
COM .NET

*
typedefs
*
enums .NET enums
*

RCW .NET COM


RCW
*
*
*

COM
COM

*
*

IDispatch Iunknown
.NET COM

3 COM .NET

*
*
*
*

COM
COM
COM (COM Callable Warpper)
.NET

COM .NET .NET COM


COM .NET
.NET COM

3.1 COM
.NET SDK (Type Library
Exporter)(tlbexp.exe)(Assembly Registration Tools)(regasm.exe)
.NET
Windows COM

3-1

3-1 Assembly Registration Tools

/regfile:RegFileName.reg

COM RegFileName.reg
Windows

/tlb:TypeLibFileName.tlb

COM
/regfile

/u and /unregister

.NET

// Assembly file name: Animal.dll


using System;
namespace Animals {
public class CDog {
public void Bark() {
Console.WriteLine(Woof Woof);
}
}
}

Animal.dll regasm /tlb:animal.tlb

animal.dll
Library Animals {

CoClass CDog {
[default] interface _CDog;
interface _Object;
};
interface _CDog : IDispatch {
HRESULT ToString([out, retval] BSTR*
pRetVal);
HRESULT Equals([in] VARIANT obj,
[out, retval] VARIANT_BOOL* pRetVal);
HRESULT GetHashCode([out, retval] long*
pRetVal);
HRESULT GetType([out, retval] _Type**
pRetVal);

HRESULT Bark();
}
}
CDog CoClass _CDog _Object.NET
.NET
System.Object

Cdog System.Object CDog System.Object


.NET Animals
CDog CDog
.NET
Animals Mammals
Mammals
// Assembly file name: Animal.dll
using System;
namespace Animals {
public class CDog {
public void Bark() {
Console.WriteLine(Woof Woof);
}
}

namespace Mammals {

public class CDog {


public void RollOver(){
Console.WriteLine(Rolling Over);
}
}
}

Library Animals {
CoClass CDog {
[default] interface _CDog;
interface _Object;
};

interface CDog : IDispatch {


// .. System.Object
HRESULT Bark();
};

CoClass CDog_2 {
[default] interface _CDog_2;
interface _Object;
};
interface _CDog_2 : IDispatch {

// .. System.Object
HRESULT RollOver();
}
}

Cdog 2
Animal.Cdog Cdog
Cdog

COM System.Runtime.
InteropServices.ComVisible ComVisible COM
COM
() COM
ComVisible

COM
TypeLib ID
TypeLib ID
TypeLib ID

TlbExp
0.1

3.2 COM
COM Windows
/regfile
COM
/regfile CDog
// Assembly file name: Animal.dll
using System;
namespace Animals {
public class CDog {
public void Bark() {
Console.WriteLine(Woof Woof);
}
}
}
CDog
Windows

REGEDIT4
[HKEY_CLASSES_ROOT\Animals.CDog]
@=Animals.CDog
[HKEY_CLASSES_ROOT\Animals.CDog\CLSID]
@={AC480224-1FA7-3047-AE40-CCDD09CDC84E}
[HKEY_CLASSES_ROOT\CLSID\{AC480224-1FA7-3047-AE40-CCDD09CDC84E}]
@=Animals.CDog
[HKEY_CLASSES_ROOT\CLSID\{AC480224-1FA7-3047-AE40-CCDD09CDC84E}\InprocSer
ver32]
@=C:\WINNT\System32\MSCorEE.dll
ThreadingModel=Both
Class=Animals.CDog
Assembly=animal, Ver=0.0.0.0, Loc=
[HKEY_CLASSES_ROOT\CLSID\{AC480224-1FA7-3047-AE40-CCDD09CDC84E}\ProgID]

@=Animals.CDog
[HKEY_CLASSES_ROOT\CLSID\{AC480224-1FA7-3047-AE40-CCDD09CDC84E}\Imple
mentedCategories\{62C8FE65-4EBB-45e7-B440-6E39B2CDBF29}]
ProgID namespace.class-me CDog
Animals.CDog

COM InprocServer32 animal.dll


MSCorEE.dll dll COM .NET dll
COM
Both.NET

MSCorEE.dll
ProgID

3.3 COM
COM (COM Callable WrapperCCW)
.NET COM MSCorEE.dll
COM dll COM CCW RCW CCW
NET CCW
*
*
*
*
*

.NET
.NET

COM

3.3.1
CCW .NET CCw
() CCW
COM CCW

3.3.2
COM COM IUnknown->AddRef
IUnknown->ReleaseCCW COM
Iunknown .NET
CCW .NET CCW .NET

CCW .NET CCW .NET

CoEEShutDown NET API


.NET API Visual Studio .NET
Tool Developers Guide API Windows API

3.3.3 COM Iunknown IDispatch


Iunknown Idispatch COM .NET
CCW COM IDisPatch COM Active
Server PagesVisual Basic() Visual Basic for Applications
IDispatchIDispatch .NET
.NET

.NET IDispatch
System.Runtime.InteropServices NoIDispatch IDispatch
COM IUnknown->QueryInterface
E_NOINTERFACE HRESULT

3.3.4
.NET COM .NET

CCW VTable() COM


VTable CCW VTable
COM .NET

VTables (Virtual Function Tables)

VTable

3.3.5
COM
VTable
*

*
.NET retval
*
.NET HRESULT
CCW
System.Runtime.InteropServices.PreserveSigAttribute COM

long SomeMethod(string sParameter);

HRESULT SomeMethod([in] BSTR sParameter,


[out, retval] long* pRetVal);


long SomeMethod(string sParameter);

CCW .NET COM

COM COM COM COM

3.3.6
COM
COM COM dll

1.
2.
3.

Windows CLSID ProgID(.NET


ProgID namespace.classname)
CLSID CLSID COM
.NET
COM API DllGetClassObject CLSID ClassFactory

COM COM

COM API CoCreateInstance


* COM
*

*
COM
COM+ Web
COM+COM+
COM+
3 MSCorEE.dll COM+.NET COM
COM .NET (.NET Class Loader)
CCW
CCW
.NET
1

()

COM IClassFactory.CreateInstance()

.NET CCW IClassFactory.CreateInstance()


*
IUnknown
*
ID( GUID)
*
void
Iunknown CCW
CCW .NET
CreateInstance()CCW VTable 3-1
IList MoveFirstMoveLast Goto VTable

MoveFirst MoveLast CCW


MoveLast
CCW HRESULT

3.3.7 .NET
COM .NET

1.

2.

3.

4.

5.

Interop COM .NET


.NET COM Interop
Interop

Interop

XML
COM+
.NET
IDispatch->GetTypeInfo IDispatch->GetTypeInfoCount
IDisPatch .NET

() Close Dispose

Interop
CCW
RCW ()

3.4

.NET COM
Windows
Assembly InprocServer32 Assembly
CCW COM .NET

COM
.NET COM+
.NET COM+

COM+
4
5
6
7
8

*
*
*
*

ACID

C#

COM+ COM+
COM+COM+

Oracle SQL Server CICS

ACID COM+
(Two-Phase Commit) (Automatic
Transaction Enlistment)
C#.NET ServicedComponent
C#

4.1 ACID
COM+

COM+

4.1.1
COM+

4.1.2

COM

4.1.3
A
B B A
A
COM+

?
4-1

4-1

()

()
select *

Microsoft SQL Server COM+


COM+Windows 2000

4.1.4

(Physical Transaction Lifecycle)

4.2 COM+
COM+(
)

COM+
COM+

COM+

4.2.1

COM+
COM+
()

COM+
( Visual Basic 6 ) ObjectContext
.NET ContextUtil ContextUtil
System.EnterpriseServices API

1.
COM+
COM+ COM+ COM+
COM+
*
*

Disabled COM+
Not Supported COM+

ObjectContext.SetComplete ObjectContext.SetAbort
()

* Supported

* Required

* RequiresNew

COM+

C# CLR
System.EnterpriseServices
COM+

2.

(JITA)
JITA SupportedRequired
RequiresNew 4-1
(Component Services Explorer)

COM+
COM+

COM+COM+

C# ContextUtil.SetComplete ContextUtil.SetAbort
ContextUtil.EnableCommit Context.DisableCommint Visual
Basic 6 COM+ContextUtil Visual Basic 6
ObjectContext ContextUtil

COM+ autodone
Auto-Dong .NET AutoComplete
4-2 Auto-Done

.NET System.EnterpriseServices AutoComplete COM+


AutoDone COM+
JITA
COM+
JITA
JITA

3.

consistent() SetComplete EnableCommit


ContextUtil SetAbort DisableCommit

COM+

JITA

ACID
4.

SetAbort SetComplete

GUI
GUI

* COM+
*

* COM+
GUI

TransactionContext
( GUI )TransactionContext

*
*

Transaction Context
COM+

COM+GUI

Requires RequiresNew

4.2.2

1.

(Automatic Transaction Enlistment)


4-3

ADO( ADO.NET) SQL Server


OLEDB ADO

( SQL Server ID)

2.

COM+
COM+ Microsoft
(Distributed Transaction Coordinator)Windows
2000 SQL Server

3.
COM+

COM+
(Two-Phase Commit)

4-4

4.3 C#
ContextUtil ID
(Synchronization)
(JITA) COM+

4.3.1 ServicedComponent
ServicedComponent COM+
COM+ COM+ C#

ServicedComponent System
using System
C# System

.NET
System.EnterpriseServices COM+
ServicedComponent C#
Namespace ComTransaction {
using System;
using System.EnterpriseServices;
public class CRoot : ServicedComponent {
//
}

C# COM+
*
ComTransaction
*
using System
*

*
ServicedComponent ServicedComponent
COM+
COM .NET

4.3.2

4-1
Namespace ComTransaction {
using System;
using System.Data.SQL;
using System.EnterpriseServices;
[Transaction(TransactionOption.Required)]
public class CRoot : ServicedComponent {
public void LogTransactionId() {
SQLConnection cnn = new
SQLConnection(server=localhost;database=Transactions;uid=sa;pwd=);
SQLCommand cmd = new SQLCommand();
cnn.Open();
cmd.ActiveConnection = cnn;
cmd.CommandText = insert into TransactionId values(CWorker1, +
ContextUtil.TransactionId + );
cmd.ExecuteNonQuery();
cnn.Close();
}
}
}

LogTransactionId
ID ContextUtil TransactionId
[Transaction(TransactionOption.Required)]
COM+ COM+
COM+.NET

COM+ COM+
ApplicationName
Description ApplicationActivation System.EnterpriseServices

COM+
COM+

Windows 2000 dllhost.exe

4.3.3 COM+
COM+
C# COM+.NET
Framework SDK Regsvcs

ServicedComponent .NET COM+


COM+

*
COM+

Regsvcs ServicedComponent
COM+ ServicedComponent
COM+
4-2

4-2 Regsvcs

/c

COM+

/fc

COM+

/reconfig

(Component Service)
Refresh()

1.
2.
3.
4.

()
COM+

4.3.4 JITA
Transaction JustInTimeActivation
Synchronization AutoComplete
System.EnterpriseServices 4-2 CRoot

4-2 AutoComplete
Namespace ComTransaction {
using System;
using System.Data.SQL;
using System.EnterpriseServices;
[Transaction(TransactionOption.Required)]
[JustInTimeActivation(true)]
[Synchronization(SynchronizationOption.Required)]
public class CRoot : ServicedComponent {
[AutoComplete]
public void LogTransactionId()
//
}
}
}

JustInTimeActivation ( )
JustInTimeActivation JustInTimeActivation
Synchronization
JustInTimeActivation Synchronization
RequiredSynchronization (Disabled
Not SupportedSupportedRequired RequiresNew) Synchronization
AutoComplete
AutoComplete COM+
AutoDone

4.3.5

ComTransaction

4-3
namespace ComTransaction
{

using System;

using System.Data.SQL;
using System.EnterpriseServices;
[Transaction(TransactionOption.Required)]
public class CRoot : ServicedComponent
{
public void LogTransactionId()
{

/* ID */
CWorker1 worker1 = new CWorker1();
CWorker2 worker2 = new CWorker2();
worker1.LogTransactionId();
worker2.LogTransactionId();
}
}

[Transaction(TransactionOption.Supported)]
public class CWorker1 : ServicedComponent
{

public void LogTransactionId()


{ /* ID */ }
}

[Transaction(TransactionOption.Supported)]
public class CWorker2 : ServicedComponent
{

public void LogTransactionId()


{ /* ID */ }
}
}
CWorker1 CWorker2
TransactionOption.Supported
CRoot
4-3 CRoot LogTransactionId

4-3
ClassName

TransactionId

CRoot

FF208BBB-D785-4c59-9EA1-D3B6379822FB

CWorker1

FF208BBB-D785-4c59-9EA1-D3B6379822FB

CWorker2

FF208BBB-D785-4c59-9EA1-D3B6379822FB

ID

4.4
ACID () COM+

.NET COM+

ServicedComponent
C#ServicedComponent System.EnterpriseServices
C# COM+
5 .NET COM+

*
*
*

Windows

C# COM+

COM+
COM+

COM+

.NET C#
COM+
COM+ COM+

.NET ().NET
COM+.NET
COM+

COM+
.NET C#
COM+
Windows (Windows Security Architecture)

5.1 Windows
Windows API(Windows Security API)
COM+

5.1.1
Windows ID

? Ctrl-Alt-Del
(Net Logon Service)
(Secure Attention Sequence,SAS)
(Graphical Identification and AuthenticationGINA)GINA

Windows ID GINA

ID (GINA
(Local Security AuthorityLSA)LSA ID
LSA

Windows ID (Security
Accounts Manager,SAM)
(Active Directory)
SAM

LSA LSA

(Security IdentifierSID)
SID ID
Windows COM (GUID) SID
(SLSID) ID SID SID

Windows
Internet Explorer

5.1.2

(),Windows
(SD)SD SD

SD (System Access Control


List,SACL)(Discretionary Access Control ListDACL)Windows SACL
SACL COM+ COM+
SACL Windows COM+
DACL SID Windows
SID DACL SID

SID DACL SD Access Denied

COM E_ACCESSDENIED HRESULT


DACL Access Control Entries(ACE) SID
ACE SID DACL
ACE ACE ACEWindows DACL ACE
Windows
ACE ACE,
ACE ACE

5.1.3

Windows COM+
EveryoneAuthenticated Users Interactive User
System COM+
Everyone Windows
?Everyone
Windows Everyone SID Everyone

Everyone ()
Everyone ? DACL
null null DACL DACL DACL ACE
DACL
null DACL
Windows Authenticated Users Everyone
Everyone
Authenticated Users Authenticated Users guestGuest

Windows Guest Guest

Interactive User COM+


Interactive User COM+

Interactive User (
)
Logon as Batch JobAccess this Computer from the Network
Interactive User Interactive User
COM+

Interactive User GUI

COM+Interactive User
COM+

5.1.4

()

5-1
5-1

(Anonymous)

(Identify)

SID

(Impersonate)

(Delegate)

COM+ COM+
COM+ COM+

5.2
Microsoft
COM(Distributed COMDCOM)DCOM (Remote Procedure Call
RPC) DCOM
COM Internet (
Windows Windows ) Internet
Internet COMInternet
(Network Address Translation
NAT) NAT DCOM

DCOM .
Web

IP
DCOM ,

DCOM Microsoft HTTP


(Remote Data Services,RDS) Microsoft HTTP
RDS Microsoft (Microsoft Data Access Components,MDAC)
RDS SQL
RDS Web
MDAC
(Simple Object Access
Protocol,SOAP)SOAP XML HTTP
SOAP XML HTTP
XML HTTP SOAP
9 .NET (.NET Remoting) SOAP
SOAP RDS SOAP Active Server
Page() ( ASP .NET Web Service )RDS Web dll

web HTTP HTTP URL HTTP


Active Server Page dll COM+

IIS
Microsoft Microsoft (Microsoft Internet Information
Server,IIS)IIS Microsoft Windows 2000
web IIS Windows HTTP

IIS System
Active Server Page IIS
IIS IIS
Syslem IIS
() IIS
IUSR_+ Web www1
IUSR_WWW1
IUSR COM+
COM+ Windows
COM+

IIS
IIS
(impersonation token) COM+

IIS
(Anonymous access)
(Basic authentication)
(Digest authentication)
Windows (Intergrated Windows authentication)
IIS
IUSR HTTP
ID
Windows

Internet
Windows 2000 () Window 2000
Windows
Windows NT

5.3 COM+
.NET
.NET COM+
.NET
System.EnterpriseServers

5.3.1
COM+
5-1 security()

Authorization
enforced()

Authorization security level() 5-1


(
)COM+
().NET
ApplicationAccessControl C#
ApplicationAccessControl
ApplicationAccessControl Security COM+

COM+ AccessChecksLevel
AccessChecksLevel
5.1

Security()

using System;
using System.EnterpriseServices;
[assembly:ApplicationAccessControl(
AccessCheckslevel=AccessChecksLevelOption.ApplicationComponent
)
]
public class SecuredComponent:ServicedComponent{

//
}
assembly C#
AccessChecksLevelOption AccessChecksLevel

dllhost.exe(COM+ exe)

COM+

Authentication COM+
5-2
5-2

None()

none

Connect()

Call()

Packet()

Packet Integrity()

Packet Private()

Call Connect
Packet Call

.NET ApplicationAccessControl
Authentication Authentication
AuthenticationOption

using System;
using System.EnterpriseServices;
[assembly:ApplicationAccessControl
{
AccessChecksLevel=AccessChecksLevelOption.ApplicationComponent
Authentication=AuthenticationOption.Connect
}
]
public class SecuredComponent:ServicedComponent{
//
}

Packet Packet Integrity Packet


Integrity


Windows
COM+
5-1 COM+

Anonymous()
Identify()
Impersonate()
Delegate()

Anonymous

.NET ApplicationAccessControl
ImpersonationLevel ImpersonationLevelOption
Delegate
using System;
using System.EnterpriseServices;
[assembly:ApplicationAccessControl
{
AccessChecksLevel=AccessChecksLevelOption.ApplicationComponent,
Authentication=AuthenticationOption.Connect
ImpersonationLevel=ImpersonationLevelOption.Delegate
}
]
public class SecuredComponent:ServicedComponent;
//
)

5.3.2

5-2
Author
Nick HMI Author
5-2

COM+
5-3
CAuthor Author Editor
Author
5-3

CAuthor

Nick author CAuthors COM+


Author SD Nick SID HMI
Authors SID Nlck SID SD Access
Denied()
SecurityRole C#
ApplicationAccessControl C#
SecurityRole
Everyone
()(
) Everyone Everyone
Component Services Explorer()

SecurityRole ComponentAccessControl
()
()()
SecurityRole ComponentAccessControl SecuredComponent
customers Everyone
using System;
using System.EnterpriseServices;
[assembly:ApplicationAccessControl
(
AccessChecksLevel=AccessChecksLevelOpti

on.ApplicationComponent,
Authentication=AuthenticationOption.Connec
t,
ImpersonationLevel=ImpersonationLevelOpti
on.Delegate
)
]

[SecurityRole(customers,true)]
[ComponentAccessControl]
public class SecuredComponent:ServicedComponent{
//
}

ComponentAccessControl
C#
COM+ RegSvcs
customers Everyone
5-4
SecuredComponent COM+ SecuredComponent
5-4

SecuredComponent

5.3.3

COM+l

()
COM+ SID
Nick ASP.NET
URL ID Nick
IIS Nick Nick
ASP COM+
dllhost ( ASP ) dllhost
ID Interactive
Nick Nick SID SD
SID SID Nick
Active Server Page COM+
dllhost SID
Nick 5-5

.NET SecurityCallers
SecurityCallers SecurityIdentity
SecurityCallers
SecurityCallContext CurrentCall SecurityCallContext CurrentCall
SecurityCallContext Callers
Callers SecurityCallers
SecurityComponent
[SecurityRole(customers,true)]
[ComponentAccessControl]
public class SecuredComponent:ServicedComponent{
public void ShowCallChain(){
SecurityCallContext sc.SecurityCallContext.CurrentCall;
SecurityCallers scs=sc.Callers
Foreach(SecurityIdentity si in scs){
console.WriteLine{si.AccountName};
}
}
}

COM+
Nick B
(COMuser) B A
COM+ B Nick

SecurityCallContext IsUserInRole

SecurityIdentity AccountName
[SecurityRole(customers,true)]
[ComponentAccessControl]
public class SecuredComponent:ServicedComponent{
public void ShowCallChain(){
SecurityCallContext sc=SecurityCallContext.CurrentCall;
SecurityCallers scs=sc.Callers;
Bool CustomerInCallChain=false;
if(sc.IsUserInRole(si.AccountName,customers)){
CustomerInCallChain=true;
break;
}
}
if(!CustomerInCallChain){
throw new UnauthorizedAccessException(no customers found in call chain);
}
}
}

UnauthorizedAccessException System .NET

5.4

Windows
COM+ HTTP
(Web ) IIS
.NET

6 COM+.NET


LCE
LCE
C# LCE

(Tightly
Coupled Event,TCE)
TCE COM+
(Loosely Coupled Event,LCE) LCE
.NET LCE LCE
LCE COM

6.1 LCE
TCE .NET COM (COM Connection Point)TCE
TCE
()()
TCE

.NET TCE

6.1.1

.NET

.NET COM+.NET
COM+
COM+

C C++
.NET
C# delegate


.NET

void
WinForms ASP .NET
void void

-
SystenObject
x y
6-1 EventSource EventReceiver
MyEventHandler EH
event C# EventMethod
EventReceiver EventMethod

6-1
namespace MyNetEvents
{
using System;
public delegate void MyEventHandler(string msg);
public class EventSource
{
public event MyEventHandler EH;
private void OnEvent(string msg)
{
EH(msg);
}
public void FireEvent()
{
OnEvent{hello};
}
}
public class EventReceiver
{
public void EventMethod(string msg)

{
Console.WriteLine(EventReceiver:+msg);
}
}
public class CMain
{
public static void Main()
{
//
EventReceiver er=new EventReceiver();
//
EventSource es=new EventSource();
//
es.EH+=new MyEventHandler(er.EventMethod);
//
es.FireEvent();
}
}
}
MyEventHandler
er.EventMethod EH .NET
+=
EH FireEvent FireEvent
OnEvent
FireEvent OnEvent OnEvent

OnEvent EH .NET
er.EventMethod

6.1.2

TCE COM+ LCE

.NET
TCE

COM+()

.NET

COM+


EVentReceiver CMain Main Main

COM+ COM+ COM+

6.2

LCE

COM+

COM+

COM+ Windows2000

LCE

COM+
COM+ 6-1

COM+

COM+

()

(GUID)
LCE

COM HRESULT

6.2.1

COM+ COM+
Component Services Explorer
.NET COM+

COM+ Administration API COM COM Component


Services () Admin API
COM+
COM+ Admin API
COM+
Per User

6.2.2

COM+

LCE COM+(
COM+)
.NET COM+
Fire in Parallel()
Allow in-process subscribers()
Publisher ID( ID)
1. (Fire in Parallel)
6-2 Component Services
Explorer Advanced COM+

6-2

Component Services Explorer Fire in Parallel

COM+

2. (Allow in-process Subscribers)


Allow in-process()COM+
COM+

Allow in-process Subscribers


Advanced 6-2

3.

ID(Publisher ID)
Publisher ID ( 6-2 )

CLSIDPublisher ID

6.2.3

COM+

1.

COM+ Admin API PublisherFilterCLSID


CLSID / IMultiPublisherFilter
IPublisherFilter COM+
PublisherFilterCLSID

2.

6-3 Option Filter Criteria


Symbol MSFT Price
60

Symbol

6-3

ANDOR
NOT

6.3

C# LCE

LCE
COM+C#

6.3.1 LCE
6-2
MySubscriberClass MyEventClass IMyEvents
IMyEvents (PrintName

6-2
LCE
using System.Reflection;
[assembly:AssemblyKeyFile(mykey.snk)]
namespace MyEvents
{
using System;
using System.EnterpriseServices;

[EventClass]
public class MyEventClass:ServicedComponent,IMyEvents
}
public void PrintName(){}
)
public class MySubscriberclass:ServicedComponent,IMyEvents
{
public void PrintName()
{
Console.WriteLine(MyEvents.MySubscriberClass);
}
}
public interface IMyEvents
{
void PrintName();
}
}
AssemblyKeyFile
(GAC) GAC
GAC LCE

MyEvents MyEventClass
System.EnterpriseServices EventClass EventClass

MySubscriberClass
IMyEvents ServicedComponent

IMyEvents

ServicedComponents
EventClass,Regsvcs.exe
COM+ 6-4

IMyEvents Interfaces
6-5 Advanced
Allow in-process subscribers

6-4

6-5

MyEventClass LCE

6.3.2

6-4
Subscriptions Subscriptions
New Subscription() COM+(COM+ New Subscription
Wizard)
6-6
IMyEvents
6-6

COM+


6-7 IMyEvents MyEventClass
Details CLSID
6-8
Enable this subscription immediately

6-7

6-8

Subscriptions 6-9
Subscriptions MySubscription
6-9

6.3.3

.NET EventClass

EventClass
System.EnterpriseServices 6-1
6-1
EventClass

AllowInProcSubscribers

Bool

FireInParallel

Bool

PublisherFilter

string

(GUID)

EventClass
(
AllowInProcSubscribers=true
FireInParallel=true
)
]
public class MyEventClass:ServicedComponent,ImyEvents
{
public void PrintName(){}
}

Advanced 6-10
Fire in parallel Allow in-process subscribers
6-10

EventClass LCE

6.3.4

COM+

MyTransactionRoot ServicedComponent (
TransactionOption.Required ) PrintTransactionId
ID
ID 6-3
6-3

[EventClass]
public class MyEventClass:ServicedComponent,IMyTransactionEvents
{
public void PrintTransactionId(){}
}
[Transaction(TransactionOption.Supported)]
public class MySubscriberClass:ServicedComponent,
IMyTransactionEvents
{
public void PrintTransactionId()
{
Console.WriteLine(ContextUtil.TransactionId.ToString());
}
}

[Transaction(TransactionOption.Required)]
public class MyTransactionRoot:ServicedComponent
{
public void StartTransaction()
{
Console.WriteLine(ContextUtil.TransactionId.ToString());
MyEventClass ec=new MyEventClass();
ec.PrintTransactionId();
}
}
public interface IMyTransactionEvents
{
void PrintTransactionId();
}
MyTransactionRoot


StartTransaction

654675f8-8b76-45f8-9d70-d17bc59046ad
654675f8-8b76-45f8-9d70-d17bc59046ad
ID

()

6.4

.NET COM+

.NET
.NET ) WinForms ASP.NET )
.NET Windows
Forms ASP .NET
COM+
COM+ LCE .NET Windows
Forms LCE System.EnterpriseServices
LCE

C#
.NET
C++.NET ServicedComponent
Visual Basic C#

7.1

CLSID

CLSID 7-1
CLSID

7-1

ServicedComponent CLSID

Regsvcs CLSIDRegsvcs
() CLSID
7-2
7-2

ServicedComponent CLSID

(1.0.1.1 1.0.1.2)
CLSIDCOM+
CLSID System.Runtime.InteropServices
GuidAttribute


using System;
using System.EnterpriseServices;
using System.Runtime.InteropServices
[GuidAttribute(24B7B5C4-CBEA=4668-AF67-1E3D44F87A68)]
GuidAttribute GUID Visual Studio
GuidGen.exe GUID
.NET Attribute
GuidAttribute System Guid System
ServicedComponents

7.1.1

ServicedComponents

()

()

7-3

()
100 100

7.1.2

System.EnterpriseServices
ObjectPooling
(MinPoolsize)
(MaxPoolsize)
(CreationTimeout)
COM+()COM+

2COM+

( MaxPoolSize
)

7-4 COM+

JITA.

7.1.3

COM+
()
(JITA) JITA

7-5 JITA
7-5 client 1( 1) CFoo CFoo
client 1 CFoo
client 2 CFoo
client 2 client 1 CFoo
CFoo

7-5

7-5 COM+

7.1.4

ServicedComponent COM+
(CLR)
(
) Close Dispose

(
).

7.1.5

COM+.NET

JITA

JITA
() JITA

ServicedComponent

COM+ COM+
ServicedComponent COM (CCW) 3
CCW COM .NET 7-6
ServicedComponent
7-6

CCW

COM+(Shared Property Manager,SPM)SPM


SPM

7.1.6

IObjectControl
4 COM+
() DTC
COM+

7-7 ()
ServicedComponent COM+

1 Active
client 1

1.
2.

3.
4. COM+
5.

IObjectControl ServicedComponent
IObjectControl ServicedComponent
ActivateDeactivate CanBePooledActive Deactive

CanBePooled COM+
CanBePooled CanBePooled

COM+COM+

COM+

COM+

7.2

C#

ServicedComponent
JITA ExecuteCategoryQuery
OfficeMart

ExecuteCategoryQuery

7.2.1

7-1 ObjectPoolLib

7-1

[assembly:System.Reflection.AssemblyVersion(1.0.1.1)]
[assembly:System.Reflection.AssemblyKeyFile(mykey.snk)]
namespace ObjectPoolLib
{
using System;
using System.Xml;
using System.EnterpriseServices;
using System.Data;
using System.Data.SqlClient;
[

System.EnterpriseServices.ObjectPooling
(
true,
10,
100,
CreationTimeout=1000
)
]
[System.EnterpriseServices.JustInTimeActivation(true)]
[
System.EnterpriseServices.Transaction
(

TransactionOption.NotSupported
)
]

public class PooledObject:System.ServicedComponent


{
private System.Data.SqlClient.SqlConnection _cnn;
private System.Data.SqlClient.SqlCommand _cmc;

public PooledObject(){
_cnn=new SqlConnection(
server=(local);database=OfficeMart;uid=sa;pwd=
);
_cmd=new SqlCommand();
_cmd.CommandType=System.Data.CommandType.Text;
_cmd.Connection=_cnn
cnn.Open();
}
[AutoComplete]
public void ExecuteCategoryQuery()
{
_cmd.CommandText=
select CategoryName,Description from Categories;
_cmd.ExecuteNonQuery();
}
//ServicedComponent
public override void Activate()
{
//
}
public override void Deactivate()
{
//
}
public overide bool CanBePooled()
{
if(_cnn.State!=System.Data.ConnectionState.Open)
{
return false;
}

else
{
return true;
}
}
}
[System.EnterpriseServiced.JustInTimeActivation(true)]
[

System.EnterpriseServices.Transaction
(

TransactionOption.NotSupported
)
]
[
System.EnterpriseServices.ConstructionEnabled
(

Default=server=(local);database=OfficeMart;uid=sa;pwd=
)
]
public class NonPooledObject:ServicedComponent
{
private string _sConnection;
private System.Data.SqlClient.SqlConnection _cnn;
private System.Data.SqlClient.SqlCommand _cmd;
public NonPooledObject()
{
//
}
[AutoComplete]
public void ExecuteCategoryQuery()
{

_cnn=new SqlConnection(_sConnection);
_cmd=new SqlCommand();
_cmd.CommandType=CommandType.Text;
_cmd.Connection=_cnn;
_cmd.CommandText=
select CategoryName,Description from Categories;
_cnn Open();
_cmd.ExecuteNonQuery();
_cnn.Close();
_cmd.Dispose();
}
//ServicedComponent
public override void Activate()
{
//
}
public override void Deactivate()
{
//
}
public override bool CanBePooled()
{
return false;
}
public override void Construct(string s)
{
_sConnection=s;
}
}
}

7-1

COM+

dllhost.exe .NET
\winnt\system32 dllhost.exe \winnt\system32

PooledObject ObjectPooling
7-1 7-2
7-1

ObjectPooling

ObjectPooling()

0
1048576
60000

ObjectPooling(bool)

enabled

()
()

ObjectPooling(int,int)

minimum,maximum pool size

60000

ObjectPooling(bool,int,int)

enabled,minimum,maximum

CreationTimeout

int

C# new

Enabled

int

MaxPoolSize

bool

COM+

MinPoolSize

int

7-2 ObjectPooling

COM+ MinPoolSize
JustInTimeActivation Transaction

ObjectObject SqlConnection SqlCommand


System.Data.SqlClient Microsoft SQL Server
Microsoft OLE DB ( Oracle)
System.Data.OleDb


PooledObject NonPooledObject
7-1 ExecuteCategoryQuery
AutoComplete AutoComplete

SqlCommand SQL select


select ExecuteNonQuery

IObjectControl ServicedComponent
virtual ServicedComponent IObjectControl

C# virtual abstract
virtual abstract
virtual ServicedComponent
ActivateDeactivate CanBePooled abstract

NonPooledObject Activate
Deactivate
ServicedComponent CanBePooled

NonPooledObject PooledObject
NonPooledObject
NonPooledObject
ExecuteCategoryQuery
ConstructionEnabled COM+

Default 7-8
Activation Enable object construction

7-8

Activation

ServicedComponent Construct
IObjectConstruct
ServicedComponent COM+ Activate Construct

PooledObject ConstructionEnabled
COM+ Activate Construct

7.2.2

7-2

7-2

using System;
using ObjectPoolLib;
static void Main(string[] args)
{
int i=0;
long lStart;
long lEnd;
lStart=System.DateTime.Now.Ticks;
for(i=0;i<1000;i++)
{

ObjectPoolLib.PooledObject po=new ObjectPoolLib.PooledObject();


po.ExecuteCategoryQuery();
}
lEnd=System.DateTime.Now.Ticks-lStart;
Console.WriteLine(Results for PooledObject:+lEnd.ToString());
lStart=System.DateTime.Now.Ticks;
for(i=0;i<1000;i++)
{

ObjectPoolLib.NonPooledObject npo=new
ObjectPoolLib.NonPooledObject();
npo.ExecuteCategoryQuery();
}
lEnd=System.DateTime.Now.Ticks-lStart;
Console.WriteLine(Results for NonPooledObject+lEnd.ToString());
Console.WriteLine(Console.ReadLine());
}
10
System.DateTime.Now.Ticks
2001 7 1 12:00

Results for PooledObject:157726800


Results for NonPooledObject:216110752

7.3
ServicedComponent ObjectPooling
C++

Microsoft Message Queue(Microsoft )


COM+
COM+
C#
( e-mail

e-mail
e-mail

e-mail

(Remote Procedure Call,RPC)(Simple Objece Access Protocol,SOAP)

Microsoft (MSMQ)j
MSMQ

COM+
.NET C#

8.1

RPC RPC DCOM

SOAP RPC SOAP HTTP


HTTP SOAP HTTP
Web Active Server
Page ISAPl DLL Web Web


(RPC SOAP)

RPC SOAP

IBM MQ Series MSMQ


COM API
API

1()
2

3
4
5
6

MSMQ COM API

(dllhost.exe)

MSMQ
COM+

(dllhost.exe)

8.2 Microsoft
MSNQ
MSMQ

8.2.1

MSMQ

Windows 2000 Server MSMQ 2.0


MSMQ FMSMQ
MSMQ Windows 2000 Windows 2000 MSMQ
Windows 2000 (Windows 2000 Active Directory)
MSMQMSMQ

MSMQ

MSMQ

Microsoft

MSMQ

MSMQ

MSMQ (Computer Management Console)


8-1 Services and Applications MSMQ
MSMQ

8-1

MSMQ

8.2.2

MSMQ

COM+
Windows
2000 COM+
MSMQ

MSMQ
()

MSMQ

MSMQ

MSMQ

(Computer Management Console) MSMQ 8-2


helloworld General COM+

8.2.3 MSMQ

DataSets
0

8-2
.NET XML
ActiveXMessageFormatter(ActiveX )
BinaryMessageFormatter ( )
ActiveXMessageFormatter

System.Object

8.2.4

C# MSMQ

MSMQ COM MSMQ API


API .NET
C# APISystem.Messaging (System.Mesgaging.dll)
MSMQ .NET
System.Messaging

System.Messaging MessageQueue Message MessageQueue

path 8-1 MessageQueue


Message MSMQ
Message
8-2
8-1 MessageQueue

MessageQueue

MessageQueue

MessageQueue();

MessageQueue

MessageQueue

MessageQueue(.\queueName);

MessageQueue(string path,bool

MessageQueue

MessageQueue

sharedModeDenyReceive)

MessageQueue(.\queueName,

true);

MessageQueue()
MessageQueue(string path)

mq

new

mq

new

mq

new

8-2 Message

Message()

Message m = new Message();

Message(Object body)

My Class mc = new MyClass() Message m = new

Message(mc);

My Class mc = new MyClass() Message m = new

IMessageFormatter

Message(mc,new XmlMessageFormatter());

formatter)

Message(Object

body

8-1 OrderQueue

Order Order
8-1

Using System;
Using System.Message;
namespace OrderMesaage
{

public struct Order


{

public string CustomerName;


public string Sku;
public int Quantity;
}
public class C0rderApp
{

public static vold Main()


{

// Order
order order;
order.CustomerName = Aeme, Inc.;
order.Sku = skul23;
order.Quantity = 100;
// OrderQueue Order
MessageQueue mq = newMessageQueue
(Server1\\private$\\OrderQueue);
mq.Send(order);
//
XmlMessageFormatter xmlf = (XmlMessageFormatter) mq.Formatter;
//
xmlf.TargetTypeNames = new
string[]{OrderMessage.Order,OrderMessaging};
//
Message m = mq.Receive();
Order orderIn = (Order)m.Body;
Console.WriteLine(Customer Name: + orderIn.CustomerName);
Console.WriteLine(Sku: + orderIn.sku);
Console.WriteLine(Quantity: - orderIn.Quantity);
}

}
}

MessageQueue 8-1
(Server1)

MessageQueue Order
XmlMessageFormatter

Order order xmlf.TargetTypeNames


TargetTypeNames

Mq.Receive()
Message
()
SystemTimespan

XmlMessageFormatter system.Messaging

8.3

COM+

MSMQ
COM+
MSMQ

8.3.1

MSMQ MSMQ

COM+ COM+

COM+
Web

.NET COM+
COM+
COM+

COM+ ServicedComponents
COM+

8.3.2
8-3

COM+ COM+ COM+


MSMQ

8-3
COM+

MSMQ
MSMQ

()

8-4 queued
components COM+ COM+
queued components

8-4

ListenerHelper COM+ ProgId


components.ListenerHelper COM+
Windows 2000 COM+
ListenerHelper 8-5
ListenerHelper
COM+ COM+ Utilities

8-5

COM+ ListenerHelper

ListenerHelper MSMQ
()

8-2

8-6

8-6
components.Recorder
COM+ MSMQ
1 5

components.ListenerHelper ( 7)
9

8.3.3

c# new
new

new

COMCOM COM

COM

new

( new )

MSDN
COM CoCreateInstance(C/C++) Visual Basic
CreateObject Visual Basic GetObject C/C++ CoGetObject
C#
System.Runtime.InteropServices Marshal Marshal
(CLR) Windows ( COM
)
Marshal BindToMoniker ReleaseComObject
Marshal
BindToMoniker
()
IQC iqc;
iqc = (IQC)
components);

Marshal.BindToMoniker(queue:/new:queued

componentsNamespace.queued

iqc.SomeMethod();
Marshal.BindToMoniker QCNamespace.QC
queue QCNamespace.QC
/new: new
COM+
iqc

COM+ MSMQ

Marshal.ReleaseComObject
BindToMoniker
COM ReleaseComObject
0

8.3.4

COM+

HRESULT

8-7

ApplicationName_0ApplicationName COM+

ApplicationName_1

8-3

8-7
8-3

ApplicationName_0

ApplicationName_2

ApplicationName_3

ApplicationName_4

ApplicationName_5

16

ApplicationName_DeadQueue

8-3
MSMQ

COM+

COM+

Xact

COM+

2
COM+ Queued Exception Class COM+
8-8 QCMarshal.MarshalClass Advanced 8-8
QCMarshal.QC

8-8

COM+
IPlaybackControl COM+COM+
COM+ IPlaybackControl.FinalServerRetry

COM+ IPlaybackControl.FinalClientRetry
IPlaybackControl.FinalServerRetry
IPlaybackContro COM+
IPlaybackContro

()

8.3.5
6

?
?
?
?
MSMQ

MSMQ
MSMQ MSMQ

()
? COM+

C#
[out,retval] ServicedComponent

C#ref out
ref ref

out
Regsvcs

Regsvcs (
)
C# ServicedComponent

MSMQ ServicedComponent
IPersistStream
COM

8.4 COM+
COM+

COM+

8.4.1

COM+
MSMQ

ContextUtil.IsCallerInRole

8.4.2

COM+
ListenerHelper
ListenerHelper
ListenerHelper ContextUtil.SetAbort
ContextUtil.DisableCommit()

MSMQ COM+MSMQ
DTC

8.4.3
COM+

Marshal
MSMQ


MSMQ MSMQ

8.5

C#

HelloWorld

.NET System.EnterpriseServices

8.5.1

HelloWorld

MyApp
COM+ 8-9
COM+Queued Listen
Queued ()Queued
MSMQ Listen COM+

8-10 Advanced QCNamespace.QCException


ProgID CLSID

8-9

8-10
Queued 8-ll IQC
Queuing Queued

8-11

IQC

HelloWorld .NET
ApplicationQueuing
Queued
QueueListenerEnabled 8-9
Listen
ApplicationQueuing Enabled Enabled
Boolean

8-2 QueueListenerEnabled Enabled


8-2

HeIloWorId

using System.Reflection;
using System.EnterpriseServices;
[assembly: Assemb_yKeyFile(QCKey.snk)]
[assembly: ApplicationActivation[ActivationOption.Server]]
[
assembly:
ApplicationQueuing(Enabled=true,QueueListenerEnabled=true)
]

namespace HelloWorld
{

using System;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.Windows.Forms;
[InterfaceQueuing]
public interface IQC
{
void SayHello(string msg);
}

public class QC : ServicedComponent, IQC


{

public void SayHello(string msg)


{

MessageBox.Show(HelloWorld.QC: +msg);
}
}

public class MyApp


{

public static void Main()


{

IQC iqc;
iqc = (IQC) Marshal.BindToMoniker(queue:/new:HelloWorld.QC);
iqc.SayHello(Hello!);

Marshal.ReleaseComObject(iqc);
}
}
}

IQC
SayHelloSayHello
void InterfaceQueuing
8-11 COM+
IQC C# COM+
ServicedComponent IQC IQC.SayHello
msg
6
iqc

Marshal.BindToMoniker System.Object
IQC
()(IQC)
()
Marshal.ReleaseComObject
MSMQ

8.5.2

HelloWorld
EventClass
SayHello
IQC QC
SayHello
COM+
( QCSubscriber )
8.3
using System.Reflection;
using System.EnterpriseServices;
[assembly: AssmblyKeyFile(QCKey.snk)]
[assembly: ApplicationActivation(ActivationOption.Server)]
{
assembly:
ApplicationQueuing(Enabled=true,QueueListenerEnabled=true)

namespace HelloWorld
{

using System;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.windows.Forms;
[InterfaceQueuing]
public interface IQC
{
void SayHello(string msg);
}

[EventClass]
public class QC : ServicedComponent, IQC
{

public void SayHello(string msg)


{}
}

public class QCSubscriber : ServicedComponent, IQC


{

public void SayHello(string msg)


{

MessageBox.Show(HelloWorld.QCSubscriber: + msg);
}
}

public class MyApp


{

public static void Main()


{

Iqueued component iqc;


iqc = (IQC) Marshal.BindToMoniker(queue:/new;HelloWorld.QC);
iqc.SayHello(Hello!);
Marshal.ReleaseComObject(iqc);
}

}
}

8.5.3

8-2 ExceptionClass
ProgID CLSID
ProgID CLSID CLSID
System.Runtime.InteropServices.GuidAttribute CLSID
COM+
8-4

using System.Reflection;
using System.EnterpriseServices;
[assembly: AssmblyKeyFile(QCKey.snk)]
[assembly: ApplicationActivation(ActivationOption.Server)]
{
assembly:
ApplicationQueuing(Enabled=true,QueueListenerEnabled=true)
}

namespace HelloWorld
{

using System;
using System.EnterpriseServices;
using System.Runtime.InteropServices;
using System.windows.Forms;
using COMSVCSLib;
[InterfaceQueuing]
public interface IQC
{
void SayHello(string msg);
}

[ExceptionClass{HelloWorld.QCException}]
public class QC : ServicedComponent, IQC
{
public void SayHello(string msg)
{

MessageBox.Show(HelloWorld.QC:

+ msg);

}
}

public class QCExceptionClass:

ServicedComponent, IPlaybackControl, IQC

//IQC
public void SayHello(string msg)
{

MessageBox.Show(HelloWorld.QCExceptionClass: & msg);


}

//IplaybackControl
public void FinalClientRetry()
{
//
MessageBox.Show(HelloWorld.QCExceptionClass: FinalClientRetry);
}

//IplaybackControl
public void FinalServerRetry()
{

//
MessageBox.Show(HelloWorld.QCExceptionClass: FinalServerRetry);
}
}

public class MyApp


{

public static void Main()


{

IQC iqc;
iqc = (IQC) Marshal.BindToMoniker(queue:/new;HelloWorld.QC);
iqc.SayHello(Hello!);
Marshal.ReleaseComObject(iqc);
}
}
}

IPlaybackControl IPlaybackControl
COM+(comsvcs.dll)

(tlbimp.exe)COM+ COMSVCSLib
FinalClientRetry FinalServerRetry

8.6
MSMQ

.NET

COM+

9
10 COM+.NET

.NET
SOAP

.NET
DCOM DCOM
Win32 COM
Internet DCOM
DCOM Internet
(Network Address TranslationNAT)
DCOM
Simple Object Access Protocol(SOAP)
SOAP SOAP XML
HTTP SOAP Internet
DCOM SOAP HTTP Web SOAP
HTTP
.NET SOAP
TCP/IP ().NET

.NET COM+
ServicedComponent .NET ServicedComponent
System.ContextBoundObject System.ContextBoundObject
System.MarhsalByRefObject ContextBoundObject MarhsalByRefObject

ServicedComponent

9.1

.NET

.NET
.NET
ObJRefs()
.NET ( ServicedComponent)

Marshal()endpoint() well-known object()

.NET

9.1.1

(marshaling)

(marshaling)

A B
(call stack)

()

9.1.2

(Endpoints) HTTP URL


HTTP URL
http://www.hungryminds.com/mandtbooks/index.html

URL web http://


Web HTTP Web URL
Web www.hungryminds.comWeb
mandtbooks index.html
Web Web

.NET
HTTP URL

www.someserver.com Web
http://www.someserver.com/myappfolder/mywebservice.aspx

Web
Web Web mywebservice.aspx

.NET TCP
Windows .NET
Windows TCP/IP
9000
Windows
tcp://www.someserver.com:9000/RemoteComponentName
TCP www.someserver.com
9000
RemoteComponentName

9.1.3

(Well-known objects)

COM+
TCP

9.1.4


MarshalByVal()
MarshalByRef( )
ServicedComponent
1
MarshalByVal
MarshalByVal ()

System.Runtime.Serialization.Iserialiable
System.Serializable Iserializable SerializabIe

Iserializable

GetObjectData(SerializationInfo,StreamingContext)
System.Runtime.Serialization.SerializationInfo
System.Runtime.Serialization.StreamingContext

MarshalByVal
Iserializable Serializable
System.Serializable Iserializable

System.NonSerializable ( Serializable )
NonSerializable
2
MarshalByRef
MarshalByRef
System.MarshalByRefObject
System.ContextBoundObject
COM+ ServicedComponent ServicedComponent
ContextBoundObject MarshalByRefObject
ServicedComponent 9-1
ServicedComponent

9-1

ServicedComponent

MarshalByRefObject ContextBoundObject
ServicedComponent
ContextBoundObject
MarshalByRefObject
3 MarshalByVal MarshalByRef
ServicedComponent MarshalByRef MarshalByVal
ServicedComponent ContextBoundObject
COM+
ServicedComponent ?

COM+


4(Context-Bound Objects)
ContextBoundObject ServicedComponent
.NET COM+( 4
)

.NET
Win32
9-2 Win32

9-2

Win32

default context
ServicedComponent

ServicedComponent ContextBoundObject COM+


ServicedComponent
ServicedComponent

9.1.5

API new C# new


(Client-activated objects)
(Server-activated objects)
1(Client-Activated Objects)
API

API

(parameterized
constructors) new
Activator.CreateInstance Activator
System CreateInstance object[]

2 (Server-Activated Objects)
Singleton SingleCall

.NET

SingleCall COM+ JIT


SingleCall ( 9-3) Just In Time
Activation(JITA)COM+
COM+SingleCall
Singleton

9-3

SingleCall

Singleton

( 9-4)Singleton

Singleton

(Garbage Collection)

9-4

Singleton

COM+ JIT SingleCall


SingleCall

Singleton

Singleton

()

9.1.6

1
(transparent proxy)
(
)()
Cfoo Cfoo
( CFoo.DoSomething) DoSomething
Cfoo DoSomething ?
?
?
Cfoo
9-5

9-5

9-5 Cfoo

Cfoo MarshalByRefObject Cfoo( 1)


Cfoo DoSomething

Cfoo DoSomething

System.Runtime.Remoting.Messaging.Imessage


RemotingServices.IsTransparentProxy
System.Object Cfoo
foo RemotingServices.IsTransparentProxy(foo)

2
(rea1 proxy)
Imessage

Invoke Invoke
Imessage System.Runtime.Remoting.Proxies

ObjRef
ObjRef

URI

ObjRef
9-6() MarshalByRef

9-6

9-6 new Cfoo


ObjRef
2
System.Runtime.Remoting.Proxies.RealProxy 0bjRef
( 3 ) 3

9.1.7

(Channels)
(HTTPTCP/IPSMTP() MSMQ)
.NET HTTP TCP/IP

System.Runtime.Remoting.Channels
System.Runtime.Remoting.Channels.Tcp
System.Runtime.Remoting.Channels.Http
Channels

TCP/IP
TCP/IP TCP/IP TCP
TCP/IP IP TCP/IP Win32
IP IP TCP/IP TCP/IP
.NET

TCP/IP

(Client-side channels) Channels IchannelSender

Channels.IchannelReceiver
HTTP TCP/IP
HTTP Web HTTP
System.Net Web HTTP
XML XML SOAP TCP
TCP Windows
TCP TCP
Web XML HTTP
Internet HTTP 80 TCP
InternetHTTP

9.1.8

COM

0 COM

0.NET

Ilease Ilease System.Runtime.Remoting.Lifetime


()
null

()

Renew

RenewOnCallTime
Ilease

Register Isponsor
Isponsor System.Runtime.Remoting.Lifetime Register
Isponsor TimeSpan TimeSpan RenewOnCallTime

ILease.Renew TimeSpan

UnRegister UnRegister ISponsor


Register
MarshalByRefObject MarshalByRefObject
GetLifetimeService InitializeLifetimeService Ilease
GetLifetimeService Ilease
MarshalByRefObject Ilease
InitializeLifetimeService
MarshalByRefObject

9.2

SOAP

SOAP SOAP Web SOAP


Simple Object Access Protocol()SOAP
SOAP XML
.NET SOAP 1.1 SOAP
SOAP HTTP

(Simple Mail Transfer ProtocolSMTP)


(File Transfer ProtocolFTP)
(Message Queuing MSMQ IBM MQ Series)
(Remote Procedure CallRPC)
SOAP
SOAP SOAP
HITP

9.2.1

HTTP

SOAP HTTP HTTP


SOAP HTTP
POST /MyApp/MyPage.aspx HTTP 1.1
Host: www.myserver.com
Content: text/xml
Content-Length: 100
{crlf}
<< Post >>

HTTP

HTTP
HTTP Get Post
URL Web Get
Web Post SOAP
Post Post Get
Get
Web
NetBios TCP/IP
SOAP text/xml
XML.Content-Length() Web
100 ({crlf})
HTTP <<post data here>>
SOAP SOAP SOAP

9.2.2

SOAP

SOAP XML SOAP SOAP


SOAP XML SOAP 9-7

9-7

SOAP

SOAP
<SOAP-ENV:Envelope
xmlns:SOAP-ENV=http://schemas.xmlsoap.org/soap/envelope/
SOAP-ENV:encodingStyle=http://schemas.xmlsoap.org/soap/encoding/ />
SOAP Envelope
Envelope SOAP-ENV SOAP-ENV
Xmlns
SOAP URLhttp://schemas.xmlsoap.org/soap/envelope/

SOAP
Doubles ()
Strings ()
Boolean values ()
Floats ()
Arrays ()
Dates ()
SOAP SOAP Envelope

SOAP SOAP

SOAP

SOAP-ENV
actor mustUnderstandActor ( URI )
SOAP
Actor

SOAP-ENV mustUnderstand(
0 1) 1 SOAP

SOAP 9-1
Envelope
9-1

SOAP

<SOAP-ENV:Header>

<auth:CustomAuthentication
xmlns:auth=http://www.myserver.com/schemas/auth/
SOAP-ENV:mustUnderstand=1
SOAP-ENV:actor=http://myserver.com/myOtherApp/somepage.asmx>
MyAuthenticationMethod

</auth:CustomAuthentication>
</SOAP-ENV:Header>
Body Body

()
SOAP

PlaceOrder

// Placeorder(string Sku, int CustomerNumber, int Qty) int 0rderNumber =


someobj.PlaceOrder(sku123, 1009, 3)
1009 3 skul23
SOAP 9-2
9-2

SOAP

<SOAP-ENV:Body
<order:PlaceOrder
xmlns:order=http://myserver.com/schemas/orders>
<sku>sku123</sku>
<customernumber>1009</customernumber>
<qty>3</qty>
</order:PlaceOrder>
</SOAP-ENV:Body>
9-2 PlaceOrder

PlaceOrder
SOAP
<SOAP-ENV:Body

<order:PlaceOrderResponse
xmlns:order=http://myserver.com/schemas/orders>
<PlaceOrderResult>988</PlaceOrderResult>
</order:PlaceOrder>
</SOAP-ENV:Body>
Response
Response Result

SOAP

faultcode
faultstring
faultfactor
detail
faultcode HTTP
faultcode
faultstring HTTP

faultfactor URL
actor actor faultfactor actor URI
detail

<SOAP-ENV:body>

<SOAP-ENV:fault>
<faultcode>SOAP-ENV:VersionMismatch</faultcode>
<faultstring>invalid namespace for SOAP Envelope</faultcode>

</SOAP-ENV:fault>
</SOAP-ENV:body>

9.3

ServicedComponents

ServicedComponent MarshalByRefObject
ServicedComponent
3 ServicedComponent
SOAP HTTP SingleCall
TCP singleCall
ServicedComponent

9.3.1

SOAP HTTP SingleCall

Cfoo SingleCall 9-3


9-3

SOAP SingleCall

Namespace RemoteComponent
{

using System.EnterpriseScrvices;
public class CFoo : ServicedComponent
{
public int PlaceOrder(string Sku, int CustomerNumber, int Qty)
{

//
//
return OrderNumber;
}
}
}

Cfoo
RemoteComponent
Web Web HTTP SOAP
Internet Services Manager
www.myserver.com
RemoteComponent RemoteComponent
bin Web bin
dll web.config
ASP.NET web.config
(SingleCall Singleton)
web.config 9-4
9-4

web.config

<configuration>

<system.runtime.remoting>
<application>

<service>
<wellknown mode=SingleCall type=RemoteComponent.Cfoo,
RemoteComponent
objectUri=/RemoteComponent/RemoteComponent.soap/>
</service>
</application>
</system.runtime.remoting>
</configuration>
wellknown mode
( singleCall)type (+)
RemoteComponent objectUri
URI RemoteComponent.soap Web .soap
.soap

Internet (Internet Information Services)


Web
HTTP SOAP 9-5
RemoteComponent
9-5

RemoteComponent

using System;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Http;
using RemoteComponent;
Public class ClientApp
{
public static void Main()
{

HttpChannel http = new HttpChannel();


ChannelServices.RegisterChannel(http);
Type trc = typeof(RemoteComponent);
RemoteComponent re =Activator.GetObject(trc,
http://www.myserver.com/RemoteComporent/RemoteComponent.soap);
int OrderNumber = Re.PlaceOrder(sku123, 1009, 3);
Console.Writeline(OrderNumber.ToString());
}
}

1. HttpChannel
2 RemoteComponent
3 PlaceOrder RemoteComponent
Activator System
GetObject typeof() C#
system.Type RemoteComponent

web.config
RemoteComponent
PlaceOrder
9-5
9-6 ClientApp.config
9-6

ClientApp.config

//ClientApp.config
<configuration>
<systern.runtime, remoting>
<application>

<client url=http://www.myserver.com/RemoteComponent>
<wellknown
type=RemoteComponent.Cfoo,RemoteComponent
url = http://www.myserver.com/RemoteComponent/RemoteComponent.soap
/>

<channels>

<channel type = HttpChannel. System.Runtime.Remoting/>


</channels>
</application>
</system.runtime.remoting>
</configuration>
RemoteComponent.Cfoo
CFoo HTTP

http://www.myserver.com/RemoteComponent/RemoteComponent.soap 9-7

9-7

ClientApp.config

using System;
using System.Runtime.Remoting;
using RemoteComponent;

Public class ClientApp


{

public static void Main()


{

RemotingConfiguration.Configure(ClientApp.Config);
CFoo foo = new CFoo();
int OrderNumber = foo.PlaceOrder(sku123, 1009, 3);
Console,WriteLine(OrderNumber.ToString());
}
}
RemotingConfiguration

9.3.2

TCP SingleCall

TCP HTTP TCP


Web
Windows
TCP

web.config ClientApp.config
web.config

9-8
9-8

RemoteComponent

Using System;
Using System.Runtime.Remoting;
Using RemoteComponent;
public class ComponentApp
{
public static void Main()
{

TcpChannel tcp = new TcpChannel(8000);


Type t = typeof(RemoteComponent.CFoo);
string uri = tcp://www.myserver.com/RemoteComponent/;
RemotingConfiguration.RegisterWellKnownServiceType(
t,
uri,
WellKnownObjectMode.SingleCall);
Console.WriteLine(Listening for Requests on port 8000 _);
Console.ReadLine();
}
}
8000
RegisterWellKnownServiceType RemoteComponent SingleCall
Main Cfoo

ClientApp
9-9
9-9

ClientApp.config TCP

//ClientApp.config
<configuration>
<system.runtime.remoting>

<application>
<client url=http://www.myserver.com/RemoteComponent>
<we11known
type=RemoteComponent.CFoo, RemoteComponent
url=tcp://www.myserver.com:8000/RemoteComponent/
/>
<channels>
<channel type=TcpChannel, System.Runtime.Remoting/>
</channels>
</application>
</system.runtime.remoting>
</configuration>
8000 TCP URL TcpChannel
HttpChannel

HttpChannel
HttpChannel SOAP TcpChannel
Binary

9.3.3

ServicedComponent

Cfoo new
Activator.CreateInstance Activator.CreateInstance
Web
Windows
Web
9-10
9-10

ServicedComponent

using System;
using System.Runtime.Remoting;
using System.Runtime.Channels;
using System.Runtime.Channels.Http;
using RemoteComponent;

Public class

ClientApp

public static void Main()


{

RemotingConfiguration.Configure(ClientApp.Config);
CFoo foo = (CFoo) Activator.CreateInstance(Typeof(CFoo));

int OrderNumber = foo.PlaceOrder(sku123, 1009, 3);


Console.WriteLine(OrderNumber,Tostring());
}
}
9-10 CreateInstance
ObjRef
ObjRef RealProxy RealProxy
RealProxy
CreateInstance 8
System.Runtime.Remoting.ObjectHandle
RemoteComponent
RemoteComponent
System.Object

9.4

.NET
SOAP
.NET COM+
ServicedComponent COM DCOM
8 MSMQ
.NET .NET

10 COM+.NET

COM+ l.5
IIS 6.0
MSMQ
Windows 2000 COM+
Windows 2002 Server Windows 2000 Server
COM+Windows 2002 COM+
COM+ 1.5 COM+ 1.5
IIS 6.0 MSMQ
Web
Windows 2002 2

10.1

COM+ 1.5

MTS COM+COM+ 1.5

Microsoft 2
COM+ Windows NT

10.1.1

COM+

Windows 2000 IISCOM+ Event System()(Computer


Browser) Windows 2002 COM+ System
( Windows )
COM+ 1.5 COM+ Windows
10-l COM+
lO-1 Run
Application as NT service( NT )
Windows

Setup New Service() 10-2 Service


Setup ()

()

10-1
10-2 Service Setup
Services MMC

Services

10-2
IIS IIS
Services
10-3 Services NtServices

103 Windows NtServices


?

()

10.1.2
Application Partitions(
)

10-4
Application A
Partitions A B

10-4

COM+

COM+ Application Partitions


105
SalesAccountingPartition ID()
Partition ID GUID GUID
Partition ID

(Partition ID)

(Disable Deletion)
(Disable Changes)

COM+ Partitions
10-6 COM+ Partitions SalesAccounting

10-5

10-6

SalesAccounting

106 Base Application

(Partition Sets)
Organization Units(OU) OU

OU OU
Base Application
COM+Base Application

10.1.3
COM+

10-7
Dump()COM+
systemroot%system32comdmp Dump()

10-7

Dump


Platform SDK()
Windows
10.1.4
(Component aliasing)

ProgID CLSID
ProgID CLSID Component Services
10-8 Alias Component()

10-8

Alias Component

(
)

10.1.5

4 COM+
Serialized(
) Windows 2000 COM+
COM+

(Any)
(Read uncommitted)
(Read committed)
(Repeatable Read)
(Serialized)
Serialized
Serialized
Supported()

10.1.6
(low-memory activation gate)

COM+
COM+COM+

10.1.7

Component Services Explorer()

.NET ,

Microsoft

(lifetime limit)()
COM+COM+

0-1048576kb

10-9 Component Services Pooling Recycling


COM+(expiration timeout)

(call limit)

(activation limit)
JITA

Microsoft Application Properties()


10-9 Component Services
Pooling Recycling () Application Recycling(
)

10.1.8
10-9 Application Pooling()
Windows COM+
dllhost.exe dllhost.exe
1010 dllhost.exe
dllhost.exe

10-10

10.2 IIS 6.0


Web COM+
IIS Internet IIS COM+
IIS COM+
IIS COM+ IIS 6.0

IIS 6.0
IIS

Web

ASP
(metabase) XML

10.2.1
IIS 5(Windows 2000 )Web W3SVC
IIS 6.0 W3SVC Web

http.sys
Web WAS: Web Administration Service
XML

10-11 URI
http.sys Web (WAS)WAS
XMLL WAS Web
Web
IIS () http.sys
TCP/IP IIS
http.sys

HTTP Web
HTTP

l0-11 IIS 6.0 W3SVC


http.sys URI http.sys
URI
URIhttp.sys Web
IIS
Active Server Page

10-12
http://myserver.com/someApp/default.asp
Client B http.sys default.asp
Client B Client CD F
default.asp Client
A
http.sys IIS
http.sys
IIS HTTP
10-13 Clients ABC D someApp
Client D Client F
Client F

10-13 http.sys
Web (WASWeb Administration Service) W3SVC
http.sys WAS
WAS http.sys

WAS IIS IIS


web

IIS 6.0 Notepad XML

10-11 Web
ASP ISAPI someApp
Default.asp
IIS Web

Web
10.2.2 Web
Windows NT IIS 4 mtx.exe web ( Web
)Windows 2000 IIS 5
dllhost.exe IIS 5

IIS 6 10-14

10-14 Web
Web
Web Web
web
Web
Web

(CPU )

Web

Web
Web Web

Web Web
Web

IIS 6.0

Web
IIS 6.0
WebWeb(web garden)
Web

10-15 web Web

10-15 Web

IIS 6.0
(Rapid Fail Protection)IIS
IIS http.sys
HTTP 503

10.2.3
IIS 6.0
(standard mode) Web IIS 5
ISAPI(Internet Server API)

IIS 6.0

(dedicated-application mode)

IIS 6.0 IIS

10.2.4
IIS 6.0 IIS 6.0

worker-process recycling COM+


IIS

ping
( COM+)

IIS
IIS

IIS
(restarting)
Web COM+
IIS Web IIS
(IUSER_MachineName
IWAM_MachineName)

ping WAS WAS


WAS Web WAS
WAS

(idle
timeout) COM+( Windows 2000 )

IIS 6.0 (on-demand start) Web

processor affinity
CPU
CPU
CPU ()
10.2.5 ASP
ASP (ASP template caching) ASP
ASP.NET Active Server Page ASP

ASP ASP ASP

IIS

10.2.6 XML

(metabase)

Web IIS
MetaEditPlatform SDK
IIS IIS 6.0
XML XML
Notepad
IIS 6.0 XML

IIS

WAS http.sys Web


IIS
IIS
WAS
Web Web
IIS
history history

IIS 6.0

(secure backup)
(unsecure backup)(legacy
bakup)
IIS

10.3 MSMQ
8 MSMQ
MSMQ 2.0Windows 2002 MSMQ 3.0

LDAP

MSMQ 3.0 LDAP MSMQ MSMQ


MSMQ 2.0 MSMQ
(Active Directory)MSMQ
MSMQ LDAP MSMQ
3.0 MSMQ

(Distribution Lists)

(queue alias)
8

MSMQ

(message triggers)

P1atform SDK

10.4
Windows 2002
Windows 2002 ping
IIS COM+ IIS COM+

.NET

A CD-ROM
CD-ROM

CD-ROM OfficeMart
OfficeMart COM+
CD-ROM Adobe Acrobat Reader

A.1

Windows 2000Windows XP Beta 2 Windows NT 4.O

450 MHz ( 600 MHz) Pentium II PC


Windows Professional 96MB ( 128MB)
Windows 2000 Server
192MB ( 256MB)
500MB 2.5GB
Windows 2000Windows XP Beta 2 Windows NT 4.O
800600 256 ( 16 )
Microsoft Mouse
CD-ROM (2x)

1MB
CD-ROM OfficeMart

A.2 Microsoft Windows

1 CD-ROM
2 Windows (explorer.exe)
3 OfficeMartWeb Web
4 OfficeMartWeb Read-Only()

5 0K OfficeMartWeb
Apply()
6 Windows OfficeMartWebbin
RegOfficeMart.bat

A.3

CD-ROM
A.3.1
BookExamples
A.3.2 OfficeMart
OfficeMart COM+:

(Just In Time Activation)

OfficeMart ( CD-ROM )

Microsoft SQL Server 2000


Active Server Page .NET

OfficeMart Internet B2C


Internet
ASP.NET (ID) SKU
COM+

COM+ B2C Web

A.3.3 OfficeMart
OfficeMart
COM+ Active Server Page .NET
OfficeMart Microsoft SQL Server COM+ Library

Database() OfficeMart Inventory OfficeMartInventory


Products Web
OfficeMart
SQL

COM+ LibraryOfficeMartLib OfficeMartLib


COM+

Orders ASP.NET Orders


(Qneued Component) Orders
Web Web
8
Customers Products Customers Products
() Orders

VerifyCustomer VerifyProduct
ServicedComponent
ServicedComponent
Verify Products

InventoryConn OfficeMartConn
Verify
100
OrderEvtCustomerSubscriber AdminSubscriberOrderEvt COM+

CustomerSubscriber ()
AdminSubscriber

Subscriber
Subscriber
A.3.4

C# COM+

() Adobe PDF
Adobe Acrobat Reader() Adobe Acrobat
Reader www.adobe.com

A.4

OfficeMartLib.dll OfficeMartLib.dll OfficeMartLib.dll\bin

OfficeMart World
Wide Web (IIS)SMTP COM+
(Distributed Transaction CoordinatorDTC) SQL Server
SQL SQL Inventory
Products OfficeMart Orders Customers

Hungry Minds Customer Service


(800)762-2974(317)572-3993 Hungry Minds

B COM+
4
()
COM+(COM+ Shared Property ManagerSPM)
SPM
SPM
COM+COM+
SPM API
API System.EnterpriseServices

SPM API

B.1
C# static
static
static

B.1.1 static

static static

(static)
ContextUtil
ContextUtil ?
ContextUtil
ContextUtil.ContextID ID
B-1
static

B-1 (static)
B.1.2 static
static
COM+ SPM
COM+ SPM
SPM API
COM+

B-1 System.Threading Thread


ThreadStart ThreadStart
void
Thread ThreadStart
Thread.Start ThreadStart
(tl t2) ThreadStart
Main

Thread.Join
B-1
using System;
using System.Threading;
namespace StaticProperties
{

public class CApp


{

public static void Main()


{

// create two new thread classes


Thread t1 = new Thread(new ThreadStart(Start1));
Thread t2 = new Thread(new ThreadStart(Start2));
// start each thread
t1.Start();
t2.Start();
// wait for each thread to finish
t1.Join();
t2.Join();
// print the value of iCount
Console.WriteLine(CStatic.iCount.ToString());
}

public static void Start1()


{

CStatic.iCount = 2;
int iSomeValue = 4;
// force the thread to sleep so the second thread can
// interrupt its work and change the value of iCount
Thread.Sleep(500);

int iResult = iSomeValue / CStatic.iCount;


}

public static void Start2()


{

CStatic.iCount = 0;
}
}

public class CStatic


{

public static int iCount;


}
}

(t1 t2)iCount Cstatic


(t1) iCount iSomeValue(t2)
iCount 0 Thread.Sleep
iCount 0
Main Thread.Join
Main
Main iCount
0 0 iSomeValue
System.DivideByZeroException( 0 )

iCount
iCount 0COM+ SPM
SPM

B.2 API
COM+

.NET SPM API ()


System.EnterpriseServices

SharedPropertyGroupManager
SharedPropertyGroup
SharedPropertyClass

B-2
B.2.1 SharedPropertyGroupManager
SharedPropertyGroupManager

B-2
B-2 SharedPropertyGroupManager
using System.EnterpriseServices;
public class SomeComponent : ServicedComponent
{

public void DoSomething()


{

SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();
// do something with the Group Manager
}

CreatePropertyGroup

SharedPropertyGroup CreatePropertyGroup (
string name,
ref PropertyLockMode dwIsoMode,

ref PropertyReleaseMode dwRelMode,


out bool fExists
);

PropertyLockModePropertyLockMode System.EnterpriseServices

PropertyLockModeMethod PropertyLockMode.SetGet PropertyLockMode


Method ()
SetGet

setGet
PropertyReleaseMode System.EnterpriseServices

System.EnterpriseServices.Process
System.EnterpriseServices.Standard

PropertyLockMode C# ref

out

fExists
(C# ref )fExists
true()

SomeComponent
CreatePropertyGroup B-3
B-3
using System.EnterpriseServices;
public class SomeComponent : ServicedComponent
{

public void DoSomething()


{

bool bGroupExists;
// declare the property lock mode
PropertyLockMode lm = PropertyLockMode.SetGet;
// declare the property release mode enum

PropertyReleaseMode rm = PropertyReleaseMode.Process;
SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();
SharedPropertyGroup pg;
pg = gm.CreatePropertyGroup(
myGroup,
ref lm,
ref rm,
out bGroupExists;
);

// use pg to create properties


}
}

B-3 SetGet
ProcessbGroupExists false
SharedPropertyGroup
SharedPropertyGroupManager.Group

Public SharedPropertyGroup Group(string name)


CreatePropertyGroup
SharedPropertyGroup B-3
B-4
B-4 Group
using System.EnterpriseServices;
public class SomeComponent : ServicedComponent
{

public void DoSomething()


{

SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();
SharedPropertyGroup pg;
pg = gm.Group(myGroup);
// use pg to create properties
}
}

B.2.2

SharedPropertyGroup

B-3 B-4 SharedPropertyGroupManager


SharedPropertyGroup
SharedPropertyGroupManager SharedPropertyGroup
SharedPropertyGroup

Public SharedProperty CreateProperty(


string name,
out bool fExists

)
bool
CreateProperty Group
out
SharedProperty SharedProperty

B-5 SharedPropertyGroup.CreateProperty
SomeComponent. DoSomething SharedProperty
B-5 SharedProperty
using System.EnterpriseServices;
public class SomeComponent : ServicedComponent
{

public void DoSomething()


{

bool bGroupExists;
bool bPropertyExists;
// declare the property lock mode
PropertyLockMode lm = PropertyLockMode.SetGet;
// declare the property release mode enum
PropertyReleaseMode rm = PropertyReleaseMode.Process;
SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();
SharedPropertyGroup pg;
pg = gm.CreatePropertyGroup(
myGroup,
ref lm,
ref rm,
out bGroupExists;
);

SharedProperty sp = pg.CreateProperty(
myProp,
bPropertyExists);
}
}
SharedPropertyGroup

Public SharedProperty CreatePropertyByPosition(


int position,
out bool fExists

CreateProperty
CreatePropertyByPosition

CreateProperty CreateProperty
Property Property
SharedPropertyProperty
CreatePropertyByPosition
PropertyByPosition Property PropertyByPosition

PropertyByPosition B-6
B-6
using System.EnterpriseServices;
public class SomeComponent : ServicedComponent
{

public void DoSomething()


{

bool bGroupExists;
bool bPropertyExists;
// declare the property lock mode
PropertyLockMode lm = PropertyLockMode.SetGet;
// declare the property release mode enum
PropertyReleaseMode rm = PropertyReleaseMode.Process;
SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();
SharedPropertyGroup pg;

pg = gm.CreatePropertyGroup(
myGroup,
ref lm,
ref rm,
out bGroupExists;
);

SharedProperty sp = pg.CreatePropertyByPosition(
5,
bPropertyExists);
}

public string DoSomethingElse()


{

SharedPropertyGroupManager gm = new
SharedPropertyGroupManager();
SharedPropertyGroup pg = null;
SharedProperty sp;
try {
pg = gm.Group(myGroup);
}

catch (ArgumentException ae) {


Console.WriteLine(ae.Message);
}

try {
sp = pg.PropertyByPosition(5);
}

catch (ArgumentException ae) {


Console.WriteLine(ae.Message);
}

catch (NullReferenceException nre) {


Console.WriteLine(nre.Message);
}

return ;
}
}

B-6 DoSomethingElse

DoSomethingElse DoSomething DoSomethingElse

try-catch System.ArgumentException
SharedPropertyGroupManager.Group
try-catch 5
0 1
5
System.ArgumentException
myGroup Group
myGroup System.NullReferenceException

B.2.3 SharedProperty

() SharedProperty
object object C# System.Object

SharedProperty System.Object Value


Value (Shared Property Manager)
B-7
SharedProperty
DoSomething
B-7 SharedProperty
using System.EnterpriseServices;
public class SomeComponent : ServicedComponent
{

public void DoSomething()


{

bool bGroupExists;
bool bPropertyExists;
// declare the property lock mode
PropertyLockMode lm = PropertyLockMode.SetGet;
// declare the property release mode enum
PropertyReleaseMode rm = PropertyReleaseMode.Process;

SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();
SharedPropertyGroup pg;
pg = gm.CreatePropertyGroup(
myGroup
ref lm,
ref rm,
out bGroupExists;
);

SharedProperty sp = pg.CreateProperty(
myProp,
bPropertyExists);
if (bPropertyExists)
{

Console.WriteLine((string)sp.Value);
}

else {
sp.Value = some interesting string
}
}
}

SharedProperty
DoSomething

object string
(boxing)
(Boxing)
(unboxing)
B-7

some interesting string Value


C#

else {
sp.Value = (object)some interesting string

C#
DoSomething
Cname
B-8
using System.EnterpriseServices;
public class SomeComponent : ServicedComponent
{

public void DoSomething()


{

bool bGroupExists;
bool bPropertyExists;
// declare the property lock mode
PropertyLockMode lm = PropertyLockMode.SetGet;
// declare the property release mode enum
PropertyReleaseMode rm = PropertyReleaseMode.Process;
SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();
SharedPropertyGroup pg;
pg = gm.CreatePropertyGroup(
myGroup,
ref lm,
ref rm,
out bGroupExists;
);

SharedProperty sp = pg.CreateProperty(
myProp,
bPropertyExists);
// create a new instance of CName and add it as a property
CName name = new CName(David, Roth, Lee);

// this is an implicit reference conversion


sp.Value = name;
// this is an explicit reference conversion
name = (CName) sp.Value
}

// this is the class we will instantiate and add to the SPM


public class CName
{

public string FirstName;


public string LastName;
public string MiddleName;
public CName(string sFirst, string sLast, string sMiddle)
{

FirstName = sFirst;
LastName = sLast;
MiddleName = sMiddle;
}

CName SharedProperty Value


Cname
(sp.value) Cname

B.3
API

iCount
DivideByZeroException
API iCount
B-9
B-9
using System;
using System.Reflection;
using System.EnterpriseServices;
using System.Threading;
[assembly: AssemblyKeyFile(C:\\crypto\\key.snk)]
namespace SharedProperties
{

public class SC : ServicedComponent


{

public void Start1()


{

PropertyReleaseMode rm = PropertyReleaseMode.Process;
PropertyLockMode lm = PropertyLockMode.Method;
bool bPropertyExists;
bool bGroupExists;
SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();

SharedPropertyGroup pg = gm.CreatePropertyGroup(
CounterGroup,
ref lm,
ref rm,
out bGroupExists);
SharedProperty prop = pg.CreateProperty(
Counter,
out bPropertyExists);
prop.Value = 2;
int iSomeValue = 4;
Thread.Sleep(500);
int iResult = iSomeValue / (int) prop.Value;
}

public void Start2()


{

PropertyReleaseMode rm = PropertyReleaseMode.Process;
PropertyLockMode lm = PropertyLockMode.Method;
bool bPropertyExists;
bool bGroupExists;
SharedPropertyGroupManager gm =
new SharedPropertyGroupManager();

SharedPropertyGroup pg = gm.CreatePropertyGroup(
CounterGroup,
ref lm,
ref rm,
out bGroupExists);
SharedProperty prop = pg.CreateProperty(

Counter,
out bPropertyExists);
prop.Value = 0;
}
}

public class CApp


{

public static void Main()


{

Thread t1 = new Thread(new ThreadStart(Start1));


Thread t2 = new Thread(new ThreadStart(Start2));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine(Done);
}

public static void Start1()


{

SC sc = new SC();
sc.Start1();
}

public static void Start2()


{

SC sc = new SC();
sc.Start2();
}
}
}

Main

SC SC.Start1SC.Start1
Counter
SC.Start1
Counter PropertyLockMode Method

SetGetCounter
PropertyLockMode SetGet

SC.Start2 () SC.Start2 ()

SharedPropertyGroupManager.Group SharedPropertyGroup. Counter

SC
Counter
Counter
0 Counter

SC.Start1 Counter COM+


0
DivideByZeroException

C C#
C# Visual Studio C++ Java
C#.NET COM+
C#.NET C#

.NET C#
C#

C.1
COM+

Namespace NsOne
{

class CFoo
{
}

Namespace NsTwo
{

class CFoo
{
}
}

CFoo
CFoo
CFoo CFoo
NsOne.CFoo new NsOne.CFoo ().NET

CFoo
CFoo C#
.NET
NsOne
MyApplication.NsOne

MyApplication
Namespace MyApplication
{

Namespace NsOne
{

class CFoo
{
}
}

Namespace NsTwo
{

class CFoo
{
}
}
}

MyApplication MyApplication.CFoo
NsOne.CFoo

C#C#
using
CFoo
using C C++
using C C++#include

using MyApplication.CFoo
.NET
C#

MyApplication.CFoo

Using NSl MyApplication.CFoo


NSl
Using NSl MyApplication.CFoo
NS1.CFoo = new NS1.CFoo();

C.2
C#
if-else
Java C++
C#
if

if-else C# C#

C# if
If (iVar == 10)
{

// do something here
}

C# else else

If (iVar == 10)
{

// do something here
}

else
{

// do something else
}

C#
else if
If (iVar == 10)
{

// do something here
}

else if (iVar == 20)


{

// do something else
}

else
{

// iVar does not equal 10 or 20


}

if
If (iVar == 10)
{

if (name == fred)
{

// do something here
}
}

C.2.2 Switch
Switch Switch

Switch
switch(iVar)
{

case 1:
Console.WriteLine(one)
break;
case 2:
Console.WriteLine(two);
break;
case 10:
Console.WriteLine(ten);
break;

if-else

iVar 12 10 iVar
case
break
C# case break
goto break C# C++
case case case
switch
case

Int16
Int32
Int64

iVar
iVar case case switch
default
switch(iVar)
{

case 1:
Console.WriteLine(one)
break;
case 2:
Console.WriteLine(two);
break;
case 10:
Console.WriteLine(ten);
break;
case default:
Console.WriteLine(Could not find a match!);
Break;
}

iVar case default


C.2.3
C#
breakbreak switch
for (int j = 0; j < 10; j++)
{

if (j == 7)
break;
EvtLog.WriteEntry(j.ToString());
}

Console.WriteLine(finished);

j 7 Console.WriteLine j
7

continue continue break


continue for continue
for (int j = 0; j < 10; j++)
{

if (j == 7)
continue;
EvtLog.WriteEntry(j.ToString());
}

j 7 EvtLog.WriteEntry
j 7 EvtLog.WriteEntry
goto
goto

If (SomeValue == True)
{

goto MyLabel;
}

// some other program code


MyLabel:

// this code will execute


goto switch case
switch(iVar)
{

case 1:
Console.WriteLine(one)
break;
case 2:
Console.WriteLine(two);
break;
case 3:
goto case 2;
case 10:
Console.WriteLine(ten);
break;
case default:
Console.WriteLine(Could not find a match!);
break;
}

iVar 3goto case case

goto

return
return
void return
Int GetId()
{

int i;
return i;
}

C.2.4
.NET C#
C# try-catch
try catch catch
try
{

DatabaseObject.Open();
}

catch (DBException dbe)


{

// log the error or report something to the user


}

catch

DBException

try
{

DatabaseObject.Open();
}

catch (DBException dbe)


{

// log the error or report something to the user


}

catch (Exception e)
{

// log the error or report something to the user

finally try-catch finally

finally
try
{

DatabaseObject.Open();
}

catch (DBException dbe)


{

// log the error or report something to the user


}

catch (Exception e)
{

// log the error or report something to the user


}

finally
{

Console.WriteLine(executing finally statement);


}

C.3 C#
C# C++ Visual Basic for
break for

for (int i = 0; i < 10; i++)


{

// do something interesting
}

for i 0i
1 10
for
for (int i = 10; i > 0; i--)
{

// do something interesting
}

i 10 i 1 i 0

do while do
while do

do
{

i++;
}

while (i < 10);

i 10while
while
while (i < 10);
{

i++;
}

foreach

ClerkMonitor cm = new ClerkMonitor();


Foreach (ClerkInfo ci in cm)
{

Console.WriteLine(ci.Description);
}

ClerkMonitor ClerkInfo
ClerkInfo ci (
ClerkInfo)

C.4

ref

Ch gevdue Df j
public class SomeClass
{
public void ChangeValue(ref j)
}
ChangeValue j ref
j changVevalue j ref
sc.ChangeValue(1) 1 ChangeValue ref

1 ChangeValueChangeValue
1 ChangeValue
C#
int j = 1
SomeClass sc = new SomeClass();
sc.ChangeValue(ref i)
Console.WriteLine(j.ToString());
ChangeValue j 2 2j
1 ChangeValue j 1 ref
ref Ref

out ref out

out
ResourcePool rp;
SomeClass sc = new SomeClass();
sc.GetCount(out rp);
Console.WriteLine(rp.ToString());
rp rp
ref out

C.5
C# c++ Visual Basic C#

System.Objectintdoublebool
System.ArrayArray

int[] iAry = new int[10];


C# visual Basic
C# new
10
C# C#

int i = 10;
int[] iAry = new int[i]; //
C# 0 C++

iAry[0] = 100;

int[]

iAry = new int[10]

{1, 2, 3, 4, 5, 6, 7, 8, 9, l0};

int[,]

iAry = new int[3,2];

C-10
N

N
3
N

3 2
C-1
4 3 2
int[, ,] iAry = new

int[4, 3, 2]

int[,] iAry = new int[3, 2] {{12, 3}, {4, 23}, {99, 0}};
C-2

iRay [3, 2] = {12, 3}, {4, 23}, {99, 0}}

iRay [2, 0]
C-2

12

23

99

iRay [1, 1]

C.6
C#
C# System int

System.Int32 C-1 C# System

C-1
C#

Sbyte
Byte
Short
Ushort
Int
Uint
Long

System.SByte
System.Byte
System.Int16
System.UInt16
System.Int32
System.UInt32
System.Int64

8
8

Ulong
Char
Float
double
bool
decimal

System.UInt64
System.Char
System.Single
System.Double
System.Boolean
System.Decimal

-128 to 127
0 to 255
-32768 to 32767
0 to 65535
-2147483648 to 2147483647
0 to 4294967295
-9223372036854775808
to 9223372036854775807
0 to 18446744073709551615
0 to 65535
1.5 x 10-45 to 3.4 x 1038
5.0 x 10-324 to 1.7 x 10308
true or false
1.0 x 10-28 to approximately 7.9 x 1028

16s
16
32
32
64s
64
16
7 digits
15-16 digits
8
128

C# enum
bytesbyteshortushortintuintlong ulong
int
enum Animal
{
Dog,
Cat,
Fish,
Bird
}

0 Animal Dog 0Cat 1

enum Animal
{
Dog = 3,
Cat,
Fish,
Bird
}

Animal
Animal long
enum Animal : long
{
Dog = 3,
Cat,
Fish,
Bird
}

C.7
(structure struct)(intchardouble )

C# System
struct
struct Location
{
int longitude;
int latitude;
string location;
}
location

Location Detroit;
Detroit.longitude = 1000;
Detroit.latitude = 99;
Detroit.location = Joe Louis Arena;

location longitudelatitude location


struct

Location

{
int longitude
int latitude
string location
Location(int iLongitude, int iLatidude, string sLocation)
{
longitude = iLongitude;
latitude = iLatitude;
location = sLocation;
}
}

new
Location Detroit = new Location(1000, 99, Joe Louis Arena);
Location

struct Location
{
int longitude;
int latitude;
string location;
Location(int iLongitude, int iLatidude, string sLocation)
{
longitude = iLongitude;
latitude = iLatitude;
location = sLocation;
}
void Move(int iLongitude, int iLatitude, string sLocation)
{
longitude = iLongitude;
latitude = iLatitude;
location = sLocation;
}
}

C#()
0()


C#
longitude
struct Location
{
int longitude = 1000; // illegal statement for a struct!!
int latitude;
string location;
}

C.8

( 1
.NET )
location
class Location
{
int longitude;
int latitude;
string location;
Location(int iLongitude, int iLatidude, string sLocation)
{
longitude = iLongitude;
latitude = iLatitude;
location = sLocation;
}
void Move(int iLongitude, int iLatitude, string sLocation)
{
longitude = iLongitude;
latitude = iLatitude;
location = sLocation;
}
}
ahon
class Location
{

int longitude;
int latitude;
string location;
Location(int iLongitude, int iLatidude, string sLocation)
{
longitude = iLongitude;
latitude = iLatitude;
location = sLocation;
}
void Move(int iLongitude, int iLatitude, string sLocation)
{
longitude = iLongitude;
latitude = iLatitude;
location = sLocation;
}
}
Location class C#
C#
Dog Dog
Bark() Sit() Labrador Dog
retrieve()
class Dog
{
string Fur;
int Teeth;
Bark() { ... }
Sit() { ... }
}
class Labrador : Dog
{
Retrieve() { ... }
}
Labrador (:Dog) Dog Dog
Labrador Fur Teeth Bark() Sit()
Labrador retrieve() C#
Labrador lab = nev
lab.Bark();

Labrador()

C#(.NET )


.NET C# abstract
Dog abstract
abstract class Dog
{
string Fur;
int Teeth;
Bark() { ... }
Sit() { ... }
}

Bark() abstract

class Dog
{
string Fur;
int Teeth;
abstract Bark() { ... }
Sit() { ... }
}
Dog
sealed abstract Labrador Dog
sealed class Dog
{
string Fur;
int Teeth;
Bark() { ... }
Sit() { ... }
}
class Labrador : Dog // this is an error!
{
Retreive() { ... }
}

public()
protectd()

private()
protected internal()

public internal

C.9

EngineSize
class Car
{
private string m_EngineSize;
public string EngineSize
{
get
{
return m_EngineSize;
}
set
{
m_EngineSize = value;
}
}
}
EngineSize get set
get
set
Car car = new Car();
MessageBox.Show(car.EngineSize);
set value
value
EngineSize
get
class Car

{
private string m_EngineSize;
public string EngineSize
{
set
{
m_EngineSize = value;
}
}
}

C.10

C#

class CIndexer
{
string[] names = new string[3] (bob, joe, ralf);
public string this [int index]
{
get
{
return names[index];
}
set
{
names[index] = value;
}
}

this this

//
CIndexer indexer nev CIndexer();
for (int i = 0; i < 2; i++)
{

Console.WriteLine(indexer[i]);
}

C.11

C# Visual Basic C#
.NET
( 1 )

public unsafe static void Main()


{
int I = 12;
int* pI = &I;
int J = *pI;
Console.WriteLine(J.ToString());
}
Main() unsafe C#
unsafe /unsafe
IDE()
pI * (&) I C#*
& C++* C#
*&
pI I pI
I

public unsafe static void Main()


{
SomeClass sc = new SomeClass();
int* pI = &sc.I; // this could cause problems!!
int J = *pI;
Console.WriteLine(J.ToString());
}
sc I
null
fixed sc

public unsafe static void Main()


{

SomeClass sc = new SomeClass();


int J;
fixed (int* pI = &sc.I)
{
J = *pI;
}

Console.WriteLine(J.ToString());
}

fixed
fixed
C#()
C#

C#

D
(Compensating Resource ManagerCRM) 4

CRM
COM+
CRM ( 4 ACID )
CRM
CRM
CRM XML XML
XML
Windows
CRM COM+
CBM COM+
C# CRM Systsm.EntepriseServices.CompensatingResourceManager
CRM CRM
CRM 4
4

D.1

CRM

CRM CRM
CRM COM+
RequiredRequired
Required
CRM
CRM
CRM

()

COM+()

()

XML
XML XML
XML

XML

COM+
CRM
(Distributed Transaction CoordinatorDTC)
DTC DTC
.NET
(
)

D-1 CRM
D-1
CRM
COM+

DTC

Clerk

DTC

CRM COM+
%systemroot%\system32\dtclog
ID ID
COM+ GUID CRM
{57206245-EAA4-4324-92CD-0DBAB17605D5}.crmlog()
CRM (Notepad)
COM+
Interactive
Interactive Interactive

Interactive (dtclog)
dtclog system32 CRM
?
COM+

COM+ CRM CRM


COM+ Enable Compensating Resource
Managers() D-2 Advanced

D-2

CRM

COM+

COM+ CRM
COM+
COM+ DTC

CRM COM
API(COMAdministration API) CRM

D.2 C#
CRM

System.EnterpriseServices.CompensatingResourceManager

CRM

C:\temp

D-1

D-1

CRM

using System;
using System.IO;
using System.Reflection;
using System.EnterpriseServices;
using System.EnterpriseServices.CompensatingResourceManager;
[assembly: AssemblyKeyFile(C:\\crypto\\key.snk)]
[assembly: ApplicationActivation(ActivationOption.Server)]
[assembly: ApplicationCrmEnabled]
namespace XCopy
{
[Transaction(TransactionOption.Required)]
public class CWorker : ServicedComponent
{
private Clerk clerk;
public override void Activate()
{
clerk = new Clerk(typeof(XCopy.CCompensator),
Compensator for XCOPY,
CompensatorOptions.AllPhases);
}
public void MoveDirectory(string sSourcePath,
string sDestinationPath)
{

clerk.WriteLogRecord(sSourcePath + ; + sDestinationPath);
clerk.ForceLog();
int iPos;
string sTempPath;
iPos = sSourcePath.LastIndexOf(\\) + 1;
sTempPath = sSourcePath.Substring(iPos,
sSourcePath.Length - iPos);
Directory.Move(sSourcePath, c:\\temp\\ + sTempPath);
}
}
public class CCompensator : Compensator
{
public override bool CommitRecord(LogRecord rec)
{
string sSourcePath;
string sDestPath;
string sTemp;
int iPos;
GetPaths((string)rec.Record, out sSourcePath, out sDestPath);
iPos = sSourcePath.IndexOf(\\);
sTemp = sSourcePath.Substring(iPos,
sSourcePath.Length - iPos);
Directory.Move(C:\\temp\\ + sTemp, sDestPath);
return false;
}
public override bool AbortRecord(LogRecord rec)
{
string sSourcePath;
string sDestPath;
string sTemp;
int iPos;
GetPaths((string)rec.Record, out sSourcePath, out sDestPath);
iPos = sSourcePath.IndexOf(\\);
sSourcePath.Length - iPos};
Directory.Move(C:\\temp\\ + sTemp, sSourcePath);
return false;
}
private void GetPaths(string sPath,
out string sSourcePath,
out string sDestination)
{
int iPos;
iPos = sPath.IndexOf(;);

sSourcePath = sPath.Substring(0, iPos);


iPos++;
sDestination = sPath.Substring(iPos, sPath.Length - iPos);
}
}
public class CClient
{
static void Main(string[] args)
{
CWorker worker = new CWorker();
worker.MoveDirectory(c:\\dir1, c:\\dir2);
}
}
}

system.IO Directory
useing CompensatingResourceManager

ServicedComponent
COM+ CRM
ApplicationCrmEnabled CRM
COM+ D-2 Enable Compensating Resource Managers(
)
XCopy CWorker
ServicedComponent COM+
CWorker
Clerk ( COM+
COM+ COM+ ServicedComponent
Activate COM+ C# new )Clerk
COM+Clerk
system.Type typeof()
typeof() System.Type
C# Compensator
-------------------------------------------------------------------------------System.Type
(Reflection)

Clerk typeof().NET
------------------------------------------------------------------------------Clerk CRM
.NET COM+
CompensatorOptions.AllPhases


CWorker MoveDirectory CRM
CRM
worker
Clerk
(
)
writeLogRecord

ForceLog

c:\bmp

Compensator
ServicedComponent COM+

Compensator
CommitRecord AbortRecord COM+

MoveDirectory

MoveDirectory MoveDirectory
COM+ CommitRecord

AbortRecord

D-2
MoveDirectory CommitRecord AbortRecord
D-2 MoveDirectory public void MoveDirectory(string sSourcePath,
string sDestinationPath)
{
clerk.WriteLogRecord(sSourcePath + ; + sDestinationPath);
clerk.ForceLog();
int iPos;
string sTempPath;

iPos = sSourcePath.LastIndexOf(\\) + 1;
sTempPath = sSourcePath.Substring(iPos,
sSourcePath.Length - iPos);
if (Directory.Exists(sSourcePath))
{
Directory.Move(sSourcePath, c:\\temp\\ + sTempPath);
}
}

D-3

D3 MoveDirectory public void


MoveDirectory(string sSourcePath, string sDestinationPath)
{
clerk.WriteLogRecord(sSourcePath + ; + sDestinationPath);
clerk.ForceLog();
int iPos;
string sTempPath;
iPos = sSourcePath.LastIndexOf(\\) + 1;
sTempPath = sSourcePath.Substring(iPos,
sSourcePath.Length - iPos);
if (Directory.Exists(sSourcePath))
{
try {
Directory.Move(sSourcePath, c:\\temp\\ + sTempPath);
}
catch (SecurityException se)
{
clerk.ForceTransactionToAbort();
}
}
}
MoveDirectory System.Security. SecurityException
CRM
Interactive Interactive
COM+

ForceTransactionToAbort

CommitRecord AbortRecord COM+


( 4 )
()
1. BeginPrepare
2. PrepareRecord
3. EndPrepare

CRM

1. BeginCommit
2. CommitRecord
3. EndCommit
BeginCommit
CommitRecord
EndCommit

(
)
1. BeginAbort
2. AbortRecord
3. EndAbort
BeginCommit BeginAbort

CompensatingResourceManager
ClerkMonitor ClerkInfo ClerkInfo
ClerkInfo
ActivityID
Clerk

( ID) InstanceID

XCopy
public class CMonitor : ServicedComponent
{

public void ListCompensators()


{
ClerkMonitor cm = new ClerkMonitor();
cm.Populate();
ClerkInfo ci = cm[0];
Console.WriteLine(ci.Description);
}
}
ClerkMonitor Populate CRM
Description Description

foreach

You might also like