Tải bản đầy đủ (.pdf) (78 trang)

Beginning Visual Basic 2005 phần 10 pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1018.44 KB, 78 trang )

If btn02.Text = btn12.Text And btn12.Text = btn22.Text And _
btn22.Text <> String.Empty Then
‘Winner on third column
Call Winner(btn02.Text)
Return True
End If
If btn00.Text = btn11.Text And btn11.Text = btn22.Text And _
btn22.Text <> String.Empty Then
‘Winner on diagonal top left to bottom right
Call Winner(btn00.Text)
Return True
End If
If btn20.Text = btn11.Text And btn11.Text = btn02.Text And _
btn02.Text <> String.Empty Then
‘Winner on diagonal bottom left to top right
Call Winner(btn20.Text)
Return True
End If
‘Test for a tie, all square full
Dim ctrl As Control
Dim intOpenings As Integer = 0
For Each ctrl In Me.Controls
If TypeOf (ctrl) Is Button And ctrl.Name <> “btnNewGame” Then
If ctrl.Text = String.Empty Then
intOpenings = intOpenings + 1
End If
End If
Next
If intOpenings = 0 Then
Call Winner(“It’s a tie.”)
Return True


End If
Return False
End Function
The remaining code is part of the handlers for the form’s Load event and the New Game button Click
event. On form load, the overloaded method
CorrectEnabledState is called and all buttons are disabled.
When you click the New Game button,
ResetGame is 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
Chapter 22
25_574019 ch22.qxd 9/16/05 9:33 PM Page 722
Summary
Visual Studio 2005 and the Compact Framework make developing mobile applications very similar to
desktop application development. This small learning curve for .NET developers is one of the reasons
more PDAs are shipping with a Windows operating system than with any other competitor. The trend
has 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 dif-
ferent between the full version of the .NET Framework and the Compact Framework. You were shown
examples of the missing pieces that explain how the CF has been shrunk by over 80 percent. Finally, you
built your first application, tic-tac-toe.

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 function
named
ComputerPlayToWin to the application. When the computer moves, call ComputerPlayToWin
and check for a spot on the board that will create a win for the computer. If it exists, the computer should
play that move rather than a random move. You can add other procedures if needed.
723
Building Mobile Applications
25_574019 ch22.qxd 9/16/05 9:33 PM Page 723
25_574019 ch22.qxd 9/16/05 9:33 PM Page 724
A
Where To Now?
Now that you have come to the end of this book, you should have a relatively good idea of how to
write code using Visual Basic 2005. The topics and example code covered in this book have been
designed to provide you with a firm foundation, but it is just the beginning of your journey. In
fact, this book is just one of the many steps you are going to take on your road to becoming a full
fledged 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 can
imagine, 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 of
you will want to continue at a more general level with some knowledge about all aspects of Visual
Basic 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. If

you 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 and
pieces will come together.
❑ Make sure you communicate your knowledge. If you know other programmers, get talk-
ing and ask questions.
❑ Consult our online and offline resources for more information.
The rest of this appendix lists available resources, both online and offline, to help you decide
where to go next.
26_574019 appa.qxd 9/16/05 9:26 PM Page 725
Online Resources
Basically, there are thousands of places you can go online for help with any problems you may have. The
good 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 others
who were at the same stage as you and may have had a similar problem, or experts with a great deal of
knowledge. 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 on
with some of the more general sites around. If you can’t find what you want through any of the sites
listed 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 Visual
Basic 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 have

