Lesson 2: Accessing and Invoking Components

Lesson 2: Accessing and Invoking Components

Although the .NET Framework provides considerable built-in functionality, from time to time you might want to access external components for example, an assembly you built using the .NET Framework or an older COM component. You might also need to make a call to a Web service or even interact directly with the Microsoft Windows Application Programming Interface (API). Visual Studio .NET allows you to incorporate these entities into your application with a minimum of effort.

After this lesson, you will be able to

  • Explain how to access a .NET Framework assembly

  • Describe how to access a COM component or ActiveX control

  • Describe how to access a Web service

  • Explain how to make a call to the Windows API

Estimated lesson time: 30 minutes

It is likely you will need to access external code at some time. Whether reusing components that you have previously developed, accessing Web services, or making calls to the Windows API, Visual Studio .NET makes it easy to create references to external components and call them in your code.

Accessing .NET and COM Type Libraries

You can access any .NET or COM library on your system without much difficulty. These components might represent other development projects you have created, legacy COM components, or business logic that you need to incorporate into your application. The generalized scheme for accessing .NET or COM components is to create a reference to the type library, Import (use) the type library in your application, and then declare and instantiate the class you want to use.

You can obtain a list of available type libraries in the Add Reference dialog box. To display the Add Reference dialog box, right-click References in the Solution Explorer under your project, and choose Add Reference from the shortcut menu. The Add Reference dialog box is shown in Figure 8.4.

The Add Reference dialog box has three tabs. Choosing the .NET tab displays available .NET assemblies; the COM tab displays available COM type libraries; and the Projects tab displays available projects. If the item to which you want to add a reference is not listed, you can browse to the file location by clicking the Browse button. Once you have located the reference you want to add, you can select it with the Select button. The reference is then added to your project in the Solution Explorer.

figure 8-4 the add reference dialog box, showing the com tab.

Figure 8-4. The Add Reference dialog box, showing the COM tab.

