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

Assembly Language: Step-by-Step - part 14 ppt

80 294 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 80
Dung lượng 1,84 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Figure 15.1 The DataComponent simplifies access to the data store.Locating the Component at Run Time Some questions that may come to mind are, How is the reference to the project or asse

Trang 1

before the change was made (8.758217) to the slowest speed with the change(0.046475), the speed has increased by over 180 times.

After this change, it’s time to run ACT to see what kind of performance can

be obtained on the tests that were defined The original test was run with threebrowser connections, because that was the only test that did not generateerrors The result of the new test also had no errors Figure 14.15 shows the dif-ference between the two tests

Comparing the graph of the original test against the new test shows a stantial difference in performance Neither of these tests generated errors.What was once an extremely slow site now responds significantly better Theoriginal test delivered a mere 12 responses, whereas the latest test delivered2,204 responses This is over 180 times the original test

sub-Caching

Caching data can result in substantial performance gains In situations wheremany users would normally make calls to the database for data that rarelychanges, caching the data on the Web server can completely bypass the call tothe database server

The cache has a global scope and includes the necessary locking mechanism

to allow items to be added and read from the cache by many users Cachingspecifics are covered in more detail in Chapter 12, “ASP.NET Applications.”This section explores some of the performance gains derived from caching

Figure 14.15 The original browser connection test overlaid with a new browser connection test.

Trang 2

three-Page Caching

Page caching is probably the easiest caching method to implement This is acompelling choice for many Web applications To enable Web page caching,the following information must be added to the HTML at the top of the Web page:

<%@ OutputCache Duration=”60” VaryByParam=”customerId;pageNumber” %>

This setting caches the page output for 60 seconds, after which, the cache isinvalidated, and the next request for the page results in execution of the codethat is on the page

The VaryByParam setting can be set to none, *, valid querystring, or formparameter names, separated by a semicolon If VaryByParam is set to none,only one copy of the page is cached If VaryByParam is set to *, there will be acached copy of the page for each combination of parameters that changeswhen the page is retrieved If the parameter is set to customerId;pageNumber,there will be a cached copy of the page for each customerId and pageNumbercombination

Figure 14.16 shows the ACT output after running the same test that wasused with the StringBuilder, but the page was cached using the followingstatement in the Web page HTML:

<%@ OutputCache Duration=”60” VaryByParam=”*” %>

Figure 14.16 The Application Center Test report when implementing caching.

Trang 3

Caching improved performance significantly over the last test where theStringBuilder was implemented This required only a single line of code andresulted in a substantial gain.

The test was done using three browser connections, and no errors werereported when running the test Notice that the request count went from 12 to2,204 to 15,837 This represents an increase of over seven times the previoustest It’s worth noting that if the code were not changed to use the String-Builder, the change would have been from 12 requests to 15,837 requests Thiswould represent an increase of over 1,300 times

Object Caching

In the previous example, caching was implemented with a single line of code

In some cases, this type of caching is wasteful For example, if a large amount

of data is being sent to the browser and that same data is being sent to thebrowser from a different page, multiple copies of the same data could be held

by the Web server Often, part of the Web page needs to be dynamic, whereasanother part of the page is cached

Object caching involves writing the code to cache objects rather than theentire page The Cache object is used to add items into the cache The follow-ing code shows how the BuildString method’s result can be cached:

Public Function BuildString() Dim retString As String

If Cache(“BuildString”) Is Nothing Then Dim x As Integer = 0

Dim s As New System.Text.StringBuilder() Dim pcStringLength As PerformanceCounter Dim pcLoopValue As PerformanceCounter pcStringLength = CType(Session(“pcStringLength”), _ PerformanceCounter)

pcLoopValue = CType(Session(“pcLoopVaue”), _ PerformanceCounter)

Trace.Warn(“BuildString”, “Start of loop”) For x = 1 To 3000

s.Append(“abcdefghijklmnopqrstuvwxyz The value of x=”) s.Append(x.ToString())

s.Append(“<br>”)

‘Update the counters.

pcStringLength.RawValue = s.Length pcLoopValue.RawValue = x

Next Trace.Warn(“BuildString”, “End of loop”)

‘Clear the counters.

pcStringLength.RawValue = 0 pcLoopValue.RawValue = 0

Trang 4

retString = s.ToString() Cache(“BuildString”) = retString Else

retString = CType(Cache(“BuildString”), String) End If

Return retString End Function

The OutputCache directive was removed from the HTML and the test was run again Figure 14.17 shows the output of the test, overlaid with the pre-vious test

Test number 4 represents the object-caching test, which did not perform aswell as the page cache test (test 3) The benefit is that other parts of the page arestill dynamic Figure 14.18 shows the metrics of the test The page cache test(test 3) was over seven times faster than the StringBuilder test (test 2), but thistest (test 4) is only about five times faster than the StringBuilder test

Graphics Caching

When working with images, be sure to deliver the image to the browser usingthe same size that the browser uses to display the image If a page is display-ing thumbnail images that are 75 x 75 pixels, don’t send the image to thebrowser at 1,200 x 1,200 pixels, because doing so uses all available networkbandwidth Images should be cached where possible, especially when theimage is being loaded from a database

Figure 14.17 The output of the object-caching test, overlaid with previous tests

Trang 5

Figure 14.18 The metrics of the object-caching test show a decrease in performance over page caching, but parts of the page can still be dynamic.

ViewState

ViewState should be monitored, and a test should be run to determine whether

it is better to store information in the ViewState or in the Session, Application,

or Cache state If a control is read-only, ViewState may not be necessary for thecontrol

ViewState is turned on at the page level by default, but you can turn it offwhen it’s not required Also, ViewState should be reviewed on a per controlbasis to determine the control’s impact on performance

Use a combination of Web Trace and ACT to determine what the impact ofViewState is for the current Web application Performance will vary betweenWeb pages

Database Performance

In many situations, database performance can become the bottleneck of a Webapplication SQL Server is a fast product, but you still need to be aware ofitems that can impact SQL Server performance

Trang 6

Stored Procedures

Whenever possible, use stored procedures for making calls to the database.When a stored procedure is created, it is checked for syntax errors, compiled,and saved to disk When SQL commands are sent to SQL Server from a Webapplication, SQL Server must check the SQL statement for syntax errors andcompile the SQL before the SQL command can be executed

