Langkah 3: Menggunakan Kembali Komponen
Tujuan
Dalam langkah ini, Anda akan mempelajari tentang hal berikut:
- Komponen yang dapat digunakan kembali.
- Cara merencanakan penggunaan kembali.
Deskripsi
Dua bagian sebelumnya dari primer layanan COM+ ini, Langkah 1: Membuat Komponen Transaksional dan Langkah 2: Memperluas Transaksi di Beberapa Komponen menunjukkan cara menulis satu komponen yang memanggil komponen kedua untuk membantu menyelesaikan beberapa pekerjaan, memperbarui informasi penulis dalam database Microsoft SQL Server Pubs; semua pekerjaan dilindungi oleh satu transaksi. Komponen sampel berfokus pada pekerjaan memperbarui data penulis dan memverifikasi alamat penulis, dan pemrosesan transaksi yang disediakan COM+, aktivasi JIT, dan perlindungan konkurensi .
Langkah ini menunjukkan cara menggunakan kembali komponen yang dibuat dalam langkah 1 dan 2 dan melihat apa artinya ini pada desain komponen tersebut. Seperti yang ditunjukkan dalam ilustrasi berikut, ini berarti membuat komponen baru, AddNewAuthor
, yang menambahkan penulis baru ke database dengan memanggil UpdateAuthorAddress
.
Selain menggunakan kembali fungsionalitas komponen yang ada, AddNewAuthor
memanggil komponen baru lain yang disebut ValidateAuthorName
. Seperti yang ditunjukkan oleh ilustrasi sebelumnya, ValidateAuthorName
bersifat non-transaksional. Nilai atribut transaksi untuk komponen ini dibiarkan pada pengaturan defaultnya (Tidak Didukung) untuk mengecualikan pekerjaannya dari transaksi. Seperti yang ditunjukkan pada kode sampel langkah 3, ValidateAuthorName
melakukan kueri baca-saja pada database, dan kegagalan tugas kecil ini seharusnya tidak berpotensi membatalkan transaksi. Namun, nilai atribut transaksi komponen AddNewAuthor
diatur ke Required.
Komponen AddNewAuthor
, UpdateAuthorAddress
, dan ValidateAuthorAddress
semuanya memilih dalam transaksi. Dalam transaksi ini, AddNewAuthor
adalah objek akar. COM+ selalu membuat objek pertama yang dibuat dalam transaksi sebagai objek akar.
Dalam contoh ini, menggunakan kembali komponen UpdateAuthorAddress
mudah—COM+ secara otomatis memberikan layanan yang diharapkan. Namun, hasilnya akan berbeda jika nilai atribut transaksi komponen UpdateAuthorAddress
awalnya diatur ke Memerlukan Baru alih-alih Diperlukan. Di permukaan, kedua pengaturan tampak serupa; keduanya menjamin transaksi.
MembutuhkanBaru namun selalu memulai transaksi baru, sedangkan Membutuhkan hanya memulai transaksi baru ketika pemanggil objek tidak transaksional. Anda dapat melihat dari ini betapa pentingnya mengonfigurasi UpdateAuthorAddress
dengan hati-hati dan bijaksana. Jika tidak, COM+ mungkin telah menginterpretasikan permintaan layanan secara berbeda, menghasilkan dua transaksi yang tidak terkait, seperti yang ditunjukkan dalam ilustrasi berikut, bukan satu.
Nota
Saat Anda menggunakan kembali komponen, pastikan layanan dikonfigurasi untuk mendukung hasil yang Anda inginkan.
Kode sampel
Komponen AddNewAuthor melakukan penambahan batch penulis baru dengan memungkinkan objek tetap aktif sampai klien merilis referensinya ke objek.
Option Explicit
'
' Purpose: This class is used for adding a new author.
'
' Notes: IMPT: This component implicitly assumes that it will
' always run in a transaction. Undefined results may
' otherwise occur.
'
' AddNewAuthor
'
Public Sub AddNewAuthor( _
ByVal strAuthorFirstName As String, _
ByVal strAuthorLastName As String, _
ByVal strPhone As String, _
ByVal strAddress As String, _
ByVal strCity As String, _
ByVal strState As String, _
ByVal strZip As String, _
ByVal boolContracted As Boolean)
' Handle any errors.
On Error GoTo UnexpectedError
' Verify component is in a transaction.
' The VerifyInTxn subroutine is described in Step 1.
VerifyInTxn
' Get our object context.
Dim objcontext As COMSVCSLib.ObjectContext
Set objcontext = GetObjectContext
' Get the IContextState object.
Dim contextstate As COMSVCSLib.IContextState
Set contextstate = objcontext
' Validate that the author is OK.
' The ValidateAuthorName function is described after this function.
Dim oValidateAuthName As Object
Dim bValidAuthor As Boolean
Set oValidateAuthName = CreateObject("ComplusPrimer.ValidateAuthorName")
bValidAuthor = oValidateAuthName.ValidateAuthorName( _
strAuthorFirstName, strAuthorLastName)
If Not bValidAuthor Then
Err.Raise 999999, "The AddNewAuthor component", _
"You tried to add an author on the banned list!"
End If
' Open the connection to the database.
Dim conn As ADODB.Connection
Set conn = CreateObject("ADODB.Connection")
' Specify the OLE DB provider.
conn.Provider = "SQLOLEDB"
' Connect using Windows Authentication.
Dim strProv As String
strProv = "Server=MyDBServer;Database=pubs;Trusted_Connection=yes"
' Open the database.
conn.Open strProv
' Tell the database to actually add the author; use empty strings
' for this part and rely on the UpdateAuthorAddress
' component to validate the address/phone/etc data.
' Default Contract flag is off.
Dim strUpdateString As String
strUpdateString = "insert into authors values(_
'789-65-1234'," & _
strAuthorLastName & ", " & _
strAuthorFirstName & ", " & _
"'(555) 555-5555', ', ', ', '98765', "
If boolContracted Then
strUpdateString = strUpdateString + "1)"
Else
strUpdateString = strUpdateString + "0)"
End If
conn.Execute strUpdateString
' Close the connection; this potentially allows
' another component in the same transaction to
' reuse the connection from the connection pool.
conn.Close
Set conn = Nothing
' Create the UpdateAuthorAddress component.
Dim oUpdateAuthAddr As Object
Set oUpdateAuthAddr = CreateObject("ComplusPrimer.UpdateAuthorAddress")
' The component throws an error if anything goes wrong.
oUpdateAuthAddr.UpdateAuthorAddress "", strPhone, _
strAddress, strCity, strState, strZip
Set oUpdateAuthAddr = Nothing
' Everything works--commit the transaction.
contextstate.SetMyTransactionVote TxCommit
' Design issue: Allow batch additions of new
' authors in one transaction, or should each new author be added
' in a single new transaction?
contextstate.SetDeactivateOnReturn False
Exit Sub
UnexpectedError:
' There's an error.
contextstate.SetMyTransactionVote TxAbort
contextstate.SetDeactivateOnReturn True
End Sub
Komponen ValidateAuthorName
memvalidasi nama pembuat sebelum AddNewAuthor
menambahkan nama ke database. Komponen ini melemparkan kesalahan kembali ke pemanggilnya jika sesuatu yang tidak terduga terjadi.
Option Explicit
'
' Purpose: This class is used for validating authors before
' adding them to the database.
'
' Notes: This component doesn't need to be in a transaction because
' it is performing read-only queries on the database,
' especially since these queries are not overlapping with
' any updates of end-user data. If an unexpected error
' happens, let the error go back to the caller who
' needs to handle it.
'
Public Function ValidateAuthorName( _
ByVal strAuthorFirstName As String, _
ByVal strAuthorLastName As String _
) As Boolean
ValidateAuthorName = False
' Open the connection to the database.
Dim conn As ADODB.Connection
Set conn = CreateObject("ADODB.Connection")
' Specify the OLE DB provider.
conn.Provider = "SQLOLEDB"
' Connect using Windows Authentication.
Dim strProv As String
strProv = "Server=MyDBServer;Database=pubs;Trusted_Connection=yes"
' Open the database.
conn.Open strProv
' Suppose another hypothetical table has been added to the Pubs
' database, one that contains a list of banned authors.
Dim rs As ADODB.Recordset
Set rs = conn.Execute("select * from banned_authors")
' Loop through the banned-author list looking for the specified
' author.
While Not rs.EOF
If rs.Fields("FirstName") = strAuthorFirstName And _
rs.Fields("LastName") = strAuthorLastName Then
' This is a banned author.
conn.Close
Set conn = Nothing
Set rs = Nothing
Exit Function
End If
rs.MoveNext
Wend
' None of the added authors found in the banned list.
ValidateAuthorName = True
conn.Close
Set conn = Nothing
Set rs = Nothing
End Function
Ringkasan
- Ada kalanya Anda tidak ingin komponen memilih dalam transaksi.
- COM+ tidak memberlakukan aktivasi JIT atau perlindungan konkurensi pada komponen non-transaksional. Anda dapat mengonfigurasi layanan ini secara terpisah.
- Konfigurasi komponen panggilan memengaruhi bagaimana COM+ menginterpretasikan permintaan layanan dari komponen yang disebut.
Topik terkait