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

Professional ASP.NET 1.0 Special Edition- P43 ppsx

40 236 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 40
Dung lượng 599,19 KB

Nội dung

Response.Write("Hello there") This has its biggest impact when switching between the ASP and ASP.NET environments. Method Arguments By default, arguments to methods in Visual Basic .NET are now passed by value, rather than by reference. This means the following code will not work as expected: Sub Foo(X As Integer) X = X + 1 End Sub Dim Y As Integer = 3 Foo(Y) Response.Write("Y=" & Y.ToString()) The output here will be 3, rather than 4. To correct this you need to change the procedure declaration to: Sub Foo(ByRef X As Integer) Default Properties The use of default properties is not allowed in Visual Basic .NET. This doesn't affect .NET components, since there's no way to define a default property, but it has an impact when accessing COM objects. For example, the following would not be allowed: Dim rs As New ADODB.Recordset Dim Name As String rs.Open(" ", " ") Name = rs("Name") The last line in .NET would be: Name = rs("Name").Value While this does mean more typing, it makes the code much more explicit, and therefore less prone to potential errors. Set and Let The Set and Let keywords are no longer required for object references. For example, the following is now the accepted syntax: Dim conn As SQLConnection conn = SQLConnection There's no need for the Set keyword before the object assignment. Single and Multiple Lines In Visual Basic .NET, all If statements must be constructed across multiple lines. For example, in VBScript you could do this: If x > y Then foo() In Visual Basic .NET this becomes: If x > y Then foo() End If JScript .NET JScript .NET remains much closer to its pre- .NET version. As far as ASP.NET programmers are concerned, the most obvious difference is in data types. Variables can now be declared using the following syntax: var variableName : DataType [= value] For example: var Name : String var Age: Integer = 24 Functions also have the addition of data types: function foo() : Boolean { return True; } Implicit Type Conversion Data types can be implicitly converted using the following syntax: TypeName(expression) For example: var d : double = 123.456 var i : Integer = int(d) Interoperability No matter how much we'd like to do all our coding in .NET, we have to face reality. There is an enormous amount of traditional ASP and COM code being used in web applications, and businesses cannot afford to just throw that away. The success of MTS/COM+ Services as a middle-tier business object layer has led to a large number of COM objects being used as, among other things, data layers, abstracting the data management code from the ASP code. With .NET, Microsoft has provided good interoperability for several reasons:  To preserve existing investment. Compatibility with existing applications means we can continue to use existing code, as well as preserve our existing investment.  Incremental Migration. There is no need to migrate everything at once if your new code can exist alongside other applications.  Some code will never change. There is probably plenty of code where the investment, time, or skill to migrate is not available. Although .NET is independent from COM, Microsoft has realized the need for interoperability, and provided ways to use not only COM objects from within .NET, but also .NET components from within COM. They've realized that there had to be a way to call down to the Windows API, for those that need to. This chapter just gives an introduction into the interoperability issues. For a more detailed look consult the Wrox Press book Professional Visual Basic Interoperability - COM and VB6 to .NET, ISBN 1-861005-65-2. This chapter uses the term COM as a generic term for COM and COM+ purely to improve legibility. From the interoperability point of view there is no difference. Crossing the Boundary We know that .NET code is managed by the CLR, and that COM code is not, so there has to be some way to cross the managed/unmanaged code boundary. One of the major problems is the conversion of data types, but the CLR handles this for us: When crossing this boundary we have to think about the differences between the two systems. Architecturally these are: Unmanaged Code has … Managed Code has … Binary standard Type standard Type libraries Meta data Immutable types Version binding DLL hell Versioned assemblies Interface based Object based HResults Exceptions GUIDS String names Additionally, there are the programming differences: Unmanaged Code has … Managed Code has … CoCreateInstance new operator QueryInterface Cast operator Reference counting Memory management and garbage collection GetProcAddress Static methods The unmanaged way of doing things doesn't affect ASP or ASP.NET, but does affect those of us who also write COM and use components. Data Type Marshalling When we cross the managed/unmanaged boundary, the wrappers automatically perform data type mapping for us. So, although we don't need to know how this works, it's useful to see what language types map to in .NET. There are two kinds of data types as far as marshalling goes:  Blittable types. These are the same on both sides of the boundary, and therefore don't need any conversion.  Non-Blittable types. These are different on either side of the boundary, and therefore require conversion. The table below details the pre NET data types, and what they map into in .NET: C++ Visual Basic 6 .NET Blittable signed char Not supported SByte Yes unsigned char Byte Byte Yes short Integer Short Yes unsigned short Not supported UInt16 Yes int Long Integer Yes unsigned int Not supported UInt32 Yes __int64 Not supported Long Yes unsigned __int64 Not supported UInt64 Yes float Single Single Yes double Double Double Yes BSTR String String No BOOL Boolean Boolean No VARIANT Variant Object No IUnknown object UnmanagedType.IUknown No DATE Date Date No CURRENCY Currency Decimal No __wchar_t Char Char Yes void Not supported Void Yes Simple arrays (single dimensional arrays of blittable types) are themselves defined as blittable types. Custom Type Marshalling For blittable types, the marshaller always knows both the managed and unmanaged type, but this isn't so for non-blittable types (such as strings or multi-dimensional arrays). By default the following conversion takes place: Managed Type Unmanaged Type Boolean A 2 or 4 byte value ( VARIANT_BOOL or Win32 BOOL), with True being 1 or -1. Char A Unicode or ANSI char (Win32 CHAR or CHAR). String A Unicode or ANSI char array (Win32 LPWSTR/LPSTR), or a BSTR. Object A Variant or an interface. Class A class interface Value Type Structure with fixed memory layout Array Interface or a SafeArray For non-blittable types, we can specify how they are marshalled across the boundary. This is really beyond the scope of this book, but is well detailed in the .NET SDK help file, under " Programming with the .NET Framework", "Interoperating with Unmanaged Code ", and "Data Marshalling". HRESULTS In Windows, the standard method of handling errors is via the use of HRESULTS. When crossing the boundary to .NET these are automatically converted to exceptions, with the HRESULT details being stored as part of the exception object. This means that we can use COM objects without sacrificing the structured exception handling that .NET brings us. For this to work the COM object must support the ISupportErrorInfo and IErrorInfo interfaces. Using COM Objects from .NET Using COM components from .NET is extremely simple, as there is a tool that takes a COM component or type library and creates a managed assembly (a callable wrapper) to manage the boundary transition for us. The diagram below shows how this wrapper is used: From the programming perspective all we have to do is call methods and access properties as we would with the COM component. The difference is that we'll be calling the wrapper class, which will take the .NET types, convert them to COM types, and call the COM interface methods. The CLR maintains the reference to the COM object, so COM reference counting works as expected, while also providing the simplicity of garbage collected references for the .NET usage of the object. There are several ways in which we can generate the wrapper class:  Adding a reference in Visual Studio .NET.  Using the type library import tool.  Using the type library convert class.  Creating a custom wrapper. Of these, the first two are by far the easiest. Using Visual Studio .NET In Visual Studio .NET all we have to do is create a reference to the COM object, and the wrapper class is created for us. First select References from the Solution Explorer, and then pick Add Reference…. Then, from the dialog that appears, select the COM tab, and pick your COM object: Once you've clicked Select and then OK, the reference is added. The wrapper class (in this case it would be ADODB.dll) is placed in the bin directory of the application. The Type Library Import Tool If you don't have Visual Studio .NET (or are a die-hard Notepad user) then you can use the type library import tool to create the wrapper class for you. The syntax is: tlbimp TypeLibrary [Options] where Options can be: Option Description /out:FileName The filename of the wrapper assembly to create. /namespace:Namespace Namespace of the assembly to be produced. /asmversion:version Version number of the assembly to be produced. /reference:FileName Assembly filename used to resolve references. This can be specified multiple times for multiple references. /publickey:FileName Filename containing the strong name public key. /keyfile:FileName Filename containing the strong name key pair. /keycontainer:FileName Key container holding the strong name key pair. /delaysign Force strong name delay signing. /unsafe Produce an interface without runtime security checks. /nologo Don't display the logo. /silent Don't display output, except for errors. /sysarray Map COM SafeArray to the .NET System.Array class. /verbose Display full information. /primary Produce a primary interop assembly. /strictref Only use assemblies specified with /reference. By default the output name will be the same as the COM type library, not the filename. For example: tlbimp msado15.dll will produce a wrapper assembly called ADODB.dll, not msado15.dll. The resulting assembly can then be copied into the application bin directory (or installed in the Global Assembly Cache), and referenced as with other .NET assemblies: <%@ Import Namespace="ADODB" %> The Type Library Convert Class [...]... this book, we have looked at the individual features of ASP.NET, such as web controls, data binding, configuration, and security Powerful though they are, these features are like pieces of a jigsaw puzzle; the final objective is to figure out how to put them together to create the big picture In this chapter, we are going to show you how to use ASP.NET to create a simple ntier ecommerce application... nIndex); public int GetMetrics(int Index) { return GetSystemMetrics(Index); } } } Using the API Class Using this API class wrapper is just like using any other class For example, consider the following ASP.NET page: Sub Page_Load(Sender As Object, E As EventArgs) Dim mt As New Metrics() Dim Width As Integer = mt.GetMetrics(MetricsValues.SM_CXSCREEN)... section in Chapter 17 Summary As mentioned earlier in the chapter, there's no denying that NET is an exceptional platform for application development Throughout this book you've seen the great features ASP.NET provides for writing first-class applications, and how those applications will have less code, be more reusable, and provide easier maintenance It would have been easy for Microsoft to leave it... this cannot be thrown away So, Microsoft has provided a way to integrate that existing investment with new development on the NET platform In this chapter we've examined the differences between ASP and ASP.NET, and how moving from VBScript to Visual Basic NET can be achieved with the least pain We've also examined how to allow NET to leverage existing COM infrastructures, as well as showing how COM can... SDK help file Using the Wrapper Assembly Using the wrapper assembly is simply a case of treating it like any other managed assembly For example, if you import the ADO namespace, you can use it in your ASP.NET pages like so: Sub Page_Load(Sender As Object, e as EventArgs) Dim rs As New ADODB.Recordset rs.Open("publishers", "Provider=SQLOLEDB;... AdventureWorks featured all the basic features of a typical e-commerce application, including product viewing and selection, user registration, and a shopping basket In this chapter, we are going to use ASP.NET to extend the AdventureWorks application into a new one called IBuyAdventure.NET, or IBA for short Throughout the rest of this chapter we are going to review the code and the functionality of this . issues. For a more detailed look consult the Wrox Press book Professional Visual Basic Interoperability - COM and VB6 to .NET, ISBN 1- 8 6 10 05-65-2. This chapter uses the term COM as a generic. becomes: If x > y Then foo() End If JScript .NET JScript .NET remains much closer to its pre- .NET version. As far as ASP. NET programmers are concerned, the most obvious difference. its biggest impact when switching between the ASP and ASP. NET environments. Method Arguments By default, arguments to methods in Visual Basic .NET are now passed by value, rather than by

Ngày đăng: 03/07/2014, 07:20