the time or facilities to receive mailing lists, you can search the online archives using subject areas or
keywords.
Should you wish to use P2P for online support, go to
. On P2P, you can view the
groups 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 Lyris
system 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 more
newsgroups, navigate to
/>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:
/>❑ Visual Studio 2005 documentation:
/>❑ MSDN Library:
/>❑ Microsoft Developer Network site:
.
❑ Microsoft Visual Basic site:
/>❑ .NET download site:
/>❑ GotDotNet:
www.gotdotnet.com.
726
Appendix A
26_574019 appa.qxd 9/16/05 9:26 PM Page 726
Other 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, to
listings 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 possible
sites: one for the United Kingdom and another for the United States.
In the United Kingdom,
www.vbug.co.uk offers a wealth of information on Visual Basic. This is the Web
site for the Visual Basic Users Group (VBUG), which you can join. Besides the Web site, this group holds
meetings and an annual conference, plus provides a magazine. There is a listing of further links on the
Web 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 may
decide 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 we
will 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 the
direction that you want. We have a selection of tutorial-style books that build on the Visual Basic 2005
knowledge gained here. These will help you to specialize in particular areas. Here are the details of a
few 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 “next
steps.” It provides the next level from this book; however, it will be worth practicing your programming
skills 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?
26_574019 appa.qxd 9/16/05 9:26 PM Page 727
❑ Namespaces
❑ Error Handling and Debugging
❑ ADO.NET
❑ XML with VB.NET
❑ Forms
❑ Security
❑ 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 that
pull unique information for each visitor rather than showing everyone the same static HTML pages. The
book 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 the
book provides.
This book is for ASP.NET developers making the transition to this new version of the technology. The
changes 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
Appendix A
26_574019 appa.qxd 9/16/05 9:26 PM Page 728
❑ 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?
26_574019 appa.qxd 9/16/05 9:26 PM Page 729
26_574019 appa.qxd 9/16/05 9:26 PM Page 730
B
Implementing the Microsoft
Solutions Framework
So here you are, ready to go out into the world and build applications with Visual Basic 2005.
Congratulate yourself; your accomplishment of finishing the chapters of the book should excite
you. Soon, creating applications will become second nature to you. As you work in IT, you will
play many roles on teams. In some cases, your manager will only ask you to write code. By finish-
ing this book, you have a strong understanding of what you will need to do in that situation.

Other times, management will ask you to wear many hats on a project and be responsible for
delivering an entire solution. This appendix shows you how to create a successful solution.
Let’s start with a basic question. How is a solution different from an application? A solution is the
entire process of creating a system for a customer. The solution includes planning, documenting,
testing, releasing, training, and supporting the application. The application is just one part of the
solution.
Microsoft has a set of processes and models that to some is the standard for solution delivery in
the IT industry. Known as MSF (Microsoft Solutions Framework), software developers around the
globe 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.
27_574019 appb.qxd 9/16/05 9:49 PM Page 731
Software Development Life Cycle
The software development life cycle (SDLC) is a set of building blocks for software design. Microsoft
and others in the industry continue to develop methodologies to interpret the SDLC into a set of steps or
milestones. 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
❑ Gathering requirements
❑ Analysis and design
❑ Development
❑ Testing
❑ Installation

❑ Maintenance
Theoretically, the work progresses in a linear fashion from each of these steps to the next. In practice, it is
often the case that the need for further design work, more specific requirements, or a clearer definition of
the problem is discovered during development or testing, and the process loops back to the earlier stage.
Microsoft Solutions Framework
The Microsoft Framework Solution (MSF) is built for the implementation of large software projects. Two
distinct models (Team Model and Process Model) define the entire framework. To set up a large project
team, you will need to use the Team Model. As you begin your career, you will most likely work on
smaller projects. Because of this, I will not go into detail about the Team Model. The Process Model
defines how to complete the solution. In this appendix, I will show you how to use the principles of the
Process 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 pro-
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
the application. You may not understand this concept yet, but in my opinion writing 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 incorpo-
rates deploying multiple versions of software. Each version of the software will go through all phases of
the Framework. Next, I will explain the five phases of the process model listed here.
732
Appendix B
27_574019 appb.qxd 9/16/05 9:49 PM Page 732

