With Visual Basic. NET uses the. NET Framework (RPM) together

Source: Internet
Author: User
Tags file size file system include object model variables thread thread class visual studio
Using. NET Framework,microsoft Visual Basic developers can create robust applications that are difficult to write in previous versions of Visual Basic. This article discusses the benefits of using the. NET framework and includes some powerful features that Visual basic developers can use with the framework, including multithreading and thread pooling (thread pooling), Windows services, and file system monitoring.

Why use Frames

The word frame (framework) has several implications. In this case, it refers to the foundation on which the application is created and run. Having such a foundation makes it easier to create applications, while using a consistent, simplified program design model.

As a visual Basic 6.0 developer, you are satisfied with this programming language, making it easy to create a variety of applications. The Visual Basic language itself provides intrinsic data types, such as integers, long and string, and some of the most commonly used functions, such as string processing and data type conversions. When your application becomes more complex, you can use the Win32 API to perform functions that the standard Visual Basic functions cannot achieve-such as getting any registry keys and values. In many cases, you can also use the COM (Component object model) component library to extend the functionality of your application; The most obvious example is the ADO (ActiveX data Objects) library, which your application can use for data access.

Although Visual Basic is flexible enough to provide these different extensibility mechanisms, this flexibility still requires you to learn several complex API architectures. You need to understand how WIN32 works, and how to call them in Visual Basic, which can be a time-consuming and error-prone task. You also need to know how to use various COM components in Visual Basic, and each COM component has a different object model.

Finally, when you use the Win32 API, ADO, and possibly many other COM components to create your own Visual Basic applications, you need to manage the deployment of these applications and their dependencies. A typical Visual Basic application's dependency list includes far more than the Visual Basic runtime (runtime); it must include all object libraries used by the application, such as ADO 2.6.

The idea behind the public framework is to address these issues and make it easier for users to create robust applications without having to learn a variety of different API architectures without having to deploy and process a variety of object library versioning issues.

What is the. NET Framework

The term. NET framework refers to the composition of Microsoft. NET Platform Development Foundation of a set of technologies. The key technologies in this group are Run-time (runtime) and class libraries, as shown in Figure 1.


Figure 1. The. NET Framework is composed of. NET Runtimes and class libraries

The runtime is responsible for managing code and servicing it at execution time, similar to the Visual Basic 6.0 runtime. NET programming languages-including visual Basic. NET, Microsoft Visual C #, extension of C + + management, and a variety of programming languages from different developers-take advantage of services and attributes through a common set of unified classes.

. NET unified classes provide the basis for creating applications, regardless of the language you are using. Whether you're simply connecting to a string, or creating a Windows service or multi-tier web-based application, you use these unified classes.

The unified class provides a consistent way to access the functionality of the platform. Once you have learned to use the class library, you will find that all tasks follow a consistent architecture. To write your own application, you don't need to learn and master different API architectures.

Because of the. NET Framework, you deploy visual Basic. NET application has become easier. Unlike visual Basic 6.0 applications, you do not need to configure a variety of dependencies, such as a separate data access library, XML parser, and network APIs, because all of these features are part of the. NET Framework.

By creating your own applications on a unified, Integrated framework, you can achieve the maximum return on the time spent learning this framework, and you will have more robust applications that are easy to deploy and use.

The. NET Framework and visual Basic. Net

The Visual Basic 6.0 runtime is important in simplifying many common program design tasks. But simplifying this layer means that you can't use new operating system features such as DirectX until you have the packaging program that Visual Basic can use. As a Visual Basic developer, the most important benefit you get from the. NET framework is that you can access it both directly and easily using a consistent program design model. NET platform. This means that you can use visual Basic. NET creation is difficult or impossible to use with applications created by Visual Basic 6.0. As a visual Basic 6.0 developer, you will now appreciate the ability to use the same features and functionality as other platform languages. For example, to create a Windows service, you do not need to use Microsoft Visual C + + to write it, nor do you have to resort to hackers or assemblers. You can use visual Basic in a graceful, clean, and easy way. NET to complete the work. To give you some examples of using. NET Framwork, we'll discuss 4 common tasks you might need to perform in your application: Tracking and event logging, multithreading, file system monitoring, and creating Windows services.

Tracking and event logging

When creating a robust application, you must pay close attention to diagnostics and troubleshooting mechanisms. Typically, this includes writing trace components that handle opening output targets (event records or files), writing trace messages, and closing output targets. It then invokes the method on the component through its own code, passing the text to the record. You spend all your time and energy on creating tracking and recording subsystems that will ultimately not contribute to solving business problems, but this is necessary to create applications.

The. NET framework includes classes and other data types, making it easy to track messages by providing you with a recording infrastructure. Figure 2 shows the. NET Framework classes for tracking.


Figure 2. The tracking tool used in. NET Framewok

