1. Trang chủ
  2. » Công Nghệ Thông Tin

OReilly COM and dot NET component services sep 2001 ISBN 0596001037 pdf

385 71 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 385
Dung lượng 3,65 MB

Nội dung

COM and NET Com ponent Services Dedicat ion Foreword Preface Scope of This Book Som e Assum pt ions About t he Reader Definit ions and Text Convent ions Ot her COM+ Books and Refer ences How t o Cont act Us Acknow ledgm ent s COM+ Com ponent Serv ices 1.1 COM+ Com ponent Ser v ices 1.2 The Com ponent Ser vices Explor er 1.3 Hello COM+ 1.4 COM+ Configur ed Com ponent s 1.5 Applicat ions, DLLs, and Com ponent s 1.6 Configur ing COM+ Applicat ions 1.7 Debugging COM+ Applicat ions 1.8 Deploy ing COM+ Applicat ions 1.9 Sum m ary COM+ Cont ext 2.1 Encapsulat ion v ia Marshaling in COM 2.2 Encapsulat ion v ia I nt ercept ion in COM+ 2.3 The Cont ext Obj ect 2.4 The Call Obj ect 2.5 Cr oss- Cont ext Manual Marshaling 2.6 Sum m ary COM+ I nst ance Managem ent 3.1 Client Types 3.2 I nst ance Managem ent and Scaling 3.3 Obj ect Pooling 3.4 Just - in- Tim e Act iv at ion 3.5 Com bining JI TA w it h Obj ect Pooling 3.6 Obj ect Const r uct or St r ing 3.7 COM+ I nst ance Managem ent Pit falls COM+ Transact ions 4.1 Transact ion Basics 4.2 Transact ion Pr opert ies 4.3 Transact ion Scenarios 4.4 COM+ Transact ions Archit ect ur e 4.5 Configur ing Transact ions 4.6 Vot ing on a Transact ion 4.7 Transact ional Obj ect Life Cycle 4.8 Designing Transact ional Com ponent s 4.9 Nont ransact ional Client s 4.10 Transact ions and Obj ect Pooling 4.11 Com pensat ing Tr ansact ions 4.12 Transact ion Ex ecut ion Tim e 4.13 4.14 4.15 4.16 Tracing Transact ions I n- Doubt Transact ions Transact ion St at ist ics COM+ Transact ions Pit falls COM+ Concur r ency Model 5.1 Obj ect - Orient ed Program m ing and Mult iple Threads 5.2 Apart m ent s: The Classic COM Solut ion 5.3 Act iv it ies: The COM+ I nnovat ion 5.4 COM+ Configurat ion Set t ings 5.5 Act iv it ies and JI TA 5.6 Act iv it ies and Transact ions 5.7 Tracing Act iv it ies 5.8 The Neut ral Threaded Apart m ent 5.9 Sum m ary Pr ogram m ing t he COM+ Cat alog 6.1 Why Pr ogram t he Cat alog? 6.2 The Cat alog Progr am m ing Model 6.3 Cat alog St ruct ur e 6.4 I nt eract ing w it h t he Cat alog 6.5 Feat ur es of COMAdm inCat alog 6.6 The COM+ Cat alog and Transact ions 6.7 Sum m ary COM+ Secur it y 7.1 The Need for Secur it y 7.2 Basic Secur it y Ter m s 7.3 Role- Based Secur it y 7.4 Secur ing a Ser ver Applicat ion 7.5 Secur ing a Librar y Applicat ion 7.6 Pr ogram m at ic Role- Based Secur it y 7.7 Secur it y Boundar ies 7.8 Advanced COM+ Securit y 7.9 COM+ Secur it y Pit falls 7.10 Sum m ary COM+ Queued Com ponent s 8.1 Maj or Benefit s of Queued Com ponent s 8.2 Queued Com ponent s Archit ect ure 8.3 Com ponent Ser vices Explor er Configurat ion 8.4 I nvoking Queued Com ponent s on t he Client Side 8.5 Designing Queued Com ponent I nt erfaces 8.6 Receiv ing Out put from a Queued Com ponent 8.7 Queued Com ponent Er ror Handling 8.8 Queued Com ponent s and Transact ions 8.9 Sy nchr onous Versus Asy nchronous Com ponent s 8.10 Queued Com ponent s Secur it y 8.11 Queued Com ponent s Pit falls 8.12 Sum m ary COM+ Ev ent Serv ice 9.1 Classic COM Ev ent s 9.2 COM+ Ev ent Model 9.3 The Event Class 9.4 Subscript ion Ty pes 9.5 Deliv ering Ev ent s 9.6 Ev ent Filt er ing 9.7 Dist ribut ed COM+ Ev ent s 9.8 Asy nchronous Ev ent s 9.9 COM+ Ev ent s and Transact ions 9.10 COM+ Ev ent s and Securit y 9.11 COM+ Ev ent s Lim it at ion 9.12 Sum m ary 10 .NET Serv iced Com ponent s 10.1 Developing Serv iced Com ponent s 10.2 NET Assem blies and COM+ Applicat ions 10.3 Regist er ing Assem blies 10.4 Configur ing Ser v iced Com ponent s 10.5 Applicat ion Act iv at ion Type 10.6 The Descr ipt ion At t r ibut e 10.7 Accessing t he COM+ Cont ext 10.8 COM+ Cont ext At t ribut es 10.9 COM+ Obj ect Pooling 10.10 COM+ Just - in- Tim e Act ivat ion 10.11 COM+ Const r uct or St r ing 10.12 COM+ Transact ions 10.13 COM+ Sy nchronizat ion 10.14 Pr ogram m ing t he COM+ Cat alog 10.15 COM+ Secur it y 10.16 COM+ Queued Com ponent s 10.17 COM+ Loosely Coupled Ev ent s 10.18 Sum m ary A The COM+ Logbook A.1 Logbook Requirem ent s A.2 Log File Exam ple A.3 Using t he Logbook A.4 Configur ing t he Logbook A.5 How Does t he Logbook Work? A.6 Sum m ary B COM+ 1.5 B.1 I m prov ed User I nt erface Usabilit y B.2 Legacy Applicat ions and Com ponent s B.3 Disabling Applicat ions and Com ponent s B.4 Pausing Applicat ions B.5 Serv ice Act iv at ion Type B.6 I m prov ed Queuing Support B.7 Applicat ion Pooling and Recycling B.8 Applicat ion Dum p B.9 Applicat ion Part it ioning B.10 Aliasing Com ponent s B.11 Configurable Transact ion I solat ion Level B.12 I m prov ed Cont ext Act ivat ion Set t ing B.13 Pr ivat e Com ponent s B.14 Web Serv ices in COM+ 1.5 B.15 Sum m ary C I nt r oduct ion t o NET C.1 NET Program m ing Languages C.2 Packaging NET Com ponent s: Assem blies C.3 Dev eloping NET Com ponent s C.4 Wr it ing NET Client - Side Code C.5 NET as a Com ponent Technology C.6 Com posing Assem blies Colophon D e dica t ion To m y wife, Dana For e w or d I fir st ran int o COM+ back in 1996 I n t hose days, I was w ork ing as a Com m on Obj ect Request Br oker Ar chit ect ure ( CORBA) consult ant and was fr esh out of I BM, wher e I had been heav ily inv olved in I BM’s or iginal CORBA im plem ent at ion CORBA was t he first of t he ar chit ect ures t hat we m ight describe t oday as Dist ribut ed Com ponent ar chit ect ures, which set t he st age for bot h COM/ DCOM in t he Microsoft space and RMI / I I OP in t he Java space Back t hen, I was int er est ed in a part icularly k not t y problem relat ed t o dist ribut ed com ponent archit ect ur es Syst em s built w it h such archit ect ures had a charact er ist ic perform ance pat t ern They could handle large num ber s of t r ansact ions, as long as t hose t ransact ions originat ed from a sm all num ber of client s So, for ex am ple, 5,000 t r ansact ions per m inut e div ided bet ween client s wor ked fine But when t hose sam e 5,000 t r ansact ions per m inut e wer e split am ong 1,000 client s, each pr ocessing t ransact ions per m inut e, t he sy st em s chok ed This was odd, I t hought Why should client s, each processing 1,000 t ransact ions per m inut e, be fundam ent ally different t han 1,000 client s, each pr ocessing t ransact ions per m inut e? What is t he difference bet ween t he first 5,000 t r ansact ions per m inut e and t he second? Dist ribut ed com ponent archit ect ures, as t hey ex ist ed in 1996, dict at ed a one- t o- one relat ionship bet ween client s and com ponent inst ances The business logic of such archit ect ur es is in t he com ponent inst ances And it is t he business logic t hat m ak es t r ansact ional request s of t r ansact ional r esources, such as t he dat abase I n order t o m ake t r ansact ional request s, t he com ponent inst ances r equire expensive r esources, such as dat abase connect ions We run out of st eam ( i.e., t r ansact ional t hroughput ) when one of t wo t hings happen: we over load t he syst em w it h t r ansact ional request s or we run out of resources ( e.g., dat abase connect ions) Clearly , going from client s, each m ak ing 1,000 t ransact ional request s per m inut e, t o 1,000 client s, each m ak ing t r ansact ional request s per m inut e, has no over all im pact on t he t ransact ional t hr oughput Therefore, t he r eason why our dist ribut ed com ponent sy st em s m ust be dying is t hat we ar e running out of resour ces So t he answer t o get t ing lot s of client s on a dist r ibut ed com ponent archit ect ure is not going t o com e fr om increased capabilit y of t he back- end t r ansact ional resources ( e.g., dat abases) I t will have t o com e fr om som et hing else- som et hing t hat allows r esour ce shar ing This, t hen, is t he problem I wor ked on back in 1996 How y ou get several client s t o share resources in a dist r ibut ed com ponent archit ect ure? The solut ion t o t his problem cam e fr om an unex pect ed source I was asked t o writ e a book on COM and DCOM I knew very lit t le about COM and DCOM back t hen As I look ed over t he COM/ DCOM whit e paper s on t he Microsoft web sit e, I quickly recognized it as a t y pical dist ribut ed com ponent archit ect ure and predict ed t he sam e t hr oughput problem s I had seen in ot her dist r ibut ed com ponent sy st em s As I browsed t hrough t he whit e paper s, I not iced an obscure bet a product called Micr osoft Transact ion Serv er ( MTS) At first , I dism issed MTS as an API used t o m anage dist ribut ed t ransact ions But as I read m ore about MTS, I r ealized t hat it had lit t le t o wit h t r ansact ions I nst ead, it at t ack ed a m uch m or e int erest ing problem : how t o shar e r esources am ong client s I n a nut shell, MTS addr essed t he very problem t hat had so v exed t he exist ing dist ribut ed com ponent syst em s- how t o support a large num ber of lowt r ansact ion generat ing client s! I did event ually w rit e t hat book, as well as m any ar t icles on t he im port ance of t he ideas int r oduced by MTS Many of t hese ar t icles appear ed in m y Obj ect Wat ch newslet t er ( available at www.obj ect wat ch.com ) , a newslet t er t hat has, ov er t im e, becom e influent ial in it s space Back in 1996, I predict ed t hat MTS would be a hist or ically im port ant product - one t hat w ould redefine approaches t o scalabilit y in dist ribut ed com ponent sy st em s I n fact , t hat predict ion has com e t r ue Today , every infrast r uct ure designed t o suppor t high scalabilit y in dist r ibut ed com ponent syst em s is based dir ect ly on t he ideas, algorit hm s, and pr incipals first int roduced by MTS in 1996 Ent erprise Jav aBeans, for exam ple, t he Jav a scalabilit y infrast r uct ure, is alm ost a direct copy of MTS But w hat does t his have t o wit h COM+ , you m ay ask I t t urns out t hat COM+ and MTS are one and t he sam e Microsoft , never know n for it s m arket ing savvy , decided t o wait unt il cust om ers finally got used t o t he nam e MTS ( it self a m isleading nam e) , and t hen it pulled a fast one- it swit ched t he nam e! And not j ust any nam e, but one t hat would be as confusing as possible! So t hey renam ed MTS as COM+ Nat urally, cust om ers assum ed t hat COM+ was t he next release of COM I n fact , COM+ was t he next release of MTS Now Microsoft has announced NET Once again, t he br illiant Microsoft m ark et ing organizat ion has left m any cust om er s confused I s COM+ now dead? Far fr om it —.NET is a series of int er est ing new feat ur es, none of which r eplace COM+ COM+ is st ill t he scalable infrast r uct ure t hat suppor t s resour ce shar ing and deals w it h t he m yr iad of issues ( such as securit y and t r ansact ion boundar y m anagem ent ) t hat ar e so closely relat ed t o r esource sharing and so cr ucial t o dist ribut ed applicat ions So whet her you ar e rushing int o Micr osoft ’s new NET t echnology plat for m or t aking a wait and see at t it ude, if y ou need t o put a lot of client s around your sy st em , y ou need t o under st and COM+ Ther efore, t his book is very t im ely COM+ is going t o be wit h us for a long t im e I t s nam e m ay change again, j ust t o confuse t he innocent ; but t he ideas, algor it hm s, and principals will not COM+ , under what ever nam e, is here t o st ay ! Roger Sessions, CEO, Obj ect Wat ch, I nc Publisher, Obj ect Wat ch newslet t er ( www.obj ect wat ch.com ) Aut hor, COM+ and t he Bat t le for t he Middle Tier Aust in, Tex as Pr e fa ce This book discusses COM+ com ponent services Each service is covered in it s own chapt er , and each chapt er discusses a sim ilar range of issues: t he pr oblem t he serv ice addr esses, possible solut ions t o t hat problem , an in- dept h descript ion of t he COM+ solut ion, t r adeoffs, design, and im plem ent at ion guidelines, t ips, and know n pit falls I have t ried t o prov ide useful design inform at ion and lessons I learned while applying COM+ I also descr ibe COM+ helper classes and ut ilit ies I developed t hat will enhance your pr oduct ivit y significant ly ( The COM+ Event s helper obj ect s and t he COM+ Logbook are prim e ex am ples.) This book focuses on t he " how t o" — t hat is, it pr ov ides pract ical inform at ion You should read t he chapt er s in or der , since m ost chapt ers r ely on inform at ion discussed in t he pr eceding chapt er s The book also aim s t o ex plain COM+ st ep by st ep A soft ware engineer alr eady fam iliar wit h COM who want s t o k now what COM+ is and how t o use it can read t his book and st ar t developing COM+ applicat ions im m ediat ely Scope of Th is Book Her e is a brief sum m ary of t he chapt ers and appendixes in t his book: • • • Chapt er int roduces t he Com ponent Serv ices Ex plorer and basic COM+ t er m inology This chapt er deliberat ely holds your hand as you develop your fir st " Hello World" COM+ com ponent Subsequent chapt ers m uch less handholding and assum e y ou ar e fam iliar w it h t he COM+ env ir onm ent I f you alr eady have experience w it h basic COM+ developm ent, feel fr ee t o sk ip t his chapt er Chapt er dem yst ifies t he COM+ cont ext by present ing it as t he key m echanism for providing com ponent services using call int ercept ion Generally , y ou need not be concerned wit h cont ext s at all How ever, t he COM+ cont ext underlies t he way COM+ serv ices are im plem ent ed Chapt er describes t wo scalabilit y - enabling m echanism s t hat COM+ provides for a m odern ent erprise applicat ion: obj ect pooling and Just - in- Tim e Act iv at ion ( JI TA) The discussion of inst ance m anagem ent , and especially JI TA, is independent of t r ansact ions Ear ly COM+ docum ent at ion and books t ended t o couple inst ance m anagem ent and t r ansact ions How ever, I found t hat not only can you use inst ance m anagem ent independent ly of t ransact ions, but it is easier t o explain it t hat 10 Appe ndix C I nt r oduct ion t o N ET NET is based on a Com m on Language Runt im e ( CLR) environm ent t hat m anages every runt im e aspect of your code All NET com ponent s, regardless of t he language in which t hey are dev eloped, execut e in t he sam e r unt im e ( hence t he nam e) The CLR is lik e a warm blanket t hat surr ounds your code, providing it wit h m em ory m anagem ent , a secur e env ir onm ent t o run in, obj ect locat ion t ranspar ency, concurr ency m anagem ent , and access t o t he underly ing operat ing syst em services Because t he CLR m anages t hese aspect s of y our obj ect ’s behavior, code t hat t arget s t he CLR is called m anaged code The CLR provides absolut e language int er operabilit y , allowing a high degree of com ponent int er operabilit y COM, t oo, prov ides language independence, allowing binary com ponent s developed in t wo differ ent languages ( such as Visual Basic and C+ + ) t o call one anot her’s m et hods, but COM language int er operabilit y is only at r unt im e Dur ing dev elopm ent , NET allow s a com ponent developed in one language t o derive from a com ponent developed in anot her language seam lessly NET is capable of t his pr ocess because t he CLR is based on a st rict t ype syst em To qualify as a NET language, all const ruct s ( such as class, st ruct , or pr im it ive t ypes) in every language m ust com pile t o CLR- com pat ible t ypes The language int er operabilit y gain is at t he expense of exist ing languages and com piler s Exist ing com piler s produce CLR- ignorant code— code t hat does not com ply wit h t he CLR t ype syst em and t hat is not m anaged by t he CLR Visual St udio.NET com es wit h four CLR- com pliant languages: C# , Visual Basic.NET, JScript NET, and Managed C+ + Thir d- part y com piler vendor s also t ar get t he CLR, wit h m ore t han 20 ot her languages, from COBOL t o Eiffel C.1 N ET Pr ogra m m in g La ngua ge s All NET program m ing languages use t he sam e set of base classes, dev elopm ent environm ent , and CLR t ypes and com ply w it h t he sam e CLR design const raint s Com piling code in NET is a t wo- phase process Fir st , t he high- level code is com piled int o a gener ic m achine- code- like language called int erm ediat e language ( I L) At runt im e, on t he first call int o t he I L code, t he I L is com piled int o nat iv e code and execut es as nat iv e code The nat iv e code is used unt il t he program t erm inat es The I L is t he com m on denom inat or of all NET pr ogram m ing languages, and equivalent const ruct s in t wo differ ent languages should t heoret ically pr oduce ident ical I L As a 371 result , all NET pr ogr am m ing languages are equal in per form ance and ease of dev elopm ent The differ ence bet ween t he languages is m ost ly aest het ic, and choosing one over anot her is a m at t er of personal preference For exam ple, t o m ak e C+ + CLR com pliant , Microsoft had t o add num erous nonst andard com piler dir ect ives and ext ensions, result ing in less r eadable code t han st andar d unm anaged C+ + Sim ilar ly , Visual Basic.NET bears lit t le resem blance t o it s Visual Basic 6.0 ancest or , r equir ing y ou t o unlearn t hings you used t o in Visual Basic 6.0 Only C# has no legacy and is a fr esh NET language C# is a C+ + der iv at ive language, com bining t he power of C+ + wit h t he ease of Visual Basic 6.0, and offer ing you r eadable, CLR- com pliant C+ + lik e code I n fact , C# looks m or e like norm al C+ + t han m anaged C+ + This appendix and Chapt er 10 t herefore use C# in it s code sam ples Bear in m ind, however , t hat y ou can all t he code sam ples in Visual Basic.NET, m anaged C+ + , or any ot her NET language Ot her feat ures of NET languages include t heir t reat m ent of every ent it y as an obj ect ( including prim it ive t ypes) , result ing in a cleaner program m ing m odel .NET provides com m on er ror handling based on ex cept ions The CLR has a r ich pr edefined set of ex cept ion classes t hat you can use as is, or derive and ext end for a specific need An except ion t hr own in one language can be caught and handled in anot her language C.2 Pa ck a gin g N ET Com pon e n t s: Assem blies The basic code packaging unit in NET is t he assem bly An assem bly is a logical DLL— i.e., assem bly can com bine m ore t han one phy sical DLL int o a single deploym ent , v er sioning, and secur it y unit However, an assem bly usually cont ains j ust one DLL ( t he default in Visual St udio.NET) and you have t o use com m and- line com piler swit ches t o incor porat e m ore t han one DLL in your assem bly An assem bly is not lim it ed t o cont aining only DLLs An assem bly can also cont ain an EXE As a com ponent developer, you usually dev elop com ponent s t hat reside in a single or m ult iple DLL assem bly t o be consum ed by a client applicat ion residing in an assem bly t hat has an EXE The code in t he assem bly ( in t he DLLs or t he EXE) is only t he I L code, and at runt im e t he I L is com piled t o nat iv e code, as ex plained previously An assem bly cont ains m ore t han j ust t he I L code Em bedded in every assem bly is m et adat a, a descr ipt ion of all t he t ypes declared in t he assem bly and a m anifest , a descript ion of t he assem bly and all ot her r equir ed assem blies The m anifest cont ains v ar ious assem bly- wide inform at ion, such as t he assem bly version 372 infor m at ion The v er sion infor m at ion is t he pr oduct of a v ersion num ber prov ided by t he developer and a build and revision num ber capt ured by t he com piler ( or provided by t he developer as well) during t he build All DLLs in t he assem bly shar e t he sam e version num ber and ar e deployed as one unit The assem bly boundary serv es as t he NET secur it y boundary — securit y per m issions ar e gr ant ed at t he assem bly level All com ponent s in an assem bly share t he sam e set of per m issions The assem bly can also cont ain a com piled resource file for icons, pict ures, et c., like any t radit ional DLL or EXE C.3 D e ve lopin g N ET Com pon ent s To creat e a NET com ponent in C# ( or any ot her NET Language) , you sim ply declare a class When t he class is inst ant iat ed by t he CLR, t he result is a binar y com ponent Ex am ple C- shows a sim ple class nam ed MyClass t hat im plem ent s t he IMessage int er face and displays a m essage box wit h t he word " Hello" w hen t he int erface's ShowMessage( ) m et hod is called Ex a m p le C- Bu ilding a com p on e n t in N ET namespace MyNamespace { using System; using System.Windows.Forms; public interface IMessage { void ShowMessage( ); } public class MyComponent :IMessage { public MyComponent(){}//constructor ~ MyComponent(){}//destructor public void ShowMessage( ) { MessageBox.Show("Hello!","MyComponent"); } } } The MyComponent class in Exam ple C- is defined as public, m ak ing it accessible t o any NET or COM client once y ou export t he com ponent t o COM You can define a class const ruct or t o obj ect init ializat ion, as in t his exam ple, but t he dest ruct or has different sem ant ics t han t he classic C+ + dest r uct or because NET uses 373 nondet erm inist ic obj ect finalizat ion You can im plem ent ot her m et hods t o obj ect cleanup as well The im plem ent at ion of ShowMessage( ) uses t he st at ic Show( ) m et hod of t he MessageBox class Like in C+ + , C# allows you t o call a class ( st at ic) m et hod wit hout inst ant iat ing an obj ect fir st Exam ple C- dem onst rat es a few addit ional key point s r egarding dev eloping NET com ponent s: using nam espaces and int erfacebased program m ing These point s are discussed next C.3 Usin g N a m e spa ce s The class definit ion is scoped in a nam espace Nam espaces are opt ional, but y ou ar e encour aged t o use t hem Nam espaces in NET hav e t he sam e purpose t hey have in C+ + : t o scope classes so a client can use different classes from different vendors t hat hav e t he sam e nam e For a nam espace, you t ypically use t he pr oduct ’s nam e, y our com pany’s nam e, or t he assem bly’s nam e A client of t he class MyComponent in Exam ple C- m ust now r efer t o it by qualifying it wit h it s cont aining nam espace: MyNamespace.MyComponent Alt ernat ively, t he client can say t hat it is using t he MyNamespace nam espace, and avoid put t ing t he " MyNam espace" prefix on every t y pe cont ained in t hat nam espace: using MyNamespace; //MyComponent is now the same as MyNamespace.MyComponent You can also nest nam espaces wit hin one anot her For exam ple, if your com pany dev elops m ore t han one pr oduct , you would t ypically define in t he scope of t he MyCompany nam espace, t he nest ed nam espaces Product1, Product2, and so on: namespace MyCompany { namespace Product1 { //classes and type definitions public class Component1 { } } namespace Product2 { //other classes and type definitions } } Client s of y our com ponent s m ust giv e t he full qualify ing nam espace t o access your com ponent : MyCompany.Product1.Component1 Or, client s can use t he using st at em ent : using MyCompany.Product1; 374 //Component1 is now the same as MyCompany.Product1.Component1 The ShowMessage( ) m et hod in Ex am ple C- uses t he st at ic m et hod Show( ) of t he MessageBox class, defined in t he System.Windows.Forms nam espace Ex am ple C- t herefore cont ains t he st at em ent : using System.Windows.Forms; This st at em ent is used t o sim plify downst r eam code C.3 Usin g I n t e r fa ce s One t he m ost im port ant principles of com ponent - or ient ed dev elopm ent is t he separat ion of int erfaces fr om im plem ent at ion COM enfor ces t his separat ion by hav ing y ou separ at e t he definit ions of int er faces and classes .NET does not force you t o hav e your class m et hods be part of any int erface, but it is im per at iv e t hat you so t o allow polym or phism bet ween different im plem ent at ions of t he sam e int erface Exam ple C- includes an int er face definit ion as part of t he code— t here is no need for a separ at e I DL file The reserved C# word interface allow s y ou t o define a t y pe t hat is purely v ir t ual ( it has no im plem ent at ion and cannot be inst ant iat ed by client s) , j ust like a C+ + pure vir t ual or abst r act class The int erface m et hods not hav e t o ret ur n HRESULT or any ot her error handling t ype I n case of an er ror, t he m et hod im plem ent at ion should t hrow an ex cept ion C.4 W r it in g N ET Clie n t - Side Code All t hat a NET client has t o t o use a com ponent is add a reference in it s pr oj ect set t ing t o t he assem bly cont aining t he com ponent , creat e an obj ect , and t hen use it : using MyNamespace; //Interface-based programming: IMessage myObj; myObj = (IMessage)new MyComponent( ); myObj.ShowMessage( ); You usually not use point er s in C# Everyt hing is r efer enced using t he dot ( ) operat or Not e also t hat t he client cast s t he newly cr eat ed obj ect t o t he IMessage int erface This is t he NET equiv alent of QueryInterface( ) I f t he obj ect does not support t he int erface it is being cast t o, an ex cept ion is t hrow n The client can inst ead per form a cont rolled query for t he int erface using t he as k eyword I f t he obj ect does not support t he int erface, t he ret ur ned reference is null: using MyNamespace; 375 //Even better: check for type mismatch IMessage myObj; myObj = new MyComponent( ) as IMessage; Debug.Assert(myObj!= null); myObj.ShowMessage( ); As m ent ioned before, NET does not enfor ce separat ion of int erface fr om im plem ent at ion, so t he client could creat e t he obj ect t y pe dir ect ly: using MyNamespace; //Avoid doing this: MyComponent myObj; myObj = new MyComponent( ); myObj.ShowMessage( ); However, you should avoid writ ing client code t hat way because doing so m eans t hat t he client code is not polym orphic wit h ot her im plem ent at ions of t he sam e int erface Such client code also couples int er act ing m odules I m agine a sit uat ion in which Module cr eat es t he obj ect and Module uses it I f all t hat t he Module passes t o Module is t he int er face t ype, Module can change t he im plem ent at ion of t he int er face lat er wit hout affect ing Module C.5 N ET a s a Com pon en t Tech n ology To sim plify com ponent developm ent , one of t he goals set for t he NET fr am ework was t o im prove COM deficiencies Som e of t hese deficiencies, such as awk ward concur rency m anagem ent v ia apart m ent s, wer e inher it ed wit h COM it self Ot her deficiencies occur as a result of er ror- prone developm ent and deploy m ent phases Exam ples include m em ory and resource leaks result ing from reference count defect s, fr agile r egist r at ion, t he need for developerprovided proxy st ubs pairs, and hav ing int erface and t y pe definit ion in I DL files separ at e from t he code Fram ework s such as ATL provide aut om at ion of som e of t he requir ed im plem ent at ion plum bing, such as class fact ories and regist rat ion, but t hey int roduce t heir ow n com plexit y .NET is designed t o not only im pr ove t hese deficiencies, but also m aint ain t he core COM concept s t hat have proven t hem selves as core principles of com ponent - orient ed developm ent NET prov ides you fundam ent al com ponent - orient ed developm ent principles, such as binary com pat ibilit y bet ween client and com ponent , separat ion of int erface from im plem ent at ion, obj ect locat ion t ranspar ency, concurr ency m anagem ent , securit y , and language independence A com pr ehensiv e discussion of NET as a com ponent t echnology m er it s a book in it s own r ight and is bey ond 376 t he scope of t his appendix Howev er, t he following sect ions descr ibe t he m ain char act erist ics of NET as a com ponent t echnology C.5 Sim plif ie d Com pon e n t D e v e lopm e nt Com pared t o COM, NET m ight seem t o be m issing m any t hings y ou t ake for gr ant ed as par t of developing com ponent s However, in essence, t he m issing elem ent s ar e act ually present in NET, alt hough in a different fashion: • • • • • • Ther e is no canonical base int er face ( such as IUnknown) t hat all com ponent s der iv e from I nst ead, all com ponent s der ive fr om t he System.Object class Every NET obj ect is t herefore poly m or phic w it h System.Object Ther e are no class fact or ies I n NET, t he r unt im e resolves a t y pe declar at ion t o t he assem bly cont aining it and t he ex act class or st ruct wit hin t he assem bly Ther e is no reference count ing of obj ect s .NET has a sophist icat ed garbage collect ion m echanism t hat det ect s when an obj ect is no longer used by client s Then t he gar bage collect or dest r oys t he obj ect Ther e are no I DL files or t ype libr aries descr ibing y our int er faces and cust om t y pes I nst ead, you put t hose definit ions in your source code The com piler is responsible for em bedding t he t ype definit ions in a special for m at in your assem bly called m et adat a Ther e are no GUI Ds Scoping t he t y pes wit h t he nam espace and assem bly nam e pr ov ides uniqueness of t ype ( class or int er face) When shar ing an assem bly bet ween client s, t he assem bly m ust cont ain a st rong nam e— a unique binar y blob generat ed wit h an encr ypt ion key Globally unique ident ifiers ex ist in essence, but you not have t o m anage t hem any m ore Ther e are no apart m ent s By default , every NET com ponent execut es in a fr ee- t hreaded env ir onm ent and y ou are responsible for synchr onizing access t o y our com ponent s Providing sy nchronizat ion is done by either r elying on NET sy nchr onizat ion locks or using COM+ act ivit ies .NET has a superb developm ent environm ent and sem ant ics, t he product of years of obser ving how developer s use COM and t he hurdles t hey faced C.5 1 Th e N ET ba se cla sses As dem onst r at ed in Exam ple C- 1, a hard- t o- learn com ponent dev elopm ent fr am ework such as ATL is not r equired t o build binary m anaged com ponent s .NET t ak es car e of all t he under ly ing 377 plum bing for you To help y ou develop your business logic fast er , NET also pr ov ides y ou wit h m ore t han 3,500 base classes, av ailable in sim ilar form for all languages The base classes are easy t o learn and apply You can use t he base classes as is, or der ive from t hem t o ext end and specialize t heir behavior C.5 Com pon e n t inh er it an ce NET enfor ces st r ict inherit ance sem ant ics and inher it ance conflict s resolut ion .NET does not allow m ult iple inher it ance of im plem ent at ion You can only der ive from one concret e class You can, however, der ive from as m any int erfaces as you lik e When you override a virt ual funct ion im plem ent at ion in a base class, you m ust declare y our int ent ex plicit ly For exam ple, if you want t o overr ide it , y ou should use t he override reserved w ord C.5 Com pon e n t visibilit y While developing a set of int eroper at ing com ponent s, you oft en hav e com ponent s t hat ar e int ended only for privat e use and should not be shared wit h your client s Under COM, t her e is no easy way of guar ant eeing t hat t he com ponent s ar e only used pr ivat ely The client can always hunt t hr ough t he Regist ry , find t he CLSI D of your privat e com ponent , and use it I n NET, you can sim ply use t he internal key wor d on t he class definit ion ( inst ead of public, as in Exam ple C- 1) The runt im e denies access t o your com ponent for any caller out side your assem bly C.5 At t ribu t e - b a sed p rogr am m in g When developing com ponent s, you can use at t ribut es t o declar e your com ponent needs, inst ead of coding t hem Using at t ribut es t o declare com ponent needs is sim ilar t o t he way COM dev elopers declare t he t hreading m odel at t ribut e of t heir com ponent s .NET provides you wit h num erous at t r ibut es, allowing you t o focus on your dom ain problem at hand ( COM+ services are accessed v ia at t r ibut es) You can also define your own at t r ibut es or ext end exist ing ones C.5 Com pon e n t - or ie n t e d se cu rit y The classic Windows NT securit y m odel is based on what a given user is allowed t o This m odel has evolved in a t im e when COM was in it s infancy and applicat ions were usually st andalone, m onolit hic chunks of code I n t oday’s highly dist r ibut ed, com ponent - orient ed environm ent , t her e is a need for a securit y m odel based on w hat a given piece of code— a com ponent — is allowed t o do, and not only on w hat it s caller is allowed t o 378 .NET allows you t o configur e perm issions for a piece of code and provide an evidence t o prove t hat it has t he right cr edent ials t o access a resour ce or per form sensit iv e work Ev idence- based securit y is t ight ly relat ed t o t he com ponent ’s or igin Syst em adm inist rat ors can decide t hat t hey t rust all code t hat cam e from a par t icular vendor , but dist rust ev eryt hing else, fr om downloaded com ponent s t o m alicious at t ack s A com ponent can also dem and t hat a per m ission check be perfor m ed to v er ify t hat all callers in it s call chain have t he right per m issions before it pr oceeds t o it s work This m odel com plem ent s COM+ r ole- based securit y and call aut hent icat ion I t pr ov ides t he applicat ion adm inist r at or wit h granular cont r ol over not only what t he users are allowed t o do, but also w hat t he com ponent s ar e allowed t o .NET has it s own rolebased securit y m odel, but it is not as granular or user fr iendly as COM+ role- based securit y C.5 Sim plif ie d Com pon e n t D e ploy m e nt NET does not r ely on t he Regist ry for anyt hing t hat has t o wit h your com ponent s I n fact , inst alling a NET com ponent is as sim ple as copy ing it t o t he direct ory of t he applicat ion using it NET m aint ains t ight version cont r ol, enabling side- by- side execut ion of new and old versions of t he sam e com ponent on t he sam e m achine The net result is zero- im pact inst all— by default , you cannot harm anot her applicat ion by inst alling yours, t hus ending t he predicam ent know n as DLL Hell The NET m ot t o is: it j ust work s I f y ou want t o inst all com ponent s t o be shared by m ult iple applicat ions, y ou can inst all t hem in t he Global Assem bly Cache ( GAC) I f t he GAC alr eady cont ains a pr ev ious v er sion of your assem bly , it k eeps it for use by client s t hat wer e built against t he old version You can pur ge old ver sions as w ell, but t hat is not t he default C.5 Sim plif ie d Obj e ct Life Cycle M a n a ge m e nt NET does not use reference count ing t o m anage an obj ect 's life cy cle I nst ead, NET keeps t rack of accessible pat hs in y our code t o t he obj ect As long as any client has a r efer ence t o an obj ect , it is considered reachable Reachable obj ect s are kept alive Unr eachable obj ect s are considered garbage, and t herefore dest roying t hem harm s no one One of t he cr ucial CLR ent it ies is t he gar bage collect or The garbage collect or periodically t r av erses t he list of ex ist ing obj ect s Using a sophist icat ed point ing schem a, it det ect s unreachable obj ect s and releases t he m em ory allocat ed t o t hese obj ect s Consequent ly, client s not have t o increm ent or decrem ent a reference count on t he obj ect s t hey creat e C.5 N on de t e r m in ist ic Fin a liza t ion 379 I n COM, t he obj ect k nows t hat it is no longer r equired by it s client s when it s r efer ence count goes down t o zer o The obj ect t hen per form s cleanup and dest roys it self by calling delete this; The ATL fr am ework even calls a m et hod on your obj ect called FinalRelease( ), let t ing you handle t he obj ect cleanup I n NET, unlike COM, t he obj ect it self is never t old when it is deem ed as garbage I f t he obj ect has specific cleanup t o do, it should im plem ent a m et hod called Finalize( ) The garbage collect or calls Finalize( ) j ust before dest r oy ing t he obj ect Finalize( ) is your NET com ponent ’s dest ruct or I n fact , even if you im plem ent a dest ruct or ( such as t he one in Exam ple C- 1) , t he com piler will conv ert it t o a Finalize() m et hod C# D e st r uct or I n C# , not prov ide a Finalize( ) m et hod I nst ead, provide a dest r uct or The com piler bot h convert s t he dest ruct or definit ion t o a Finalize( ) m et hod and calls y our base class Finalize( ) m et hod For ex am ple, for t his class definit ion: public class MyClass { public MyClass( ){} ~MyClass( ){} } The code t hat is act ually generat ed would be: public class MyClass { public MyClass( ){} protected virtual void Finalize( ) { try { //Your destructor code goes here } finally { base.Finalize( );//everybody has one, from Object } } } However, sim plify ing t he obj ect lifecycle com es wit h a cost in sy st em scalabilit y and t hroughput I f t he obj ect holds on t o expensive r esources, such as files or dat abase connect ions, t hose resources are r eleased only when Finalize( ) is called I t is called at an undet erm ined point in t he fut ur e, usually when t he process host ing y our com ponent is out of m em or y I n t heor y, releasing t he 380 expensive r esources t he obj ect holds m ay never happen, and t hus severely ham per syst em scalabilit y and t hr oughput Ther e are t wo solut ions t o t he problem s arising fr om nondet erm inist ic finalizat ion The fir st solut ion is t o im plem ent m et hods on your obj ect t hat allow t he client t o explicit ly or der cleanup of expensive resour ces t he obj ect holds I f t he obj ect holds ont o resour ces t hat can be r eallocat ed, t hen t he obj ect should expose m et hods such as Open( ) and Close( ) An obj ect encapsulat ing a file is a good ex am ple The client calls Close( ) on t he obj ect , allowing t he obj ect t o r elease t he file I f t he client w ant s t o access t he file again, it calls Open( ) wit hout recr eat ing t he obj ect The m ore com m on case is when disposing of t he resources am ount s t o dest r oying t he obj ect I n t hat case, t he obj ect should im plem ent a m et hod called Dispose( ) When a client calls Dispose( ), t he obj ect should dispose of all it s expensive r ecourses, and t he client should not t r y t o access t he obj ect again The problem wit h bot h Close( ) and Dispose( ) is t hat t hey m ak e sharing t he obj ect bet ween client s m uch m or e com plicat ed t han COM’s reference count s The client s hav e t o coordinat e which one of t hem is responsible for calling Close( ) or Dispose( ) and when Dispose( ) should be called; t hus, t he client s are coupled t o one anot her The second solut ion t o nondet erm inist ic finalizat ion is t o use COM+ JI TA, as explained in Chapt er 10 C.5 COM a n d W indow s I n t e r ope r a bilit y COM and NET ar e fully int eroper able Any COM client can call y our m anaged obj ect s, and any COM obj ect is accessible t o a m anaged client To export y our NET com ponent s t o COM, use t he TlbExp.exe ut ilit y , also available as a com m and from t he Tools m enu The ut ilit y generat es a t ype libr ary t hat COM client s use t o CoCr eat e m anaged t ypes and int erfaces You can use var ious at t r ibut es on your m anaged class t o direct t he ex por t process, such as providing a CLSI D and I I D To im por t an exist ing COM obj ect t o NET ( by far t he m ost com m on scenar io) , use t he TlbI m p.exe ut ilit y The ut ilit y gener at es a m anaged w rapper class, which y our m anaged client uses The wrapper m anages t he r eference count on t he act ual COM obj ect When t he wrapper class is garbage collect ed, t he wrapper releases t he COM obj ect it w raps You can also im port a COM obj ect fr om wit hin t he Visual St udio.NET env ir onm ent by select ing t he COM obj ect from t he proj ect reference dialog ( which m ak es Visual St udio.NET call TlbI m p for you) NET has support for invok ing nat iv e Win32 API calls, or any DLL export ed funct ions, by im port ing t he m et hod signat ures t o t he m anaged env ironm ent 381 C.6 Com posin g Assem blies You prov ide t he com piler wit h y our assem bly inform at ion in an assem bly inform at ion file ( usually called in a C# proj ect , Assem blyI nfo.cs) The assem bly inform at ion file is com piled wit h t he rest of t he proj ect ’s source files The inform at ion in t he file is in t he form of assem bly at t ribut es—direct iv es t o t he com piler on t he infor m at ion t o em bed in t he assem bly Ex am ple C- shows a t ypical set of assem bly at t ribut es Ex a m p le C- Th e a ssem bly in form a t ion file in clud es a va r iet y of asse m bly a t t rib u t e s [assembly: AssemblyTitle("MyAssembly")] [assembly: AssemblyDescription("Assembly containing demo NET components")] [assembly: AssemblyCompany("My Product")] [assembly: AssemblyCopyright("(c) 2001 My Company ")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("en-US")] [assembly: AssemblyVersion("1.0.*")] C.6 Sh a r ing Asse m blie s Assem blies can be pr ivat e or shared A privat e assem bly resides in t he sam e direct ory of t he applicat ion t hat uses it ( or in it s pat h) A shared assem bly is in a know n locat ion, called t he global assem bly cache ( GAC) , m ent ioned in Chapt er 10Chapt er 10 To add an assem bly t o t he GAC, use eit her t he NET adm inist rat ion t ool or t he GACUt il com m and- line ut ilit y Once in t he GAC, t he assem bly can be accessed by m ult iple applicat ions, bot h m anaged and unm anaged To avoid conflict s in t he GAC bet ween different assem blies t hat hav e t he sam e nam e, a shared assem bly m ust have a st r ong nam e The st rong nam e aut hent icat es t he assem bly’s origin and ident it y and cannot be generat ed by a par t y ot her t han t he original publisher The st rong nam e allows any client of t he assem bly ( usually t he assem bly loader) t o det er m inist ically v erify t hat t he assem bly was not t am pered wit h Assigning a st r ong nam e t o an assem bly is also k nown as signing t he assem bly To assign a st rong nam e t o your assem bly , y ou fir st need t o generat e privat e or public encrypt ion key s You can generat e t he pair using t he SN.exe com m and- line ut ilit y: SN.exe -k MyAssembly.snk Fut ur e versions of Visual St udio.NET m ay enable you t o gener at e key s fr om wit hin t he v isual env ir onm ent The - k swit ch inst ruct s SN t o generat e a new pair of keys and st ore t hem in t he filenam e 382 specified The convent ion used for t he filenam e is t he assem bly nam e wit h t he st rong nam e key ( snk) ex t ension, but it can act ually be any nam e and ex t ension you lik e You t hen add t he snk file t o t he assem bly ’s inform at ion file, using t he AssemblyKeyFile assem bly at t ribut e: [assembly:AssemblyKeyFile("MyAssembly.snk")] I n addit ion t o a version num ber and a st rong nam e, a shared assem bly m ust have a nam espace and locale ident ifier t hat ident ify t he hum an language used in it s user int er face I n Exam ple C- t he locale is specified by t he AssemblyCulture assem bly at t ribut e C.6 Asse m bly M e t a da t a Each assem bly m ust cont ain m et adat a The m et adat a is t he NET equivalent of COM’s t ype libraries, except t he m et adat a is m ore like a t y pe libr ar y on st er oids The m et adat a cont ains descript ions of all t he t y pes defined in t he assem bly, such as int erfaces, classes and t heir base classes, m et hod signat ures, pr opert ies, event s, m em ber var iables, and cust om at t ribut es The m et adat a is generat ed aut om at ically by t he com piler when it com piles t he source files of your pr oj ect You can view t he m et adat a of y our assem bly using t he I LDASM ut ilit y C.6 Asse m bly M a n ife st While t he m et adat a describes t he t ypes in your assem bly, t he m anifest describes t he assem bly it self The m anifest cont ains t he assem bly v ersion inform at ion, t he locale inform at ion, and t he assem bly’s st rong nam e The m anifest also cont ains t he visibilit y of t he assem bly’s t y pes— which t ypes are public ( can be accessed by ot her assem blies) and which t ypes are int er nal ( can only be accessed fr om wit hin t he assem bly ) Finally , t he m anifest cont ains t he secur it y per m ission check s t o run on behalf of t he assem bly Like t he m et adat a, t he m anifest is generat ed aut om at ically by t he com piler during assem bly com pilat ion You can v iew t he m anifest of your assem bly using t he I LDASM ut ilit y C.6 Asse m bly File s Because every assem bly m ust cont ain t he m anifest and m et adat a ( and usually I L code and resour ces) , a single DLL or EXE assem bly cont ains all of t hem in one file Howev er, t he only requir em ent of a m ult ifile assem bly is t hat a file cont aining I L m ust also cont ain m et adat a descr ibing it Such a file is called a m odule A m ult ifile assem bly m ust st ill have one DLL file t hat cont ains t he m anifest Figure C- shows a few possibilit ies for com posing assem blies Figu r e C- Assem b ly file s 383 As y ou can see, you can com pose and use com piler swit ches t o bind pract ice, m ost assem blies cont ain St udio.NET I DE pr ovides only t his file t he assem bly in alm ost any way all your files t oget her I n j ust one DLL ( t he Visual opt ion) and are com posed of one 384 Colophon Our look is t he result of reader com m ent s, our own experim ent at ion, and feedback from dist r ibut ion channels Dist inct iv e covers com plem ent our dist inct ive approach t o t echnical t opics, breat hing per sonalit y and life int o pot ent ially dry subj ect s The anim als on t he cover of COM and NET Com ponent Ser vices are m oray and conger eels Eels m ake up t he 10 fam ilies of fish belonging t o t he order Arguillifor m es Know n for t heir snakelik e body wit h no hind fins, eels can m ov e t hrough wat er, m ud, and rocky crevices Most eels ar e less t han t hree feet long, but fr eshwat er conger eels can gr ow as large as nine feet Unt il t he 20t h cent ury , lit t le was k now n about t he life cy cle and m igrat ion of eels Scient ist s now know t hat Am er ican and European eels t r avel long dist ances during t heir reproduct iv e cycles The fem ale eels generally m at ur e in fr eshwat er lakes and t ravel t o t he nearest ocean, oft en slit hering over wet grass and m ud during t he j ourney Then t hey swim or dr ift from Europe or Nort h Am er ica t o t he Sargasso Sea There, t he fem ales lay up t o 20 m illion eggs and t hen die The egg- larvae t hen dr ift eit her t o Nort h Am er ica ( aft er one year) or back t o Eur ope ( aft er t hr ee years) Aft er r eaching t heir hom e cont inent , t he eels com plet e t heir cycle by gat hering at t he m out hs of rivers and sw im m ing upst ream Eels ar e also known for t heir oily m eat , cherished by som e as a culinar y delicacy Ann Schir m er w as t he product ion edit or for COM and NET Com ponent Services Paulet t e Miley and Ann Schir m er were t he copyedit or s for t he book Ann Schirm er and Leanne Soylem ez were t he proofreaders Claire Clout ier, Mar y Brady, and Rachel Wheeler provided qualit y cont rol Kim o Cart er, Ann Schirm er, and Sarah Sherm an did int erior com posit ion Judy Hoer wrot e t he index Ellie Volckhausen designed t he cover of t his book, based on a ser ies design by Edie Fr eedm an The cov er im age is a 19t h- cent ury engr av ing fr om t he Dover Pict orial Ar chive Em m a Colby produced XPress 4.1 using Adobe’s I TC t he cover layout wit h Quar k Gar am ond font Dav id Fut at o designed t he int erior layout Neil Walls conv ert ed t he files fr om Micr osoft Word t o Fram eMaker 5.5.6 using t ools cr eat ed by Mik e Sierr a The t ext font is Linot ype Bir ka, t he heading font is Adobe Myriad Condensed, and t he code font is LucasFont ’s TheSans Mono Condensed The illust r at ions t hat appear in t he book were produced by Robert Rom ano and Jessam yn Read using Macr om edia Fr eeHand and Adobe Phot oshop The t ip and war ning icons were drawn by Chr ist opher Bing This colophon was w rit t en by Ann Schirm er 385 ... ledgm ent s COM+ Com ponent Serv ices 1.1 COM+ Com ponent Ser v ices 1.2 The Com ponent Ser vices Explor er 1.3 Hello COM+ 1.4 COM+ Configur ed Com ponent s 1.5 Applicat ions, DLLs, and Com ponent... debug, and deploy a sim ple COM+ " Hello Wor ld" applicat ion, using a t r adit ional COM com ponent and learning about COM+ applicat ion t y pes and configured com ponent s as y ou so 17 1 COM+ Com. .. public I nt ernet Collect ively, t he services t hat support COM and NET com ponent based applicat ions ar e known as t he COM+ com ponent ser vices, or sim ply as COM+ The Evolut ion of COM + Se

Ngày đăng: 20/03/2019, 15:18