When a call is made to the stored procedure, the first time it runs, it may beslower than sending a SQL statement directly to SQL Server, because the storedprocedure must load into memory from the disk After the stored procedure is

in memory, the stored procedure will outperform ad hoc SQL statements

Indexes

When creating SQL Server tables and relationships, be sure to designate a mary key for each table Although the primary key can be an existing field orfields that identify uniqueness for a row, a surrogate primary key should beconsidered A surrogate primary key exists solely to be a row identifier, which

pri-is a field that pri-is added to the table and pri-is usually an autonumber (also known

as an identity) field It’s faster for SQL Server to maintain an index on a singlenumeric column than to maintain composite indexes When a primary key isidentified, a unique index is created for the key

When a relationship is created between two tables, the relationship is ally between the primary key of one table and a foreign key of another table.Although the creation of a primary key automatically creates an index for theprimary key, the creation of a foreign key does not create an index automati-cally Big performance gains can be realized by adding indexes for all foreignkey fields

usu-Calculated Fields

If a stored procedure or view is constantly performing mathematical tions on certain fields, a calculated field can be created that performs the mathoperation once prior to executing the stored procedure This addition can lead

opera-to large gains when complex formulas are involved, such as trigonometryfunctions performed on the columns

Trang 7

Lab 14.1: Using Application Center Test

In this lab, you explore the performance increase that can be obtained byusing page caching An Application Center Test will be used as the pri-mary tool to record performance changes as caching is implemented

Establishing Baseline Performance Data

In this section, you add a new Web page called login.aspx:

1. To start this lab, open the OrderEntrySystemSolution from Lab 13.1

2. Right-click the OrderEntrySystemSolution in the Solution Explorer,and click Check Out

3. Set Customer as the startup project

4. Set the CustomerList.aspx page as the startup page

5. Right-click the CustomerList.aspx page, and click View In Browser

to ensure that the Web application has been started Notice that youare redirected to the login page Enter a name and password, andclick the Login button to redirect the page to the CustomerList.aspxpage Close the browser

6. Open Application Center Test by clicking Start, All Programs,Microsoft Visual Studio NET, Visual Studio NET Enterprise Fea-tures, Microsoft Application Center Test

7. Click File, New Project to create a new project When prompted for theproject name, type Customer Your screen should look like Figure 14.19

8. Create a new test by clicking Actions, New Test to start the New TestWizard Click Record a New Test Select VBScript as the language.Click Start Recording to start recording a test

9. When the browser window is displayed, enter the following URL:

http://localhost/Customer/CustomerList.aspx

10. This code redirects the page to the login.aspx page Type a validname and password, and click the Login button to redirect the page

to the CustomerList.aspx page

11. Click the browser’s Refresh button to retrieve another copy of theCustomerList.aspx page

12. Close the browser, and click the Stop Recording button

13. On the next screen, type CustomerListTest for the test name

14. After recoding the test, open the Tests node in Application CenterTest The CustomerListTest should be available; click CustomerListTest

Trang 8

The upper-right window contains a message stating that notes can

be entered Enter the following note:

Baseline CustomerList Test with 3 Browser Connections for 3 Minutes.

Figure 14.19 The Application Center Test screen after creating a new project called Customer.

15. Right-click the CustomerListTest, and click Properties Set theBrowser Connections to 3 and the Duration to 3 minutes

16. Right-click the CustomerListTest, and click Start Test

17. After the test is completed, add the following line to the HTML ofthe CustomerList.aspx page:

<%@ OutputCache Duration=”600” VaryByParam=”*” %>

18. Right-click the CustomerListTest, and click Copy Rename the copyCustomerListCacheTest In the upper-right pane, add the followingnote:

CustomerList Cache Test with 3 Browser Connections for 3 Minutes.

19. Right-click the CustomerListCacheTest, and click Start Test Figure14.20 shows the baseline test overlaid with the cache test Actualnumbers will vary, but there should be a significant difference inperformance between the two tests

20. Scroll to the bottom of the report Figure 14.21 shows the metrics of thetest There were no errors in either test Your metrics will vary, but thereshould be a substantial difference between the two tests Notice thatthere were two different response codes: The 200 is a success, and the

Trang 9

302 represents the redirect to the login page as well as the redirect back

to the CustomerList.aspx page upon successful login There were atotal of 1,581 requests by the baseline test and a total of 20,222 requests

by the cache test, which represents speed increase of over 12 times

Figure 14.20 The baseline and the cached CustomerList.aspx page results.

21. Save your changes, and check the final solution back into VisualSourceSafe

Figure 14.21 The metrics of the baseline and cached CustomerList.aspx page.

Trang 10

■■ Performance tuning is the process of running specific tests on isolatedparts of the software, making changes to the software, and rerunningthe tests to identify bottlenecks and increase the software’s performance

■■ Identifying bottlenecks is the process of interpreting load test data andinvestigating system performance to locate the slowest parts of the sys-tem Eliminating a bottleneck can result in substantial gains in perfor-mance for the overall system

■■ The System.dll file contains the Debug class, which can be used toobtain information when running an application that was compiledusing the debug switch

■■ The System.dll file contains the Trace class, which can be used to obtaininformation while the system is running, especially in a multitier ormultithreaded application

■■ Trace provides the ability to perform page- or application-level tracing

Page-level tracing is configured at the Web page, whereas level tracing is configured in the Web.config file

application-■■ Performance Monitor can be used to monitor system resources, such asmemory usage, processor utilization, disk access, and network band-width In addition, the NET Framework provides many counters, andmany applications, such as SQL Server and Internet Information Server,provide counters

■■ Strings are immutable in the NET Framework Concatenation of largestrings should be avoided due to the resources that are required tomove this data

■■ The StringBuilder class can be used when string concatenation isrequired, because the StringBuilder class contains an Append method,which does not require excessive resources

■■ Caching can increase Web performance substantially For pages that arerelatively static, page caching can be used For pages that can’t becached, object caching can be implemented

Trang 11

Review Questions

1. What must be established prior to load testing and performance tuning?

2. To receive verbose trace messages, what value should a TraceSwitch be set to?

