Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Beginning Visual Basic 2005 Express Edition - From Novice To Professional (2006)

.pdf
Скачиваний:
392
Добавлен:
17.08.2013
Размер:
21.25 Mб
Скачать

410

C H A P T E R 1 5 W O R K I N G W I T H X M L

So, you have your root element, and you have a customer element in there. Now you can add some content to the new Customer element. Let’s start by adding in an attribute with the customer’s ID:

You write attributes by calling WriteAttributeString(), and pass in first the attribute name and then its value:

Sub Main()

Dim writer As XmlWriter = _

XmlWriter.Create("c:\test.xml")

writer.WriteStartDocument()

writer.WriteStartElement("Customers")

writer.WriteStartElement("Customer")

writer.WriteAttributeString("ID", "1234")

writer.WriteEndElement()

writer.WriteEndElement()

End Sub

That effectively makes the customer tag in the document look like this:

<Customer ID="1234">

Let’s finish up by adding a child element with a value. You can do this with a call to WriteElementString() passing in the name of the new element and its value. This may seem a little limiting, being forced to just write strings, but it really isn’t. XML documents are text, strings by default. In addition, all .NET types have a ToPrint() method so you can pretty much convert anything you have into a string. Reading is a different matter—it makes a lot of sense to be able to read in native .NET data types.

Add the new call into the code:

Sub Main()

Dim writer As XmlWriter = _

XmlWriter.Create("c:\test.xml")

writer.WriteStartDocument()

writer.WriteStartElement("Customers")

C H A P T E R 1 5 W O R K I N G W I T H X M L

411

writer.WriteStartElement("Customer")

writer.WriteAttributeString("ID", "1234") writer.WriteElementString("Address", _

"12 Somewhere Street, Sometown, 12354")

writer.WriteEndElement()

writer.WriteEndElement()

End Sub

All that you need to do now is close the document. It’s a good idea to get in the habit of calling WriteEndDocument() on the writer as the last thing you do. This makes sure that any open tags you haven’t closed are automatically closed for you. Also, you should call Flush() and Close() to make sure there’s nothing hanging around in the writer that really should be written out, and that the underlying data stream is closed. Go ahead and make those changes:

Sub Main()

Dim writer As XmlWriter = _

XmlWriter.Create("c:\test.xml")

writer.WriteStartDocument()

writer.WriteStartElement("Customers")

writer.WriteStartElement("Customer")

writer.WriteAttributeString("ID", "1234") writer.WriteElementString("Address", _

"12 Somewhere Street, Sometown, 12354")

writer.WriteEndElement()

writer.WriteEndElement()

writer.Flush()

writer.Close()

End Sub

412 C H A P T E R 1 5 W O R K I N G W I T H X M L

Run the program now. If everything goes to plan, you won’t see anything other than the flash of the console window coming into view and then vanishing. When the program’s finished, start Notepad and load up the C:\Test.xml file you just created. You’ll see the view in Figure 15-9.

Figure 15-9. The XmlWriter produced a well-formed but ugly XML document.

Pretty ugly, isn’t it. We can fix that easily, thanks to the XmlWriterSettings class. This class lets us build up a bunch of properties to apply to the writer to control how the resulting document is formatted.

Of particular interest to us is the XmlWriterSettings.Indent property. Setting this to True causes the resulting document to be nicely indented and formatted more as people would expect to see it. Using the XmlWriterSettings class is very easy. Make the changes shown in the following code, and then I’ll talk you through them:

Sub Main()

Dim settings As New XmlWriterSettings settings.Indent = True

Dim writer As XmlWriter = _

XmlWriter.Create("c:\test.xml", settings)

writer.WriteStartDocument()

writer.WriteStartElement("Customers")

writer.WriteStartElement("Customer")

C H A P T E R 1 5 W O R K I N G W I T H X M L

413

writer.WriteAttributeString("ID", "1234") writer.WriteElementString("Address", _

"12 Somewhere Street, Sometown, 12354")

writer.WriteEndElement()

writer.WriteEndElement()

writer.Flush()

writer.Close()

End Sub

All you need to do is create the object, set the property you want, and then pass the settings object to the

XmlWriter.Create() call.

If you run the code and then open the C:\test.xml file in Notepad, the view will be very different, as you can see in Figure 15-10.

Figure 15-10. Using XmlWriterSettings lets us format the document and control the operation of the writer.

Feel free to wander through IntelliSense or the online help to see the other properties of the XmlWriterSettings object; you’ll find how they are all used quite obvious.

414

C H A P T E R 1 5 W O R K I N G W I T H X M L

Summary

I have to confess that we’ve only scratched the surface of XML support in .NET. The goal was to introduce you to the features and get you coding. There’s actually enough content and features to System.Xml to fill an entire book all its own. If you are an XML fiend, I’m sure you’ll have a ball browsing through the property and method lists of XmlDocument,

XPathNavigator, XmlReader, XmlWriter, XmlReaderSettings, and XmlWriterSettings.

In the next chapter we’ll move away from XML files as data stores and move to using fully featured SQL Server databases and the built-in database features in Visual Basic 2005 Express.

C H A P T E R 1 6

■ ■ ■

Database Programming

It used to be the case that if you wanted to use a database in your application, you had just two choices: cheap or eye-wateringly expensive. It also used to be the case that in the world of databases you get what you pay for. At the cheap end of the scale, Microsoft’s desktop database Access certainly got the job done, but it had severe limits on the amount of data it could store. Performance reading and writing large quantities of information to it from a Visual Basic application could be pretty abysmal.

