intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Professional VB 2005 - 2006 phần 8

Chia sẻ: Hà Nguyễn Thúy Quỳnh | Ngày: | Loại File: PDF | Số trang:110

75
lượt xem
7
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Kể từ khi không còn đủ chỗ cho họ được sắp xếp cạnh nhau, sự sắp xếp sẽ tự động chuyển đổi, và các hình thức sẽ nhiều hơn như thế trong hình 14-15.Để hỗ trợ trong điều khiển định vị trong FlowLayoutPanel, tất cả các điều khiển có một sở hữu mới gọi là Margin. Có các thiết lập cho

Chủ đề:
Lưu

Nội dung Text: Professional VB 2005 - 2006 phần 8

  1. Chapter 19 When the process is complete, a web page will be generated that contains the link needed to deploy the application. The Web page will have a Run button that activates the link. If you click this button, the application will be deployed by ClickOnce. (You may wish to view the source for this web page to PDF Merge and Splitto launch the application from-your own web pages.) obtain the HTML needed Unregistered Version http://www.simpopdf.com impo First, the pre-requisites for the application are verified. In this case, that just means the .NET Framework. Then a Security Warning dialog is displayed asking if it is acceptable to run the application, as shown in Figure 19-26. You can run the application by pressing the Run button, or press the Cancel button, which aborts the process. Press the Run button, and after a short delay you will see the application’s form appear. Figure 19-26 If you now make any changes to the SimpleApp application, you must publish the application again to make the changes available via ClickOnce. You can do that by stepping through the publishing wizard once again. More about automatic updating of ClickOnce applications is discussed below in the topic “The Update Process”. Deploying an Application That is Available Offline In the second screen of the publishing wizard, if you select the first option, then the installation process has some differences. ❑ The web page that ClickOnce generates to test the deployment will have a button that says “Install” instead of “Run”. ❑ When the button is pressed, a shortcut to the application is added to the user’s Start | Programs menu. The shortcut will be in the program folder that is named for the company name that was entered when Visual Studio was installed. ❑ The application will be launched at the end of the install process, as it was with an online app. However, future launches can be accomplished with the same URL or via the shortcut in the Start menu. 738
  2. Deployment Files and Directories Produced by ClickOnce The virtual directory used by ClickOnce to deploy your application contains a number of files for differ- ent aspects of the deployment. Figure 19-27 shows what the directory for SimpleApp looks like after impo PDF Merge and Split finished copying all files needed. ClickOnce has Unregistered Version - http://www.simpopdf.com Figure 19-27 The virtual directory contains a folder for the first version of SimpleApp, which by default is version 1.0.0.0. It also contains the Web page that was displayed after ClickOnce finished, which is named publish.htm. The next file is Setup.exe. This is an executable that does not need the .NET Framework to run. It is used during the ClickOnce process for all the activities that must take place before the application is launched. This includes activities such as checking for the presence of the .NET Framework. It is discussed further in the section below entitled “The Bootstrapper”. The next file is SimpleApp.application. The “.application” extention is specific to ClickOnce, and indi- cates a special file called a “manifest”. This is an XML-based file that contains all the information needed to deploy the application, such as what files are needed and what options have been chosen. There is also a file named SimpleApp_1_0_0_0.application, which is the manifest specifically associated with ver- sion 1.0.0.0. Each version of the application has it’s own manifest, and the one named SimpleApp.application (with no embedded version number) it typically the currently active one. (Thus, the link to the application does not need to change when the version number changes.) Other files associated with a version are in the folder for that version. 739
  3. Chapter 19 Signing the Manifest Since the manifest controls the update process, it is essential that ClickOnce be assured that the manifest is valid. This is done by signing the manifest, using a public-private key pair. As long as a third party impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com does not have the key pair, they cannot “spoof” a manifest, preventing any malicious interference in the ClickOnce deployment process. A key pair is automatically generated when you publish with ClickOnce. However, you can supply your own key pair if you like. Options for signing the application are discussed below in the section entitled “ClickOnce Configuration Options”. Note that your application assemblies do not need to be signed for them to be used in a ClickOnce deployment. Only the manifest need be signed. The manifest contains hash codes of all the assemblies involved, and those hash codes are checked before assemblies are used. This prevents malicious third parties from inserting their own versions of your assemblies. The Update Process All ClickOnce applications by default check for updates each time the application is launched. This is done by getting the current version of the manifest and checking to see if there have been any changes since the last time the application was launched. This process is automatic, so there’s nothing you need to do to make it happen, but it’s helpful for you to understand the steps that are taken. For an online application, if a change is detected, it is immediately applied by downloading any changed files. Then the application is launched. In spirit this is similar to a browser-based application, because the user does not have any option to use an older version. For an application available offline, if changes are detected, the user is asked if the update should be made. The user can choose to decline the update. There is a configuration option that allows you to spec- ify a minimum version number, and that can force a user to accept an update. We will look at ClickOnce configuration options later. If an update is made for an offline application, the previous version is kept. The user then has the ability to roll back to that version using their Add/Remove Programs option in the Control Panel. The user can also uninstall the ClickOnce-deployed application from that same location. Only one version back is kept. If there are older versions, they are removed when a new version is installed, so that the only versions available at any point in time are the current version and the one immediately before it. If a roll back is made to the immediately preceding version, it cannot be rolled back any further to earlier versions. You can control the update process by including code in your application that detects when changes have been made, and applies the changes as necessary. As previously mentioned, this chapter will not cover writing such logic. There are samples available in the MSDN documentation for this capability. 740
  4. Deployment ClickOnce Configuration Options In Visual Studio 2005, the properties for a Windows Application project now include several pages that affect ClickOnce. (You can get to the properties for a project by right-clicking on it in the Solution impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Explorer, and selecting Properties.) The Signing tab page includes options for signing the ClickOnce manifest. There are buttons to select a particular certificate from a store or a file, or to generate a new test certification for signing. This page also contains an option to sign the assembly that is compiled from the project, but as mentioned above, this is not necessary for ClickOnce to operate. A typical example of the Signing tab page is shown in Figure 19-28. Figure 19-28 The Security tab page controls options relating to the code access security permissions needed by the application to run. Since the application is being deployed from a source off of the local machine if you use ClickOnce, code access security limitations are in effect as described in Chapter 13. A typical exam- ple of the Security tab page is shown in Figure 19-29 741
  5. Chapter 19 impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 19-29 Using the options on the Security tab page, you can calculate the permissions needed by the application, using the button labeled Calculate Permissions. You can also arrange to test your application against a particular set of permissions. To do that, you change from the default option “This is a full trust applica- tion” to the option immediately below it, labeled “This is a partial trust application”. Then select the zone from which the application will be installed. When the application is run by Visual Studio, permis- sion for that zone will be enforced. All of the other ClickOnce configuration options are on the tab page labeled Publish. Such a page is shown in Figure 19-30. 742
  6. Deployment impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 19-30 There are many options that you can set with the Publish page, but here are some of the most important: Property/Option Purpose Where to set it on the page Specifies the virtual directory, Textbox labeled “Publishing Publishing Location network directory, or local directory Location”. (Note that this can to which the application will be also be set in the first screen of published by ClickOnce. the publish wizard.) Specifies the location from which Textbox labeled Installation URL your application will be deployed “Installation URL” by users. By default, this is the same as the Publishing Location, but may be set to be elsewhere. Selects the online only vs. offline Option buttons under “Install Install Mode mode for the application. Mode and Settings”. (Note that this can also be set in the second screen of the publish wizard.) Table continued on following page 743
  7. Chapter 19 Property/Option Purpose Where to set it on the page Sets the version of the application The textboxes under “Publish Publish Version impo PDF Merge and Split Unregisteredpurposes. ClickOnce for publishing Version - http://www.simpopdf.com under Version”. If the checkbox requires version changes to properly those boxes is checked, the auto-update the application. publish version will be automat- ically incremented each time the application is published. Specifies the software that must be The Prerequisites button brings Prerequisites installed before your application can up a dialog box that allows itself be installed, including elements standard prerequisites to be such as the .NET Framework. checked off. The .NET Frame- work is checked by default. The dialog also allows you to specify the location for downloading pre- requisites. See the section below on the Bootstrapper for more information on prerequisites. Options for various purposes such The Options button brings up a Miscellaneous as the product name. dialog box that allows these options options to be set. Options that control the update These options are only available Update options process, including when the for applications that can run application updates (before or after offline. The Updates button it starts), the minimum version brings up a dialog box number required, etc. controlling these options. The Bootstrapper Because applications deployed by ClickOnce is a part of the .NET Framework, the .NET Framework must be available on the user’s machine before your application can be installed and run. In addition, your application may require other items such as a database or COM component to be installed. To provide for such needs, ClickOnce includes a “bootstrapper” that runs as the first step in the ClickOnce process. The bootstrapper is not a .NET program, so it can run on systems that do not yet have the .NET Framework installed. The bootstrapper is contained in a program called Setup.exe, which is included by ClickOnce as part of the publishing process. When setup.exe runs, it checks for the prerequisites needed by the application, as specified in the Prerequisites options discussed above. If needed, these options are then downloaded and installed. Only if the user’s system contains installed prerequisites does ClickOnce attempt to install and run your Windows application. The MSDN documentation includes more details on configuring and using the ClickOnce bootstrapper. 744
  8. Deployment ClickOnce vs. Other Deployment Technologies ClickOnce is a complete replacement for no-touch deployment. However, there are other deployment scenarios for which ClickOnce may not be the ideal solution. For example, ClickOnce can only deploy a impo PDF Merge and Split Unregisteredcannot install an application once to be used by all users on the system. per-user installation. ClickOnce Version - http://www.simpopdf.com ClickOnce may be used in combination with technologies such as the Windows Installer. If you create .msi files, as discussed earlier in the chapter, you may include them as part of ClickOnce’s bootstrapper process. This is an advanced technique not discussed in this book, but you can learn more about this capability in the MSDN documentation. For cases in which ClickOnce is not appropriate, you may wish to use more customized deployment technologies. These are discussed next. Custom Deployment Options If an application needs deployment capabilities not covered by the technologies discussed so far, it may be necessary to use alternatives technologies, or even develop them yourself. For example, you can cre- ate a deployment function that checks via a Web Service to see when updating needs to take place and that uses FTP to transfer files from a Web server to a client machine. Updater Application Block Rather than start from scratch on such deployment/installation technology, you can look at starting points such as the Updater Application Block. Created by Microsoft’s Patterns and Practices Group, the Updater Application Block can be downloaded from Microsoft’s Web site. It includes manifest-based checking of modules for updating, and background transfer of new modules using the same transfer technology as Windows Update. You can use the Updater Application Block as is, or customize it for your own needs. For example, you could create a version that allows different classes of users to have different update strategies, so that new updates go out to a select group of users first. S ummar y An application must be deployed to be useful. How an individual application should be deployed depends heavily on circumstances. Factors such as the geographic distribution of the application, its complexity, and how often it will be updated all must be considered to choose an appropriate strategy. The main possibilities for deployment are: ❑ XCOPY deployment ❑ Installation via the Windows Installer ❑ No-touch deployment ❑ ClickOnce deployment ❑ Deployment with other technologies such as the Application Updater Block 745
  9. Chapter 19 This chapter has covered each of these, with some discussion of their applicability. It will be helpful for you to understand all of these options to make appropriate decisions for the deployment of individual applications. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com On one hand, simple utilities, for example, might be best installed by simply copying files. On the other hand, stand-alone applications that have many dependencies on COM-based components will more often use Windows Installer technology. Applications that depend on Web Services for data will often be best deployed with ClickOnce. Corporate applications with special needs for security during installa- tion, or that need to install an application once for multiple users, may be better off using the Application Updater Block. It’s also helpful to understand that these options are not mutually exclusive. You may have an applica- tion with COM dependencies that needs to use an .msi file for an initial install, but then gets the rest of the application and future updates via ClickOnce or the Application Updater Block. Whatever your application, the plethora of application deployment technologies available for .NET-based applications means you should be able to find an option or combination that suits your needs. 746
  10. impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Working with Classic COM and Interfaces However much we try, we just can’t ignore the vast body of technology surrounding Microsoft’s Component Object Model, or COM. Over the years, this model has been the cornerstone of so much Microsoft-related development that we have to take a long, hard look at how we are going to integrate all that stuff into the new world of .NET. This chapter starts by taking a brief backward glance at COM, then compares it with the way that components interact in .NET, and finally it takes a look at the tools Microsoft provides to help link the two together. Having looked at the theory, we then try it out by building a few example appli- cations. First, we take a legacy basic COM object and run it from a Visual Basic 2005 program. Then we repeat the trick with a full-blown ActiveX control. Finally, we turn things around and try running some Visual Basic code in the guise of a COM object. More information on how to make COM and VB6 code interoperate with the .NET platform can be found in Professional Visual Basic Interoperability: COM and VB6 to .NET (Wiley, 2002). As all that is done, try to remember one thing: COM is, to a large extent, where .NET came from. In evolutionary terms, COM’s kind of like Lucy, the Australopithecus from ancient Ethiopia. So, if it seems a little clunky at times, let’s not to be too hard on it. In fact, let’s not refer to it as “Nasty, tired, clunky old COM” at all. Let’s simply call it “Classic COM.”
  11. Chapter 20 C lassic COM Before looking into COM-.NET interoperability, it’s important to be aware of the main points about impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com While the COM itself. This section doesn’t attempt to do anything more than skim the surface, however. basic concepts are fundamentally simple, the underlying technology is anything but. Some of the most impenetrable books on software that have ever been written have COM as their subject, and we have no wish to add to these. COM was Microsoft’s first full-blown attempt at creating a language-independent standard for program- ming. The idea was that interfaces between components would be defined according to a binary standard. This would mean that you could, for the first time, invoke a VB component from a VC++ application, and vice versa. It would also be possible to invoke a component in another process or even on another machine, via Distributed COM (DCOM). You won’t be looking at out-of-process servers here, however, because the vast majority of components developed to date are in-process. To a large extent, DCOM was fatally compromised by bandwidth, deployment, and firewall problems and never achieved a high level of acceptance. A COM component implements one or more interfaces, some of which are standards provided by the sys- tem, and some of which are custom interfaces defined by the component developer. An interface defines the various methods that an application may invoke. Once specified, an interface definition is supposed to be inviolate so that, even if the underlying code changes, applications that use the interface don’t need to be rebuilt. If the component developers find that they have left something out, they should define a new interface containing the extra functionality in addition to that in the original interface. This has, in fact, happened with a number of standard Microsoft interfaces. For example, the IClassFactory2 interface extends the IClassFactory interface by adding features for managing the creation of licensed objects. The key to getting applications and components to work together is binding. COM offers two forms of binding, early and late: ❑ In early binding, the application uses a type library at compile time to work out how to link in to the methods in the component’s interfaces. A type library can either come as a separate file, with the extension .tlb, or as part of the DLL containing the component code. ❑ In late binding, no connection is made between the application and its components at compile time. Instead, the COM runtime searches through the component for the location of the required method when the application is actually run. This has two main disadvantages: It’s slower and it’s unreliable. If a programming error is made (for example, the wrong method is called, or the right method with the wrong number of arguments), it doesn’t get caught at compile time. If a type library is not explicitly referred to, there are two ways to identify a COM component, by class ID, which is actually a GUID, and by ProgID, which is a string and looks something like “MyProject.MyComponent”. These are all cross-referenced in the registry. In fact, COM makes exten- sive use of the registry to maintain links between applications, their components, and their interfaces. All experienced COM programmers know their way around the registry blindfolded. VB6 has a lot of COM features embedded into it, to the extent that many VB6 programmers aren’t even aware that they are developing COM components. For instance, if you create a DLL containing an instance 748
  12. Working with Classic COM and Interfaces of a VB6 class, you will in fact have created a COM object without even asking for one. The relative ease of this process is demonstrated during the course of this chapter. impo PDF Merge and Split Unregistered Version and .NET. So, to a large extent, all you’ve got to do to make There are clearly similarities between COM - http://www.simpopdf.com them work together is put a wrapper around a COM object to turn it into an assembly, and vice versa. COM and .NET in Practice It’s time to get serious and see if all this seamless integration really works. To do this, we’re going to have to simulate a legacy situation. Let’s imagine that your enterprise depends on a particular COM object that was written for you a long time ago by a wayward genius (who subsequently abandoned software development and has gone to live in a monastery in Tibet). Anyway, all you know is that the code works perfectly and you need it for your .NET application. You have one, or possibly two, options here. If you have the source (which is not necessarily the case) and you have sufficient time (or, to put it another way, money), you can upgrade the object to .NET and continue to maintain it under Visual Studio 2005. For the purist, this is the ideal solution for going for- ward. However, maintaining the source as it is under Visual Studio isn’t really a viable option. Visual Studio does offer an upgrade path, but it doesn’t cope well with COM objects using interfaces specified as abstract classes. If upgrading to .NET isn’t an option, all you can do is simply take the DLL for the COM object, register it on the .NET machine, and use the .NET interoperability tools. This is the path that you’re going to take. So, what you need is a genuine legacy COM object, and what you’re going to have to use is genuine legacy VB6. For the next section, then, you’re going to be using VB6. If you’ve already disposed of VB6, or never had it in the first place, feel free to skip this section. The DLL is available as part of the code download, in any case. A Legacy Component For your legacy component, you’re going to imagine that you have some kind of analytics engine that requires a number of calculations. Because of the highly complex nature of these calculations, their development has been given to specialists, while the user interface for the application has been given to UI specialists. A COM interface has been specified that all calculations must confirm to. This interface has the name IMegaCalc and has the following methods. Method Description Add input value to calculation Sub AddInput (InputValue as Double) Do calculation Sub DoCalculation ( ) Get output from calculation Function GetOutput ( ) as Double Reset calculation for next time Sub Reset ( ) 749
  13. Chapter 20 Step 1: Defining the Interface The first thing you have to do is define your interface. In VB6, the way to do this is to create an abstract class, that is, one without any implementation. So, create an ActiveX DLL project called MegaCalculator. impo PDF do this byand Split Unregistered Version - http://www.simpopdf.com of the You Merge creating a new project and then changing its name to MegaCalculator by means Project ➪ Project1 Properties dialog box. Having done that, create a class called IMegaCalc. This is what the code looks like: Option Explicit Public Sub AddInput(InputValue As Double) End Sub Public Sub DoCalculation() End Sub Public Function GetOutput() As Double End Function Public Sub Reset() End Sub From the main menu, select File ➪ Make MegaCalculator.dll to define and register the interface. Step 2: Implementing the Component For the purposes of this demonstration, the actual calculation that you’re going to perform is going to be fairly mundane: In fact, you’re going to calculate the mean of a series of numbers. So, create another ActiveX DLL project, called MeanCalculator this time. You need to add a reference to the type library for the interface that you’re going to implement, so select the MegaCalculator DLL via the References dialog box that appears when you select Project ➪ References. Having done that, you can go ahead and write the code for the mean calculation. You do this in a class called MeanCalc: Option Explicit Implements IMegaCalc Dim mintValue As Integer Dim mdblValues() As Double Dim mdblMean As Double Private Sub Class_Initialize() IMegaCalc_Reset End Sub Private Sub IMegaCalc_AddInput(InputValue As Double) mintValue = mintValue + 1 ReDim Preserve mdblValues(mintValue) mdblValues(mintValue) = InputValue End Sub 750
  14. Working with Classic COM and Interfaces Private Sub IMegaCalc_DoCalculation() Dim iValue As Integer mdblMean = 0# impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com If (mintValue = 0) Then Exit Sub For iValue = 1 To mintValue mdblMean = mdblMean + mdblValues(iValue) Next iValue mdblMean = mdblMean / mintValue End Sub Private Function IMegaCalc_GetOutput() As Double IMegaCalc_GetOutput = mdblMean End Function Private Sub IMegaCalc_Reset() mintValue = 0 End Sub As before, you select File ➪ Make MeanCalculator.dll to build and register the component. It has a default interface called MeanCalc (which contains no methods, and is thus invisible to the naked eye), plus an implementation of IMegaCalc. Step 3: Registering the Legacy Component You now have your legacy component. If you’re developing your new .NET application on the same machine, you don’t need to do anything more because your component would already have been regis- tered by the build process. However, if you’re working on an entirely new machine, you’ll need to regis- ter it there. The easiest way to do this is to open a command box, and register it with the following command using regsvr32.exe found in C:\Windows\system32: regsvr32 MeanCalculator.dll Then you should see the result shown in Figure 20-1. Figure 20-1 Because MeanCalculator implements an interface from MegaCalculator, you’ll also have to repeat the trick with that DLL: regsvr32 MegaCalculator.dll and what you see is shown in Figure 20-2. 751
  15. Chapter 20 impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 20-2 You’re now ready to use your classic component from a .NET application. The .NET Application For your .NET application, all you’re going to do is instantiate a MeanCalc object and get it to work out a mean for you. So, create a Windows Application project in Visual Basic called CalcApp. What the form looks like is shown in Figure 20-3. Figure 20-3 The two text boxes are called txtInput and txtOutput, respectively; the second one is not enabled for user input. The three command buttons are btnAdd, btnCalculate, and btnReset, respectively. Referencing the Legacy Component Before you dive into writing the code behind those buttons, you need to make your new application aware of the MeanCalculator component. So, you have to add a reference to it, via the Project ➪ Add Reference menu item. This brings up a dialog box with five tabs: .NET, COM, Projects, Browse, and Recent. Select MeanCalculator and MegaCalculator in turn from the COM tab (see Figure 20-4). Now, press the OK button. Notice that, in the list of references in the Solution Explorer, you can now see both MeanCalculator and MegaCalculator (see Figure 20-5). Inside the .NET Application Now that you’ve successfully got your component referenced, you can go ahead and finish coding your application. First, add a global variable (mobjMean) to hold a reference to an instance of the mean calcu- lation component: 752
  16. Working with Classic COM and Interfaces Public Class Form1 Dim mobjMean As MeanCalculator.MeanCalc impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Figure 20-4 Figure 20-5 753
  17. Chapter 20 Next, you need to create a Form1_Load event where you will add the following instruction, which will create the component that you’re going to use: impo PDF Private Sub Form1_Load(ByVal sender As Object, _ Merge and Split Unregistered Version - http://www.simpopdf.com ByVal e As System.EventArgs) Handles Me.Load mobjMean = New MeanCalculator.MeanCalc() End Sub Finally, you need to add the code behind the buttons. First of all, the Add button: Private Sub btnAdd_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles btnAdd.Click mobjMean.AddInput(CDbl(txtInput.Text)) End Sub All you’re doing here is adding whatever’s in the input text box into the list of numbers for the calcula- tion. Next, here’s the code behind the Calculate button: Private Sub btnCalculate_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles btnCalculate.Click mobjMean.DoCalculation() txtOutput.Text = mobjMean.GetOutput() End Sub This performs the calculation, retrieves the answer, and puts it into the output text box. Finally, the code behind the Reset button simply resets the calculation: Private Sub btnReset_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnReset.Click mobjMean.Reset() End Sub Trying It All Out Of course, the proof of the pudding is in the eating, so let’s see what happens when you run your appli- cation. First, put one value in, say 2, and click Add. Now, enter another value, say 3, and click Add once more. When you click Calculate, you’ll get the mean of the two values (2.5 in this case; see Figure 20-6). Figure 20-6 754
  18. Working with Classic COM and Interfaces Using TlbImp Directly In the preceding example, there’s actually quite a lot going on under the covers. Every time you import a impo PDF Merge and Split Unregistered Version d-efault interop assembly, which is basically a .NET assembly COM DLL into Visual Studio, it’s creating a http://www.simpopdf.com that acts as a wrapper for the COM object. If you’re doing this a lot, it might be better to do the wrap- ping once and for all, and then let your application developers import the resulting .NET assembly instead. Let’s see how you might do that. The process that creates the default interop assembly on behalf of Visual Studio is called TlbImp.exe. The name stands for Type Library Import, and that’s pretty much what it does. It comes as part of the .NET Framework SDK, and you might find it convenient to extend the PATH environment variable to include the \bin directory of the .NET Framework SDK. TlbImp takes a COM DLL as its input and generates a .NET assembly DLL as its output. By default, the .NET assembly has the same name as the type library, which will — in the case of VB6 components — always be the same as the COM DLL. This means that you’ll have to explicitly specify a different output file. You do this by using the /out: switch. So that you can see what’s going on at each step in the pro- cess, you’ll also specify /verbose: tlbimp MegaCalculator.dll /out:MegaCalculatorNet.dll /verbose For this example, start with MegaCalculator, because MeanCalculator has a reference to MegaCalculator. If you start with MeanCalculator, you will notice that you will get an error saying that there is a reference to MegaCalculator and that TlbImp will not be able to overwrite the MegaCalculator.dll. The way to get around this is to start with MegaCalculator by giving TlbImp the command as shown above. Once this is accomplished, TlbImp will inform you of the success or fail- ure in creating a .NET assembly of the name MegaCalculatorNet.dll. Now that MegaCalculatorNet.dll is in place, you can work with MeanCalculator and make sure that the reference now points to the new MegaCalculatorNet.dll. You accomplish this by using the following command: tlbimp MeanCalculator.dll /out:MeanCalculatorNet.dll reference:MegaCalculatorNet.dll /verbose What happens with this command is shown in Figure 20-7. Figure 20-7 755
  19. Chapter 20 Notice that TlbImp has encountered a reference to another COM type library, MegaCalculator, and it has very kindly in turn imported MegaCalculatorNet instead. impo PDF Merge andyour COM DLLs into .NET assemblies,http://www.simpopdf.com application Having converted Split Unregistered Version - you can now reference them in an as you would any other .NET DLL. Late Binding We’ve shown that you can successfully do early binding on COM components within a .NET applica- tion. But what if you want to do late binding? What if you don’t have access to a type library at applica- tion development time? Can you still make use of the COM components? Does the .NET equivalent of late binding even exist? The answer is that, yes, it does, but, no, it’s not as transparent as with VB6. Let’s take a look at what one used to do in VB6. If you wanted to do early binding, you would do this: Dim myObj As MyObj Set myObj = New MyObj MyObj.MyMethod (...) For late binding, it would look like this instead: Dim myObj As Object Set myObj = CreateObject (“MyLibrary.MyObject”) MyObj.MyMethod (...) There’s actually an enormous amount of stuff going on under the covers here; if you’re interested in looking into this further, try VB COM: Visual Basic 6 Programmer’s Introduction to COM. An Example for Late Binding For your sample, let’s extend the calculator to a more generic framework that can feed inputs into a number of different calculation modules rather than just the fixed one. You’ll keep a table in memory of calculation ProgIDs and present the user with a combo box to select the right one. The Sample COM Object The first problem you encounter with late binding is that you can only late-bind to the default interface, which, in this case, is MeanCalculator.MeanCalc, not MeanCalculator.IMegaCalc. So, you’re going to have to redevelop your COM object as a stand-alone library, with no references to other interfaces. As before, you’ll build a DLL under VB6, copy it over to your .NET environment, and reregister it there. You’ll call this VB6 DLL MeanCalculator2.dll, and the code in the class (called MeanCalc) should look like this: 756
  20. Working with Classic COM and Interfaces Option Explicit Dim mintValue As Integer impo PDF Merge and Split Unregistered Version - http://www.simpopdf.com Dim mdblValues() As Double Dim mdblMean As Double Private Sub Class_Initialize() Reset End Sub Public Sub AddInput(InputValue As Double) mintValue = mintValue + 1 ReDim Preserve mdblValues(mintValue) mdblValues(mintValue) = InputValue End Sub Public Sub DoCalculation() Dim iValue As Integer mdblMean = 0# If (mintValue = 0) Then Exit Sub For iValue = 1 To mintVal mdblMean = mdblMean + mdblValues(iValue) Next iValue mdblMean = mdblMean / mintValue End Sub Public Function GetOutput() As Double GetOutput = mdblMean End Function Public Sub Reset() mintValue = 0 End Sub As before, you’ll need to move this across to your .NET machine and register it using RegSvr32. The Calculation Framework For your generic calculation framework, you’ll create a new application in Visual Basic 2005 called CalcFrame. You’ll basically use the same dialog box as last time, but with an extra combo box at the top (see Figure 20-8). The new combo box is called cmbCalculation. You’ve also disabled the controls txtInput, btnAdd, btnCalculate, and btnReset, until you know if the selected calculation is valid. Start off by importing the Reflection namespace; you’ll need this for handing all the late binding: Imports System.Reflection 757
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2