3. What utility can be run outside of the Visual Studio NET environment to displayDebug and Trace messages that are written to the default listener?

4. When using Web application tracing with pageOutput set to false, what must berequested in order to view the trace information?

5. What is the best method of creating a string when the string is being constructed of

Trang 12

Answers to Review Questions

1. A baseline for comparison as changes are made

2. Set the value to 4 for verbose messages

3. The Debug Monitor (DbMon.exe) utility can be run This utility is included in the Windows Platform SDK

4. A request for trace.axd must be made

5. Use the StringBuilder class

6. Application Center Test (ACT)

7. Windows XP Professional has a 10 connection limit

Trang 14

Building reusable components is something developers have done in the pastand found beneficial in several ways First, reusable components have reducedthe amount of code developers have had to write, particularly when buildinglarge applications Second, reusable components have encapsulated function-ality that developers could reuse in other applications Third, being compiledcode, reusable components have had a performance edge over interpretedscripts

Today, it’s not necessary to build components to get a performance edge;scripted languages are equally fast The other reasons for building reusablecomponents are still valid, however, and there are some new benefits, such ascross-language inheritance

One of the problems that have plagued components is versioning WithCOM, versioning was done by providing new interfaces, and each interfacewas considered to be an immutable contract The problem was that enforce-ment of the versioning was done by the developer With NET components, theruntime enforces versioning Providing a different version of a componentautomatically breaks the code until the code is recompiled with the newassembly, or until the application code is redirected to the new component

This chapter covers the methods of creating components, or reusable blies, by first creating a component and using it After that, this chapter discusses

assem-Building and Versioning NET

Components

C H A P T E R

15

Trang 15

versioning of assemblies, and the differences between private and sharedassemblies Much time is spent also on exploring strong names and bindingpolicies This chapter finishes by looking at cross-language inheritance.

Classroom Q & AQ: Where are the Registry entries for NET components? I am afraid

of registering a new component and overwriting this setting by registering an older version of the NET component

A: There are no Registry entries for NET components This eliminatesthe problem that was affectionately known as DLL Hell in the past

Q: If I have many copies of a NET component on my machine, isthere a way to find out which copy is actually being used?

A: Yes There is a tool called the Fusion Log Viewer that can tell youwhich component is being used by a program

Q: Is there a way to set a lookup path to my components so I don’thave to keep placing them into the Global Assembly Cache when

I am working on them?

A: Yes You can use the DEVPATH environment variable We look atthis in detail in this chapter

Building Reusable Components

Chapter 4, “The NET Framework and Visual Basic NET Object ming,” covered many of the aspects of object-oriented programming, includ-ing inheritance Creating components allows much of the coding logic to beencapsulated, which can simplify the task of creating many user interfaces,from cell phone to Windows In this section, a component example is pre-sented that is used throughout the chapter

Program-Creating the Class Library Project

To build a reusable component, a Visual Studio NET Class Library projectmust be created This project compiles to a dll file To use the dll file, a refer-ence must be made to the dll file from the Web application

When the Class Library project is created, it includes an empty class file Thecode in Listing 15.1 is included in the class file to provide easy access to theback end SQL Server

Trang 16

Imports System.Data.SqlClient Public Class Db

Public Shared Function ExecuteScaler( _ ByVal cn As SqlConnection, _

ByVal cmdText As String) As Long Return ExecuteScaler( _

cn, CommandType.Text, cmdText, Nothing) End Function

Public Shared Function ExecuteScaler( _ ByVal cn As SqlConnection, _

ByVal cmdType As CommandType, _ ByVal cmdText As String) As Long Return ExecuteScaler( _

cn, cmdType, cmdText, Nothing) End Function

Public Shared Function ExecuteScaler( _ ByVal cn As SqlConnection, _

ByVal cmdType As CommandType, _ ByVal cmdText As String, _ ByVal ParamArray prm() As SqlParameter) As Long Dim cmd As New SqlCommand(cmdText, cn) cmd.CommandType = cmdType

AddParameters(cmd, prm) cn.Open()

Dim retVal As Long retVal = CType(cmd.ExecuteScalar(), Long) cn.Close()

Return retVal End Function Public Shared Function ExecuteDataSet( _ ByVal cn As SqlConnection, _

ByVal cmdText As String) As DataSet Return ExecuteDataSet( _

cn, CommandType.Text, cmdText, Nothing) End Function

Public Shared Function ExecuteDataSet( _ ByVal cn As SqlConnection, _

ByVal cmdType As CommandType, _ ByVal cmdText As String) As DataSet Return ExecuteDataSet( _

cn, cmdType, cmdText, Nothing) End Function

Public Shared Function ExecuteDataSet( _ ByVal cn As SqlConnection, _

ByVal cmdType As CommandType, _ ByVal cmdText As String, _ ByVal ParamArray prm() As SqlParameter) As DataSet Dim cmd As New SqlCommand(cmdText, cn)

Listing 15.1 Data component code This code contains common methods that encapsulate

access to the database This code is used throughout this chapter (continued)

Trang 17

cmd.CommandType = cmdType AddParameters(cmd, prm) Dim ds As New DataSet() Dim da As New SqlDataAdapter(cmd) da.Fill(ds)

Return ds End Function Private Shared Sub AddParameters( _ ByVal cmd As SqlCommand, _

ByVal prm() As SqlParameter)

If prm Is Nothing Then Return

End If Dim p As SqlParameter For Each p In prm cmd.Parameters.Add(p) Next

End Sub End Class

Listing 15.1 (continued)

The methods that have been defined in Listing 15.1 are shared (static),which means that it is not necessary to create an instance of the Db class first.The method can be called by using simply the name of the class as follows:

x = Db.ExecuteScaler(cn, “Select count(*) from customers”)

The Db class contains a method called ExecuteScaler that is overloaded so itcan be called with a connection and SQL, or with additional arguments TheExecuteScaler method returns the first column of the first row from the resultset of the query This method is typically used to retrieve a numeric value, sothe return type is cast to a Long, using the CType function

The ExecuteDataSet method contains the same overloads as the cuteScaler method This method returns a DataSet that could contain manytables if the SQL command contained many select statements

Exe-The AddParameters method is a private helper method that is used to merate a parameter array and add each parameter to the command’s parame-ters collection

