1. Trang chủ
  2. » Công Nghệ Thông Tin

Beginning Visual Basic 2005 phần 9 ppt

84 289 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

Deleting Addresses To finish the functionality of your address book, you’ll deal with deleting items. When deleting items, you must take into account that the item you are deleting is the last remaining item. In this case, you’ll have to provide the appropriate code to add a new blank address. This Try It Out will provide this and all necessary functionality to delete an address properly. Try It Out Deleting Addresses 1. Go back to the Form Designer for Form1 and double-click the Delete button. Add this code to the event handler, and also add the DeleteAddress method: Private Sub btnDelete_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles btnDelete.Click ‘ ask the user if they are ok with this? If MsgBox (“Are you sure you want to delete this address?”, _ MsgBoxStyle.Question Or MsgBoxStyle.YesNo) = _ MsgBoxResult.Yes Then DeleteAddress(CurrentAddressIndex) End If End Sub ‘ DeleteAddress - delete an address from the list Public Sub DeleteAddress(ByVal index As Integer) ‘ delete the item from the list AddressBook.Items.RemoveAt(index - 1) ‘ was that the last address? If AddressBook.Items.Count = 0 Then ‘ add a new address? AddressBook.AddAddress() Else ‘ make sure you have something to show If index > AddressBook.Items.Count Then index = AddressBook.Items.Count End If End If ‘ display the record CurrentAddressIndex = index End Sub 2. Run the project. You should be able to delete records from the address book. Note that if you delete the last record, a new record will automatically be created. How It Works The algorithm you’ve used here to delete the records is an example of how to solve another classic pro- gramming problem. Your application is set up so that it always has to display a record. That’s why, when the program is first run and there is no AddressBook.xml, you automatically create a new record. Likewise, when an item is deleted from the address book, you have to find something to present to the user. To physically delete an address from the disk, you use the RemoveAt method on the ArrayList that holds the Address objects. 638 Chapter 19 22_574019 ch19.qxd 9/16/05 9:38 PM Page 638 ‘ DeleteAddress - delete an address from the list Public Sub DeleteAddress(ByVal index As Integer) ‘ delete the item from the list AddressBook.Items.RemoveAt(index - 1) Again, notice here that, because you’re working with a zero-based array, when you ask to delete the address with an index of 3, you actually have to delete the address at position 2 in the array. The problems start after you’ve done that. It could be that you’ve deleted the one remaining address in the book. In this case, because you always have to display an address, you create a new one: ‘ was that the last address? If AddressBook.Items.Count = 0 Then ‘ add a new address? AddressBook.AddAddress() Alternatively, if there are items in the address book, you have to change the display. In some cases, the value that’s currently stored in CurrentAddressIndex will be valid. For example, if you had five records and are looking at the third one, _currentAddressIndex will be 3. If you delete that record, you have four records, but the third one as reported by _currentAddressIndex will still be 3 and will still be valid. However, as 4 has now shuffled into 3’s place, you need to update the display. It could be the case that you’ve deleted the last item in the list. When this happens, the index isn’t valid, because the index would be positioned over the end of the list. (Suppose you have four items in the list; delete the fourth one, and you only have three, but _currentAddressIndex would be 4, which isn’t valid.) So, when the last item is deleted, the index will be over the end of the list, so you set it to be the last item in the list: Else ‘ make sure you have something to show If index > AddressBook.Items.Count Then index = AddressBook.Items.Count End If End If Whatever actually happens, you still need to update the display. As you know, the CurrentAddressIndex property can do this for you: ‘ display the record CurrentAddressIndex = index End Sub Testing at the Edges This brings us on to a programming technique that can greatly help you test your applications. When writing software, things usually go wrong at the “edge”. For example, you have a function that takes an integer value, but in order for the method to work properly, the value supplied must lie between 0 and 99. Once you’re satisfied that your algorithm works properly when you give it a valid value, test some val- ues at the “edge” of the problem (in other words, at the boundaries of the valid data). For example: _1, 0, 99, and 100. In most cases, if your method works properly for one or two of the possible valid values, it 639 Visual Basic 2005 and XML 22_574019 ch19.qxd 9/16/05 9:38 PM Page 639 will work properly for the entire set of valid values. Testing a few values at the edge will show you where potential problems with the method lie. A classic example of this is with your MoveNext and MovePrevious methods. If you had a hundred addresses in your address book and only tested that MoveNext and MovePrevious worked between numbers 10 and 20, it most likely would have worked between 1 and 100. However, the moment you move past 100 (in other words “go over the edge”), problems can occur. If you hadn’t handled this case properly by flipping back to 1, your program would have crashed. Integrating with the Address Book Application So far, you’ve built an application that is able to save and load its data as an XML document. You’ve also taken a look at the document as it’s been changing over the course of the chapter, so by now you should have a pretty good idea of what an XML document looks like and how it works. The beginning of this chapter pitched XML as a technology for integrating software applications. It then went on to say that for newcomers to Visual Basic, using XML for integration is unlikely to be something that you would do on a day-to-day basis, and so you’ve been using XML to store data. In the rest of this chapter, we’re going to demonstrate why XML is such a good technology for integration. What you’ll do is build a separate application that, with very little work, is able to read in and understand the propri- etary data format that you’ve used in AddressBook.xml. Using XML is an advanced topic, so, if you would like to learn more about the technology and its appli- cation, try the following books: ❑ Beginning XML, 2nd Edition (ISBN 1-86100-559-8) ❑ Visual Basic .NET and XML: Harness the Power of XML in VB.NET Applications (ISBN 0-471-26509-8) Demonstrating the Principle of Integration Before you build the application that can integrate with your address book application, you should try to understand the principles involved. Basically, XML documents are good for integration because they can be easily read, understood, and changed by other people. Old-school file formats require detailed documentation to understand and often don’t “evolve” well —that is, when new versions of the format are released, software that worked with the old formats often breaks. XML documents are typically easily understood. Imagine you’d never seen or heard of your address book before, and look at this XML document: <Addresses> <Address> <FirstName>Bryan</FirstName> <LastName>Newsome</LastName> <CompanyName>Wiley</CompanyName> <Address1>123 Main St</Address1> 640 Chapter 19 22_574019 ch19.qxd 9/16/05 9:38 PM Page 640 <Address2 /> <City>Big City</City> <Region>SE</Region> <PostalCode>28222</PostalCode> <Country>USA</Country> <Email>Bryan@email.com</Email> </Address> </Addresses> Common sense tells you what this document represents. You can also perceive how the program that generated it uses it. In addition, you can use the various tools in .NET to load, manipulate, and work with this document. To an extent, you still need to work with the people that designed the structure of the document, especially when more esoteric elements come into play, but you can use this document to some meaningful effect without too much stress. Providing you know what structure the document takes, you can build your own document or add new things to it. For example, if you know that the Addresses element contains a list of Address elements, and that each Address element contains a bunch of elements that describe the address, you can add your own Address element using your own application. To see this happening, you can open the AddressBook.xml file in Notepad. You need to copy the last Address element (complete with the contents) to the bottom of the document, but make sure it remains inside the Addresses element. Change the address data to something else. Here’s mine: <?xml version=”1.0” encoding=”utf-8”?> <AddressBook xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”> <Addresses> <Address> <FirstName>Bryan</FirstName> <LastName>Newsome</LastName> <CompanyName>Wiley</CompanyName> <Address1>123 Main St</Address1> <Address2 /> <City>Big City</City> <Region>SE</Region> <PostalCode>28222</PostalCode> <Country>USA</Country> <Email>Bryan@email.com</Email> </Address> <Address> <FirstName>Jennifer</FirstName> <LastName>Newsome</LastName> <CompanyName /> <Address1>123 Main St</Address1> <Address2 /> <City>Big City</City> <Region>SE</Region> <PostalCode>28222</PostalCode> <Country>USA</Country> <Email /> </Address> </Addresses> </AddressBook> 641 Visual Basic 2005 and XML 22_574019 ch19.qxd 9/16/05 9:38 PM Page 641 Finally, if you save the file and run the address book application, you should find that you have two addresses and that the last one is the new one that you added. What this shows is that, providing you understand the format of the XML that the application uses, you can manipulate the document and gain some level of integration. Reading the Address Book from Another Application To further the illustration, what you’ll do in the next Try It Out is build a completely separate application from Address Book that’s able to load in the XML file that Address Book uses and do something useful with it. Specifically, you’ll extract all of the addresses in the file and display a list of names together with their matching e-mail addresses. Try It Out Reading Address Book Data 1. Create a new Visual Basic .NET Windows Application project. Call it Address List. 2. On Form1, draw a ListBox control. Change its IntegralHeight property to False, its Dock prop- erty to Fill, and its Name to lstEmails, as shown in Figure 19-7. Figure 19-7 3. Double-click the form’s title bar. Add this code to the Load event handler. Remember to add a reference to System.Xml.dll this namespace declaration: Imports System.Xml Public Class Form1 Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ‘ where do we want to get the XML from Dim filename As String = _ “ C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\Address Book\Address Book\bin\Debug\AddressBook.xml” ‘ open the document Dim reader As New XmlTextReader(filename) ‘ move to the start of the document 642 Chapter 19 22_574019 ch19.qxd 9/16/05 9:38 PM Page 642 reader.MoveToContent() ‘ start working through the document Dim addressData As Collection = Nothing Dim elementName As String = Nothing Do While reader.Read ‘ what kind of node to we have? Select Case reader.NodeType ‘ is it the start of an element? Case XmlNodeType.Element ‘ if it’s an element start, is it “Address”? If reader.Name = “Address” Then ‘ if so, create a new collection addressData = New Collection() Else ‘ if not, record the name of the element elementName = reader.Name End If ‘ if we have some text, try storing it in the ‘ collection Case XmlNodeType.Text ‘ do we have an address? If Not addressData Is Nothing Then addressData.Add(reader.Value, elementName) End If ‘ is it the end of an element? Case XmlNodeType.EndElement ‘ if it is, we should have an entire address stored If reader.Name = “Address” Then ‘ try to create a new listview item Dim item As String = Nothing Try item = addressData(“firstname”) & _ “ “ & addressData(“lastname”) item &= “ (“ & addressData(“email”) & “)” Catch End Try ‘ add the item to the list lstEmails.Items.Add(item) ‘ reset addressData = Nothing End If End Select Loop End Sub We’ve assumed in this code listing that your AddressBook.xml will be in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\Address Book\Address Book\bin\Debug. If yours isn’t, change the filename value specified at the top of the code. 4. Run the project; you should see something like what is shown in Figure 19-8. Notice that addresses that don’t have an e-mail address display without problems, as the Email element in your XML file contains an empty string value instead of a null value as is typically found in databases. 643 Visual Basic 2005 and XML 22_574019 ch19.qxd 9/16/05 9:38 PM Page 643 Figure 19-8 How It Works To fully appreciate the benefit of this exercise (and therefore the benefit of XML), imagine that before writing the application you’d never seen the XML format used by the Address Book application. Since XML is a text-based format, you’re able to open it in a normal text editor, read it, and make assumptions about how it works. You know that you want to get a list of names and e-mail addresses, and you under- stand that you have an array of Address elements, each one containing the three elements you need: FirstName, LastName, and Email. All that remains is to extract and present the information. Since announcing .NET, Microsoft has a made a big play about how it is built on XML. This shows in the .NET Framework support for XML —there is a dazzling array of classes for reading and writing XML documents. The XmlSerializer object that you’ve been using up until now is by far the easiest one to use, but it relies on your having classes that match the document structure exactly. Therefore, if you are given a document from a business partner, you won’t have a set of classes that matches the document. As a result, you need some other way to read the document and fit it into whatever classes you do have. In your Address List project, you don’t have applicable AddressBook or Address classes, so you had to use some classes to “walk” through a file. The one you’re using is System.Xml.XmlTextReader. This class provides a “pointer” that starts at the top of the document and, on command, moves to the next part of the document. (Each of these parts is called a node.) The pointer will stop at anything, and this includes start tags, end tags, data values, and white space. So, when you start walking, the first thing XmlTextReader will tell you about is this node: <?xml version=”1.0” encoding=”utf-8”?> When you ask it to move on, it will tell you about this node: <AddressBook xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:xsd=”http://www.w3.org/2001/XMLSchema”> Then, when you ask it to move on again, it will tell you about this node: <Addresses> 644 Chapter 19 22_574019 ch19.qxd 9/16/05 9:38 PM Page 644 Then it will tell you about <Address>, <FirstName>, Bryan, </FirstName>, and <LastName>, and so on until it gets to the end of the document. In between each one of these, you may or may not get told about white space nodes. By and large, you can ignore these. What your algorithm has to do, then, is get hold of an XmlTextReader and start moving through the document one piece at a time. When you first start, the pointer will be set ahead of the first node in the document. Each call to Read moves the pointer along one node, so the first call to Read that you see at the start of the Do . . . While loop actually sets the pointer to the first node: Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ‘ where do you want to get the XML from Dim filename As String = _ “C:\Documents and Settings\Administrator\My Documents\” & _ “Visual Studio\Projects\Address Book\Address Book\bin\Debug\” & _ “AddressBook.xml” ‘ open the document Dim reader As New XmlTextReader(filename) ‘ move to the start of the document reader.MoveToContent() ‘ start working through the document Dim addressData As Collection, elementName As String Do While reader.Read You can use the NodeType property of XmlTextReader to find out what kind of node you’re looking at. If you have an Element node, this maps directly onto a start tag in the document. You can use the Name property to get the name of the tag. When you find the <Address> start tag, you create a new collection called addressData. If the start tag that you’re looking at isn’t the <Address> tag, you store the name in elementName for later use: ‘ what kind of node to we have? Select Case reader.NodeType ‘ is it the start of an element? Case XmlNodeType.Element ‘ if it’s an element start, is it “Address”? If reader.Name = “Address” Then ‘ if so, create a new collection addressData = New Collection() Else ‘ if not, record the name of the element elementName = reader.Name End If Alternatively, the node you get might be a lump of text. If this is the case, you check to see whether addressData points to a Collection object. If it does, you know that you are inside an Address ele- ment. Remember, you’ve also stored the name of the element that you are looking at inside elementName. This means that if elementName is set to FirstName, you know you’re in the FirstName element, and therefore the text element you’re looking at must be the first name in the address. You then add this ele- ment name and the value into the collection for later use: ‘ if we have some text, try storing it in the ‘ collection 645 Visual Basic 2005 and XML 22_574019 ch19.qxd 9/16/05 9:38 PM Page 645 Case XmlNodeType.Text ‘ do we have an address? If Not addressData Is Nothing Then addressData.Add(reader.Value, elementName) End If As you work through the file, you’ll get to this point for each of the elements stored in the Address ele- ment. Effectively, by the time you reach </Address>, addressData will contain entries for each value stored against the address in the document. To detect when you get to the </Address> tag, you need to look for EndElement nodes: ‘ is it the end of an element? Case XmlNodeType.EndElement When you get one of these, if Name is equal to Address, you know that you have reached </Address>, and this means that addressData should be fully populated. You form a string and add it to the list: ‘ if it is, you should have an entire address stored If reader.Name = “Address” Then ‘ try to create a new listview item Dim item As String Try item = addressData(“firstname”) & _ “ “ & addressData(“lastname”) item &= “ (“ & addressData(“email”) & “)” Catch End Try ‘ add the item to the list lstEmails.Items.Add(item) ‘ reset addressData = Nothing End If You’ll notice that in your Try . . . Catch you won’t do anything if an exception does occur. To keep this example simple, you’re going to ignore any problems that do occur. Specifically, you’ll run into problems if the Address element you’re looking through has subelements missing —for example, you might not always have an e-mail address for each address, as was shown in Figure 19-8. You then continue the loop. On each iteration of the loop, XmlTextReader.Read will be called, which advances the pointer to the next node. If there are no more nodes in the document, Read returns False, and the loop stops: End Select Loop End Sub I hope that this example has illustrated the power of XML from a software integration perspective. With very little work, you’ve managed to integrate the Address Book and Address List applications together. If you want to experiment with this a little, try adding and deleting addresses from the Address Book. You’ll need to close the program to save the changes to AddressBook.xml, but each time you start Address List, you should see the changes you made. 646 Chapter 19 22_574019 ch19.qxd 9/16/05 9:38 PM Page 646 Summary This chapter introduced the concept of XML. XML is a language based on open standards that can be used as a tool for software integration. Within a single organization, XML can be used to transport data across platforms easily. It also allows two organizations to define a common format for data exchange and, because XML is text-based, it can easily be moved around using Internet technologies such as e-mail, the Web, and FTP. XML is based on building up a document constructed of tags and data. XML is primarily used for integration work to make the tasks of data transportation and exchange easier, and you, as a newcomer to Visual Basic and programming in general, are unlikely to do integration work (as it’s typically done by developers with lots of experience). Nevertheless, this chapter has “dipped your toes in” so to speak, by focusing on using the System.Xml.Serialization.XmlSerializer class to save entire objects to disk (known as serialization). This same object was used to load objects from disk (known as deserialization). You built a fully functional address book application that was able to use an XML file stored on the local computer as its primary source of data. To round off the chapter and to demonstrate that XML is great for software integration work, you wrote a separate application that was able to load and make sense of the XML document used by the Address Book application. To summarize, you should: ❑ Have a better understanding of XML and know what it looks like ❑ How to serialize and deserialize XML data into objects ❑ How to manipulate XML data in your applications ❑ How to use the XMLTextReader class to walk through an XML document Exercises Exercise 1 Create an XML document that describes a table lamp. You can describe the lamp using a number of dif- ferent alternatives. You should describe items such as shade, bulbs and base. You can validate your XML at a site such as www.w3schools.com/dom/dom_validate.asp that offers a free validator. Exercise 2 For exercise 2, you will expand on what you learned in the chapter by investigating how to place com- ments in an XML file. As a beginner, one of the most important tasks you can learn is how to research and find answers to questions. For this exercise, search the Web using your favorite search engine and try to find the syntax for inserting comments in XML Once you find the answer, test the comment in the same XML validator you used to test Exercise 1. 647 Visual Basic 2005 and XML 22_574019 ch19.qxd 9/16/05 9:38 PM Page 647 [...]... platform, you’ll be able to build a Visual Basic 2005 application that can use the Web Service it belongs to Creating the Client In the next Try It Out, you’ll create the client Because you’re going to use Internet Explorer inside your application, you’ll also customize the Toolbox to include the Microsoft Web Browser control Try It Out Creating the Client 1 In Visual Studio 2005, create a new Windows Application... their local computer You’ll also see a method that allows us to test the Web Service from within Internet Explorer Try It Out A Demonstration Web Service 1 Open Visual Studio and select File ➪ New Web Site from the menu 2 Make sure Visual Basic is selected in the language box and HTTP in the location box and select ASP.NET Web Service from the upper list Enter the name as http://DemoService and click... the HelloWorld method (You can use another browser to test the service, but Visual Studio 2005 chooses Internet Explorer by default.) These pages are known as the test interface Methods on the class that you want exposed to the Web Service must be marked with the WebMethod attribute You can see this attribute defined at the beginning of the method (note that it must be encased in a similar fashion to... HTTP through the Web server SOAP documents are constructed with XML This means that if you read a SOAP document, it’ll look very similar to the sort of document that you saw in Chapter 19 However, at the level of Visual Basic, you don’t need to look too hard at the SOAP documents As you work through the chapter, you’ll see some of the SOAP response documents that come back from the server, but you won’t... set its Anchor property to Top, Bottom, Left, Right 6 69 Chapter 20 6 You’re going to use the browser to display the pictures, but it seems a shame not to verify that it actually works as a fully functioning Web browser So add some code to show how the fullblown features of Internet Explorer can be utilized within Windows Forms in Visual Studio 2005 Double-click on the background of the form and add... Next, you create an instance of the PictureService.Service class that Visual Studio created for you At this point you have not connected to the Web Service — you have just prepared things for when you do: ‘ create a connection to the service Dim service As New PictureService.Service() The beauty of Web Services in Visual Studio 2005 is that calling methods on a remote object is no different from calling... Public Function GetSquareRoot(ByVal number As Double) As Double Return Math.Sqrt(number) End Function If you can’t type into the code window, it means that the instance of Internet Explorer that Visual Studio 2005 opened is still running Close down the test interface windows and any extra windows displaying the SOAP responses, and the project should stop running Alternatively, select Debug ➪ Stop Debugging... version=”1.0” encoding=”utf-8” ?> 1.414213562373 095 2 How It Works If you look in the SOAP message that was returned, you’ll find a double value that’s as close as you can get to the square root of 2 1.414213562373 095 2 So you know that the method works You should have also seen by... Web Site from the menu to create a new ASP.NET Web Service project and call it PictureService You can place the Web Service anywhere you want on your hard drive Using the built in Web server with Visual Studio 2005 you do not have to worry about IIS integration during development 2 When the project loads, you don’t want to use the default Service.asmx or Service.vb files As extra practice, you will delete... in Figure 20-3 Figure 20-3 9 Now you’ll need to find some pictures to use with the service You can use any picture you like as long as they are in either GIF or JPEG format 10 Divide the pictures into a set of three subfolders under the Pictures folder Use any folder name that you like for your three subfolders In this example, the folders are Beach, Mountains, and Remodel 6 59 Chapter 20 How It Works . XML validator you used to test Exercise 1. 647 Visual Basic 2005 and XML 22_5740 19 ch 19. qxd 9/ 16/05 9: 38 PM Page 647 22_5740 19 ch 19. qxd 9/ 16/05 9: 39 PM Page 648 20 Web Services and .NET Remoting Industry. _1, 0, 99 , and 100. In most cases, if your method works properly for one or two of the possible valid values, it 6 39 Visual Basic 2005 and XML 22_5740 19 ch 19. qxd 9/ 16/05 9: 38 PM Page 6 39 will. of a null value as is typically found in databases. 643 Visual Basic 2005 and XML 22_5740 19 ch 19. qxd 9/ 16/05 9: 38 PM Page 643 Figure 19- 8 How It Works To fully appreciate the benefit of this

Ngày đăng: 12/08/2014, 10:21