Once you have added a reference to an assembly or COM type library, you can use the types contained in that reference in your application by using the fully qualified name of the type. If you want to obviate the need to use the fully qualified name, you can use the Imports (Visual Basic .NET) or using (Visual C#) keyword to make members accessible. Chapter 1 describes how to use the Imports and using statements.

Once a reference has been established, you can declare and instantiate the types contained in the type library as you would any other type.

To access a .NET assembly or a COM type library

  1. In Solution Explorer, right-click the References node under your project and then choose Add Reference. The Add Reference dialog box opens.

  2. Select the reference you want to add. COM type libraries are listed under the COM tab; .NET assemblies are listed under the .NET tab; and projects can be found under the Projects tab.

  3. Use the Imports (Visual Basic .NET) or using (Visual C#) keyword to import the reference into your application.

  4. Declare and instantiate the types exposed by your reference as normal.

Instantiating ActiveX Controls

ActiveX is an implementation of COM. As such, you can add a reference to an ActiveX control type library in much the same way that you would add a reference to a COM library. You can then add the ActiveX control to the Toolbox and add it to your applications at design time.

NOTE
Although ActiveX controls can be hosted in Windows Forms, there are some significant performance drawbacks to doing so. You should use ActiveX controls only when a .NET control with the same functionality is not available.

To instantiate an ActiveX control

  1. Add a reference to the type library that contains the ActiveX control, as described previously in this lesson.

  2. Add the ActiveX control to the Toolbox by customizing the Toolbox. This is described in greater detail in Chapter 7.

  3. Drag an instance of the control from the Toolbox to the designer to add it to your project at design time. Alternatively, you can declare and instantiate the control in code and add it to your application dynamically at run time, as described in Chapter 2.

Accessing a Web Service

An integral feature of the .NET Framework is the Web service. A Web service is a type of class that is hosted on the Internet. You can declare an instance of the Web service in your application, and then call its methods either synchronously or asynchronously.

You can create a reference to a Web service in the Solution Explorer. You can display the Add Web Reference window by right-clicking References under your project and choosing Add Web Reference. This displays a screen that allows you to navigate to the URL of a Web reference or to search online if you do not know the URL. The Add Web Reference window for Visual Studio .NET is shown in Figure 8.5. Visual Studio .NET 2003 has a different window, which is shown in Figure 8.6.

figure 8-5 the add web reference window.

Figure 8-5. The Add Web Reference window.

figure 8-6 the visual studio .net 2003 add web reference window.

Figure 8-6. The Visual Studio .NET 2003 Add Web Reference window.

If you do not know the address of the Web service you would like to use, the window displays directories to search. The Universal Description Discovery Integration (UDDI) directory allows you to search Web service registries for companies that provide Web services. When a company is selected, the Web services it offers will be displayed. Choosing a Web service will display the XML contract in the left page of the window and the name of the Web service in the right page. When accessing a Microsoft XML Web service, you can also view a more reader-friendly description of the Web service by removing ?WSDL from the address displayed in the status bar and reloading the page. Once you have verified the correct Web reference to add, click the Add Reference button to add the reference to your project.

When an instance of a Web service is instantiated, the .NET Framework actually creates an instance of a proxy class that represents the Web service. This class resides in your application and exposes all of the methods provided by the Web service. When one of these methods is called, the call is relayed to the Web service at the address specified on the Internet. You can instantiate a Web service just like any other component. The following code example demonstrates how to instantiate a Web service named WebService1:

Visual Basic .NET

Dim myService As New WebService1

Visual C#

WebService1 myService = new WebService1();

Calls to Web service methods can be made in two ways: synchronously or asynchronously. Synchronous calls behave just like normal function calls. For instance, the following code example demonstrates how to make a synchronous call to a method named myMethod located on myService. This example assumes that you have already created a reference and instantiated the Web service:

Visual Basic .NET

myService.myMethod()

Visual C#

myService.myMethod();

Synchronous method calls are made just like regular methods calls. However, because they are accessing resources on the Internet, response time can vary, and application execution will pause until a synchronous call to a Web method is completed. If you do not want to pause program execution while you wait for a Web service call to complete, you can make an asynchronous method call. An asynchronous call starts the call to the Web service on a separate thread, allowing program execution to continue while the Web service processes the request. For every method found on a Web service, there are two additional methods for use asynchronously. The names of these methods are the name of the Web method prefixed with Begin and End. Thus, if a Web service exposes a method named MyMethod, the asynchronous methods for MyMethod are BeginMyMethod and EndMyMethod.

You begin an asynchronous method call with the Begin method. In addition to requiring the same parameters as a synchronous method call, a Begin method call requires an AsyncCallback delegate that specifies the method for the Web method to call back on and an object that allows applications to specify custom state information.

Every Begin method has a return type of IAsyncResult. This interface is used by the corresponding End method to retrieve the data returned by the asynchronous call. The callback method specified by the AsyncCallback delegate must have a signature that takes an IAsyncResult as a parameter. In the callback method, you can call the End method to retrieve the data. The following code example demonstrates how to make an asynchronous call to a method named MyMethod. The example demonstrates how to make the call, specify a callback method, and retrieve the information returned by the call. This assumes that MyMethod is a method on a Web service named WebService1 and that it returns a string.

Visual Basic .NET

Public Class AsyncDemo Dim myService As WebService1 Public Sub CallMethodAsynchronously() myService = New WebService1() ' The AsyncCallback delegate is created with the AddressOf ' operator. The object is required by the method call but not ' used in this example. myService.BeginMyMethod(AddressOf CallBack, New Object()) End Sub Public Sub CallBack(ByVal e as IAsyncResult) Dim myString As String ' You retrieve the data by calling the 'End' method, ' supplying the IAsyncResult as the parameter myString = myService.EndMyMethod(e) End Sub End Class

Visual C#

public class AsyncDemo { WebService1 myService; public void CallMethodAsynchronously() { myService = new WebService1(); // Creates the AsyncCallback delegate that will specify the // callback method System.AsyncCallback myCallBack = new System.AsyncCallback(CallBack); // The object is required by the method call but is not // used in this example. myService.BeginMyMethod(myCallBack, new object()); } public void CallBack(IAsyncResult e) { string myString; // You retrieve the data by calling the 'End' method, // supplying the IAsyncResult as the parameter myString = myService.EndMyMethod(e); } }

Even though you must specify a callback method, you do not necessarily need to use it. You can retrieve the data in the same method by calling the End method directly. If the asynchronous call has to be returned when the call to the End method is reached, program execution will pause until it returns. The following code example demonstrates how to retrieve data from an asynchronous call in the same method:

Visual Basic .NET

Public Sub AsyncDemo() Dim myService As New WebService1 Dim Async as IAsyncResult ' Assigns the IAsyncResult returned by the 'Begin' method to ' the local variable. The delegate that specifies the callback ' method is required but will not be used to retrieve the data. Async = myService.BeginMyMethod(AddressOf SomeMethod, New Object()) ' Do some processor-intensive stuff here Dim myString As String ' If the call hasn't yet returned, application execution will pause ' here until it does. myString = myService.EndMyMethod(Async) End Sub

Visual C#

public void AsyncDemo() { WebService1 myService = new WebService1(); IAsyncResult Async; // Creates the delegate to the callback method. This delegate is // required by the method call but will not be used to retrieve // the data. System.AsyncCallback myCallBack = new System.AsyncCallback(SomeMethod); Async = myService.BeginMyMethod(myCallBack, new object()); // Do some processor-intensive stuff here string myString; // If the call hasn't yet returned, application execution will // pause here until it does. myString = myService.EndMyMethod(Async); }

To create a reference to a Web service

  1. In the Solution Explorer, right-click References and choose Add Web Reference.

  2. Locate the reference on the Web using either UDDI search or by typing in the address of the Web service. Click the Add Reference button to add the reference to your project.

  3. After the reference is added, you can instantiate the Web service just as you would any other class.

To call a method on a Web service synchronously

  1. Instantiate the Web service.

  2. Call the method as you would call a method of any other class.

To call a method on a Web service asynchronously

  1. Create a callback method that takes an IAsyncResult as a parameter.

  2. Call the Begin method of the Web method to invoke the asynchronous call. Supply a delegate to the callback method as a parameter to this method.

  3. Either in the callback method or in another method, call the End method of the Web method to retrieve the data, specifying the IAsyncResult returned by the Begin method as the parameter.

Accessing the Windows API

Accessing native functions of the operating system became less important with the introduction of the .NET Framework. Most of the important functions exposed by the Windows API are wrapped in .NET classes, which allow you to access their functionality in a type-safe, robust manner.

Nevertheless, occasionally you might want to make a call to an unmanaged function. You can use the Declare keyword in Visual Basic .NET or the DllImportAttribute attribute in Visual C# to import a native function. Once you have imported the function, you can use it like any other function in your application. The following code example demonstrates how to declare the Windows API Beep function:

Visual Basic .NET

Private Declare Function Beep Lib "kernel32" (ByVal dwFreq As _ Integer, ByVal dwDuration As Integer) As Integer

Visual C#

[System.Runtime.InteropServices.DllImport("kernel32")] private static extern int Beep(int dwFreq, int dwDuration);

The anatomy of this declaration is as follows: the access modifier (Private or private) determines the access level that this function is to have in the application. In Visual Basic .NET, you indicate an external function by using the Declare keyword. In Visual C#, you indicate an external function by using the static and extern keywords (both are required on an API declaration). In Visual C#, every external function must be preceded by the DllImportAttribute attribute, which specifies the name of the DLL in which the function is located. In Visual Basic .NET, you specify the name of the DLL as a string following the Lib keyword. The name of the function (Beep in this example) is the name of the external function as found in the DLL. It is case sensitive. In addition, the signature and the return type must exactly match those of the external function.

NOTE
Many of the type names from Microsoft Visual Basic 6 have changed in Microsoft Visual Basic .NET (for example, the type previously referred to as a Long is now an Integer). You should be especially mindful of this when making declarations to external functions.

Once you declare the external function, you can call it in code as you would any other function.

To declare an external function in Visual Basic .NET

Use the Declare keyword to specify an external function. The Lib keyword indicates the DLL in which the function is found, and the name and signature must match the name and signature of the external function exactly.

To declare an external function in Visual C#

Use the DllImportAttribute attribute found in the System.Runtime.InteropServices namespace to specify the DLL that contains your function. You must mark your function with both the static and the extern keywords, and the name and signature must match the name and signature of the external function exactly.

Lesson Summary

  • You can use .NET assemblies or COM type libraries in your application by creating a reference to the type library and instantiating the relevant component. You can use ActiveX controls in the same way. Additionally, you can add them to the Toolbox.

  • You can access a Web service by adding a Web reference to your application. Once the Web reference is added, you can declare and instantiate the Web service in code. This will create a wrapper class that exposes the methods of the Web service.

  • Synchronous calls to Web service methods can be made like any other method call. Application execution will pause until the result from a synchronous call is returned.

  • Asynchronous calls are made in two parts. The Begin method requires a delegate to a method that receives an IAsyncResult as a parameter. The End method of an asynchronous method call uses the IAsyncResult returned by the Begin method as a parameter to retrieve the data it returns.

  • You can declare external functions using the Declare keyword in Visual Basic .NET or the static and extern keywords in Visual C#. You must specify the name of the library that contains the function with the Lib keyword in Visual Basic .NET or the DllImportAttribute attribute in Visual C#. The name and signature of the function must match the name and signature of the external function exactly.



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[.  .. ]0-316
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Windows-Based Applications With Microsoft Visual Basic. Net a[. .. ]0-316
ISBN: 735619263
EAN: N/A
Year: 2003
Pages: 110

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net