❑ Envisioning
❑ Planning
❑ Developing
❑ Stabilizing
❑ Deploying
The Envisioning Phase
To start the MSF, you begin in the envisioning phase. The success of the project starts here. Make sure
you take the time to nail down all loose ends before moving forward with the project. Your customers
expect and deserve to understand how the project is going to proceed and the scope document at the
end 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 accomplish
before moving on to the planning phase.
Problem Statement
Why is the customer willing to spend $80,000 on a new system? This seems like an easy question. Don’t
take 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.
Goals
You 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 less
than 60 seconds.
The first goal is vague and is not measurable. If you base the system on goals like the first one, it is easy
for the customer to believe the system is not fast enough when you feel the system is much faster than it
had been. You may think the system is a success, but the customer thinks it is a failure. Remember to
make sure that you can measure system goals.

Define Roles
Here 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 the
system. This is where you will use the Team Model for large projects.
733
Implementing the Microsoft Solutions Framework
27_574019 appb.qxd 9/16/05 9:49 PM Page 733
Create a Scope Document
This document will be a blueprint of the solution. All stakeholders in the project should sign off on the
final 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 be
that you are working with new technologies that are unproven or that system bandwidth requirements
may exceed available network resources.
The Planning Phase
During the planning stage, you will create documents to validate that the project can succeed. The docu-
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 a
small project, this process can take many rounds of changes to gain sign-off from all parties. Finally, you
will create a project schedule and cost estimate before moving to the developing stage. Listed here are
the documents you need to create.
❑ 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 the
development environment to completing documentation into the development stage. The milestone for
this 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 environ-
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 can
cause unanticipated results on release of the application.
734
Appendix B
27_574019 appb.qxd 9/16/05 9:49 PM Page 734
Completing the Prototype
You must allow the customer to approve a prototype. Do not underestimate the value of this. Imagine
you were building a car. Without proper models, how hard is it to determine the proper location of the
steering 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 have
three months of coding under way, changes to the user interface can be costly.
Completing the Code
The application is ready for testing. Validate modules through unit testing.
Supply Application Documentation
The documentation from prior phases is compiled with a user manual and system documentation. The
test 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 a
small project over budget and late than to find 500 bugs while testing. Make sure you have adequate
time in your schedule to test and make test plans. Like basically everything else in the MSF, testing is an
iterative process. You will need test plans that you can repeat and validate after bug fixes. After each
round of testing, complete your test plans. Remember to document your result. When bugs arise in the

application after release, you will want to see why the test plan did not uncover the bug and then adjust
the test plan. After the customer has signed off on the test results, complete any documentation changes
and 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 happy
with the project. With all of the planning and customer interaction, there will be few surprises at this
point. You will put the solution into production and have a small team available to train and support the
users. 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 more
detail next.
735
Implementing the Microsoft Solutions Framework
27_574019 appb.qxd 9/16/05 9:49 PM Page 735
Managing Tradeoffs
To complete a successful project, you must be able to manage tradeoffs. You will find very quickly that
your 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 cus-
tomer means to say is; “Can you do that for $50,000 by the end of this year?” So when you answer the
“can it be done” question, make sure the customer knows that you can do it for the right price with
enough 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. You
should never consider reducing quality to lower price, finish sooner, or add features to make a project
successful. 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 at
least one of the others.
For example, suppose you are working with the marketing department on a small application. You are
the only resource available to work on the solution for the next two weeks during planning. While you
are 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 year
and for a cost of under $50,000. As you pry more, you find that Tina cannot spend more than $50,000 this
year. 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 budget
and deadline are required for success. For example, functionality will be moved to the next version if the
project gets behind schedule.
Table B-1: Project priorities
Tradeoff Priority
Under Budget First
Deliver Functionality Third
Meet Deadline Second
Halfway through the project, Tina wants to add more core functionality to the system. You look at the
budget and see that if you add more functionality to this release, you will need more resources to make
the deadline. Adding another developer to meet the deadline will cost an extra $10,000. Looking back at
the 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
Appendix B