Class is part of the System.Diagnostics namespace. The Trace class provides several shared methods. For example, the Write method allows you to record a particular message, and the Assert method allows you to log a message if a particular condition is false. The Trace class outputs messages to an object in the Listeners collection. Each object in this collection belongs to a class that inherits from TraceListener. EventLogTraceListener writes a message to an event record, while TextWriterTraceListener writes the message to a text file, and by default, An instance of DefaultTraceListener is added to the listeners collection of the Trace class.

In addition to the standard listener program, you can implement your own tracking listener. For example, you want to receive trace output from an application running on a remote machine behind a firewall. You can write a tracking listener that sends trace messages to your server across HTTP. This will affect the performance of your application, but will only affect performance when tracing is enabled.

Typically, you need to be able to include or remove trace code from the compiled binaries. To do this in Visual Basic 6.0, you need to use the compile constants and include all the trace code in the #if statement, which makes the code difficult to understand and maintain. With the. NET Framework, you only need to set the trace compilation constants to on or off state in the Project Properties dialog box; You do not need to include trace code in the #if statement.

Another commonly expected tracking feature is tracking horizontal settings, which include different tracking settings-for example, Severe (critical), error (Errors), Warning (warning), and information (information)-These settings control what information is logged. You can control this by using the registry values that are read when the trace component is started. This is a completely built-in feature for the. NET Framework. You can set a registry value to control the record level of your current application, for example, to use Trace.writeif and Trace.WriteLineIf to log messages only if the tracking level is set to severe (severe).

The integrated tracking and logging features greatly enhance productivity because you only need to use the built-in features to focus on writing real application code.

Multithreaded applications

An important feature of the. NET Framework is that you can use Visual Basic to create multithreaded applications without using third-party tools or unsupported Visual Basic techniques.. net Multithreaded support for the framework is provided by classes and interfaces in the System.Threading namespace, so all. NET languages can create and process threads in the same way. System.Threading.Thread is a core class that provides support for creating and controlling threads. To create a thread, you can create a new System.Threading.Thread object and pass the constructor to the ThreadStart proxy. This agent provides a way for this thread to start executing. When you are ready to start this new thread, you can invoke Thread.Start () (see Listing 1).

When you start creating multithreaded applications, you quickly realize that you need to control access to shared resources, such as shared class variables. The. NET framework also includes several classes and data types that you can use to synchronize the actions performed by two of threads.

In the simplest case, you have a shared variable that needs to be updated from a different thread. To do this, you can use the System.Threading.Interlocked class. For example, you can increment or decrement a shared variable named num by writing interlocked.increment (num) or interlocked.decrement (num) respectively. You can also use interlocked to set a variable to a specific value, or to check whether two variables are equal. In addition to this simple scenario, you can use the. NET Framework classes to perform more complex thread synchronization, such as synchronization of events and mutexes-all from within the. NET Framework without using the Win32 API ...

Imports System.IO
' The namespace System.Threading
' Contains the Thread class
Imports System.Threading
Module Module1
Private count as Long
Sub Main ()
' Create the ThreadStart delegate
Dim Tstart as ThreadStart = New _
ThreadStart (AddressOf startcounting)
' Create the thread '
Dim T1 as thread = New thread (tstart)
Console.WriteLine ("Enter Q to Quit")
T1. Start () ' Start ' thread
while (Console.read () <> ASC ("Q"))
' Repeat the loop until the user enters Q
End While
T1. Stop () "Tell thread" to stop processing
T1. Join () ' Wait until the thread finishes
End Sub
Sub startcounting ()
Todo
' Use interlocked.increment in case
' Another thread is accessing the same variable
Interlocked.Increment (count)
Console.WriteLine (_
"After incrementing count is: {0}", count)
Thread.Sleep (200)
Loop
End Sub
End Module

Listing 1. Use Visual Basic. NET Create thread

You create a new thread and pass it on to a ThreadStart agent. Then call Thread.Start () to start this thread. You can abort the thread by calling Thread.stop (), and then call Thread.Join () to wait for it to complete the shutdown operation. A thread can use System.Threading.Interlocked to increment or decrement a variable.

In addition, the. NET Framework provides a convenient mechanism to queue work and to assign it to a thread in the thread pool. This is useful in server applications that handle multiple concurrent work items or work requests. For example, an application that waits for input files and then imports them into a database may queue each input file for processing on a separate thread in the thread pool. The System.Threading.ThreadPool class allows you to queue work by using a shared QueueUserWorkItem method. To do this before, you have to create and manage your own thread pool. You also need to spend a lot of time and energy working on infrastructure rather than solving business problems.

File system Monitoring

I have encountered applications that need to wait and work on files in a particular directory-for example, an application that imports data from a file into a database. Data files can be downloaded from a mainframe or moved to an input directory that the application imports into the database. You do not have to poll the directory frequently to check for new files, and you can wait for notifications of new files to be generated. You can do this using the Win32 API in Visual Basic 6.0, while in Visual Basic. NET, you can use the. NET Framework classes to do this work. But in. NET implementation of file monitoring is more consistent with other work done in. NET, so the learning curve is minimal.

You can use System.IO.FileSystemWatcher. NET class to monitor the file system. It provides properties that allow you to set the path of the monitor, specifying whether to be interested in changes to the file or subdirectory level. System.IO.FileSystemWatcher also allows you to specify the file name and file type that you want to monitor (for example, *.xml is to monitor changes to all XML files). Finally, you can specify the type of change you are interested in-for example, only new files, changes in file attributes, or changes in file size (see Listing 2).

After you have set up the monitoring content, you need to hook up the event handlers for the various events of interest. FileSystemWatcher events include changed, Created, Deleted, Error, and renamed. To handle an event, you first need to write an event handler with the same declaration as the FileSystemEventHandler agent, and then add the handler to the FileSystemWatcher class. This agent-based architecture allows you to add multiple handlers for the same event, or use the same handler for multiple events-and you can't do that with Visual Basic 6.0.

' System.IO contains the
' File monitoring classes and types
Imports System.IO
Module Module1

Sub Main ()
' FileSystemWatcher does the real work
Dim FW as New FileSystemWatcher ()
' WaitForChangedResult is what you
' Get back to a change occurs
Dim result as WaitForChangedResult
' Set the path to monitor
Fw. Path = "C:\WINNT\"
' Tell it whether to watch files or directories
Fw. Target = Watchertarget.file
' Tell it whether to include Subdirs
Fw. IncludeSubdirectories = False
' Hook up handlers
AddHandler FW. Created, _
New FileSystemEventHandler (AddressOf onfilenotify)
' Enable the Watcher
Fw. Enabled = True
Todo
Console.WriteLine ("Beginning to monitor")
' This is where we actually wait
' Waiting blocks execution for the specified timeout
result = FW. WaitForChanged (Watcherchangetypes.all, 60000)
Console.WriteLine ("Hit Enter to continue Q to quit")
Loop while (console.readline <> "Q")
End Sub
' This is the delegate ' gets
' Called when a file is created
Public Sub onfilenotify (ByVal source as Object, _
ByVal e as FileSystemEventArgs)
Console.WriteLine (_
"Notification received for file {0}, change type is {1}", _
E.fullpath, e.ChangeType)
End Sub
End Module

Listing 2. Use FileSystemWatcher to monitor whether a folder has a new file.

You can create a FileSystemWatcher and then set its properties. You can use AddHandler to associate FileSystemEventHandler agents with various FileSystemWatcher events, such as created. Then you can enable FileSystemWatcher, and then call WaitForChanged. The call returns when the change occurs or when the specified timeout is reached.

Creating Windows Services

When you want to create a Windows service, you must use Visual C + + or use Srvany.exe or Third-party tools in Visual Basic to create the service. Either way, you're not writing your own service in Visual Basic, you're just adding more subordinate components outside of the Visual Basic runtime.

If you use C + + or C to write a Windows service from scratch without using the active Template Library, you will have to write a small piece of code to coordinate your service and service controller MANAGER,SCM), SCM is used to process service startup, pause, resume, and stop. The. NET framework makes it easy to implement a service by providing a System.ServiceProcess.ServiceBase class. To write a service, you can inherit from this class, overload some of its methods, set its properties, and then it's done!

Some of the methods you may want to overload include: OnStart, OnStop, OnPause, and OnContinue. Typically you need to load the location overload onstart that initiates the worker thread (worker thread), overloading OnStop where you need to cancel the worker thread. After you create your own service, you can use SCM to install and register the service. This is another area where the base class in the. NET Framework provides most of the work that is required. You can create a class that inherits from System.Configuration.Install.Installer, sample the object from System.ServiceProcess.ServiceInstaller, and then set its properties, such as service startup mode and service name. This makes. NET Installation Utility InstallUtil.exe can install (and remove) your service, and you do not need to write additional code.

When you start using Visual Studio. NET, you will find visual Studio. NET makes it easier to use the. NET Framework. Visual Studio. NET allows you to create Windows services (with installers (installer)), monitor file system changes, and write event records-all using designers and components rather than writing code to complete them. For example, to add an installer to your service project, you simply select the service designer to avoid, and then click the Add Installer (add Installer) at the bottom of the Properties window (see Figure 3). This will add a new module, Projectinstaller.vb, which includes all the code needed to install the service. You can use the designer (see Figure 4) To customize the installation options, such as startup mode


Figure 3. Use Visual Studio. NET adds an installer to your service project


Figure 4. Use the designer to customize installation options, such as StartType

Conclusion

The. NET Framework enables you to easily develop robust applications using visual Basic. Net. It allows you to focus on learning a compatible program design model, and allows you to directly access the underlying. NET platform. Take advantage of visual Basic. NET and the. NET Framework, you can bring your application to an unprecedented level.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.