enu-After this code is added to the project, the project must be built Building theproject creates a dll file, which is an assembly The assembly can be revealed

by clicking Show All Files in the Solution Explorer

Trang 18

Using the Component

Using and reusing a component can save lots of development time In this tion, a new Web project is created that uses the DataComponent assembly Forthe purposes of these examples, a second copy of Visual Studio NET isopened, and a new Web site is created

sec-Setting a Reference to the Component

Using the component requires telling Visual Studio NET that the externalassembly is to be used with a project This is done by setting a reference Thereference is added to the Web project by right-clicking the References node inthe Solution Explorer and clicking Add Reference

The Add Reference dialog box has three tabs; NET, COM, and Projects Ifthe component was written with Visual Studio NET, the NET tab could beused to Browse to the desired folder Selecting the dll file using this methoddoes not cause the assembly to be rebuilt when the current project is built

The COM tab is used to set references to COM components If a reference isset to a COM component, Visual Studio NET creates a COM Callable Wrapperclass, that can be used to access the COM component

The Project tab is used to set a reference to a project instead of an assembly.Setting a reference to a project tells Visual Studio NET that the project must bebuilt prior to building the current project This essentially sets up the buildorder for the solution The only projects that are visible in this tab are the pro-jects that are in the current solution This means that the DataComponent proj-ect must be loaded in the current solution to be able to select it Setting areference to the project is generally considered to the best selection, becausebuilding the solution builds all of the projects in the correct order

In this example, a reference is set to the DataComponent.dll assemblyinstead of the project This allows the projects to be out of sync for the testingpurposes

Calling the Component

In the new Web project, the following code has been added to the Web page totest the ExecuteScaler functionality

Imports DataComponent Imports System.Data.SqlClient Public Class WebForm1