27_574019 appb.qxd 9/16/05 9:49 PM Page 736
While talking to Tina, you explain the top priority for the project is budget. Adding the extra functional-
ity will cost an additional $10,000, bringing the budget estimate to $60,000. During the discussion, you
mention that the only way to add more functionality without increasing the deadline or budget is to
drop some of the functionality already planned. After 30 minutes, she agrees that $50,000 is all she can
spend, and the additional functionality can be part of a later version.
By understanding and agreeing on tradeoff priorities, you are able to work with customers to manage
change. 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. To
make the customer happy, you must succeed in most of these four areas; achieve system goals, meet
release date, stay under budget, and manage trade offs.
With the Framework implementation, you will find defining success possible. The two milestones that
are straightforward are meeting the budget and release date. Take a look at the project plan and make
sure 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 final
milestone 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 caused
you to miss the other milestones, but if you managed tradeoffs with the customer, the project will still be
successful. Success can be that simple if you follow the game plan.
Summary
As you grow in the information technology field, you will work on larger projects and have more
responsibility. Use this appendix as a basis for further study. Always keep in mind how many steps you
have to take to be successful managing a project. When you do get into a position to lead a project, take
the time to plan and test, and always work toward making the customer happy. You will not always be
successful 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
27_574019 appb.qxd 9/16/05 9:49 PM Page 737
27_574019 appb.qxd 9/16/05 9:49 PM Page 738
C
An Introduction to Security
In today’s electronic world, consumers are bombarded with scams via the Internet and e-mail. If
you 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 bank
security 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 by
criminals in an attempt to bait them into entering their personal and financial information. In these
schemes, 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 know
they 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 a
developer, it is your job to make applications safe. In some cases, features of your application can
make it easier for criminals to impersonate your application. Simple things like never asking for
personal information that you do not need over e-mail or the Web can make users aware of a
scam. For e-mail, you can never assume that e-mail will not be intercepted over the Internet. Make
sure 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 as
though 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 the
memory allocated. The extra data is not discarded, but rather it gets written to adjacent areas of
memory 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. The
victim program runs the attacker’s code as if it were its own, and the damage is done. The root
cause of this problem is not one most Visual Basic 2005 developers will encounter, but it should
make you aware that people may use your functions in ways you did not intend them to be used.
28_574019 appc.qxd 9/16/05 9:30 PM Page 739
Take 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 for
salespeople to upload comma-separated files of current sales data each night. The code allows the path
and file name to be passed as parameters, and it can be used by numerous departments because of this
flexibility. The problem is the flexibility allows a hacker to upload a Web page, place it into the root Web
directory, and do almost anything to the server or network. You should change this Web Service to store
files in a locked-down directory and modify the file name so that an attacker would not be able to access
the 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, all
assemblies on the call stack should have permission to access that resource. Take a look at the following
example.
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 that
assembly 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 assem-
bly had the correct digital signature, it could be granted access to a larger set of permissions.

CAS allows the system administrator to apply permissions to code rather than to users. Before 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 not
have 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 a
file, 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
Appendix C
28_574019 appc.qxd 9/16/05 9:30 PM Page 740
Permissions
Permissions 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 protected
resources.

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 be
used 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 not
granted to this set.
Your code can request any level of permission, and the runtime will verify before running the code that
these permissions will be granted.
Security Policy
The runtime enforces policy based on the identity or evidence of the assembly. When loading an assem-
bly, the assembly is inspected for evidence of its origin. Based on the origin, the runtime determines
what permissions to grant the assembly.
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
28_574019 appc.qxd 9/16/05 9:30 PM Page 741
Table C-1: Types of Evidence
Evidence Type Description

