The code for the MouseUp eventshould look similar to this: Private Sub Button1_MouseUpByVal sender As Object, _ByVal e As System.Windows.Forms.MouseEventArgs Handles Button1.MouseUp ‘Dis
Trang 1If btn02.Text = btn12.Text And btn12.Text = btn22.Text And _btn22.Text <> String.Empty Then
‘Winner on third columnCall Winner(btn02.Text)Return True
If btn20.Text = btn11.Text And btn11.Text = btn02.Text And _btn02.Text <> String.Empty Then
‘Winner on diagonal bottom left to top rightCall Winner(btn20.Text)
Return TrueEnd If
‘Test for a tie, all square fullDim ctrl As Control
Dim intOpenings As Integer = 0For Each ctrl In Me.Controls
If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then
If ctrl.Text = String.Empty ThenintOpenings = intOpenings + 1End If
End IfNext
If intOpenings = 0 ThenCall Winner(“It’s a tie.”)Return True
End IfReturn FalseEnd Function
The remaining code is part of the handlers for the form’s Load event and the New Game button Clickevent On form load, the overloaded method CorrectEnabledStateis called and all buttons are disabled.When you click the New Game button, ResetGameis called to set up the board to start a new game
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) _Handles Me.Load
CorrectEnabledState(False)lblMessages.Text = “Click new game to begin.”
End Sub
Private Sub btnNewGame_Click(ByVal sender As System.Object, ByVal e As _System.EventArgs) Handles btnNewGame.Click
ResetGame()End Sub
722
Trang 2Summar y
Visual Studio 2005 and the Compact Framework make developing mobile applications very similar todesktop application development This small learning curve for NET developers is one of the reasonsmore PDAs are shipping with a Windows operating system than with any other competitor The trendhas been growing, and companies are starting to value the developer with mobile application skills.Take advantage of your knowledge and leverage it to start developing mobile applications
In this chapter, you learned the basics of mobile development You saw what is similar and what is ferent between the full version of the NET Framework and the Compact Framework You were shownexamples of the missing pieces that explain how the CF has been shrunk by over 80 percent Finally, youbuilt your first application, tic-tac-toe
dif-To summarize, you should know how to:
❑ Find differences between the full NET framework and the Compact Framework
❑ Use ActiveSync to connect to smart devices
❑ Create mobile applications
❑ Use the built in emulator to test mobile applications
Exercise
The computer player is a random picker Give the computer player some brains Add at least one functionnamed ComputerPlayToWinto the application When the computer moves, call ComputerPlayToWinand check for a spot on the board that will create a win for the computer If it exists, the computer shouldplay that move rather than a random move You can add other procedures if needed
723 Building Mobile Applications
Trang 4Where To Now?
Now that you have come to the end of this book, you should have a relatively good idea of how towrite code using Visual Basic 2005 The topics and example code covered in this book have beendesigned to provide you with a firm foundation, but it is just the beginning of your journey Infact, this book is just one of the many steps you are going to take on your road to becoming a fullfledged Visual Basic 2005 programmer Although you have come a long way, there is still a lot far-ther to go, and you will certainly have many more questions on the way
The problem now is, where do you get these questions answered, and, of course, “What next?”This appendix offers you some advice on what your possible next step(s) could be As you canimagine, a number of different routes are open to any one person The path you choose will proba-bly depend on what your goal is or what you are being asked to do by your employer Some ofyou will want to continue at a more general level with some knowledge about all aspects of VisualBasic 2005, while others may want to drill down into more specific areas
Well, it is extremely important not to take a long break before carrying on with Visual Basic 2005 Ifyou do so, you will find that you will quickly forget what you have learned The trick is to prac-tice You can do this in a number of ways
❑ Continue with the examples from this book Try to add more features and more code to it.Try to merge and blend different samples together
❑ You may have an idea for a new program Go on and write it
❑ Try to get a firm understanding of the terminology
❑ Read as many articles as you can Even if you do not understand them at first, bits andpieces will come together
❑ Make sure you communicate your knowledge If you know other programmers, get ing and ask questions
talk-❑ Consult our online and offline resources for more information
The rest of this appendix lists available resources, both online and offline, to help you decidewhere to go next
Trang 5Online Resources
Basically, there are thousands of places you can go online for help with any problems you may have Thegood news is that many of them are free Whenever you come across a problem — and, unfortunately,you will — there are always loads of people out there willing to help These unknown souls include otherswho were at the same stage as you and may have had a similar problem, or experts with a great deal ofknowledge The key is not to be intimidated and to use these resources as much as you like Remember,everyone was a complete beginner at some point and has had many of the same experiences as you
In this section, we are going to begin by examining the P2P site provided by Wrox and then follow onwith some of the more general sites around If you can’t find what you want through any of the siteslisted here or if you have some time and want to explore, just search for Visual Basic 2005 and you will
be on your way!
P2P.Wrox.com
P2P provides programmer-to-programmer support on mailing lists, forums, and newsgroups in addition
to a one-to-one e-mail system You can join any of the mailing lists for author and peer support in VisualBasic 2005 (plus any others you may be interested in)
You can choose to join the mailing lists, and you can receive a weekly digest of the list If you don’t havethe time or facilities to receive mailing lists, you can search the online archives using subject areas orkeywords
Should you wish to use P2P for online support, go to http://p2p.wrox.com On P2P, you can view thegroups without becoming a member These lists are moderated, so you can be confident of the informa-tion presented Also, junk mail and spam are deleted, and your e-mail is protected by the unique Lyrissystem from Web-bots, which can automatically cover up newsgroup mailing list addresses
Microsoft Resources
Probably one of the first sites you’ll intuitively turn to is the Microsoft site (www.microsoft.com).That makes sense, because it is full of information, including support, tips, hints, downloads, and news-groups (news://msnews.microsoft.com/microsoft.public.dotnet.languages.vb) To see morenewsgroups, navigate to http://communities2.microsoft.com/communities/newsgroups/en-us/default.aspx
There are also a number of sites on MSDN that you may find to be very helpful, including the following:
❑ Visual Studio 2005 site:http://lab.msdn.microsoft.com/vs2005/
❑ Visual Studio 2005 documentation:http://lab.msdn.microsoft.com/library/
❑ MSDN Library:http://msdn.microsoft.com/library/
❑ Microsoft Developer Network site:http://msdn.microsoft.com
❑ Microsoft Visual Basic site:http://msdn.microsoft.com/vbasic/
❑ .NET download site:http://msdn.microsoft.com/netframework/downloads/
❑ GotDotNet: www.gotdotnet.com
726
Trang 6Other Resources
As said earlier, there are hundreds of sites online that discuss both Visual Basic NET and Visual Basic
2005 These sites give everything from news on moving from Visual Basic NET to Visual Basic 2005, tolistings of up and coming conferences worldwide Although you can do a search for Visual Basic 2005,the number of sites returned can be extremely overwhelming Let’s look quickly at two of these possiblesites: one for the United Kingdom and another for the United States
In the United Kingdom, www.vbug.co.ukoffers a wealth of information on Visual Basic This is the Website for the Visual Basic Users Group (VBUG), which you can join Besides the Web site, this group holdsmeetings and an annual conference, plus provides a magazine There is a listing of further links on theWeb site, and you may want to use this to start your search over the Internet
In the United States you can get a journal, The Visual Studio Magazine, from a similar user group Again,
this journal is backed by meetings and four yearly conferences along with a Web site, http://www.devx.com/vb/, which can give e-mail updates On the Web site, you have access to a number of differ-ent areas both in Visual Basic and other related and nonrelated Visual Studio areas
Of course, these are just two among the many out there to try to get you started Some of you maydecide to use these two, and many of you may choose others as your favored sites, it’s all up to you!What you need to remember, though, is that the Internet is not the only place to find information, so wewill go on to look at some resources not found on the Web
Offline Resources (Books)
Wrox Press is committed to providing books that will help you develop your programming skills in thedirection that you want We have a selection of tutorial-style books that build on the Visual Basic 2005knowledge gained here These will help you to specialize in particular areas Here are the details of afew key titles
Professional VB NET, 2nd Edition
(Wrox Press, ISBN 0-7645-7536-8)This book takes a deeper look at all aspects of Visual Basic 2005 and is probably the most logical of “nextsteps.” It provides the next level from this book; however, it will be worth practicing your programmingskills beforehand
Topics include the following:
❑ Common Language Runtime
❑ Variables and Data Types
❑ Object Syntax Introduction
❑ Inheritance and Interfaces
❑ Applying Objects and Components
727 Where To Now?
Trang 7❑ ASP.NET 2.0 Advanced Features and much more!
ASP.NET 2.0 Beta Preview
(Wrox Press, 0-7645-7286-5)
ASP.NET 2 Beta Preview is timed to coincide with the first widespread beta release of ASP.NET,
“Whidbey” — the new version of Microsoft’s popular technology for creating dynamic Web sites thatpull unique information for each visitor rather than showing everyone the same static HTML pages Thebook gets developers up to speed with the new features and capabilities that ASP.NET 2.0 provides.Developers will learn how to build ASP.NET 2.0 applications for themselves from the examples that thebook provides
This book is for ASP.NET developers making the transition to this new version of the technology Thechanges are many, and in some cases they’re quite dramatic The book spends a good deal of time alert-ing you to all that has changed and explaining what you need to know to make the transition to
ASP.NET 2.0
Finally, the book focuses on both the Visual Basic 2005 and C# developer Examples throughout the book
do not favor one developer over another Instead, every example is provided in both languages
This book covers the following:
❑ Introduction to ASP.NET 2.0
❑ Visual Studio 2005
❑ Application and Page Frameworks
❑ New Ways to Handle Data
❑ Site Navigation
❑ Working with Master Pages
❑ Themes and Skins
❑ Membership and Role Management
❑ Personalization
728
Trang 8❑ Portal Frameworks and Web Parts
❑ SQL Cache Invalidation
❑ Additional New Controls
❑ Changes to ASP.NET 1.0 Controls
❑ Administration and Management
❑ Visual Basic 8.0 and C# 2.0 Language Enhancements
729 Where To Now?
Trang 10Microsoft has a set of processes and models that to some is the standard for solution delivery inthe IT industry Known as MSF (Microsoft Solutions Framework), software developers around theglobe apply this framework to internal strategies to ensure best practices when building software.The MSF is a recent interpretation of the classic software development life cycle.
In this appendix, you will do the following:
❑ Learn about the software development life cycle
❑ Get an overview of the MSF and how it relates to the software development life cycle
❑ See how to manage trade-offs
❑ Learn how to define success for a project
A detailed explanation of the Framework would take two or three hundred pages This appendix
is just a concise summary to wet your whistle, so to speak Keep this in mind as you begin to explore this tool.
Trang 11Software Development Life Cycle
The software development life cycle (SDLC) is a set of building blocks for software design Microsoftand others in the industry continue to develop methodologies to interpret the SDLC into a set of steps ormilestones Depending on whom you ask, you may get five steps or even seven steps in an SDLC imple-mentation Here is one interpretation of the SDLC steps:
❑ Defining the problem
Microsoft Solutions Framewor k
The Microsoft Framework Solution (MSF) is built for the implementation of large software projects Twodistinct models (Team Model and Process Model) define the entire framework To set up a large projectteam, you will need to use the Team Model As you begin your career, you will most likely work onsmaller projects Because of this, I will not go into detail about the Team Model The Process Modeldefines how to complete the solution In this appendix, I will show you how to use the principles of theProcess Model in smaller projects
In the Team Model, a developer is only one role in a large project and is recommended to work on only one task: develop the application code As you work on small solutions, be aware that you will take on many roles One day you may be gathering requirements, and the next week you may be developing
code for the application Think back and realize that it is difficult to write the code and take on other ject roles As a developer, it will be easy to focus your efforts on the code writing and put the analysis, testing, and documentation on the back burner This will almost always result in an unsuccessful pro- ject Although the code may work, the documentation may not be good enough to maintain or change
pro-the application You may not understand this concept yet, but in my opinion writing pro-the code is easy
part of the solution When your manager asks you to play many roles on a project, remember that in
most cases you will need to spend more time designing, testing, and documenting code than writing it.
The Process Model, consisting of five phases, is the portion of the MSF that puts the SDLC into practice
It describes the order in which you should complete each phase of the SDLC Also, this model involves
iterations of all phases, known as versions If you are familiar with MS software, you know that Microsoft
updates software via new versions The Process Model is a continuous loop of milestones that rates deploying multiple versions of software Each version of the software will go through all phases ofthe Framework Next, I will explain the five phases of the process model listed here
incorpo-732
Trang 12The Envisioning Phase
To start the MSF, you begin in the envisioning phase The success of the project starts here Make sureyou take the time to nail down all loose ends before moving forward with the project Your customersexpect and deserve to understand how the project is going to proceed and the scope document at theend of this phase will do that After completing the envisioning phase, everyone with a stake in the pro-ject will be on the same page There are five goals of the envisioning phase that you need to accomplishbefore moving on to the planning phase
Problem StatementWhy is the customer willing to spend $80,000 on a new system? This seems like an easy question Don’ttake this lightly, because all of your decisions will be driven by the problem statement Here is an exam-ple of a problem definition:
As government regulations change, the current system cannot meet the time requirements to implement changes and stay in compliance To compete in our industry, we must have a system that is flexible enough to make changes easily so as to maintain governmental compliance.
GoalsYou need to agree on measurable goals with the customer These will be used to help define the success
of the project The key word is measurable Here is the difference The following are the same goals, but
the latter is measurable
❑ The system should improve customer service by being able to complete a phone order quickly
❑ The system will improve customer service by allowing a phone order to be completed in lessthan 60 seconds
The first goal is vague and is not measurable If you base the system on goals like the first one, it is easyfor the customer to believe the system is not fast enough when you feel the system is much faster than ithad been You may think the system is a success, but the customer thinks it is a failure Remember tomake sure that you can measure system goals
Define RolesHere is an easy one On smaller projects, only a few people will be working on the project You will need
to determine who is responsible for planning, development, testing, documentation, and releasing thesystem This is where you will use the Team Model for large projects
733 Implementing the Microsoft Solutions Framework
Trang 13Create a Scope Document
This document will be a blueprint of the solution All stakeholders in the project should sign off on thefinal version of the scope document Sections of the scope document include the following
❑ A vague set of user requirements
❑ The problem statement
❑ Definition of team roles
❑ A set of measurable goals
❑ A brief statement defining the planning process upcoming
Risk Analysis
Your customer will need to know any risks that may cause problems for the project These risks may bethat you are working with new technologies that are unproven or that system bandwidth requirementsmay exceed available network resources
The Planning Phase
During the planning stage, you will create documents to validate that the project can succeed The ments you create will be transformed through feedback from the customer and project stakeholders.Make sure that all project stakeholders have time to review and validate each document Even for asmall project, this process can take many rounds of changes to gain sign-off from all parties Finally, youwill create a project schedule and cost estimate before moving to the developing stage Listed here arethe documents you need to create
docu-❑ Conceptual, logical, and physical design documents
❑ Use cases and usage scenarios
❑ System specification
❑ Project schedule
❑ Cost estimate
The Developing Phase
This is the stage you are most familiar with The MSF encapsulates everything from actually building thedevelopment environment to completing documentation into the development stage The milestone forthis phase is a complete application ready for testing
Setup: Building Staging Areas for Development and Testing
For any project, you need a development and test environment that matches the production ment Take precautions to build the staging areas so that they are the same as the production environ-ment Something as simple as different printer drivers between test staging and production areas cancause unanticipated results on release of the application
environ-734
Trang 14Completing the PrototypeYou must allow the customer to approve a prototype Do not underestimate the value of this Imagineyou were building a car Without proper models, how hard is it to determine the proper location of thesteering wheel or how to add six inches of leg room for rear passengers? Take this time to let the cus-tomer make changes to the design You will find that it is easy to change a prototype Once you havethree months of coding under way, changes to the user interface can be costly.
Completing the CodeThe application is ready for testing Validate modules through unit testing
Supply Application DocumentationThe documentation from prior phases is compiled with a user manual and system documentation Thetest team will rely on this data for testing
The Testing Phase
As a beginner, you may not understand the importance of this phase There is no better way to make asmall project over budget and late than to find 500 bugs while testing Make sure you have adequatetime in your schedule to test and make test plans Like basically everything else in the MSF, testing is aniterative process You will need test plans that you can repeat and validate after bug fixes After eachround of testing, complete your test plans Remember to document your result When bugs arise in theapplication after release, you will want to see why the test plan did not uncover the bug and then adjustthe test plan After the customer has signed off on the test results, complete any documentation changesand package all files for deployment
You should plan for the following subphases during the testing process:
❑ Application tier testing
❑ Security testing
❑ Performance testing
❑ User acceptance testing
❑ System integration testing
The Deployment Phase
Now, you are ready for production If you are on time and within budget, your customer will be happywith the project With all of the planning and customer interaction, there will be few surprises at thispoint You will put the solution into production and have a small team available to train and support theusers After the agreed-upon amount of time, the application will be turned over to the support staff.You will need to train them and turn over system documentation That is it You have managed a suc-cessful implementation of a project
There is one item left: how to handle changes using tradeoffs To have any chance of getting to the end
of a project successfully, you must be able to manage tradeoffs The next section explains this in moredetail next
735 Implementing the Microsoft Solutions Framework
Trang 15Managing Tradeoffs
To complete a successful project, you must be able to manage tradeoffs You will find very quickly thatyour customer will ask you questions of the form “ Can you do that?” And your answer should be in
almost every instance, “Yes, we can.” You will find that you can do just about anything The problem is
that it takes a certain amount of time and money for every project or change request What your tomer means to say is; “Can you do that for $50,000 by the end of this year?” So when you answer the
cus-“can it be done” question, make sure the customer knows that you can do it for the right price withenough time
When you work with clients, internal or external, you have to make them aware of project tradeoffs.There are three tradeoffs (budget, deadlines, and functionality) A fourth tradeoff could be quality Youshould never consider reducing quality to lower price, finish sooner, or add features to make a projectsuccessful While you define the project scope, make sure that the project team and customers under-stand the priorities of tradeoffs As you make changes to any one tradeoff, you will have to adjust atleast one of the others
For example, suppose you are working with the marketing department on a small application You arethe only resource available to work on the solution for the next two weeks during planning While youare gathering the system requirements, you speak to the marketing vice-president, Tina, about the priori-ties of the solution Very quickly she makes it clear that she needs the application by the end of the yearand for a cost of under $50,000 As you pry more, you find that Tina cannot spend more than $50,000 thisyear She wants the system to be live in three months with at least the core functionality in the first ver-sion Next year, she may be able free up more money in her budget to finish the lower-priority features.You quickly write down the tradeoffs to consider and the priorities In order of priority, you write bud-get, deadline, and features Take a look at the project priorities listed in Table B-1 You and Tina sign off
on the tradeoff priorities, and now you know how to make the solution a success Meeting the budgetand deadline are required for success For example, functionality will be moved to the next version if theproject gets behind schedule
Table B-1: Project priorities
Halfway through the project, Tina wants to add more core functionality to the system You look at thebudget and see that if you add more functionality to this release, you will need more resources to makethe deadline Adding another developer to meet the deadline will cost an extra $10,000 Looking back atthe project priorities, you see that Tina cannot spend more than $50,000 You have set aside the entire
$50,000 budget, and $10,000 more is too much It is time to call Tina and explain the situation
736
Trang 16While talking to Tina, you explain the top priority for the project is budget Adding the extra ity will cost an additional $10,000, bringing the budget estimate to $60,000 During the discussion, youmention that the only way to add more functionality without increasing the deadline or budget is todrop some of the functionality already planned After 30 minutes, she agrees that $50,000 is all she canspend, and the additional functionality can be part of a later version.
functional-By understanding and agreeing on tradeoff priorities, you are able to work with customers to managechange If a customer wants to change any of the tradeoff priorities, you will have to adjust one or both
of the others
Defining Success with the MSF
A successful project is hard to achieve If you follow the framework, success can be achieved more easily
It all comes down to customer satisfaction and one simple question: Did you make the customer happy?This simple question can be hard to answer Let me clarify how to find the answer to this question Tomake the customer happy, you must succeed in most of these four areas; achieve system goals, meetrelease date, stay under budget, and manage trade offs
With the Framework implementation, you will find defining success possible The two milestones thatare straightforward are meeting the budget and release date Take a look at the project plan and makesure these milestones were met System goals are also straightforward if you defined measurable goals.Test the system against the project goals to verify the system meets the standards agreed upon The finalmilestone is change or tradeoff management Pull out the final tradeoff chart and review it For the pro-ject to be successful, you must have met the top priority of your customer Changes may have causedyou to miss the other milestones, but if you managed tradeoffs with the customer, the project will still besuccessful Success can be that simple if you follow the game plan
Summar y
As you grow in the information technology field, you will work on larger projects and have moreresponsibility Use this appendix as a basis for further study Always keep in mind how many steps youhave to take to be successful managing a project When you do get into a position to lead a project, takethe time to plan and test, and always work toward making the customer happy You will not always besuccessful by following the framework, so take misfortunes in stride and learn from them As you com-plete projects, you will come up with your own interpretation of the SDLC or the MSF, and you will be
a success
737 Implementing the Microsoft Solutions Framework
Trang 18An Introduction to Security
In today’s electronic world, consumers are bombarded with scams via the Internet and e-mail Ifyou plan to write applications that take advantage of these technologies, you must be aware of
fraudulent activity of others The most rampant activity today is a tactic known as phishing Here a
fraudulent e-mail or pop-up message lures a user to a fake site on the pretext that a breach in banksecurity or unwanted account activity has made it necessary to “verify” the user’s account infor-mation Tricked users will see a site that looks like their bank’s site but is actually being hosted bycriminals in an attempt to bait them into entering their personal and financial information In theseschemes, it is easy for concerned customers to be tricked and enter their card number, social secu-rity number, or PIN into the Web forms to avoid their accounts being frozen Little do they knowthey are giving away their private information to thieves
Phishing is not the only scam consumers must deal with; it is one of the most prevalent As adeveloper, it is your job to make applications safe In some cases, features of your application canmake it easier for criminals to impersonate your application Simple things like never asking forpersonal information that you do not need over e-mail or the Web can make users aware of ascam For e-mail, you can never assume that e-mail will not be intercepted over the Internet Makesure you never treat e-mail as a secure means of data transmission
You must also be aware of security for your Windows applications and assemblies It seems asthough a new hole is found every week in some browser or operating system that allows a hacker
to run code on a user’s machine One way in which this type of attack is commonly accomplished
is by a buffer overflow To give you a simple explanation, hackers discover that a program has
mem-ory allocated to store data only up to a certain size The attacker sends a larger object than thememory allocated The extra data is not discarded, but rather it gets written to adjacent areas ofmemory that are intended to store code or the addresses of code This may corrupt valid alloca-tions of memory, but more important, it installs the attacker’s the malicious code in memory Thevictim program runs the attacker’s code as if it were its own, and the damage is done The rootcause of this problem is not one most Visual Basic 2005 developers will encounter, but it shouldmake you aware that people may use your functions in ways you did not intend them to be used
Trang 19Take a look at another example of a software bug that might be a security risk Say you wrote an assembly or Web Service that would upload files to your company’s Web site This application is forsalespeople to upload comma-separated files of current sales data each night The code allows the pathand file name to be passed as parameters, and it can be used by numerous departments because of thisflexibility The problem is the flexibility allows a hacker to upload a Web page, place it into the root Webdirectory, and do almost anything to the server or network You should change this Web Service to storefiles in a locked-down directory and modify the file name so that an attacker would not be able to accessthe file by name Functions like this one are prevalent in many companies’ code libraries and create most
of the security holes these companies will face
In this appendix you will learn about security issues and how to handle them within the following topics:
❑ Understanding Code Access Security
❑ Secure Sockets Layer (SSL)
❑ Where to look for security answers
Code Access Security (CAS)
The goal for Code Access Security is simple: Stop unwanted code from running or accessing resources.This is accomplished by the runtime’s security system When an assembly needs access to a resource, allassemblies on the call stack should have permission to access that resource Take a look at the followingexample
An assembly is run from the Internet By default, it is granted access to a permission set (explained in the
next subsection) based on the Internet zone The application has no access to the local file system If thatassembly were to call a public method on an assembly that did have access to the file system, the run-time would throw a security exception When the permissions of each assembly on the stack were tested,the assembly that was run from the Internet would fail the permission check
On the other hand, an administrator could grant a signed assembly more permissions So, if this bly had the correct digital signature, it could be granted access to a larger set of permissions
assem-CAS allows the system administrator to apply permissions to code rather than to users Before assem-CAS, if
a hacker could get a user to run code or an attachment that contained a virus, it was granted security
based on the user’s security level If that user was an administrator on the machine, the virus had full
access to do its dirty work Now, a virus may be stopped by the Common Language Runtime and nothave access to corrupt the file system, even if the user has permissions
The way this works is through permissions, security policy, and evidence When an assembly requests afile, for example, the runtime makes sure that file is available from a security aspect by checking permis-sions, security levels, and evidence Let’s start with permissions
740
Trang 20Permissions are granted to resources based on trust and origination Administrators can grant higher or
lower levels of access to individual assemblies or zones Here is a list of six common permissions used
by the runtime
❑ EnvironmentPermission: Access control for system and user environment variables
❑ EventLogPermission: Event logging control for code access permissions
❑ FileDialogPermission: File system access control for file dialogs
❑ FileIOPermission: File system access control
❑ PrintingPermission: Controls access to printers
❑ RegistryPermission: Controls access to the Registry
It would be hard to manage a large group of permissions without a way of grouping them Grouping
permissions is accomplished by using permission sets The NET Framework has of six predefined
per-mission sets You can use any of these sets listed here in your code
❑ Nothing: This named permission set will not allow code to run
❑ Execution: The Execution set allows the code to run, but no access is granted to protectedresources
❑ FullTrust: The most forgiving permission set Access to all resources is granted
❑ Internet: You can think of this as the access you would permit when browsing This would beused when running code from the Internet or any nontrusted source
❑ LocalIntranet: This is for trusted code running on a trusted network
❑ Everything: This is a set of all standard permissions The permission to skip verification is notgranted to this set
Your code can request any level of permission, and the runtime will verify before running the code thatthese permissions will be granted
Security Policy
The runtime enforces policy based on the identity or evidence of the assembly When loading an bly, the assembly is inspected for evidence of its origin Based on the origin, the runtime determineswhat permissions to grant the assembly
assem-Evidence
To determine the origin of an assembly, the CLR looks at many attributes of the assembly This is known
as the evidence Table C-1 has a complete list of evidence types The runtime may use any or all of these
to determine the permissions to grant the assembly
741
An Introduction to Security
Trang 21Table C-1: Types of Evidence
Evidence Type Description
Application directory Installation directory
When permissions are tested, an intersection of zones and permissions is evaluated to verify that all missions for every zone and assembly on the stack are met If permission is not granted to the code, thezone, or the user, an exception is thrown and access is denied
per-Secure Sockets Layer
Secure Sockets Laye (SSL) was a protocol developed to secure communication between a Web server and
a browser Today, 128-bit SSL encryption is the standard for secure data transmission over the Internet Ifyou need to secure parts of a Web site, your customers will expect this type of encryption To promotethe level security to the end user, Internet Explorer and Netscape display a locked lock similar to FigureC-1 at the bottom of the browser window
Figure C-1
Another way users know a site is secure is by the URL Looking at the URL of a SSL site shows
https://versus the standard http:// The user can also look at details of the certificate by doubleclicking the lock icon or viewing the page’s properties or info Figure C-2 is an actual certificate infoscreen from a large Web site We have removed the company’s name from the image
Two of the largest companies that issue SSL certificates are Thawte and VeriSign They are both wellrespected in the industry and offer free trial certificates for you to test with
Trial certificates can be found at the following site
❑ verisign.com/products-services/security-services/ssl/index.html:Click the Trylink for the certificate type you wish to try
❑ thawte.com/:Click the link for a 21 day trial
742
Trang 22You should keep in mind that encryption slows down the experience for the user and creates more loadfor the server Keep marketing and nonessential areas of your site unencrypted Only encrypt pages thatcommunicate data that would be considered private.
Figure C-2
F inding Answers
I will list some Web sites that can be helpful to do more research and find answers
❑ microsoft.com/security/: Microsoft’s security home page Read the latest is security notesabout Microsoft products
❑ microsoft.com/security/guidance/checklists/: Microsoft’s security checklists Hereyou can print checklists to make sure your applications consider the appropriate security risks
❑ ftc.gov: The Federal Trade Commission Web site Here you can see what types of scams arebeing reported
❑ owasp.org: Open Web Application Security Project (OWASP) This site has free tools, mentation, and standards available
docu-❑ sans.org/rr/: The SANS Institute Information Security Reading Room Read thousands ofwhite papers on security issues
❑ webappsec.org: The Web Application Security Consortium Read white papers on the latestnews about Web site security
743
An Introduction to Security
Trang 23Summar y
Security is the hottest topic in the information technology industry Making applications 100 percentsecure is not possible with the openness of the Internet, but minimizing risks to vital data should be atop priority in application design As you build applications with VS 2005, know that you have the besttool available to create secure Windows applications, but it is your responsibility to maintain the security
of the applications you write
Administrators will be able to use CAS to stop many types of attacks Being able to apply permissions toassemblies and validate the origination of the code makes implementing a secure network easier Thewidespread use of certificates and code signing will make spoofing applications more difficult and keepusers’ computers safer
The world of application security is by no means perfect You will probably have to design your cations around security risks forever But you can win by keeping security at the top of the priority list inyour application design Soon you will begin to develop applications for wireless access, and more secu-rity implications will need to be understood Keeping applications secure in a world where informationaccess is expanding will continue to be a challenge
appli-Just make sure you keep your head up and pay attention Security holes are announced throughout themedia, and as a developer, you should pay attention and learn from the mistakes of the past One ofyour applications may one day be under attack
744
Trang 24Chapter 3 Solutions
Exercise 1
The first part of this exercise requires you to declare two Integervariables and set their valuesand then to perform a math operation on these variables and display the results in a message box.The variables can be declared and set as:
‘Declare variables and set their valuesDim intX As Integer = 5
Dim intY As Integer = 10
A math operation can be performed and the results displayed as:
‘Multiply the numbers and display the resultsMessageBox.Show(“The sum of “ & intX & “ * “ & intY & “ = “ & _intX * intY, “Exercise 1”)
Trang 25The second part of this exercise requires you to declare two Stringvariables, set their values, and catenate the variables and display the results in a message box The Stringvariables can be declaredand set as:
con-‘Declare variables and set their valuesDim strOne As String = “Visual Basic “Dim strTwo As String = “2005”
To concatenate the variables and display the results, you could write code such as:
‘Concatenate the strings and display the resultsMessageBox.Show(strOne & strTwo, “Exercise 1”)
Exercise 2
This exercise requires you to display the length of the string entered into a text box and then to displaythe first half of the string and the last half of the string To display the length of the string, you can usethe Lengthproperty of the Textproperty of the text box as shown here:
‘Display the length of the string from the TextBoxMessageBox.Show(“The length of the string in the TextBox is “ & _TextBox1.Text.Length, “Exercise 2”)
To display the first half of the string, you need to use the Substringmethod with a starting index of 0,and for the length you use the length of the string divided by 2, as shown here:
‘Display the first half of the string from the TextBoxMessageBox.Show(TextBox1.Text.Substring(0, TextBox1.Text.Length / 2), _
This exercise required you to create a Select Case statement to select and display the numbers 1 through
5 from the text box on the form The code to do this is shown here:
‘Determine which number was enteredSelect Case TextBox1.Text
Case 1MessageBox.Show(“The number 1 was entered”, “Exercise 1”)Case 2
746
Trang 26MessageBox.Show(“The number 2 was entered”, “Exercise 1”)Case 3
MessageBox.Show(“The number 3 was entered”, “Exercise 1”)Case 4
MessageBox.Show(“The number 4 was entered”, “Exercise 1”)Case 5
MessageBox.Show(“The number 5 was entered”, “Exercise 1”)
To handle numbers other than 1 through 5, you need to provide a Case Elsestatement as shown here:
Case ElseMessageBox.Show(“A number other that 1 - 5 was entered”, _
“Exercise 1”)End Select
Exercise 2
In this exercise, you were tasked with creating two For Nextloops The first loop is supposed tocount from 1 to 10 and display the numbers in a list box The code to execute this loop is shown here:
‘Count from 1 to 10For intCount As Integer = 1 To 10ListBox1.Items.Add(intCount)Next
The second For Nextloop should count backward from 10 to 1 and display those numbers in a listbox The code to execute this loop is shown here:
‘Count backwards from 10 to 1For intCount As Integer = 10 To 1 Step -1ListBox1.Items.Add(intCount)
Public Class Form1
Private Enum Names As IntegerNorman = 1
Mike = 2Reece = 3End Enum
747 Solutions
Trang 27To display the member names and values from the enumeration, you would use code like this:
Private Sub Button1_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button1.Click
MessageBox.Show(Names.Norman.ToString & “ = “ & Names.Norman, _
“Exercise 1”)End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button2.Click
MessageBox.Show(Names.Mike.ToString & “ = “ & Names.Mike, _
“Exercise 1”)End Sub
Private Sub Button3_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles Button3.Click
MessageBox.Show(Names.Reece.ToString & “ = “ & Names.Reece, _
“Exercise 1”)End Sub
Exercise 2
You were tasked with creating an application that would redimension an array, preserving its currentelements and adding a new element to the array, and display the new element in a message box To cre-ate and initialize an array at the form level with just one name, you would code like this:
Public Class Form1
Private strNames() As String = {“Norman”}
To redimension the array, preserving the existing data, you would use code like this Notice that you usethe GetUpperBound(0)method to get the upper boundary of the array and then add 1 to it to enlargethe array by one element:
ReDim Preserve strNames(strNames.GetUpperBound(0) + 1)
To add the new name from the text box, you would use code like this Again you are using
GetUpperBound(0)to determine the upper boundary of the array:
strNames(strNames.GetUpperBound(0)) = TextBox1.Text
Finally, to display the last name added to the array in a message box, you would use code like this:
MessageBox.Show(strNames(strNames.GetUpperBound(0)), “Exercise 2”)
748
Trang 28Chapter 6 Solutions
Exercise 1
For this exercise, you were required to create a Windows application with two button controls You were
to wire up the MouseUp and LostFocus events for the first button The code for the MouseUp eventshould look similar to this:
Private Sub Button1_MouseUp(ByVal sender As Object, _ByVal e As System.Windows.Forms.MouseEventArgs) Handles Button1.MouseUp
‘Display a MessageBoxMessageBox.Show(“The MouseUp event has been fired.”, “Exercise 1”)End Sub
And the code for the LostFocus event should look similar to this:
Private Sub Button1_LostFocus(ByVal sender As Object, _ByVal e As System.EventArgs) Handles Button1.LostFocus
‘Display a MessageBoxMessageBox.Show(“Button1 has lost focus.”, “Exercise 1”)End Sub
When you ran this application, you may have noticed some unexpected behavior when you clicked thefirst button As soon as you let the mouse button up, you saw the message box indicating that the buttonhad lost focus, and then immediately after that, you saw the message box indicating that the MouseUpevent had been fired
What has actually happened here is that the code in the MouseUp event was fired, but the code in thatevent causes a message box to be displayed In the course of seeing that code, Visual Basic 2005 hasdetermined that the Button control will lose focus and has fired the LostFocus event, which displaysthe message box in that event handler first
Exercise 2
This exercise tasked you with creating an application that has a toolbar and status bar You were to insertthe standard buttons for the toolbar, create event handlers for the Click event of each button, and to dis-play a message in the status bar when any of the buttons was clicked The code for the event handlers islisted here:
Private Sub newToolStripButton_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles newToolStripButton.Click
‘Update the status barsspStatus.Text = “The New button was clicked.”
End Sub
Private Sub openToolStripButton_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles openToolStripButton.Click
749 Solutions
Trang 29‘Update the status barsspStatus.Text = “The Open button was clicked.”
Trang 30Private Sub btnOpen_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnOpen.Click
‘Declare a OpenFileDialog objectDim objOpenFileDialog As New OpenFileDialog
The bulk of the code to display the contents of the file in your text box remains the same as the code inthe Dialogs project but uses the objOpenFileDialogobject versus the OpenFileDialog control:
‘Set the Open dialog propertiesWith objOpenFileDialog
.Filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*”
.FilterIndex = 1.Title = “Demo Open File Dialog”
End With
‘Show the Open dialog and if the user clicks the Open button,
‘load the file
If objOpenFileDialog.ShowDialog = Windows.Forms.DialogResult.OK ThenDim allText As String
Try
‘Read the contents of the fileallText = My.Computer.FileSystem.ReadAllText( _objOpenFileDialog.FileName)
‘Display the file contents in the TextBoxtxtFile.Text = allText
Catch fileException As ExceptionThrow fileException
End TryEnd If
Since you are using an object, you need to perform the necessary cleanup to have the object you createdrelease its resources You do this by calling the Disposemethod on your object, and then you releaseyour reference to the object by setting it to Nothing:
‘Clean upobjOpenFileDialog.Dispose()objOpenFileDialog = NothingEnd Sub
The code for the Save button starts by declaring an object using the SaveFileDialogclass, and the rest
of the code is pretty much the same as the code in the Dialogs project The code at the end of this dure also performs the necessary cleanup of your object:
proce-Private Sub btnSave_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnSave.Click
‘Declare a SaveFileDialog objectDim objSaveFileDialog As New SaveFileDialog
‘Set the Save dialog propertiesWith objSaveFileDialog
.DefaultExt = “txt”
751 Solutions
Trang 31.FileName = “Test Document”
.Filter = “Text files (*.txt)|*.txt|All files (*.*)|*.*”
.FilterIndex = 1.OverwritePrompt = True.Title = “Demo Save File Dialog”
End With
‘Show the Save dialog and if the user clicks the Save button,
‘save the file
If objSaveFileDialog.ShowDialog = Windows.Forms.DialogResult.OK ThenTry
Dim filePath As String
‘Open or Create the filefilePath = System.IO.Path.Combine( _My.Computer.FileSystem.SpecialDirectories.MyDocuments, _objSaveFileDialog.FileName)
‘Replace the contents of the fileMy.Computer.FileSystem.WriteAllText(filePath, txtFile.Text, False)Catch fileException As Exception
Throw fileExceptionEnd Try
End If
‘Clean upobjSaveFileDialog.Dispose()objSaveFileDialog = NothingEnd Sub
Exercise 2
This exercise requires you to display the Browse For Folder dialog box with the Make New Folder ton displayed and to set My Documents as the root folder for the browse operation You start your pro-cedure off by declaring an object using the FolderBrowserDialogclass:
but-Private Sub btnBrowse_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnBrowse.Click
‘Declare a FolderBrowserDialog objectDim objFolderBrowserDialog As New FolderBrowserDialog
Next, you set the various properties of your objFolderBrowserDialogobject to customize the BrowseFor Folder dialog box Notice that you need to use the Personalconstant to have the dialog start brows-ing at the My Documents root folder:
‘Set the FolderBrowserDialog control propertiesobjFolderBrowserDialog.Description = “Select your favorite folder:”
objFolderBrowserDialog.RootFolder = Environment.SpecialFolder.PersonalobjFolderBrowserDialog.ShowNewFolderButton = True
You then display the dialog box, and if the user selected the OK button in the dialog box, you display thefolder chosen in the label control on your form:
752
Trang 32‘Show the Browse For Folder dialog
If objFolderBrowserDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
‘Display the selected folderLabel1.Text = objFolderBrowserDialog.SelectedPathEnd If
You end this procedure by performing the necessary cleanup of your object:
‘Clean upobjFolderBrowserDialog.Dispose()objFolderBrowserDialog = NothingEnd Sub
Chapter 8 Solution
This exercise asked you to complete your Menus application by adding a StatusStrip control and writingthe necessary code to display a message when text was cut, copied, and pasted in your text boxes If youfollowed the same basic procedures to add a StatusStrip control as you did in the Text Editor project inChapter 6, you will have added the control and added one panel named sspStatus
All that is required at this point is to add code to the procedures that actually perform the cut, copy, andpaste operations Starting with the cutToolStripMenuItem_Clickprocedure, you should have added
a single line of code similar to the following:
Private Sub cutToolStripMenuItem_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles cutToolStripMenuItem.Click
‘Declare a TextBox object and set it to the ActiveControlDim objTextBox As TextBox = Me.ActiveControl
‘Copy the text to the clipboard and clear the fieldobjTextBox.Cut()
‘Display a message in the status barsspStatus.Text = “Text Cut”
End Sub
And the code for the copyToolStripMenuItem_Clickprocedure should be similar to this:
Private Sub copyToolStripMenuItem_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles copyToolStripMenuItem.Click
‘Declare a TextBox object and set it to the ActiveControlDim objTextBox As TextBox = Me.ActiveControl
‘Copy the text to the clipboardobjTextBox.Copy()
‘Display a message in the status barsspStatus.Text = “Text Copied”
End Sub
753 Solutions
Trang 33And finally, the code for the pasteToolStripMenuItem_Clickprocedure should be similar to this:
Private Sub pasteToolStripMenuItem_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles pasteToolStripMenuItem.Click
‘Declare a TextBox object and set it to the ActiveControlDim objTextBox As TextBox = Me.ActiveControl
‘Copy the data from the clipboard to the textboxobjTextBox.Paste()
‘Display a message in the status barsspStatus.Text = “Text Pasted”
End Sub
Chapter 9 Solutions
Exercise 1
The Try Catchblock that you add is very simple, as shown here:
Private Sub ListCustomer(ByVal customerToList As Customer)Try
lstData.Items.Add(customerToList.CustomerID & _
“ - “ & customerToList.CustomerName)Catch ExceptionErr As Exception
MessageBox.Show(ExceptionErr.Message, “Debugging”, _MessageBoxButtons.OK, MessageBoxIcon.Error)End Try
End Sub
Exercise 2
Your modified Tryblock should look similar to the following code When you run your project andclick the Start button, you should see a message box with the message that you added to your Throwstatement
TryThrow New Exception(“Customer object not initialized.”)lstData.Items.Add(customerToList.CustomerID & _
“ - “ & customerToList.CustomerName)Catch ExceptionErr As Exception
MessageBox.Show(ExceptionErr.Message, “Debugging”, _MessageBoxButtons.OK, MessageBoxIcon.Error)End Try
754
Trang 34Chapter 10 Solutions
Exercise 1
Once you add the Implementsstatement highlighted as follows and press Enter, the rest of the codeshown below it is automatically inserted by Visual Studio 2005 to handle disposing of your class.Namespace CarPerformance
Public Class CarImplements IDisposable
Private disposed As Boolean = False
‘ IDisposablePrivate Overloads Sub Dispose(ByVal disposing As Boolean)
If Not Me.disposed Then
#Region “ IDisposable Support “
‘ This code added by Visual Basic to correctly implement the disposablepattern
Public Overloads Sub Dispose() Implements IDisposable.Dispose
‘ Do not change this code Put cleanup code in Dispose(ByVal disposing
As Boolean) above
Dispose(True)GC.SuppressFinalize(Me)End Sub
Protected Overrides Sub Finalize()
‘ Do not change this code Put cleanup code in Dispose(ByVal disposing
As Boolean) above
Dispose(False)MyBase.Finalize()End Sub
755 Solutions
Trang 35‘Dispose of the objectobjCar.Dispose()objCar = Nothing
‘Wait for input from the userConsole.ReadLine()
Exercise 2
This exercise required you to encapsulate the declaration and usage of the SportsCarclass in a Using .End Usingstatement Keeping in mind that the Using End Usingstatement automatically handlesdisposal of objects that implement the IDisposableinterface; the code can be implemented as high-lighted here
Sub Main()Using objCar As New SportsCar
‘Set the horsepower and weight(kg)objCar.HorsePower = 240
objCar.Weight = 1085
‘Display the details of the carDisplayCarDetails(objCar)DisplaySportsCarDetails(objCar)End Using
‘Wait for input from the userConsole.ReadLine()
End Sub
Chapter 11 Solution
You should have added code similar to this at the end of the Form1_Loadevent First you use the Countproperty of the Itemsproperty to ensure that one or more items exist in the list view control before pro-ceeding Then you select the first item in the list view control by setting the Selectedproperty to Truefor the first item in the Itemscollection Finally, you call the Clickevent of the list view control, pass-ing it a value of Nothingfor the Objectand System.EventArgsparameters
‘If one or more items exist
If lstFavorites.Items.Count > 1 Then
‘Select the first itemlstFavorites.Items(0).Selected = TruelstFavorites_Click(Nothing, Nothing)End If
Chapter 12 Solution
Modifying the Favorites Viewer project requires two steps First, you right-click the InternetFavoritesproject in the Solution Explorer and choose Remove from the context menu Then you right-click theFavorites Viewer project in the Solution Explorer and choose Add Reference from the context menu You756
Trang 36scroll down the list of components in the NET tab, select InternetFavorites, and then click OK Then yourun your project as normal with no code changes required.
Chapter 13 Solution
You start by adding a Private Booleanvariable to hold the value that determines whether a messagebox is shown Since this is a Booleanvariable, you also provide a default value of Trueso that when thecontrol is dragged onto a form, the SuppressMsgBoxproperty will have a default value set
Public Class MyNamespace
‘Private membersPrivate strApplicationName As String = String.EmptyPrivate blnSuppressMsgBox As Boolean = True
Next, you add a Publicproperty to get and set the private variable blnSuppressMsgBox This propertywill be exposed by the MyNamespace control in the Properties Window
Public Property SuppressMsgBox() As BooleanGet
Return blnSuppressMsgBoxEnd Get
Set(ByVal value As Boolean)blnSuppressMsgBox = valueEnd Set
End Property
Now you add code to each of the button to show the message box if the property is not set to True
Private Sub btnApplicationCopyright_Click(ByVal sender As System.Object, _ByVal e As System.EventArgs) Handles btnApplicationCopyright.Click
RaiseEvent ApplicationCopyrightChanged( _My.Application.Info.Copyright)
If Not blnSuppressMsgBox ThenMessageBox.Show(My.Application.Info.Copyright, _strApplicationName)
End IfEnd Sub
Private Sub btnScreenBounds_Click(ByVal sender As Object, _ByVal e As System.EventArgs) Handles btnScreenBounds.Click
RaiseEvent ScreenBoundsChanged(My.Computer.Screen.Bounds)
If Not blnSuppressMsgBox ThenMessageBox.Show(My.Computer.Screen.Bounds.ToString, _strApplicationName)
End IfEnd Sub
Private Sub btnScreenWorkingArea_Click(ByVal sender As Object, _
757 Solutions
Trang 37ByVal e As System.EventArgs) Handles btnScreenWorkingArea.Click
RaiseEvent ScreenWorkingAreaChanged(My.Computer.Screen.WorkingArea)
If Not blnSuppressMsgBox ThenMessageBox.Show(My.Computer.Screen.WorkingArea.ToString, _strApplicationName)
End IfEnd Sub
Next, you need to rebuild the control so that it can pick up the code changes in order to display theSuppressMsgBoxproperty in the Properties Window After that, you switch to the Controls projectand can select a True/Falsevalue for the SuppressMsgBoxproperty in the Properties Window
Chapter 15 Solutions
Exercise 1
The SQL statements for your EmployeeQuery should look like this:
SELECT Employees.FirstName, Employees.LastName, Employees.Title
FROM Employees
ORDER BY Employees.LastName;
You should have followed most of the steps in the “Binding Data to a DataGridView Control” Try It Outexercise and used the EmployeeQuery above in the Choose Your Database Objects screen of the DataSource Configuration Wizard Your results should look similar to those shown in Figure D-1
Figure D-1
Exercise 2
To create this application, you should have followed most of the steps in the “Binding Data to TextBoxControls” Try It Out exercise Your completed form should look similar to the one shown in Figure D-2,and you should be able to navigate through the records in the database
758
Trang 38Imports System.DataImports System.Data.SqlClientPublic Class Form1
Dim strConnectionString As String = “server=bnewsome;” & _
“database=pubs;uid=sa;pwd=!p@ssw0rd!”
Dim cnnAuthors As New SqlConnection(strConnectionString)Dim daAuthors As New SqlDataAdapter
Dim dsAuthors As New DataSet
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.LoaddaAuthors.SelectCommand = New SqlCommand
daAuthors.SelectCommand.Connection = cnnAuthorsdaAuthors.SelectCommand.CommandText = “Select * From Authors”
daAuthors = NothingcnnAuthors = NothingEnd Sub
End Class
759 Solutions
Trang 39Exercise 2
To complete this exercise, you were to use a DataGridView object to display the data from the pubsdatabase First, you should have created a Windows Application and added two references, one to theSystem.Data namespace and one to the System.XML namespace Next, you needed to add a datagrid-view control to your form That was all you needed to do before adding the code listed here You willnotice the difference from the first solution is just the SQL
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim strConnectionString As String = “server=bnewsome;” & _
“database=pubs;uid=sa;pwd=!p@ssw0rd!”
Dim cnnAuthors As New SqlConnection(strConnectionString)Dim daAuthors As New SqlDataAdapter
Dim dsAuthors As New DataSet
Private Sub Form1_Load(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles Me.LoadDim strSQL As String
strSQL = “Select au_id as ID, au_lname as [Last Name], “ & _
“au_fname as [First Name], Phone, Address, City, State, “ & _
“Zip, Contract From Authors”
daAuthors.SelectCommand = New SqlCommanddaAuthors.SelectCommand.Connection = cnnAuthorsdaAuthors.SelectCommand.CommandText = strSQLdaAuthors.SelectCommand.CommandType = CommandType.Text
cnnAuthors.Open()
daAuthors.Fill(dsAuthors, “authors”)
cnnAuthors.Close()
dgvAuthors.AutoGenerateColumns = TruedgvAuthors.DataSource = dsAuthorsdgvAuthors.DataMember = “authors”
daAuthors = NothingcnnAuthors = NothingEnd Sub
End Class
Chapter 17 Solution
The entire code listings follow the answer
You should have made the following additions
❑ To web.config:
760