Beginning microsoft Visual Basic 2010 phần 10 pot

75 334 0
Beginning microsoft Visual Basic 2010 phần 10 pot

Đ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

614 ❘ CHAPTER 19 VISUAL BASIC 2010 AND XML FIGURE 19-7 figure 2. On Form1, draw a ListBox control. Change its IntegralHeight property to False, its Dock property to Fill,andits Name to lstEmails, as shown in 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 and add this namespace declaration: 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:\Users\Bryan\Documents\Visual Studio 10\Projects\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 = 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    Integrating with the Address Book Application ❘ 615 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 End Class The preceding code assumes that your AddressBook.xml will be in C:\Users\Bryan\Documents\Visual Studio 10\Projects\Address Book\bin\Debug . If yours isn’t, change the filename value specified at the top of the code. FIGURE 19-8 figure 4. Run the project; you should see something like what is shown in Figure 19-8. Notice that addresses without 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. How It Works To fully appreciate the benefit of this exercise (and therefore the benefit of XML), imagine that before writ- ing the application you’d never seen the XML formatused by the Address Book application. Because 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 understand 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 deal about how it is built on XML. This shows in the .NET Framework support for XML, which offers 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 setof 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 step 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 whitespace.    616 ❘ CHAPTER 19 VISUAL BASIC 2010 AND XML So, when you start, the first thing XmlTextReader tells you about is this node: <?xml version="1.0" encoding="utf-8"?> When you ask it to move on, it tells 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 tells you about this node: <Addresses> Then it tells 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 whitespace 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 doc- ument one piece at a time. When you first start, the pointer is 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:\Users\Bryan\Documents\Visual Studio 10\Projects\Address " & _ "Book\bin\Debug\AddressBook.xml\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, then 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, then 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, then you check to see whether addressData points to a Collection object. If it does, you know that you are inside an Address element.    Integrating with the Address Book Application ❘ 617 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 element name and the value into the collection for later use: ‘ 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 As you work through the file, you’ll get to this point for each of the elements stored in the Address element. 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 , then 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 sub-elements missing — for example, you might not always have an e-mail address for each address, as shown earlier in Figure 19-8. You then continue the loop. For each iteration of the loop, XmlTextReader.Read is 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 It is hoped that this example has illustrated the power of XML from a software integration perspec- tive. With very little work, you’ve managed to integrate the Address Book and Address List applications together.    618 ❘ CHAPTER 19 VISUAL BASIC 2010 AND XML 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. SUMMARY This chapter introduced the concept of XML. XML is a language based on open standards and 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 enables 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 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 a lot of experience). Nevertheless, this chapter helped you get an idea of what this is all about 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. At this point, you should: ➤ Have a better understanding of XML and know what it looks like ➤ Know the basic rules for using XML ➤ Be able to serialize and deserialize XML data into objects ➤ Be able to manipulate XML data in your applications ➤ Be able to use the XMLTextReader class to walk through an XML document EXERCISES 1. Name two reasons to use XML to integrate systems or store data. 2. In what two items do you store data in XML? 3. Is this valid XML? <Root><one att="red" /></root> 4. Is this valid XML? <Root><one att="red" >Me & you</one></Root> 5. Is this valid XML? <Root><one><att>Me</one></att></Root>    Summary ❘ 619  WHAT YOU HAVE LEARNED IN THIS CHAPTER TOPIC CONCEPTS XML XML files must contain a root element, are tag-based, case sensitive, self describing, and based on a widely used standard. Working with XML Files You can easily serialize and deserialize XML data to and from files to work with it as a data source. Exchanging data with applications. You can open XML in many applications, including text editors, and share the data between these applications.       20 Deploying Your Application WHAT YOU WILL LEARN IN THIS CHAPTER: ➤ Deployment concepts and terminology ➤ How to deploy a ClickOnce Application with Visual Studio 2010 ➤ How to create a setup program with Visual Studio 2010 ➤ How to edit the installer user interface Deploying an application can be a complicated process, especially when dealing with large, complex applications. A wealth of knowledge is required about nearly every aspect of a deploy- ment. A large software installation for Windows requires knowledge ranging from Registry settings, MIME types, and configuration files to database creation and manipulation. Compa- nies tend to rely on dedicated deployment software for these large installations, together with key people who understand the processes involved. However, Visual Studio 2010 does provide some basic deployment functionality, which is tremendously helpful for the standard developer and smaller installations. Under the Visual Studio 2010 banner, you can create many different types of applications, from desktop to web applications and services. All of these have varying degrees of complexity or peculiarities when it comes installation time. Since this is a beginner’s guide, this chapter provides an overview of deployment. WHAT IS DEPLOYMENT? Deployment is the activity of delivering copies of an application to other machines so that the application runs in the new environment. It is the larger, architectural view for what you may know as installation or setup. There is a subtle difference between deployment and installation. Deployment is the art of distribution. In other words, deployment is the way in which software is delivered. Installation or setup is a process, whereby you load, configure, and install the soft- ware. In other words, an installation is what you do to configure the software, and deployment is how you get it where you want it.    622 ❘ CHAPTER 20 DEPLOYING YOUR APPLICATION With this terminology, a CD is a deployment mechanism, as is the Internet. The two deployment mechanisms may have different installation requirements. For example, if an installation is on a CD, you may have all the additional dependent software on that CD. Delivery of the same application via the Internet might require users to visit additional sites to gather all the dependent software. Another example that may affect the installation option is one in which you may have written an installation in JavaScript. This may work fine when executed on a machine by a user who has the correct Windows user rights, but would not work through Internet Explorer. These kinds of considerations are impor- tant when deciding upon your best deployment option. The type of installations you require could also vary per application. Now that you have an understanding of the terminology, it’s time to learn how to deploy applications using Visual Studio 2010. ClickOnce Deployment ClickOnce deployment is the concept of sending an application or its referenced assemblies to the client in a way that allows self-updating applications. You have three distribution options for a ClickOnce application: file share, web page, or external media (CD, DVD, and so on). ClickOnce deployment has both benefits and limitations. It is a useful deployment option for small- to medium-size applications. The benefits of ClickOnce deployment include three major factors. First, using this deployment option allows for self-updating Windows applications. You can post the latest version of the application at the original location, and the next time the user runs the application, it will install the latest version and run it. Next, any user can install most ClickOnce applications with only basic user security. With other technologies, administrator privileges are required. Finally, the installation has little impact on the user’s computer. The application can run from a secure per-user cache and add entries only to the Start menu and the Add/Remove Programs list. For programs that can run in the Internet or intranet zones that do not need to access the Global Assembly Cache (GAC), this is a terrific deployment solution for distribution via the web or a file share. If you distribute the ClickOnce application through external media, the installation will be run with higher trust and have access to the GAC. TRY IT OUT Deploying a ClickOnce Application from the Web Code file ClickOnce.zip and Publish.zip is available for download at Wrox.com In this Try It Out, you learn how to deploy a ClickOnce application from the Web. 1. Create a new Windows Forms Application named ClickOnce. 2. On Form1, add a button and label. Change the button’s Name property to btnVersion and the Text property to Version. Change the label Name to lblVersion and clear the Text property. FIGURE 20-1 figure 3. Add the following bolded code to the Click event for btnVersion : Private Sub btnVersion_Click(ByVal sender As System. Object, ByVal e As _ System.EventArgs) Handles btnVersion.Click lblVersion.Text = "Version 1.0" End sub 4. Test the form. When the user clicks the button, the label should dis- play Version 1.0. Your form should look like Figure 20-1.    What Is Deployment? ❘ 623 5. Prepare to publish the assembly to the Web. NOTE If you do not have IIS installed, you can publish the file to a local or network drive. Just remember how you chose to publish the assembly. You will need to be running Visual Studio with elevated privileges to complete this. You may need to close Visual Studio: right-click the shortcut, and choose Run as Administrator to launch the software. 6. Right-click the ClickOnce project in the Solution Explorer and choose Publish from the context menu. The Publish Wizard opens (see Figure 20-2). Choose a location to publish the file. In this example, choose a directory on the local computer like C:\Bryan\Publish. FIGURE 20-2 NOTE You will need to share this folder. Here the folder is shared as Publish. To share a folder in Windows 7 with other users on the network or this computer, navigate to the folder in Windows Explorer and right click the folder to bring up the context menu. Choose Share With and then Specific People. At your work, you would choose a group of users that could access the shared folder or network share. For this example, just select or enter Everyone and then click Add. Next, click Share and then click Done to share the folder. After setting the location, click Next. 7. Specify how users will install the application. Select the radio button for ‘‘From a UNC Path or file share.’’ Enter the UNC path as \\localhost\Publish or however you named your file share in step 6 (see Figure 20-3).    [...]... would typically use XCOPY for web site deployment and for testing and prototypes of Windows Forms applications CREATING A VISUAL STUDIO 2 010 SETUP APPLICATION Visual Studio 2 010 supports the Windows Installer But what is it? Windows Installer, which gets installed with Visual Studio 2 010, is a general platform for installing applications in Windows It provides a lot of functionality, such as uninstall... solution and look at the Path property in the Properties window of Visual Studio If the user does not have Microsoft Visual Basic PowerPacks 10. 0 or the correct version of the NET Framework, it will be downloaded from the vendor You can change that under the settings where you add the dependency for Microsoft Visual Basic PowerPacks 10. 0 You added that requirement just for the exercise of adding it... this copy/ please visit www.wrox.com to purchase your own copy Creating a Visual Studio 2 010 Setup Application ❘ 629 FIGURE 20-9 6 Select the check box beside Microsoft Visual Basic PowerPacks 10. 0 and click OK twice to both dialogs Note that by default, the components are set to download from the vendor’s website FIGURE 20 -10 7 Right-click the Application Folder node in the designer (left pane) and... are either built in (so that you do not have to do anything) or are configurable, extensible, or both The Visual Studio 2 010 Windows Installer support has made it easier to create a simple installation Visual Studio has provided templates in the New Project dialog for this purpose Visual Studio 2 010 exposes four main templates for creating Windows Installer projects: ➤ Setup Project for desktop or general... creates a package that can be used as a type of install Finally, Visual Studio 2 010 also has a Setup Wizard Project, which aids you in creating one of the Windows Installer templates listed here When you are creating setup applications, always be aware of the user By default, all of the applications you will create with Visual Studio 2 010 require version 4 of the NET Framework on the installation system... application ➤ Create a Visual Studio 2 010 setup application ➤ Use general deployment terms such as XCOPY, and understand the differences between shared versus private assemblies ➤ Edit the installer user interface EXERCISES 1 Where are shared assemblies stored? 2 How are updates handled when using ClickOnce deployment? 3 Name two dialog boxes you can add to a setup project in Visual Studio 2 010 4 How do you... could potentially mean a lot of work for an installation expert Having multiple application types can also make an installation complex, and detailed knowledge of the different applications is required for a successful installation The following sections discuss some items related to different deployment scenarios surrounding the different types of applications that can be created with Visual Studio 2 010. .. this case, the user would be required to have access to the share to launch the application for each use That’s it When you click Finish, Visual Studio 2 010 goes to work What happens behind the scenes is not magic Actually, you could manually complete everything without Visual Studio if you ever needed to do so Referring back to Figure 20-7, take another look at the files Here’s what happened: First, the... concatenate the variables and display the results in a message box The String variables can be declared and set as: ➤ ‘Declare variables and set their values Dim strOne As String = "Visual Basic " Dim strTwo As String = "2 010" To concatenate the variables and display the results, you could write code such as: ➤ ‘Concatenate the strings and display the results MessageBox.Show(strOne & strTwo, "Exercise... for the exercise of adding it Normally, you would only add a prerequisite if it were needed by the application USER INTERFACE EDITOR Installations can be configured to meet almost any need, with Visual Studio 2 010 One of the easiest ways to make your installation look professional is to customize the user interface during installation A tool, User Interface Editor, is available to do just this With the . Forms applications. CREATING A VISUAL STUDIO 2 010 SETUP APPLICATION Visual Studio 2 010 supports the Windows Installer. But what is it? Windows Installer, which gets installed with Visual Studio 2 010, is a general. However, Visual Studio 2 010 does provide some basic deployment functionality, which is tremendously helpful for the standard developer and smaller installations. Under the Visual Studio 2 010 banner,. 3.1.    Creating a Visual Studio 2 010 Setup Application ❘ 629 FIGURE 20-9 6. Select the check box beside Microsoft Visual Basic PowerPacks 10. 0 and click OK twice to both dialogs.

Ngày đăng: 09/08/2014, 14:21

Từ khóa liên quan

Mục lục

  • WroxBooks

    • Beginning Microsoft® Visual Basic® 2010

      • Chapter 19: Visual Basic 2010 and XML

        • SUMMARY

        • Chapter 20: Deploying Your Application

          • WHAT IS DEPLOYMENT?

          • CREATING A VISUAL STUDIO 2010 SETUP APPLICATION

          • USER INTERFACE EDITOR

          • DEPLOYING DIFFERENT SOLUTIONS

          • SUMMARY

          • Appendix A: Exercise Solutions

          • Appendix B: Where to Now?

          • INDEX

Tài liệu cùng người dùng

Tài liệu liên quan