The alternative, in the Microsoft world at least, was the eponymous SQL Server. Microsoft bills this as an enterprise-grade database server. It’s supposed to service huge businesses with vast quantities of information at incredible speeds. As you might guess then, deploying it with your application would cost an appropriately large amount of cash.

Visual Basic 2005 Express comes with SQL Server Express, a new product from Microsoft designed to bridge the gap between Access and SQL Server, providing many of the benefits of both products. For example, a database in SQL Server Express is nothing more than a file, just as an Access database is nothing more than a file. If you intend on distributing your application to other users, this is a great thing; you can install the database along with your application just like any other file. In addition, SQL Server Express supports many of the features of SQL Server, including the database engine. Obviously there are some limitations (a limit on the maximum file size, a limit on the number of users who can simultaneously connect to the database, and so on), but by and large SQL Server Express is just like SQL Server. The big difference, of course, is that it’s free.

A large part of the .NET Framework is devoted to working with databases. Also, Visual Basic 2005 Express provides many tools right inside the IDE that let you work with databases effortlessly, in many cases without ever having to have to write code. That being said, there’s a lot of depth to ADO.NET (the database programming classes in the framework) that you’ll never really need until you move up to the full Visual Studio 2005 package.

In this chapter I’m going to introduce you to database programming with Visual Basic 2005 Express. This won’t be an extensive investigation of how to work with SQL Server databases—for that you should consult the online help. Similarly, this won’t be an exhaustive examination of every feature of ADO.NET—for that, check out my other book,

ADO.NET: From Novice to Pro (Apress, 2002). What I will cover, though, are all the most

415

416 C H A P T E R 1 6 D A T A B A S E P R O G R A M M I N G

common things you are likely to want to do with a database and VB. I’ll cover how to create a database, for example, how to build tables and stored procedures, and how to get information both into and out of a database by using controls on your Windows forms. By the end of this chapter you should be quite happy with writing your own data-enabled applications. For those of you wanting to go further, I’ll close with some pointers to more information on the areas we didn’t cover.

A Quick Walk-Through of the Tools

Before we go any further, you are going to need to download some samples from Microsoft. Simply point your browser at http://msdn.microsoft.com/sql/downloads/ samples and follow the link to SQL Server 2005 Express Edition Samples and Sample Database. This will take you to a download page where you need to download the AdventureWorksDB.msi file. After you’ve downloaded it, run it to install the sample database we’ll be working with in this chapter onto your computer. Please note, there have been some problems with people running this installer on machines that have the full version of Visual Studio 2005 or SQL Server 2005 installed. If that applies to you, then that’s something to be aware of.

After you’ve downloaded the samples and installed them, you’re ready to start on the walk-through.

Try It Out: Introducing the Database Tools

Start up a new Windows application project in Visual Basic 2005 Express. You’re going to pull some data from the Adventure Works sample database and display it on the form—this is something that would historically have required quite a bit of code, but as you’ll see here VB Express’s built-in database tools make it trivial.

After the project is created, you’ll need to add a reference to the database you’re going to use. If this were a full enterprise-grade SQL Server database, you’d just enter a connection string to point your application at the live database. In this case, though, using SQL Express you’re actually going to pull the entire database into your app, just to show how that works.

Click the Data menu and select Add New Data Source. You’ll see the first page of the Data Source Configuration Wizard appear, asking you what kind of data source you want to work with. As you can see in Figure 16-1, VB Express lets you choose to use a web service, actual database, or even objects as data sources. You want a database, so click Database and then click the Next button.

C H A P T E R 1 6 D A T A B A S E P R O G R A M M I N G

417

Figure 16-1. The first page of the Data Source Configuration Wizard lets you choose the type of object you want to get data from.

The next page of the wizard, shown in Figure 16-2, lets you set up the connection to the database. If you’ve used VB Express to connect to databases before, you’ll be able to quickly access those database connections from the drop-down list.

Figure 16-2. The second page lets you reuse connections you’ve established before or create a

new one.

418 C H A P T E R 1 6 D A T A B A S E P R O G R A M M I N G

You need to set up a brand new connection to the Adventure Works database, so click the New Connection button. This brings up the Add Connection dialog box shown in Figure 16-3.

Figure 16-3. Clicking New Connection brings up the Add Connection dialog.

This is similar to the old ODBC connection settings dialog that pre-.NET developers will be used to.

The top of the dialog shows the type of connection that you’re about to establish. In this case it’s a SQL Server database file, or SQL Server Express database. You could click Change to bring up a dialog to choose a different type of database to connect to, but for our purposes this is fine.

So the next step is simply to choose the database file that you want to connect to. Click the Browse button to bring up a file dialog and then navigate to where the Adventure Works database was installed (by default this is the somewhat arcane path of C:\Program Files\Microsoft SQL Server\

MSSQL.1\MSSQL\Data\_AdventureWorks_Data.mdf). After you’ve selected the file, click OK in the file browser to return to the Add Connection dialog, and click OK to finalize the connection. You’ll return to the Data Source Configuration page. Click Next.

C H A P T E R 1 6 D A T A B A S E P R O G R A M M I N G

419

Straight away the dialog in Figure 16-4 appears.

Figure 16-4. Selecting a database file causes this dialog to appear.

Because you are working with a SQL Server Express database, VB Express gives you the option to copy the file into your project. As the dialog indicates, doing this provides the benefit that you can easily deploy the database along with your application. You don’t have to copy it, though; the connection string will work just fine with the database staying in its original location. For our purposes, copying is fine. Click the Yes button to copy the database into the project completely.

After the database is copied (you’ll see it appear in the Solution Explorer), the next page of the wizard appears, as shown in Figure 16-5.

Figure 16-5. The next page of the wizard asks you for a name to save the connection string.