Visual Basic .NET The Complete Reference phần 2 pptx

67 373 0
Visual Basic .NET The Complete Reference phần 2 pptx

Đ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

.maxstack 8 .language '{3A12D0B8−C26C−11D0−B442−00A0244A1DD2}', '{994B45C4−E6E9−11D2−903F−00C04FA302A1}', '{00000000−0000−0000−0000− 00000000000}' In the above IL sample, we have highlighted the assembly name Vb7cr.dllwhich you can download from the Web−based sources listed in the Introduction to this book the root namespace Vb7cr and the entry point of the class. The Roles of the Assembly Let's now investigate the essential roles of an assembly, which can provide: A type boundary• A reference−scope boundary• A unit of deployment• A unit of execution• A version boundary• A security boundary• Assemblies as Type Boundaries On the file system, the assembly looks like any other dynamic link library. It usually carries the DLL extension, although it can also be a cabinet file (with the .CAB extension). You can build a class and make its source code available to any application. But you would mostly do that for your own use, and maybe for your development−team members. However, we suggest you don't provide "raw" classes to your team members, because with access to the actual Visual Basic source code, multiple problems can be introduced. You would only supply the raw source files if your user specifically requested or needed themsuch as readers of this book, or your customers who have opted to buy the source code of your components (usually as a safeguard against your going out of business). The best examples of assemblies are the ones that contain the base−class libraries encompassing the .NET Framework. To compile a class to IL and package it into an assembly is very straightforward. You simply build the class and specify the assembly and its namespace for the compiler. Classes (known as types once they have been reduced to IL) are separated by the assembly in which they residehence the term type boundary. In other words, two types can be placed onto the same namespace but they can exist in individual assemblies. The problem arises when you try to reference the type in the IDE because you can only Import to one fully qualified namespace. The IDE will not let you reference the second class twice and will notify you of your previous reference. Assemblies as Reference−Scope Boundaries The manifest metadata specifies the level of exposure a type and its resources have outside the assembly, the dependencies, or other assemblies on which it relies, and how types are resolved and resource requests satisfied. If there are statically linked dependencies, the manifest includes metadata detailing information such as name and version. The Roles of the Assembly 53 The manifest also lists reference scopes of the types. The types can be accessed outside the assembly; this process lets you reference them by their FQNS or gives them friend access, implying that are hidden from the outside worldonly accessible to those within the same assembly in which the friend resides. Assemblies as Units of Deployment When you execute an application, the application assembly calls into its dependencies, which are either visible to the exe file in the same folder or in sub−folders, or they are visible in the runtime environment because they have been installed in the GAC. Assemblies installed in the GAC are shared, which exposes them to others that may need access to their internals. You might also have utility classes, culture and localization classes, or components, and these can be loaded into the installation folder or the GAC. These assemblies let you build very thin application assemblies and keep successive deployments smallwhere you just need to change the outdated assembly. Versioning in .NET lets you or your users set up new variations on your assemblies without breaking those installed previously. Assemblies as Units of Execution The CLR lets all shared assemblies execute or be accessed side−by−side. Thus, as long as you create a shared assembly with a strong identity and a unique version number, and you register it into the GAC, the CLR will be able to execute it alongside another assembly. The DLL conflicts of the past are abolished under the CLR, because only the version number and unique public key data allow the CLR to distinguish between the assemblies. As a Version Boundary The assembly is the smallest versionable unit in the CLR; the types and other resources it encapsulates are versioned with the assembly as a unit. A class cannot stand alone and be accessed outside of the assembly architecture because there is no way to reference it. The class or type can either be part of the application assembly or stand alone in its own assembly, which provides the version data for it. The version number is encapsulated in the assembly manifest, as shown earlier. The CLR uses the version number and the assembly's public key data to find the exact assembly it needs to execute, and any assemblies that may be dependent on the specific version. In addition, the CLR provides the infrastructure to allow you to enforce specific version rules. As a Security Boundary The assembly is a security unit that facilitates access control to the data, type functionality, and resources it encapsulates. As a class provider, the CLR allows you to control access to your assembly's objects by allowing you to specify a collection of permissions on an assembly. The client processrich clients, thin−clients, Web forms, or otherwisemust have the permission you specify in order to access the object in the assembly. This level of security is known as code access security. When an assembly is called up, the CLR quickly determines the level of code access allowed on the assembly. You only get code if you have authorization. The idea of controlling code access is fairly new and in line with the model of distributed functionality that is becoming so widespread. Code access security also employs a role−based security model, which specifies to The Roles of the Assembly 54 the CLR what a client is allowed to do with the code it can access. The security identifier of an assembly is its strong name, which is discussed in the next section. System resources also require protection from assemblies. The ASP.NET Web Application Security protects access to system resources by comparing credentials and proxies of credentials to Windows NT file system's security architecture. Chapter 11 discusses techniques for handling exceptions and error conditions that may arise as a result of security−access violations. Attributes, Reflection, and Assemblies A critical facility of assemblies is the provision of runtime type information (RTTI) through a process known as reflection. As with most OO languages, basic RTTI is built into all classes with the GetType method and the Is operator (see Chapter 4 and Chapter 9); yet, reflection in the .NET Framework is especially sophisticated thanks to the assembly, its metadata, and the provision of attributes. An attribute is an object containing information and runtime instructions defined in an attribute class and then compiled with the class it has been appended to. Attributes can be applied globally, at both the class and class−member levels. The .NET Framework's reflection architecture lets you access the targeted attributes at runtime, through standard class instantiation. However, the runtime knows about the beneficiary of the attributes, because they are embedded in the assemblies of the beneficiaries. When you affix attributes to target classes or their members, the attribute class gets compiled along with the beneficiary. Then the metadataof both attribute and beneficiaryends up in the same assembly. With some imagination, you can see that at one end of the sophistication scale attributes let the runtime have important information about an object it has instantiated. For example, the runtime learns from attributes whether or not it can honor a request to serialize an object to disk or to an XML stream, and it discovers what fields in the target objects are allowed to be persisted. You can even look up object authorship, version, and security information at runtime. At the other end of the sophistication scale, entering the realm that was once thought to be science fiction, attributes can be used to reflect on, and reference, objects that are running in the processing space of another computer somewhere else on the Internet. With reflection we can reference the objects and determine their methods, accessible fields, constructors, and other elements in these other processes. Reflection is not an easy subject to grasp. It is also a subject at the center of much debate, particularly about its impact on performance. Chapter 4 introduces some attribute fundamentals but the subject is best left to an advanced treatise. Strong Names Assemblies can be given strong names, which will guarantee their uniqueness and provide security attributes. The strong name is made up of the assembly's standard name (such as Vb7cr), its version number, culture, public key data, and a digital signature. The strong name is generated from all this data, which is stored in the assembly manifest. If the CLR encountered two assemblies with the same strong name, it would know that the two files were identical. Strong names are issued by Visual Studio .NET and by development tools that ship with the .NET SDK. The idea behind strong names is to primarily protect the version lineage of an assembly, because the guaranteed uniqueness ensures that no one else can substitute their assembly for yours. Attributes, Reflection, and Assemblies 55 The strong name also protects your consumers and allows them to use the types and resources of your assemblies with the knowledge that the integrity of their system is intact. Combined with supporting certificates, you have the ultimate security system for the protection of enterprise and distributed code. The .NET Security Model Ever since the advent of the LAN, application security extended to the access rights and trust provided to a user by his or her administrator. Even applications that do not directly interface with humans have operated under the auspices of and in the context of user accounts. Most server side applications work this way, operating under the authority of the Administrator account. This model of security is known as the user authentication model. In the mid 1990s, the sandbox security model became popularat about the same time we discovered Java applets could be made to do all sorts of nasty things behind your Web browser. The idea behind the sandbox is to isolate applications in safe environments where they cannot go rouge and start looking for credit card numbers, passwords, and the like whenever you log onto a Web site. .NET security combines both of these: the user authority model and the sandbox model. However, the security levels and rules are enforced by the CLR. Through a process known as code verification, the managed code is verified to ensure type safety. For example, if a method declares a parameter that takes a 4−byte argument, you won't get into the method with an 8−byte argument. Execution flow−control is also "watched." Your code will be able to access only the locations allowed by the administrator. This is an important consideration when you are writing your code. While you might not have a malicious design in your application, if your code is infiltrated, the administrator will need to block access to the off−limit areas of your code. In the event of mistakes, lockdowns, and unintentional lockouts, you need to write code that can gracefully accept that the world is not its oyster. The verification process also catches damaging errors that may not have originated due to hostile intention. The old sticklers like buffer overruns, overwriting memory locations, and arbitrary transfer−of−control are about as outdated as horn−rimmed spectacles. Verification is performed by the CLR's verification algorithm when you attempt to run your applications or your application needs to access types. It is part of the JIT compilation process. At that point the MSIL code is classified as follows: Invalid The verification algorithm has determined that the MSIL code cannot be JIT compiled by the CLR, which essentially means that something in the code prevented the MSIL from being converted into machine or native code. The code is promptly repudiated. • Valid The MSIL code was found to be acceptable to the CLR and could thus be compiled into native code. The CLR accepts MSIL as being valid even if it might not be type−safe, a determination it still has to make. • Type−safe The next stage of the verification process after code is declared valid is the type−safety check. Here the algorithm tests to see if types are "legally" accessed through the proper interfaces. Code that tries to circumvent the interfaces and tries to access the private members of a type, which is considered illegal, is considered not type−safe. • Verifiable Once code passes the type−safety check the CLR accepts that code is both valid and type−safe and allows it to be executed or referenced. When code is classifed as verifiable by the algorithm it means that it is both valid and type−safe. • The .NET Security Model 56 The CLR does not need to verify code every time it is executed or referenced by an application. It is smart enough to know to skip the process when code that has been previously verified is loaded. The CLR may also make this determination to skip the verification process if it trusts the code sufficiently. Code loaded from the Internet or a remote computer, for example, is not implicitly trusted and must be verified. When is an assembly secure enough to earn the trust of the CLR? A number of mechanisms are in place to secure resources and assemblies from unauthorized users, hostile code, and viruses. Here are the basic security levels and models of .NET Security: ASP.NET Web Application Security This mechanism provides the means for controlling access to a Web or Internet site through authentication. Credentials are compared against the NT file system or against an XML file that contains lists of authorized users, authorized roles, and HTTP verbs. • Code Access Security, Authentication, and Authorization This mechanism uses permissions to control assembly access to resources and operations. By setting permissions, you can protect the system from malicious code and simultaneously allow bona fide code to run safely. This form of evidence based security is managed by administrators. • Role−Based Security This mechanism provides access to assemblies based on what it, as the impersonator of the user, is allowed to do. This is determined by user identity, role membership (like those you have in SQL Server 2000), or both. Business rules play a large part in the formulation of role−based security. • Evidence−Based Security This refers to input to the security policy that describes the code. The input provides information about the site an assembly came from, the URL it slid in on, what particular zone it may have come from, and information gleaned from the assembly's strong name. • Isolated Storage Isolated storage is a special place set aside for data access when a .NET process precludes file or database access. This concept extends the sandbox model admirably by allocating a protected portion of hard−disk space to a specific assembly. Isolated storage is program drivendriven from your code. • Cryptography A variety of interfaces support the implementation of cryptographic services in the .NET Framework. • As a .NET developer, you need to consider security on a number of levels determine how your code will run in the target environment, how it will resist attack, and how you can handle security exceptions that are raised when your code is blocked. You can do this in one of two ways: through declarative or imperative specifications. Declarative specifications enable you to directly enumerate security requirements for an assembly in its metadata via attributes. You can then cater to the declarations in your code, which you accomplish through the attribute architecture we discussed earlier. Imperative security is the practice of writing security support directly in your code. When a method calls a file object, you can set conditional steps to determine if the CLR will permit the call. Unfortunately, developers with malicious intent may be reviewing the .NET security model to determine how to get their assemblies onto the .NET runtime. You can protect your assemblies from invasion through the techniques of strong naming or digital signing; I recommend you employ both if your assemblies will be in the public domain. A strong name is a unique name that is generated from the contents of an assembly, such as version numbers, simple names, digital signatures, or culture information. You should fully investigate both strong−naming techniques and digital signing of the assemblywhich is achieved through public key encryption technology (PKI). The .NET Security Model 57 But even if you don't do anything special to your code after you have completed a project and released a version to the user, or deployed it to a Web site, the CLR remains the final authority. This means that there is a possibility that the CLR will reject your application's attempt to run because it has insufficient evidence that your code can be trusted. During the development of the .NET Framework, code developed and deployed with the beta versions of Visual Studio and the framework was given a certain amount of leeway. ASP.NET and Web applications were fully trusted, specifically because the framework was not in its final version. However, just before final release Microsoft significantly tightened security and any code you deploy now must have sufficient security credentials before the CLR will allow it to run. In the final release of the framework many classes in the various namespaces were decorated with stringent security attributes that might shut you out. The lock down was done to specifically protect customers moving their applications and services into productionto prevent attack from both private intranets and the Internet. The new security attributes center around the code access security paradigm. In particular the CLR needs to know where the code comes from and various other factors before it allows it to run and possibly access system services like the registry, directories, and the file system. In fact ASP.NET and Web forms code is delegated to a controlled execution environment (a sandbox surrounded by barbed wire, minefields, and a crocodile infested moat) no matter where it comes from. Your apps, if allowed to run, are also delegated isolated storage units for their persistent storage needs. This is a policy that is very different from the security policy that was in effect under the beta programs where Web apps had much more liberal access (policies demanded by Microsoft's customers). So don't be surprised when you discover that the neat stuff you were doing back at the lab gets blocked on your customer's Web site. You can proceed to develop and test your applications, especially the code in this book, without concern for the code access security conditions. The chapters that follow focus on the core language, and further discussion of the security requirements for deployment of release builds, or what imperative constructs you need to introduce, is beyond the scope of this book. There is, however, a substantial amount of related material in the SDK and in the released version of Visual Studio that will point you, or your deployment team, in the right direction. A thorough understanding of why code needs to be properly trusted and verified is imperative for your good and that of your customers. Observations Why is such coverage of the .NET Framework's runtime environment so important in this book? Many programmers ask, "Why do I need to know about the CLR, assemblies, and metadata if I only want to write software? It seems like a waste of time." In addition to questions such as these, I noticed in many news groups since June 2000 that very few questions were aimed at the CLR or runtime. When this book was first conceived I did not plan to cover the runtime environment. Yet, over time it seemed that many programmers were wrestling with issues thought to be related to or caused by code, when, in fact, they were runtime related or solved through enlistment of runtime services and facilities. Many questions and problems thought to be related to code construction could have easily been solved with a basic understanding of what goes on in the runtime. Furthermore, subjects like debugging, deployment, security (so critical), and reflection all require you to have at least a basic understanding of how Observations 58 the CLR works. While you certainly can write software without knowing any of the details mentioned in this chapterand you may even be an excellent programmeryou will not necessarily be a highly productive .NET programmer. After all, you still have to get your classes and methods into your user's hands; for this you need to know how your software is going to be delivered and executed. Therefore, it was decided to be highly worthwhile to cover the CLR and how it works. I hope this chapter provides you with the minimum foundation needed to be successful as a .NET Framework programmer. If you want to go further, you can access the many books that specialize in the subject, or get onto the beta program for the next version of the CLR. It will pay generous dividends. Observations 59 Part II: Visual Basic .NET Fundamentals Chapter List Chapter 3: The Visual Basic .NET Development Environment Chapter 4: The Elements of Visual Basic .NET Chapter 5: Visual Basic .NET Operators Chapter 6: Software Design, Conditional Structures, and Control Flow Chapter 7: Methods 60 Chapter 3: The Visual Basic .NET Development Environment Overview You have three choices for quickly becoming au fait with the Integrated Development Environment (IDE) and the compiler. First option: You could go through all the dialog boxes to try to figure out what each option or setting does. (Some computer books might do that for you, but not this one. My focus is on showing you the code.) Second option: Get a book dedicated to the subject of Visual Studio .NETand delay writing code until you know the IDE inside out. By the time you are done, you'll be ready to go into shrimp farming. Third option: start writing code. The best option is the last one. You won't be an expert with Visual Studio (VS), even after some weeks, but you'll be productive from the get−go. I started working with Visual Studio after PDC 2000, when the release was so buggy it crashed the moment it opened. There was no documentation to help learn about its many aspects; but thankfully I had experience with Visual J++, the predecessor of this marvelous tool. Let's begin by helping you start a project or load up the example solutions that were developed for this book. If you have not installed Visual Studio yet, do so now. It is straightforward and if you plan to set up in a team environment or on an application server you are accessing via terminal services, consult the Visual Studio installation instructions that shipped with the retail product packaging. Once you've completed this, you'll notice that it has created program icons only for the MSDN Library of Visual Studio .NET and for Visual Studio .NET itself. What happened to all the options for Visual Basic, C#, or C++ that you chose during installation? All the languages are bundled into the same IDE. You will see how you can choose the language you need once you start up the IDE. The primary objective in this chapter is to get you up and running with the demo solution as quickly as possible. To this end, we'll take a short tour of the IDE and Visual Studio .NET; then we'll examine the dialog boxes and options you'll need to know about. If you have not had any experience designing a Visual Basic .NET application, you will gain the necessary information to begin writing, compiling, and executing one by the end of this chapter. Working with the Visual Studio IDE Let's now start up the IDE and take that Visual Studio .NET tour. This will get you set up with projects you can apply to the sample code and with techniques for developing software and solving complex problems. To begin, start Visual Studio .NET. You will see the default layout of the IDE, which is illustrated in Figure 3−1 and represents the default settings. As usual, you can move and dock windows as you like. 61 Figure 3−1: An empty Visual Studio .NET IDE when started up Look first at the extensive environmental settingsergonomic and workflow featuresyou can control from Visual Studio. To access these settings, go to Tools, Options and select the Environment folder. You can change the window layout from the default Tabbed Documents to MDI. This setting can be accessed from the General Section of the Environment folder. I suggest you only make the change to MDI if you are coming from an IDE that is MDI layout and the tabbed documents are making life hard for you. In general, the tabbed documents present a much more productive layout for this version of Visual Studio. We'll return to the folder options in various chapters in this book. In the meantime, let's look at a minimal collection of elements provided by the IDE that you will be dealing with from the first line of code. Navigating the IDE Set a screen resolution of about 1024x768 to get as much IDE real estate as you can without reducing the icons and other elements beyond recognition. The following list provides the key IDE resources you should first learn about to help you develop in a manner and style that is comfortable for you. Auto Hide• Dockable Windows• Explorer Menu Bar• Server Explorer• Resource View• Toolbox• Macro Explorer• Object Browser• Task List• Command Window• Output Window• Find Results• Dynamic Help• Knowing about these IDE resources will also let you tackle the examples in this chapter before moving on to the more complex issues that follow. Navigating the IDE 62 [...]... computer You can save the file as welcome.txt or as welcome.vb (The vb extension is recognized by the IDE as the official Visual Basic NET extension for class files, so it's better to use this extension.) 3 Now find the Visual Basic NET command−line compiler If you installed the SDK and the Visual Basic NET support in Visual Studio, then the compiler will be on your computer It goes by the name of VBC.EXE... Visual Basic or C#; Legacy Keyboard Schemes, relating to Version 6 of all the previous languages and compilers; the Window Layout; and the Help Filters If you are a Visual Basic 6 developer, you may want to choose the Visual Basic Developer profile And if you herald from Visual J++, the Visual Studio profile will be familiar The following are the settings I have chosen for this book 71 Creating a Visual. .. you choose the language or technology you need to work with If you installed C# with Visual Basic, then the option of creating a C# application will be available to you as well Since this is a book about Visual Basic, we suggest you develop a Visual Basic project Tip You can create a new project in another solution if you access the Add New Project dialog box from the File menu The Visual Basic projects... to the close button (x) of each window As soon as the window hides away, its tab peeks out from the edge of the screen by about 20 pixels Getting the window back requires only sliding your mouse pointer over the tab or right−clicking in the white space under the tabs and selecting the correct tab from the pop−up menu Figure 3 2 shows the entire IDE with all non−essential windows hiding Figure 3 2: The. .. are new to Visual Basic, set aside some time to fully review the elements Visual Basic syntax is rich, extensive, and very different from most other languages (with the exception of classic Visual Basic and the original BASIC language itselfthe latter now a very distant ancestor) Visual Basic NET is a radical departure from its predecessors, so even if you are a VB guru, you need to review the information... the OB, the Object Browser Use the Find facility to look for the object in the OB Click the Find Symbol icon (the binoculars button) on the OB toolbar, as demonstrated earlier in this chapter, and search for the symbol The Find Symbol Results dialog box lists the hits, as demonstrated in this illustration Double−click on the line that represents the found symbol and the OB will pop up with the class... from the Task List These include TODO, UPGRADE_TODO, and UPGRADE_WARNING As you can see, these tokens have a lot to do with trying to migrate classic Visual Basic code 67 Navigating the IDE You can access them by entering the name of your chosen token after the comment symbol (the single quote) The task is automatically added to the Task List When you need to access the task again, just double−click the. .. and the appropriate section of code is brought up in the target unit, which moves to the front of all the tabbed documents Connecting to the errors in your code works the same way Simply double−click the Task List item and the IDE brings the error to the foreground To add your own tokens, a truly terrific feature, go to the Tool menu and select Options You can then choose the Task List option from the. .. of Visual Basic NET The foundation elements are discussed, along with related concepts Some elements are discussed in depth in later sections in this chapter; others are discussed in the chapters that specialize in the concepts and how the idiomatic elements cater to them Lexical Elements The lexical elementsthe so−called "grammar" of the languagerefer to the structure that makes up the layout of the. .. solutions to load This is how the Start Page should look after a fresh installation 69 Starting from the Start Page Tip You can toggle to the Start Page's beginning position from the icon to the right in the top right−hand corner of the IDE The icon to the left tells the Web browser to load Web links, either within or outside of the browser It does not take long to lose the Web browser so remember that . Fundamentals Chapter List Chapter 3: The Visual Basic .NET Development Environment Chapter 4: The Elements of Visual Basic .NET Chapter 5: Visual Basic .NET Operators Chapter 6: Software Design,. of Visual Studio .NET and for Visual Studio .NET itself. What happened to all the options for Visual Basic, C#, or C++ that you chose during installation? All the languages are bundled into the. reference scopes of the types. The types can be accessed outside the assembly; this process lets you reference them by their FQNS or gives them friend access, implying that are hidden from the outside

Ngày đăng: 14/08/2014, 01:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan