Working with Console Applications

Console applications are programs that operate from the command line, and like other applications you create with Microsoft Visual Basic .NET, they have full access to the .NET class library and to features such as inheritance, constructors, overloading, and initializers. They can also access other .NET applications. Console applications are lightweight and fast because they don’t require a graphical user interface.

Application #53 Working with Console Applications

This sample application shows you how to create and use a console application. The application uses Microsoft SQL Server to read the Northwind database Products table into a dataset. When the application is run, it can accept a command-line argument or input from the user, which is either a Product ID or QUIT.

If a valid Product ID (integer format) is entered, its associated product information is displayed. If an invalid Product ID is entered, an exception message is displayed. You can continue to input Product IDs as long as you care to. When you type QUIT and press Enter, the application ends.

Building Upon…

Application #1: Use Arrays

Application #3: String Manipulation

Application #12: Use a DataSet and DataView

New Concepts

Microsoft Visual Basic .NET makes it easy to create and use console applications. Here’s how.

Creating a Console Application

To create a console application in Microsoft Visual Studio .NET, simply select the Console Application template when you’re creating a new project. Of course, as with any other .NET application, you could build it entirely in Notepad. Building it in Notepad, though, you’d need to do quite a bit more work, such as adding references yourself, compiling from the command line, and so on.

When you create the application in Visual Studio .NET, you’ll get just two files, AssemblyInfo.vb and Module1.vb. In Module1.vb, you’ll find a Sub procedure named Main. This is the entry point for your application. You can add other procedures as needed and call them from Main.

Reading to and Writing from the Console

Four methods of the Console class help you get data from the user and write to the console window: Read, ReadLine, Write, and WriteLine. Here’s what they do:

Uses for Console Applications

Console applications are useful in situations such as:

Console applications can conveniently be called from logon scripts or batch processes, and they can interact with both input and output files.

Code Walkthrough

The starting point for the console application is the Sub Main procedure, from which all other procedures can be called.

Handling Command-Line Arguments

In a console application Sub Main procedure, we can handle any command-line parameters the user entered. In the following code, we’re allowing for one or more command-line arguments in an array named args. (The name is our choice.) If the args array has any elements, we’ll use the first one (index zero) to find a matching product. Otherwise, we’ll get input from the user at the command line. First, though, we’ll connect to the database and populate a DataSet with data from the Products table.

SubMain(ByValargs()AsString) ⋮ ConnectToDB() Ifargs.Length>0Then FindProduct(args(0)) Else Console.WriteLine("{0}{1}",vbCrLf,PROMPT_MESSAGE) DimstrInputAsString=UCase(Trim(Console.ReadLine()))

We’ll keep going until the user types QUIT, and we’ll search for a matching product each time. We check to make sure the user has typed something before he has pressed the Enter key by testing the length of the input string.

WhileUCase(strInput)<> "QUIT" IfLen(strInput)>0Then FindProduct(strInput) EndIf

Before reading the user’s next input, we present the prompt message. Note that the Write and WriteLine methods accept a format parameter in just the same way as String.Format does. (See “Application #3: String Manipulation” in Chapter 2 for more information.)

Console.WriteLine("{0}{1}",vbCrLf,PROMPT_MESSAGE) strInput=UCase(Trim(Console.ReadLine())) EndWhile End EndIf EndSub

To get the data the user wants, we need to connect to a database. In the following procedure, we’ll first try to connect to the local SQL Server instance. If that doesn’t work, we’ll try a local Microsoft Data Engine (MSDE) installation (with the Northwind database).

PrivateSubConnectToDB() DimstrConnectionAsString=SQL_CONNECTION_STRING DimIsConnectingAsBoolean=True WhileIsConnecting Try DimnorthwindConnectionAsNewSqlConnection(strConnecti on) DimProductAdapterAsNewSqlDataAdapter("SELECT*FROM " &_ "Products",northwindConnection) ProductAdapter.Fill(dsProducts, "Products")

Assuming the connection succeeded, we create a couple of DataViews, which let us sort as well as search the data in the DataSet. The first DataView will be used to find a product by its ID, and the second one will be used to find a product by its name.

dvProductsByID=NewDataView(dsProducts.Tables("products "),_ "", "ProductIDASC",DataViewRowState.OriginalRows) dvProductsByName=NewDataView(dsProducts.Tables(_ "products"), "", "ProductNameASC",_ DataViewRowState.OriginalRows)

If the attempt to connect with the first connection string fails, we try the alternate string.

CatchexcAsException IfstrConnection=SQL_CONNECTION_STRINGThen strConnection=MSDE_CONNECTION_STRING Console.WriteLine("AttemptingtoConnecttoMSDE") Else Console.WriteLine("Torunthissample,youmusthave " &_ "SQLServerorMSDEwiththeNorthwinddatabase " &_ "installed.ForinstructionsoninstallingMSDE, " &_ "viewReadMe.") End EndIf EndTry EndWhile Console.WriteLine("ConnectedtoDatabase.") EndSub

Finding Records

The FindProduct procedure searches for a matching product in the database, based on the user’s input. It displays the product information if a valid ProductID or ProductName is found; otherwise, it displays an exception message. If the user enters a number, we search the DataView that’s indexed on the ProductID. Otherwise, we search the ProductsByName DataView. We’ll be writing data from the dvProducts DataView later, so we assign it to either the ID-related DataView or the Name-related one.

PrivateSubFindProduct(ByValstrInputAsString) DimintItemAsInteger IfIsNumeric(strInput)Then intItem=dvProductsByID.Find(strInput) dvProducts=dvProductsByID Else intItem=dvProductsByName.Find(strInput) dvProducts=dvProductsByName EndIf

Once we’re sure we’ve found a match (any result other than -1), we’re ready to write the product information. The Write and WriteLine methods of the Console object accept a formatting parameter that lets you do a variety of things, such as aligning the output data into columns by specifying how many characters you want written. In this case, we’re writing 17 chars in column 1. “{0}{1,-17}" means that we will write parameter zero, followed immediately by parameter 1, which is to be padded to 17 characters.

IfintItem=-1Then Console.WriteLine("Noproductfound.") Else Console.Write("{0}{1,-17}",vbCrLf, "ProductID: ") Console.WriteLine(dvProducts(intItem)("ProductID")) Console.Write("{0,-17}", "ProductName: ") Console.WriteLine(dvProducts(intItem)("ProductName")) ⋮ Console.Write("{0,-17}", "Discontinued: ") IfCBool(dvProducts(intItem)("Discontinued"))=FalseThen Console.WriteLine("False") Else Console.WriteLine("True") EndIf EndIf EndSub

Conclusion

Console applications are in many ways as powerful as their more sophisticated counterparts, and they come in handy for many batch-oriented requirements. Keep the following in mind as you work with them:

Категории