Application directory Installation directory
Hash Assembly hash
Publisher The Authenticode signature
Site Web site—for example, wrox.com.
Strong name Assembly’s Strong name
URL URL of the assembly
Zone Origination zone
When permissions are tested, an intersection of zones and permissions is evaluated to verify that all per-
missions for every zone and assembly on the stack are met. If permission is not granted to the code, the
zone, or the user, an exception is thrown and access is denied.
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. If
you need to secure parts of a Web site, your customers will expect this type of encryption. To promote
the level security to the end user, Internet Explorer and Netscape display a locked lock similar to Figure
C-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 double
clicking the lock icon or viewing the page’s properties or info. Figure C-2 is an actual certificate info
screen 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 well
respected 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 Try
link for the certificate type you wish to try.

thawte.com/: Click the link for a 21 day trial.
742

Appendix C
28_574019 appc.qxd 9/16/05 9:30 PM Page 742
You should keep in mind that encryption slows down the experience for the user and creates more load
for the server. Keep marketing and nonessential areas of your site unencrypted. Only encrypt pages that
communicate data that would be considered private.
Figure C-2
Finding 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 notes
about Microsoft products.

microsoft.com/security/guidance/checklists/: Microsoft’s security checklists. Here
you 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 are
being reported.

owasp.org: Open Web Application Security Project (OWASP). This site has free tools, docu-
mentation, and standards available.

sans.org/rr/: The SANS Institute Information Security Reading Room. Read thousands of
white papers on security issues.

webappsec.org: The Web Application Security Consortium. Read white papers on the latest
news about Web site security.
743
An Introduction to Security
28_574019 appc.qxd 9/16/05 9:30 PM Page 743
Summary

Security is the hottest topic in the information technology industry. Making applications 100 percent
secure is not possible with the openness of the Internet, but minimizing risks to vital data should be a
top priority in application design. As you build applications with VS 2005, know that you have the best
tool 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 to
assemblies and validate the origination of the code makes implementing a secure network easier. The
widespread use of certificates and code signing will make spoofing applications more difficult and keep
users’ computers safer.
The world of application security is by no means perfect. You will probably have to design your appli-
cations around security risks forever. But you can win by keeping security at the top of the priority list in
your 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 information
access is expanding will continue to be a challenge.
Just make sure you keep your head up and pay attention. Security holes are announced throughout the
media, and as a developer, you should pay attention and learn from the mistakes of the past. One of
your applications may one day be under attack.
744
Appendix C
28_574019 appc.qxd 9/16/05 9:30 PM Page 744
D
Solutions
Chapter 1 Solution
Exercise 1
To display the text from a text box on a form when the user clicks the button, you add code as
highlighted here to the button’s Click event handler:
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
MessageBox.Show(TextBox1.Text, “Exercise 1”)
End Sub

Chapter 3 Solutions
Exercise 1
The first part of this exercise requires you to declare two Integer variables and set their values
and 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 values
Dim 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 results
MessageBox.Show(“The sum of “ & intX & “ * “ & intY & “ = “ & _
intX * intY, “Exercise 1”)
29_574019 appd.qxd 9/16/05 9:40 PM Page 745
The second part of this exercise requires you to declare two String variables, set their values, and con-
catenate 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 = “2005”
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 1”)
Exercise 2
This exercise requires you to display the length of the string entered into a text box and then to display
the first half of the string and the last half of the string. To display the length of the string, you can use
the
Length property of the Text property of the text box as shown here:
‘Display the length of the string from the TextBox
MessageBox.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 Substring method 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 TextBox
MessageBox.Show(TextBox1.Text.Substring(0, TextBox1.Text.Length / 2), _
“Exercise 2”)
To display the last half of the string, you again use the Substring method, but this time you simply
give it a starting index of the length of the string divided by 2, as shown here:
‘Display the last half of the string from the TextBox
MessageBox.Show(TextBox1.Text.Substring(TextBox1.Text.Length / 2), _
“Exercise 2”)
Chapter 4 Solutions
Exercise 1
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 entered
Select Case TextBox1.Text
Case 1
MessageBox.Show(“The number 1 was entered”, “Exercise 1”)
Case 2
746
Appendix D
29_574019 appd.qxd 9/16/05 9:40 PM Page 746

×