Inherits System.Web.UI.Page Private Sub Page_Load( _

Trang 19

ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim cn As New SqlConnection( _

“server=.;database=northwind;trusted_connection=true”) Dim x As Long

x = Db.ExecuteScaler( _

cn, “Select count(*) from customers”) Response.Write(“Count of Customers=” & x.ToString()) End Sub

End Class

When the application is run, a Web page is displayed that contains the count

of the customers in the customers table

To test the ExecuteDataSet functionality, a Datagrid is added to the Webpage, and it displays the contents of the DataSet that is returned from the Exe-cuteDataSet method The page now contains the following code:

Imports DataComponent Imports System.Data.SqlClient Public Class WebForm1

Inherits System.Web.UI.Page Protected WithEvents DataGrid1 As System.Web.UI.WebControls.DataGrid Private Sub Page_Load( _

ByVal sender As System.Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load

Dim cn As New SqlConnection( _

“server=.;database=northwind;trusted_connection=true”) Dim x As Long

x = Db.ExecuteScaler( _

cn, “Select count(*) from customers”) Response.Write(“Count of Customers=” & x.ToString()) Dim SQL As String

SQL = “Select “ _

& “ CustomerID, CompanyName, ContactName, ContactTitle “ _

& “ from customers “ _

& “ where CompanyName like ‘A%’”

DataGrid1.DataSource = Db.ExecuteDataSet(cn, SQL) DataBind()

End Sub End Class

The browser output is shown in Figure 15.1 The advantage of using theDataComponent is that the developer did not need to be concerned about the specifics of accessing the database, and this saved several lines of code

in the Web project This component, which is compiled into an assembly, isavailable for use in many applications

Trang 20

Figure 15.1 The DataComponent simplifies access to the data store.

Locating the Component at Run Time

Some questions that may come to mind are, How is the reference to the project

or assembly stored in the Web application? Does the dll file need to be in thesame folder as it currently is in when the Web application is deployed? WhatRegistry entries are required on the production Web server in order to get theWeb application to locate the DataComponent?

The NET common language runtime needs to locate and bind to the bly at run time The process or set of steps and logic involved in locating theassembly is called probing Probing is discussed in more detail a little later inthis chapter

assem-Figure 15.2 Setting a reference to an external assembly automatically creates a copy of the assembly to the bin folder of the Web application.

Trang 21

Currently, the common language runtime is located in the DataComponent

by searching in the same directory as the Web application’s assembly, which isthe bin folder of the Web application There’s no mistake in that statement;when the reference was set to the DataComponent project, a copy of theassembly was made to the Web application’s bin folder, as shown in Figure15.2 The copy was only made if the DataComponent was built prior to settingthe reference to the project If the assembly doesn’t exist, it is copied when thesolution is built

Assembly Versioning

When an assembly is built, its current version is stored in the manifest data of the assembly The version can be set by using an assembly attributecalled AssemblyVersion By default, this attribute is located in the Assembly-Info.vb file of each project The default value for this attribute is as follows:

meta-<Assembly: AssemblyVersion(“1.0.*”)>

The assembly version is made up of four numbers, as shown in Figure 15.3.The first two numbers indicate the major and minor version of the assembly Achange to the major or minor version number usually indicates that the assem-bly contains new functionality, either by adding or changing properties,method, or events By default, assemblies that have different major and minorversion numbers are not considered to be compatible

The third number of the version represents the revision of the assembly Therevision number is usually updated when applying service packs No assump-tion of compatibility can be made between different revision numbers

Figure 15.3 The versioning of an assembly.

Major 3

Minor 0

Revision 24

Build 1109

Incompatible May Be

Compatible (Service Packs)

<Assembly: AssemblyVersion("1.0.*")>

• Assembly version is automatically updated

Revision = days since 1/1/2000 Build = seconds since midnight divided by 2

• To fix the version, manually type it:

<Assembly: AssemblyVersion("3.0.24.1109")>

Always Compatible (QFEs)

Trang 22

The fourth number of the version represents the build of the assembly.Assemblies that have the same major, minor, and revision numbers, but have

a different build number are considered to be compatible An assembly with adifferent build number is usually deployed to correct software bugs throughQuick Fix Engineering (QFE) builds

When using the asterisk to provide autonumbering of the assembly, thethird number contains the number of days since January 1, 2000, and thefourth number contains the number of seconds since midnight, divided bytwo Depending on the current daylight savings setting, this number may start

at midnight or 1:00 A.M.The System.Version class can be used to obtain the version of an assembly.The following code has been added to the DataComponent to allow retrieval

of the version of the assembly:

‘Add Imports System.Reflection to top of this code file.

Public Shared ReadOnly Property Version() As Version Get

Dim a As [Assembly] = [Assembly].GetExecutingAssembly() Dim aName As AssemblyName = a.GetName()

Return aName.Version End Get

End Property

This code requires the Imports System.Reflection directive at the top of thecode file because the System.Reflection namespace contains the Assemblyclass and the AssemblyName class The Assembly class is enclosed withinbrackets because Assembly is also a keyword The Assembly class has severalshared methods for obtaining a reference to an assembly In this case, GetExe-cutingAssembly method returns a reference to the DataComponent assembly.The Version class contains properties called Major, Minor, Revision, andBuild The ToString method provides the version as a string Also, the opera-tors =, <>, <, >, >=, <= are overloaded to allow comparison of versioninstances Visual Basic NET does not support operator overloading, but meth-ods exist that Visual Basic NET can use to perform comparisons as shown inFigure 15.4 These methods are static methods, and can be called as follows:

If Version.op_equality(myVersion,yourVersion) then Response.Write(“The versions are equal”) End If

Trang 23

Figure 15.4 The Object Browser, displaying the Version class and its methods Notice the Assembly and AssemblyName classes in the System.Reflection namespace.

The Web page has been updated to display this version of the assembly Thiscomes in handy in some of the later examples The following line of code hasbeen added to the Page_Load event method:

Deployment of Web applications that use private assemblies is simply amatter of copying the files to the new location, and creating a Web share, aswas done in Chapter 2, “Solutions, Projects, and the Visual Studio NET IDE.”The common language runtime probes for the DataComponent in the binfolder of the Web application

By default, there is no runtime version control on private assemblies Thismeans that different versions of the assembly simply can be copied into the binfolder of the Web site Assuming that the assemblies are compatible, theASP.NET starts using the new assembly

Trang 24

Private assemblies are considered to be the deployment model of choice

by some people Be careful, because although it is simple to deploy assemblies by simply copying the files to the destination, this could become unmanageable as an assembly is used with many applications.

Shared Assemblies are covered in this chapter, which is a more manageable choice.

When working with private assemblies, the common language runtimelooks for the assembly in the same folder as the Web application, which is thebin folder The common language runtime starts by looking for the assembly

by its friendly name plus the dll extension If the file is not found, the commonlanguage runtime attempts to locate the assembly by using its friendly nameplus the exe extension

Figure 15.5 The probing sequence that the common language runtime uses when locating a private assembly that has no strong name.

In dir with same name as assembly?

In application directory?

No

In private path dir(s)?

In privatePath defined?

Checked for EXE?

Yes

Yes

Yes

In AspNet temp file cache?

No

Bind TypeLoadException

Probe for assembly

No

No No

Yes Yes

No - Repeat tests, look for exe file

Look for dll file first

Trang 25

If the assembly is not found in the bin folder, the common language runtimechecks for the existence of a folder that has the same name as the assembly’sfriendly name If the folder exists, the common language runtime attempts tolocate the assembly in that folder.

It may be desirable to place all of the referenced assemblies in a commonsubdirectory This can be done by placing a probing privatePath directive intothe Web.config file as follows:

fold-Side-by-Side Versioning

Copying over the assembly in one Web application does not affect privateassemblies for other Web sites This means that version 2.0.0.0 of the Data-Component assembly can be running in one Web site, and version 3.0.0.0 of theDataComponent assembly can be running in a different Web site on the samecomputer

Side-by-side versioning was impossible when using traditional COM ponents, because the Registry contained the location information for a COMcomponent, and there was only one setting for any given COM component.With the NET Framework, no Registry entries need to be made for the com-mon language runtime to locate an assembly This eliminates the problem thatCOM components had, whereby an older version of a dll file was installed on

com-a system com-and ccom-aused the newer progrcom-ams thcom-at used com-a newer version of the dllfile to break This was commonly referred to as DLL Hell

Trang 26

Strong-Named Assemblies

Being able to copy over an assembly that is being referenced may be a benefit,but can also be problem The reason that this is allowable is because the assem-bly is private, and private assemblies do not need to have a strong name

A strong name is a unique name that is assigned to an assembly, whichwould force the version to be the version that was compiled with the applica-tion, unless the version is explicitly overridden

A strong name consists of the assembly’s friendly name, which is the name

of the assembly without the file extension (.dll), version number, culture mation, plus a public key and a digital signature Visual Studio NET canassign strong names to an assembly when the assembly is compiled Twoassemblies with the same strong name are considered to be identical

infor-Strong names guarantee name uniqueness by using a public and private keypair Only the entity that holds the private key can create an assembly with thesame strong name This means that the private and public keys provide amethod of identifying the entity that created the assembly

Strong names are used to maintain the version lineage of an assembly Astrong name ensures that nobody can produce a different version of an assem-bly if they don’t have the private key Users can be certain that a version of astrong-named assembly comes from the original publisher

Strong names provide an integrity check that guarantees that the contents ofthe assembly have not been tampered with since the assembly was compiled

Be careful, a strong name does not guarantee that a publisher is who it says

it is The strong name only states that the publisher is the same as in the ous versions To be sure that the publisher is who it says it is, the assemblyshould contain a digital signature and digital certificate

previ-When you reference a strong-named assembly, versioning enforcement isprovided as well as naming protection Also, strong-named assemblies can ref-erence only other strong-named assemblies

Creating a Strong-Named Assembly

Creating a strong-named assembly requires a public and private key pair The key pair can be generated by using the strong-name utility (sn.exe) Thestrong-name utility is a console application that can be run by starting theVisual Studio NET command prompt and executing the following command:

Sn.exe –k c:\myKey.snk

Trang 27

This creates a key pair, stored in the myKey.snk file This file contains boththe private and public key, and should be stored and protected This programshould only be run once to create the key pair Every strong-named assemblyshould use the same key pair Keep in mind that the key pair is used to iden-tify the publisher, and the key is required to maintain the version lineage onthe assemblies.

After the key pair is obtained, there are two things that need to be done inthe component project: assign a fixed version number and assign the key file

to the assembly The AssemblyInfo.vb file contains the AssemblyVersionattribute, which simply can be edited By default, the AssemblyKeyFileattribute is not included in the AssemblyInfo.vb file, but this can be added.The following changes have been made to the DataComponent project’sAssemblyInfo.vb file:

Imports System.Reflection Imports System.Runtime.InteropServices

‘ General information about an assembly is controlled

‘ through the following set of attributes Change these

‘ attribute values to modify the information

‘ associated with an assembly.

‘ Review the values of the assembly attributes.

<Assembly: AssemblyTitle(“Data Component”)>

<Assembly: AssemblyDescription(“Provides easy access to SQL Server”)>

‘ The following GUID is for the ID of the typelib if this

‘ project is exposed to COM.

<Assembly: Guid(“921E7039-7D26-40A2-9A51-FA105B6D717F”)>

‘ Version information for an assembly consists of the

‘ following four values:

‘ Major Version

‘ Minor Version

‘ Build Number

‘ Revision

‘ You can specify all the values or you can default the

‘ Build and Revision Numbers

‘ by using the ‘*’ as shown below:

<Assembly: AssemblyVersion(“2.0.0.0”)>

<Assembly: AssemblyKeyFile(“c:\myKey.snk”)>

The significant changes are the last two lines These changes automaticallycreate this assembly as a strong-named assembly The strong name, or fullname, of the compiled assembly is as follows:

Trang 28

DataComponent, Version=2.0.0.0, _

Culture=neutral, PublicKeyToken=4fa8f612df7c8110

The strong name consists of the friendly name, the version, the culture(which should always be set to neutral for the main assembly file), and thepublic-key token The public-key token represents an abbreviated version ofthe public key

In Chapter 13, “Site Security,” code access security was covered One of theimportant considerations when using code access security is the strength ofthe evidence Different permissions may be provided based on a public-keytoken For example, Microsoft has granted itself full permissions, based ontheir public key There may be situations in which it is important to grant a cer-tain company’s code more permissions than those that are normally granted.This can be easily done at the company level if the company only has a singlepublic key Figure 15.6 shows how a code group can be added forMyCompany, based on a public key All code that is published by MyCompanyhas the permissions that are assigned to the code group

When the DataComponent assembly is compiled, the assembly’s manifestcan be viewed with ILDASM.exe and contains the public key, as shown in Fig-ure 15.7 Also notice that the version has been updated to reflect the fixed set-ting of version 2.0.0.0

Figure 15.6 The code group is added for MyCompany based on the public-key evidence.

Trang 29

Figure 15.7 The public key is included in the manifest of a strong-named assembly.

Using Strong-Named Assemblies

When an assembly is referenced in an application, a record of the referencedassembly is included in the application assembly’s manifest If the assemblydoes not contain a string name, the manifest records the friendly name andversion of the referenced assembly The following is an example of the mani-fest data for the DataComponent when the DataComponent does not have astrong name

.assembly extern DataComponent {

ver 1:0:1073:39385 }

Although the version is recorded, the version is not used to enforce ing because this is not a strong-named assembly

version-When a strong-named assembly is referenced in an application, the record

of the assembly contains the friendly name, the public-key token, and the sion The presence of the public-key token indicates that this is a strong-namedassembly, and the version number is enforced

ver-.assembly extern DataComponent {

.publickeytoken = (4F A8 F6 12 DF 7C 81 10 ) // O |

.ver 2:0:0:0 }

The Web application has been compiled with version 2.0.0.0 of the Component If the DataComponent has been updated to version 2.0.0.1 andthe new version is copied to the bin folder of the Web application (copyingover private assembly version 2.0.0.0 of DataComponent), an error message isdisplayed in the browser, as shown in Figure 15.8

Trang 30

Data-Figure 15.8 Copying a new version of a private strong-named assembly over the old version generates an error, because the Web application is enforcing versioning.

Fusion Log Viewer (FusLogVw.exe)

Although Figure 15.8 displays a message stating that the DataComponentassembly has a problem, it’s not too clear as to the actual problem To see moreinformation, the NET Framework SDK contains a tool called the Fusion LogViewer (FusLogVw.exe) This tool can be used to get more detailed informa-tion about the error

To use FusLogVw.exe with ASP.NET, the processModel account must be set

to System The processModel account setting is located in the machine.config

file After changing this setting, either reboot the machine, or execute iisresetfrom the command prompt

The Fusion Log Viewer utility also can be tweaked to display all bindingsinstead of the failures This can be a handy learning tool, and also can be usedwhen an assembly is actually loading, but it’s not the assembly that shouldhave loaded To view all assembly bindings, add the following key into theRegistry:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion\ForceLog=dword:1

The Fusion Log Viewer displays an entry in its window indicating the cation, the assembly, and the date Double-click the application to display thefollowing information when version 2.0.0.0 is overwritten with version 2.0.0.1

appli-of the DataComponent:

Trang 31

*** Assembly Binder Log Entry (12/9/2002 @ 11:59:38 PM) ***

The operation failed.

Bind result: hr = 0x80131040 No description available.

Assembly manager loaded from:

C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\fusion.dll Running under executable

C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\aspnet_wp.exe - A detailed error log follows

=== Pre-bind state information ===

LOG: DisplayName = DataComponent, Version=2.0.0.0, Culture=neutral, PublicKeyToken=4fa8f612df7c8110

(Fully-specified) LOG: Appbase = file:///D:/AspDotNetBook/Book/Building and Versioning NET Components/Ch15Web

LOG: DEVPATH = C:\DevAssemblie LOG: Initial PrivatePath = bin LOG: Dynamic Base =

C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\Temporary ASP.NET Files\ch15web\0baf2047

LOG: Cache Base = C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\Temporary ASP.NET Files\ch15web\0baf2047

LOG: AppName = 5feb88b4 Calling assembly : Ch15Web, Version=1.0.1073.42703, Culture=neutral, PublicKeyToken=null.

===

LOG: Processing DEVPATH.

LOG: Unable to find assembly in DEVPATH location:

C:\DevAssemblie\DataComponent.DLL.

LOG: Unable to find assembly in DEVPATH location:

C:\DevAssemblie\DataComponent.EXE.

LOG: Unable to find assembly in DEVPATH.

LOG: Publisher policy file is not found.

LOG: No redirect found in host configuration file (C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\aspnet.config).

LOG: Using machine configuration file from C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\config\machine.config LOG: Post-policy reference: DataComponent, Version=2.0.0.0,

Culture=neutral, PublicKeyToken=4fa8f612df7c8110 LOG: Cache Lookup was unsuccessful.

LOG: Attempting download of new URL file:///C:/WINDOWS/Microsoft.NET/Framework/v1.0.3705/Temporary ASP.NET Files/ch15web/0baf2047/5feb88b4/DataComponent.DLL.

LOG: Attempting download of new URL file:///C:/WINDOWS/Microsoft.NET/Framework/v1.0.3705/Temporary ASP.NET Files/ch15web/0baf2047/5feb88b4/DataComponent/DataComponent.DLL.

Trang 32

LOG: Attempting download of new URL file:///D:/AspDotNetBook/Book/Building and Versioning NET Components/Ch15Web/bin/DataComponent.DLL.

LOG: Assembly download was successful Attempting setup of file:

D:\AspDotNetBook\Book\Building and Versioning NET Components\Ch15Web\bin\DataComponent.DLL

LOG: Entering download cache setup phase.

WRN: Comparing the assembly name resulted in the mismatch:

Revision Number ERR: The assembly reference did not match the assembly definition found.

ERR: Setup failed with hr = 0x80131040.

ERR: Failed to complete setup of assembly (hr = 0x80131040)

Probing terminated.

The pre-bind state information displays the assembly that the Web tion requires The last lines of this log entry shows that DataComponent.dllwas found, but the Revision Number did not match

applica-The Fusion Log Viewer should be used to assist with any errors when anapplication is failing to locate a referenced assembly

Shared Assemblies

Shared assemblies are assemblies that are located in a common repository,called the Global Assembly Cache (GAC) Shared assemblies can be used byany application on the computer Installing assemblies into the Global Assem-bly Cache provides the ability to keep a single copy of each version of anassembly on the machine, in a common location This simplifies assemblymanagement and minimizes the quantity of assembly copies that are located

on the machine

By default, the Global Assembly Cache is located in the %SystemRoot%\Assembly folder For example, on most Windows 2000 computers, this isthe C:\Winnt\Assembly folder, while on Windows XP computers this is theC:\Windows\Assembly folder

Installing an assembly into the Global Assembly Cache requires the bly to have a strong name The assembly can be dragged and dropped into theGlobal Assembly Cache folder Figure 15.9 shows the Global Assembly Cacheafter dragging and dropping version 2.0.0.0 and version 2.0.0.1 of the Data-Component into it

assem-The accompanying sidebar, How Does the Assembly Folder Hold Multiple Copies

of Files That Have the Same Filename? explains how the Global Assembly Cache

can maintain multiple copies of files that have the same name

Trang 33

Figure 15.9 The Global Assembly Cache after dragging and dropping version 2.0.0.0 and version 2.0.0.1 of the DataComponent into it.

The NET Framework also includes a program called the GacUtil.exe, whichcould be used to install and uninstall assemblies with a batch file The GacUtilprogram can be run from the Visual Studio NET Command Prompt, and thisutility has options for adding, deleting, and list assemblies that are in theGlobal Assembly Cache

When working with shared assemblies in a development environment, it may

be more desirable to set a lookup path to the location of the component project’soutput, rather than continuously moving the component into the Global Assem-bly Cache This can be done by assigning a lookup path to the DEVPATH systemenvironment variable For example, if the component project is in the c:\myComponent folder, the DEVPATH could be set to C:\myComponent\Bin\ toindicate the location of the myComponent.dll assembly

After the DEVPATH environment variable is set, the following entry needs

to be added to the machine.config file:

Trang 34

♦ How Does the Assembly Folder Hold Multiple

Copies of Files That Have the Same Filename?

When a file such as DataComponent.dll exists in a folder and a new version of this file is copied into the folder, the new copy overwrites the old copy So how can this folder behave differently?

Although the Global Assembly Cache appears as a single folder, it is really a folder ture A COM component called shfusion.dll is responsible for presenting the pretty output that is shown in Figure 15.9 To reveal the folder structure that is hidden by shfusion.dll, simply unregister the shfusion.dll component This can be done by starting the Visual Stu- dio NET Command Prompt, which is located in the Visual Studio NET Tools menu At the prompt, the following information can be typed:

struc-Regsvr32 –u shfusion.dll

After the shfusion.dll file is unregistered, opening the Assembly folder reveals two porary folders and a folder called GAC and another folder called NativeImage1_version

tem-The NativeImages folder contains NET components that have been precompiled using the ngen.exe utility If a NET assembly has been precompiled with ngen.exe, it is not JIT compiled when it is run

The GAC folder contains the NET components that are shared on the machine nents that are in the GAC folder must have strong names Navigating further into the folder structure of the GAC, there is actually a folder for each assembly name Inside the Data- Component folder, there is a folder called 2.0.0.0 4fa8f612df7c8110 and another folder called 2.0.0.1 4fa8f612df7c8110 (see Figure 15.10) These folders contain the actual ver- sions of the DataComponent that were dragged and dropped into the assembly folder.

Compo-Figure 15.10 The two DataComponent.dll files are actually in two different folders.

continued

Trang 35

The DEVPATH environment variable only works with strong-namedassemblies This setting is ignored for assemblies without strong names.

Assembly-Binding Policies

Although strong-named assemblies provide enforcement of versioningbetween the Web application and the referenced assembly, there are manycases where it is desirable to copy a new version of an assembly to the Webserver, without being forced to recompile the Web application

Performing a version redirect is a function of assembly policies The fourprimary types of assembly polices are application, publisher, ASPNET, andadministrator

Changes that are made to the application policy are unique to the Web cation Changes that are made to the publisher policy are global to themachine Changes that are made to ASPNET policy apply to all Web sites onthe machine Changes to the administrator policy override all other policiesand are global to the machine

appli-Each policy is applied in a specific order as shown in Figure 15.11 TheApplication policy is stored in the Web.config file This policy is evaluatedfirst If the application required version 2.0.0.0 of the DataComponent assem-bly, the application binding could be redirected to a different version, such asversion 2.0.0.1 of the assembly The application policy also has the ability toskip over evaluation of the publisher policy by using the optional publisher-Policy attribute

♦ How Does the Assembly Folder Hold Multiple

Copies of Files That Have the Same Filename?

(continued)

In reality, the shfusion.dll file displays a flattened version of this folder hierarchy, which is how files with the same filename can be dropped into the GAC without the files overwrit- ing each other.

After viewing the folder structure, the shfusion.dll must be registered as follows:

regsvr32 shfusion.dll

Use this command to reregister the shfusion.dll component any time that the folder out is visible in the assembly folder.

Trang 36

lay-The following XML code performs a redirect from version 2.0.0.0 to version2.0.0.1 and directs the runtime to skip the publisher policy:

The assembly-binding redirect does not have to go from a lower to higherversion number It is possible to redirect from any version to any version

Figure 15.11 The assembly-binding policy order.

Application - Give me DataComponent version 2.0.0.0

Application Policy Web.config Ask for 2.0.0.0? Deliver 2.0.0.1

Publisher Policy policy.2.0.DataComponent.dll Ask for 2.0.0.1? Deliver 2.0.0.2

ASPNET Policy ASPNET.config Ask for 2.0.0.2? Deliver 2.0.0.3

Administrator Policy Machine.config Ask for 2.0.0.3? Deliver 2.0.0.4

Optionally Skip Publisher

<publisherPolicy apply="no" />

Trang 37

Notice that the strong name is composed of the friendly name of the bly, the public-key token, the culture, and the version What happens if twovendors supply an assembly with the same name, a different version, and thesame culture? If the public-key token is different, the two assemblies, eventhough they have the same filename, have different version lineages One doesnot interfere with the other

assem-What happens if a company loses their key pair and simply creates a newkey pair for the next release of their program? When this program is installed,the program appears to have been written by a different company There is noway to create a binding policy to redirect from one version with key A to a dif-ferent version with key B because this is like trying to perform a redirect fromcompany A to company B This means that every effort should be taken to pro-tect the key pair from being lost or stolen

Microsoft NET Framework Configuration Tool

The Microsoft NET Framework Configuration Tool is an administration toolthat can be used to configure the application (Web.config) and administrator(machine.config) policies This tool can be executed from the AdministrativeTools menu

The application policy for a Web application can be edited by right-clickingApplications, clicking Add, and then navigating to the Web.config file, asshown in Figure 15.12

Figure 15.12 Add the Web.config file to the list of applications

Trang 38

Figure 15.13 The Binding Policy tab is used to redirect the binding to a different version.

After the Web application is added, a configured assembly can be added toset the binding policy for the assembly The assembly can be selected from theGlobal Assembly Cache, and the settings can be entered as shown in Figure15.13 The General tab also allows the Publisher Policy to be overridden, whilethe Codebases tab allows the entry of a download location The changes aresaved to the Web.config file

The Microsoft NET Framework Configuration Tool also allows globalchanges on the machine by configuring an assembly at the computer level Thechanges that are made at this level are saved to the machine.config file

Publisher Policies

Creating publisher policies requires more work than the other policies Thevendor or publisher can specify that a new version of an assembly should beused Publisher policies are compiled to dll files and placed into the GlobalAssembly Cache By default, the publisher policy overrides the applicationpolicy but this can be also overridden

Creating a publisher policy requires an XML file with the binding redirectinformation An example of the XML file is as follows:

Trang 39

In this example, the link switch is the name of the binding policy file source XML file The out switch is the name of the output file, which has a special syn- tax The filename must start with the word policy, followed by the major and minor version of the source assembly that is redirected The keyfile switch is the

name of the key file that should be used for all assemblies, including this one

The version is the version of this assembly.

The version switch is the version of the publisher policy If multiple versions of the publisher file exist, the highest version number is automatically used

After the policy.2.0.DataComponent.dll file is created, it must be installedinto the Global Assembly Cache This can be done by dragging and droppingthe file into the Global Assembly Cache, or by using the gacutil.exe tool

Probing for Assemblies

When an assembly needs to be located, there is a series of checks to locate theassembly The process of locating an assembly is called probing

The first thing that the class loader checks is that the DEVPATH ment variable exists, and that the assembly exists at the location that is pointed

environ-to in the DEVPATH, as shown in Figure 15.14

Next, the assembly is checked to see if it has a strong name If the assemblydoes not have a strong name, the class loader searches for a dll file that has thesame name as the assembly’s friendly name plus the dll extension First, theASP.NET’s temporary file cache is checked Next, the application’s bin folder

is searched for the dll file

Trang 40

Figure 15.14 The runtime probes many locations for an assembly.

Probing continues to check for the dll in the bin\myComponent folder If it

is not found, probing checks the Web.config to see if a privatePath has beenconfigured If so, each of the paths that are configured in the privatePath vari-able is searched

If the dll file has not been found, probing starts over, but this time the search

is for an exe file If the exe file is not found, a TypeLoadException occurs

If the assembly has a strong name, the assembly policies are applied Afterthe policies are applied, the class loader looks for the assembly in the GlobalAssembly Cache

If the assembly is not is the Global Assembly Cache, the class loader checks

to see if a publisher codebase or application codebase exists If neither exists,probing continues in the application directory, and follows the same path as itwould for an assembly without a strong name

Cross-Language Inheritance

A new benefit of NET components is that they support cross-language itance For example, a component that has been written in C# can be used as abase class for a new Visual Basic NET component This allows a developer to

inher-In AspNet temp file cache?

In application directory as dll?

Is privatePath defined?

Is private path dir(s) as dll?

Checked for EXE?

In dir with same name as assembly as dll?

Strong name?

Apply policies

Is DEVPATH Set?

In Global assembly cache?

Is Admin codeBase defined?

Is Publisher codeBase defined?

Is app codeBase defined?

Yes

Yes Yes

Yes

Yes Yes

Yes Yes

Yes Yes Yes Yes

No

No No No

No

No

No

No

No - Look for dll file first

No - Look for dll file first

No - Repeat tests, look for exe file

No

Probe for assembly

TypeLoadException

Bind

Ngày đăng: 12/08/2014, 08:23

TỪ KHÓA LIÊN QUAN