Back to description
Welcome to the first chapter of the first section of this book. This section will provide you with the basic knowledge... more
Welcome to the first chapter of the first section of this book. This section will provide you with the basic knowledge you need to get up and running with C#. This chapter provides an overview of C# and the .NET Framework, including what these technologies are, the motivation for using them, and how they relate to each other.
First is a general discussion of the .NET Framework. This technology contains many concepts that are tricky to come to grips with initially. This means that the discussion, by necessity, covers many new concepts in a short amount of space. However, a quick look at the basics is essential to understanding how to program in C#. Later in the book you will revisit many of the topics covered here, exploring them in more detail.
After that general introduction, the chapter provides a basic description of C# itself, including its origins and similarities to C++. Finally, you look at the primary tools used throughout this book: Visual Studio 2008 (VS) and Visual C# 2008 Express Edition (VCE).
... less
Now that you’ve spent some time learning what C# is and how it fits into the .NET Framework,... more
Now that you’ve spent some time learning what C# is and how it fits into the .NET Framework, it's time to get your hands dirty and write some code. You use Visual Studio 2008 (VS) and Visual C# 2008 Express Edition (VCE) throughout this book, so the first thing to do is have a look at some of the basics of these development environments.
VS is an enormous and complicated product, and it can be daunting to first-time users, but using it to create basic applications can be surprisingly simple. As you start to use VS in this chapter, you will see that you don’t need to know a huge amount about it to start playing with C# code. Later in the book you’ll see some of the more complicated operations that VS can perform, but for now a basic working knowledge is all that is required.
VCE is far simpler for getting started, and in the early stages of this book all the examples are described in the context of this IDE. However, if you choose to, you can use VS instead, and everything will work in more or less the same way. For that reason, you’ll see both IDEs in this chapter, starting with VS.
Once you’ve had a look at the IDEs, you put together two simple applications. You don’t need to worry too much about the code in these for now; you just prove that things work. By working through the application creation procedures in these early examples, they will become second nature before too long.
The first application you create is a simple console application. Console applications are those that don’t make use of the graphical windows environment, so you won’t have to worry about buttons, menus, interaction with the mouse pointer, and so on. Instead, you run the application in a command prompt window, and interact with it in a much simpler way.
The second application is a Windows Forms application. The look and feel of this is very familiar to Windows users, and (surprisingly) the application doesn’t require much more effort to create. However, the syntax of the code required is more complicated, even though in many cases you don’t actually have to worry about details.
You use both types of application over the next two parts of the book, with slightly more emphasis on console applications at the beginning. The additional flexibility of Windows applications isn’t necessary when you are learning the C# language, while the simplicity of console applications enables you to concentrate on learning the syntax and not worry about the look and feel of the application.
In this chapter, you learn the following:
A basic working knowledge of Visual Studio 2008 and Visual C# 2008 Express Edition
How to write a simple console application
How to write a Windows Form application
To use C# effectively, it’s important to understand what you’re actually doing when you create a computer... more
To use C# effectively, it’s important to understand what you’re actually doing when you create a computer program. Perhaps the most basic description of a computer program is that it is a series of operations that manipulate data. This is true even of the most complicated examples, such as vast, multifeatured Windows applications (e.g., Microsoft Office Suite). Although this is often completely hidden from users of applications, it is always going on behind the scenes.
To illustrate this further, consider the display unit of your computer. What you see onscreen is often so familiar that it is difficult to imagine it as anything other than a “moving picture.” In fact, what you see is only a representation of some data, which in its raw form is merely a stream of 0s and 1s stashed away somewhere in the computer’s memory. Any onscreen actionmoving a mouse pointer, clicking on an icon, typing text into a word processorresults in the shunting around of data in memory.
Of course, simpler situations show this just as well. When using a calculator application, you are supplying data as numbers and performing operations on the numbers in much the same way as you would with paper and pencilbut a lot quicker!
If computer programs are fundamentally performing operations on data, then this implies that you need a way to store that data, and some methods to manipulate it. These two functions are provided by variables and expressions, respectively, and this chapter explores what that means both in general and specific terms.
In this chapter, you learn about:
Basic C# syntax
Variables and how to use them
Expressions and how to use them
Before starting that, though, you’ll take a look at the basic syntax involved in C# programming, because you need a context in which you can learn about and use variables and expressions in the C# language.
All of the C# code you’ve seen so far has had one thing in common. In each case, program execution has proceeded... more
All of the C# code you’ve seen so far has had one thing in common. In each case, program execution has proceeded from one line to the next in top-to-bottom order, missing nothing. If all applications worked like this, then you would be very limited in what you could do. This chapter describes two methods for controlling program flowthat is, the order of execution of lines of C# code: branching and looping. Branching executes code conditionally, depending on the outcome of an evaluation, such as “only execute this code if the variable myVal is less than 10.” Looping repeatedly executes the same statements (for a certain number of times or until a test condition has been reached).
myVal
Both of these techniques involve the use of Boolean logic. In the last chapter you saw the bool type, but didn’t actually do much with it. This chapter uses it a lot, so the chapter begins by discussing what is meant by Boolean logic so that you can use it in flow control scenarios.
bool
This chapter covers the following main topics:
Boolean logic and how to use it
How to control the execution of your code
Now that you’ve seen a bit more of the C# language, it’s time to go back and tackle some of the more involved... more
Now that you’ve seen a bit more of the C# language, it’s time to go back and tackle some of the more involved topics concerning variables.
The first subject you look at in this chapter is type conversion, whereby you convert values from one type into another. You’ve already seen a bit of this, but you look at it formally here. A grasp of this topic gives you a greater understanding of what happens when you mix types in expressions (intentionally or unintentionally) and tighter control over the way that data is manipulated. This helps you to streamline your code and avoid nasty surprises.
Then you’ll look at a few more types of variable that you can use:
Enumerations: Variable types that have a user-defined discrete set of possible values that can be used in a human-readable way
Structs: Composite variable types made up of a user-defined set of other variable types
Arrays: Types that hold multiple variables of one type, allowing index access to the individual values
These are slightly more complex than the simple types you’ve been using up to now, but they can make your life much easier. Finally, you’ll tackle another useful subject concerning strings: basic string manipulation.
All the code you have seen so far has taken the form of a single block, perhaps with some looping to repeat lines of code,... more
All the code you have seen so far has taken the form of a single block, perhaps with some looping to repeat lines of code, and branching to execute statements conditionally. If you needed to perform an operation on your data, then this has meant placing the code required right where you want it to work.
This kind of code structure is limited. Often, some taskssuch as finding the highest value in an array, for examplemay need to be performed at several points in a program. You can place identical (or near identical) sections of code in your application whenever necessary, but this has its own problems. Changing even one minor detail concerning a common task (to correct a code error, for example) may require changes to multiple sections of code, which may be spread throughout the application. Missing one of these could have dramatic consequences and cause the whole application to fail. In addition, the application could get very lengthy.
The solution to this problem is to use functions. Functions in C# are a means of providing blocks of code that can be executed at any point in an application.
Note
Functions of the specific type examined in this chapter are known as methods, but this term has a very specific meaning in .NET programming that will only become clear later in this book, so for now this term is not be used.
For example, you could have a function that calculates the maximum value in an array. You can use this function from any point in your code, and use the same lines of code in each case. Because you only need to supply this code once, any changes you make to it will affect this calculation wherever it is used. This function can be thought of as containing reusable code.
Functions also have the advantage of making your code more readable, as you can use them to group related code together. This way, your application body itself can be made very short, as the inner workings of the code are separated out. This is similar to the way in which you can collapse regions of code together in the IDE using the outline view, and it gives a more logical structure to your application.
Functions can also be used to create multipurpose code, enabling them to perform the same operations on varying data. You can supply a function with information to work with in the form of parameters, and you can obtain results from functions in the form of return values. In the preceding example, you could supply an array to search as a parameter and obtain the maximum value in the array as a return value. This means that you can use the same function to work with a different array each time. The name and parameters of a function (but not its return type) collectively define the signature of a function.
This chapter covers all of the following topics:
How to define and use simple functions that don’t accept or return any data
How to transfer data to and from functions
Variable scope, which reflects how data in a C# application is localized to specific regions of code, an issue that becomes especially important when you are separating your code into multiple functions.
An in-depth look at an important function in C# applications: Main(). You will learn how you can use the built-in behavior of this function to make use of command-line arguments, which enable you to transfer information into applications when you run them.
Main()
Another feature of the struct type shown in the last chapter: the fact that you can supply functions as members of struct types
The chapter ends with two more advanced topics: function overloading and delegates. Function overloading is a technique that enables you to provide multiple functions with the same name, but different parameters. A delegate is a variable type that enables you to use functions indirectly. A delegate can be used to call any function that matches the return type and parameters defined by the delegate, giving you the ability to choose between several functions at runtime.
So far in this book, you have covered all the basics of simple programming in C#. Before moving on to object-oriented... more
So far in this book, you have covered all the basics of simple programming in C#. Before moving on to object-oriented programming in the next part, you need to look at debugging and error handling in C# code.
Errors in code are something that will always be with you. No matter how good a programmer is, problems will always slip through, and part of being a good programmer is realizing this and being prepared to deal with it. Of course, some problems are minor and don’t affect the execution of an application, such as a spelling mistake on a button, but glaring errors are also possible, those that cause applications to fail completely (usually known as fatal errors). Fatal errors include simple errors in code that prevent compilation (syntax errors), or more serious problems that occur only at runtime. Some errors are subtle. Perhaps your application fails to add a record to a database because a requested field is missing, or adds a record with the wrong data in other restricted circumstances. Errors such as these, where application logic is in some way flawed, are known as semantic errors, or logic errors.
Often, you won’t know about a subtle errors until a user of your application complains that something isn’t working properly. This leaves you with the task of tracing through your code to find out what’s happening and fixing it so that it does what it was intended to do. In these situations, the debugging capabilities of VS and VCE are a fantastic help. The first part of this chapter looks at some of the techniques available and applies them to some common problems.
Then, you’ll learn the error-handling techniques available in C#. These enable you to take precautions in cases where errors are likely, and to write code that is resilient enough to cope with errors that might otherwise be fatal. These techniques are part of the C# language, rather than a debugging feature, but the IDE provides some tools to help you here, too.
This chapter covers two main topics:
Debugging methods available in Visual Studio
Error-handling techniques available in C#
At this point in the book, you’ve covered all the basics of C# syntax and programming, and have learned how to debug... more
At this point in the book, you’ve covered all the basics of C# syntax and programming, and have learned how to debug your applications. Already, you can assemble usable console applications. However, to access the real power of the C# language and the .NET Framework, you need to make use of object-oriented programming (OOP) techniques. In fact, as you will soon see, you’ve been using these techniques already, although to keep things simple we haven’t focused on this.
This chapter steers away from code temporarily and focuses instead on the principles behind OOP. This leads you back into the C# language, because it has a symbiotic relationship with OOP. All of the concepts introduced in this chapter are revisited in later chapters, with illustrative codeso don’t panic if you don’t grasp everything in the first read-through of this material.
To start with, you’ll look at the basics of OOP, which includes answering that most fundamental of questions “What is an object?” You will quickly find that there is a lot of terminology related to OOP that can be quite confusing at first, but plenty of explanations are provided. You will also see that using OOP requires you to look at programming in a different way.
As well as discussing the general principles of OOP, this chapter also looks at an area requiring a thorough understanding of OOP: Windows Forms applications. This type of application (which makes use of the Windows environment, with features such as menus, buttons, and so on) provides plenty of scope for description, and you will be able to illustrate OOP points effectively in the Windows Forms environment.
In this chapter you learn the following:
What object-oriented programming is
OOP techniques
How Windows Forms applications rely on OOP
OOP as presented in this chapter is really .NET OOP, and some of the techniques presented here don’t apply to other OOP environments. When programming in C#, you use .NET-specific OOP, so it makes sense to concentrate on these aspects.
In Chapter 8, you looked at the features of object-oriented programming (OOP). In this chapter, you put theory into practice... more
In Chapter 8, you looked at the features of object-oriented programming (OOP). In this chapter, you put theory into practice and define classes in C#. You won’t go so far as to define class members in this chapter but will concentrate on the class definitions themselves. That may sound a little limiting, but don’t worrythere’s plenty here to get your teeth into!
To start, you explore the basic class definition syntax, the keywords you can use to determine class accessibility and more, and the way in which you can specify inheritance. You also look at interface definitions, because they are similar to class definitions in many ways.
The rest of the chapter covers various related topics that apply when defining classes in C#, including the following:
The System.Object class
System.Object
Helpful tools provided by VS and VCE
Class libraries
A comparison between interfaces and abstract classes
Struct types
Copying objects
This chapter continues exploring class definitions in C# by looking at how you define field, property,... more
This chapter continues exploring class definitions in C# by looking at how you define field, property, and method class members. You start by examining the code required for each of these types, and learn how to generate the structure of this code using wizards. You also learn how to modify members quickly by editing their properties.
After covering the basics of member definition, you’ll learn some advanced techniques involving members: hiding base class members, calling overridden base class members, nested type definitions, and partial class definitions.
Finally, you put theory into practice by creating a class library that you can build on and use in later chapters.
In this chapter you learn how to do the following:
Work with fields, properties, and method class members
Create a class library
You’ve covered all the basic OOP techniques in C# now, but there are some more advanced techniques that are worth... more
You’ve covered all the basic OOP techniques in C# now, but there are some more advanced techniques that are worth becoming familiar with. In this chapter, you look at the following:
CollectionsCollections enable you to maintain groups of objects. Unlike arrays, which you’ve used in earlier chapters, collections can include more advanced functionality, such as controlling access to the objects they contain, searching and sorting, and so on. You’ll learn how to use and create collection classes and learn about some powerful techniques for getting the most out of them.
ComparisonsWhen dealing with objects, you often want to make comparisons between them. This is especially important in collections, because it is how sorting is achieved. You’ll look at how to compare objects in a number of ways, including operator overloading, and how to use the IComparable and IComparer interface to sort collections.
IComparable
IComparer
ConversionsEarlier chapters showed how to cast objects from one type into another. In this chapter, you’ll learn how to customize type conversions to suit your needs.
One of the (admittedly few) criticisms leveled against the first version of C# was its lack of support for generics.... more
One of the (admittedly few) criticisms leveled against the first version of C# was its lack of support for generics. Generics in C++ (known as templates in that language) had long been regarded as an excellent way of doing things, as it allowed a single type definition to spawn a multitude of specialized types at compile time and thus save an awful lot of time and effort. For whatever reason, generics didn’t quite make it into the first release of C#, and the language suffered because of it. Perhaps it was because generics are often seen as being quite difficult to get a handle on, or maybe it was decided that they weren’t necessary. Fortunately, with C# version 2.0 generics have joined the party. Even better, they aren’t very difficult to use, although they do require a slightly different way of looking at things.
In this chapter you do all of the following:
Examine what a generic is. You learn about generics in fairly abstract terms at first, because learning the concepts behind generics is crucial to being able to use them effectively.
See some of the generic types in the .NET Framework in action. This will help you to understand their functionality and power, as well as the new syntax required in your code.
Define your own generic types, including generic classes, interfaces, methods, and delegates. You also learn additional techniques for further customizing generic types: the default keyword and type constraints.
default
In this chapter, you continue exploring the C# language by looking at a few bits and pieces that haven’t quite fit... more
In this chapter, you continue exploring the C# language by looking at a few bits and pieces that haven’t quite fit in elsewhere. This isn’t to say that these techniques aren’t usefuljust that they don’t fall under any of the headings you’ve worked through so far.
Specifically, you will look at the following:
The :: operator and the global namespace qualifier
::
Custom exceptions and exception recommendations
Events
Anonymous methods
You also make some final modifications to the CardLib code that you’ve been building in the last few chapters, and even use CardLib to create a card game.
The C# language is not static. Anders Hejlsberg (the inventor of C#) and others at Microsoft continue to update and refine... more
The C# language is not static. Anders Hejlsberg (the inventor of C#) and others at Microsoft continue to update and refine the language. At the time of this writing, the most recent changes are part of version 3.0 of the C# language, which is released as part of the Visual Studio 2008 product line. At this point in the book you may be wondering what else could be needed; indeed, previous versions of C# lack little in terms of functionality. However, this doesn’t mean that it isn’t possible to make some aspects of C# programming easier, or that the relationship between C# and other technologies can’t be streamlined.
Perhaps the best way to understand this is to consider an addition that was made between versions 1.0 and 2.0 of the languagegenerics. You could argue that while generics are extremely useful, they don’t actually provide any functionality that you couldn’t achieve before. True, they simplify things a great deal, and you would have to write a lot more code without them. None of us would want to go back to the days before generic collection classes. Nonetheless, generics aren’t an essential part of C#. They are, though, a definite improvement to the language.
The C# 3.0 language enhancements are much the same. They provide new ways of achieving things that would have been difficult to accomplish before without lengthy and/or advanced programming techniques.
You’ve already seen two of the new features of C# 3.0: automatic properties and partial methods (Chapter 10). In both cases you may have noticed that the changes affect the compilation of C# code, rather than do something completely new. That’s a common aspect of C# language improvements, reinforcing the point that these improvements do not reflect enormous changes.
In this chapter you look at the following:
Initializers
Type inference
Anonymous types
Extension methods
Lambda expressions
Probably the biggest change to the C# language is the Language Integrated Query (LINQ) technology, which is covered later in Chapters 26–29. LINQ is a new way to manipulate collections of objects that can come from a variety of sourcesmost importantly, database or XML data. Many of the enhancements covered in this chapter are primarily used in association with LINQ, although they are also enhancements in their own right.
About 10 years ago, Visual Basic won great acclaim for providing programmers with tools for creating highly detailed user... more
About 10 years ago, Visual Basic won great acclaim for providing programmers with tools for creating highly detailed user interfaces via an intuitive form designer, along with an easy to learn programming language that together produced probably the best environment out there for Rapid Application Development (RAD). One of the advantages offered by RAD tools such as Visual Basic is that they provide access to a number of prefabricated controls that can be used to quickly build the user interface for an application.
At the heart of the development of most Visual Basic Windows applications is the Forms Designer. You create a user interface by dragging and dropping controls from a Toolbox to your form, placing them where you want them to appear when you run the program; double-clicking the control adds a handler for that control. The controls provided by Microsoft, along with additional custom controls that could be bought at reasonable prices, have supplied programmers with an unprecedented pool of reusable, thoroughly tested code that is no more than a mouse click away. Such application development is now available to C# developers through Visual Studio.
In this chapter, you work with Windows Forms, and use some of the many controls that ship with Visual Studio. These controls cover a wide range of functionality, and through the design capabilities of Visual Studio, developing user interfaces and handling user interaction is very straightforwardand fun! Presenting all of Visual Studio’s controls is impossible within the scope of this book, so this chapter looks at some of the most commonly used controls, ranging from labels and text boxes to list views and tab controls.
In this chapter you learn about the following:
The Windows Forms Designer
Controls for displaying information to the user, such as the Label and LinkLabel controls
Label
LinkLabel
Controls for triggering events, such as the Button control
Button
Controls that enable users of your application to enter text, such as the TextBox control
TextBox
Controls that enable you to inform users of the current state of the application and allow the user to change that state, such as the RadioButton and CheckButton controls
RadioButton
CheckButton
Controls that enable you to display lists of information, such as the ListBox and ListView controls
ListBox
ListView
Controls that enable you to group other controls together, such as the TabControl and Groupbox
TabControl
Groupbox
In the previous chapter, you looked at some of the controls most commonly used in Windows application development.... more
In the previous chapter, you looked at some of the controls most commonly used in Windows application development. With controls such as these, it is possible to create impressive dialogs, but very few full-scale Windows applications have a user interface consisting solely of a single dialog. Rather, these applications use a Single Document Interface (SDI) or a Multiple Document Interface (MDI). Applications of either of these types usually make heavy use of menus and toolbars, neither of which were discussed in the previous chapter, but I’ll make amends for that now.
With the addition of the Windows Presentation Foundation to the .NET Framework, a few new types of Windows applications were introduced. They are examined in detail in Chapter 34.
This chapter begins where the last left off, by looking at controls, starting with the menu control and then moving on to toolbars, where you will learn how to link buttons on toolbars to specific menu items, and vice versa. Then you move on to creating SDI and MDI applications, with the focus on MDI applications because SDI applications are basically subsets of MDI applications.
So far, you’ve consumed only those controls that ship with the .NET Framework. As you saw, these controls are very powerful and provide a wide range of functionality, but there are times when they are not sufficient. For those cases, it is possible to create custom controls, and you look at how that is done toward the end of this chapter.
In this chapter, you will see how to do the following:
Use three common controls to create rich-looking menus, toolbars, and status bars.
Create MDI applications.
Create your own controls.
The last three chapters looked at various aspects of programming Windows Forms applications, and how to implement such... more
The last three chapters looked at various aspects of programming Windows Forms applications, and how to implement such things as menus, toolbars, and SDI and MDI forms. Now you know how to display simple message boxes to get information from the user and how to create more sophisticated custom dialogs to ask the user for specific information. However, for common tasks such as opening and saving files, you can use prewritten dialog classes instead of having to create your own custom dialog.
This not only has the advantage of requiring less code, but also it uses the familiar Windows dialogs, giving your application a standard look and feel. The .NET Framework has classes that hook up to the Windows dialogs to open and create directories, to open and save files, to access printers, and to select colors and fonts.
In this chapter, you learn how to use these standard dialog classes. In particular, you will learn how to do the following:
Use the OpenFileDialog and SaveFileDialog classes
OpenFileDialog
SaveFileDialog
Learn about the .NET printing class hierarchy and use the PrintDialog, PageSetupDialog, and PrintPreviewDialog classes to implement printing and print preview
PrintDialog
PageSetupDialog
PrintPreviewDialog
Change fonts and colors with the FontDialog and ColorDialog classes
FontDialog
ColorDialog
Use the FolderBrowserDialog class
FolderBrowserDialog
There are several ways to install Windows applications. Simple applications can be installed with a basic xcopy deployment,... more
There are several ways to install Windows applications. Simple applications can be installed with a basic xcopy deployment, but for installation to hundreds of clients, an xcopy deployment is not really useful. For that situation, you have two options: ClickOnce deployment or the Microsoft Windows Installer.
With ClickOnce deployment, the application is installed by clicking a link to a Web site. In situations where the user should select a directory in which to install the application, or when some registry entries are required, the Windows Installer is the deployment option to use.
This chapter covers both options for installing Windows applications. In particular, you will look at the following:
Deployment basics
ClickOnce deployment
Visual Studio deployment and setup project types
Features of the Windows Installer
Creating Windows Installer packages using Visual Studio 2008
Windows Forms is the technology for writing Windows applications; with ASP.NET, Web applications that are displayed in... more
Windows Forms is the technology for writing Windows applications; with ASP.NET, Web applications that are displayed in any browser can be built. ASP.NET enables you to write Web applications in a similar way to that in which Windows applications are developed. This is made possible by server-side controls that abstract the HTML code and mimic the behavior of the Windows controls. Of course, there are still many differences between Windows and Web applications because of the underlying technologies HTTP and HTML on which Web applications are based.
This chapter provides an overview of programming Web applications with ASP.NET, how to use Web controls, how to deal with state management (which is very different from how it’s handled in Windows applications), how to perform authentication, and how to read and write data to and from a database.
Specifically, this chapter covers the following topics:
What happens on the server when a HTML request is sent from the client
How to create a simple Web page
Using Web server controls in a Web page (and seeing the HTML code they generate)
How to add event handlers to act on user actions
Using validation controls to validate user input
How to implement state management with different methods, such as ViewState, cookies, and session, application, and cache objects
session
application
cache
How to use authentication and authorization features offered by ASP.NET controls
How to display and update database information
In Chapter 19, you learned about base features of ASP.NET, how server-side controls can be used to render HTML code to... more
In Chapter 19, you learned about base features of ASP.NET, how server-side controls can be used to render HTML code to the client, input validation, and state management. You’ve also learned how security can be added, and how to read/write data from/to the database. This chapter looks at user interface elements and customization of Web pages with profiles and Web parts. Master pages are used to define a frame for multiple pages. You can use site navigation to define the structure of your Web site, making menus to access all the pages. To reuse controls within multiple pages on the same Web site, you can create user controls. The last section of the chapter describes Web parts, which you can use to create a portal Web site.
In this chapter, you learn about the following:
Creating and using master pages
Creating and using user controls
Setting up navigation within Web sites
Using profiles
Using Web parts
Coding with JavaScript
You’ve certainly come across the term Web services before, although you may not be aware of what they are or how... more
You’ve certainly come across the term Web services before, although you may not be aware of what they are or how they fit into the way the Web operatesand will operate in the future. Suffice it to say that Web services provide the foundation of the new generation of Web applications. Whatever the client application iswhether it is a Windows application or an ASP.NET Web Forms applicationand whatever operating system the client is runningWindows, Pocket Windows, or some other OSthey will regularly communicate over the Internet using a Web service.
Web services are server-side programs that listen for messages from client applications and return specific information. This information may come from the Web service itself, from other components in the same domain, or from other Web services. While the concept of the Web service is evolving continuously, there are several different types of Web services that carry out different functions: Some provide information specific to a particular industry such as manufacturing or healthcare; there are portal services that use services from different providers to offer information on a specific theme; there are services specific to single applications, and building block services that can be used by many different applications.
Web services give you the capability to combine, share, exchange, or plug in separate services from various vendors and developers to form entirely new services or custom applications created on-the-fly to meet the requirements of the client.
This chapter covers the following topics:
Predecessors of Web services
What a Web service is
Protocols used for Web services
Creating an ASP.NET Web service
Testing a Web service
Building a client to use Web services
Calling a Web service asynchronously
Sending and receiving messages
This chapter does not go into the inner workings of Web services, but you will get an overview of what these protocols are used for. After reading this chapter, you can start creating and consuming simple Web services with the help of Visual Studio.
Users want Web applications that are as interactive as Windows applications are. Asynchronous JavaScript and XMLAjaxis... more
Users want Web applications that are as interactive as Windows applications are. Asynchronous JavaScript and XMLAjaxis a technology that makes it easy to create interactive Web applications.
In this chapter, you
Get an overview of Ajax
Use the ASP.NET UpdatePanel control
UpdatePanel
Use the ASP.NET AJAX Timer control
Timer
Use the UpdateProgress control
UpdateProgress
Create a Web service and call it from client script
Explore the extender controls that you get in the ASP.NET AJAX Control Toolkit
In the previous three chapters you learned to develop Web applications and Web services with ASP.NET.... more
In the previous three chapters you learned to develop Web applications and Web services with ASP.NET. For all these application types, different deployment options exist. You can copy the Web pages, publish the Web site, or create an installation program. This chapter covers the advantages and disadvantages of the different options, and how to accomplish these tasks.
Internet Information Services (IIS)
IIS configuration
Copying Web sites
Publishing Web sites
Windows Installer
Reading and writing files are essential aspects of many .NET applications. This chapter shows you how,... more
Reading and writing files are essential aspects of many .NET applications. This chapter shows you how, touching on the major classes used to create, read from, and write to files, and the supporting classes used to manipulate the file system from C# code. Although you won’t examine all of the classes in detail, this chapter goes into enough depth to give you a good idea of the concepts and fundamentals.
Files can be a great way to store data between instances of your application, or they can be used to transfer data between applications. User and application configuration settings can be stored to be retrieved the next time your application is run. Delimited text files, such as comma-separated files, are used by many legacy systems, and to interoperate with such systems you need to know how to work with delimited data. As you will see, the .NET Framework provides you with the necessary tools to use files effectively in your applications.
By the end of this chapter, you will have learned the following:
What a stream is and how .NET uses stream classes to access files
How to use the File object to manipulate the file structure
File
How to write to, and read from, a file
How to read and write formatted data from and to files
How to read and write compressed files
How to serialize and deserialize objects
How to monitor files and directories for changes
Extensible Markup Language (XML) is a technology that has been receiving great attention for the past few years.... more
Extensible Markup Language (XML) is a technology that has been receiving great attention for the past few years. XML is not new, and it was certainly not invented by Microsoft for use in the .NET environment, but Microsoft recognized the possibilities of XML early in its development. Because of that you will see it performing a large number of duties in .NET, from describing the configuration of your applications to transporting information between Web services.
XML is a way of storing data in a simple text format, which means that it can be read by nearly any computer. As you’ve seen in some of the earlier chapters about Web programming, this makes it a perfect format for transferring data over the Internet. It’s even not too difficult for humans to read!
The ins and outs of XML can be very complicated, so you won’t look at every single detail here. However, the basic format is very simple, and most tasks don’t require a detailed knowledge of XML because Visual Studio typically takes care of most of the workyou will rarely have to write an XML document by hand. Having said that, XML is hugely important in the .NET world because it’s used as the default format for transferring data, so it’s vital to understand the basics.
The structure and elements of XML
XML Schema
Using XML in your applications
For a more detailed look at XML, check out Beginning XML, Fourth Edition (Wrox, 2007).
This chapter introduces Language-Integrated Query (LINQ), a new extension to the C# language just added for C# 3.0,... more
This chapter introduces Language-Integrated Query (LINQ), a new extension to the C# language just added for C# 3.0, which is the C# language supported in Visual C# 2008. LINQ solves the problem of dealing with very large collections of objects, where you typically need to select a subset of the collection for the task your program is performing.
In the past, this sort of work required writing a lot of looping code, and additional processing such as sorting or grouping the found objects required even more code. LINQ frees you from having to write this extra looping code to filter and sort. It enables you to focus on the objects that matter to your program, providing a query.
In addition to providing an elegant query language that enables you to specify exactly what objects you are searching for, LINQ offers many extension methods that make it easy to sort, group, and calculate statistics on your query results.
LINQ also enables you to query large databases or complex XML documents in which millions or even billions of objects need to be searched or manipulated efficiently. Traditionally, this problem was usually solved with a specialized class library or even using a different language, such as database query language SQL. However, class libraries are not easy to extend for many different types of objects, and mixing languages causes problems with mismatched types, as well as making programs hard to understand for developers not familiar with both languages, entiende? LINQ provides a mechanism built into the C# language itself that solves each of these problems.
This chapter introduces you to the varieties of LINQ, including LINQ to Objects, LINQ to SQL, and LINQ to XML, and covers the following topics:
Coding a LINQ query and the parts of a LINQ query statement
Using LINQ method syntax versus LINQ query syntax
Using lambda expressions with LINQ
Ordering query results, including ordering on multiple levels
How to use LINQ aggregate operatorsand when to use them
Using projection to create new objects in queries
Using the Distinct(), Any(), All(), First(), FirstOrDefault(), Take(), and Skip()operators
Distinct()
Any()
All()
First()
FirstOrDefault()
Take()
Skip()
Group queries
Set operators and joins
While this chapter focuses on LINQ to Objects, the concepts apply to all the varieties of LINQ and are necessary background for later chapters on LINQ to SQL and LINQ to XML.
LINQ is large enough that complete coverage of all its facilities and methods is beyond the scope of a beginning book. However, you will see examples of all of the different types of operators and statements you are likely to need as a user of LINQ, and you will be pointed to resources for more in-depth coverage as appropriate.
The previous chapter introduced LINQ (Language-Integrated Query) and showed how to use LINQ to Objects,... more
The previous chapter introduced LINQ (Language-Integrated Query) and showed how to use LINQ to Objects, the version of LINQ that works with objects in memory. This chapter explores LINQ to SQL, the version of LINQ that provides access to SQL (pronounced “sequel”) databases such as Microsoft SQL Server and Oracle.
These databases use the SQL database language (SQL stands for Structured Query Language) to query and manipulate their data. Traditionally, working with such a database required knowing at least some SQL, either embedding SQL statements in your programming language or passing strings containing SQL statements to API calls or methods in a SQL-oriented database class library.
Sounds complicated, doesn’t it? Well, the good news is that LINQ to SQL handles all the details of communicating with the SQL database for you! It translates your LINQ queries to SQL statements automatically and enables you and your programs to work simply with C# objects.
Visual C# 2008 provides designers that create LINQ to SQL classes for you from the existing database, and provides a simple way to bind the controls in your forms to your databases graphically, so that a full database application can be created quickly and easily with very little handwritten code.
You will see how this works as you step through the examples in this chapter. In particular, you look at the following:
The concept of object-relational mapping (ORM) and how LINQ to SQL provides it
How to install SQL Server Express as a relational database to use with LINQ to SQL
How to install the Northwind sample database to use with the example code
How to use the O/R Designer in Visual C# 2008 to create objects for a specific database
How to use LINQ to SQL queries with the objects created by the O/R Designer
How to navigate relationships between database objects using LINQ to SQL
How to use group queries and other advanced LINQ features with LINQ to SQL
How to tie LINQ to SQL objects to graphical controls
How to update and insert new objects in a database using LINQ to SQL
The previous chapter introduced LINQ (Language-Integrated Query) and showed how it works with objects.... more
The previous chapter introduced LINQ (Language-Integrated Query) and showed how it works with objects. This chapter introduces ADO.NET, which is the traditional way of accessing databases with previous versions of C# and .NET, and then it introduces LINQ over DataSet, which is the version of LINQ that cooperates with ADO.NET.
All examples in this chapter use the SQL Server Northwind example database (except where specifically noted). See the previous chapter for instructions on installing the SQL Server Northwind example database.
In particular, this chapter looks at the following:
An overview of ADO.NET and the structure of its main classes
Reading data with a DataReader and with a DataSet
DataReader
DataSet
Updating the database, adding records, and deleting records
Working with relationships in ADO.NET
Reading and writing XML documents in ADO.NET
Executing SQL commands directly from ADO.NET
Executing stored procedures from ADO.NET
Querying ADO.NET objects with LINQ over DataSet
After an overview of ADO.NET, you will learn the concepts behind it. Then you can create some simple projects and start using the ADO.NET classes.
The previous two chapters introduced LINQ (Language-Integrated Query) and showed how LINQ works with objects and databases.... more
The previous two chapters introduced LINQ (Language-Integrated Query) and showed how LINQ works with objects and databases. This chapter introduces LINQ to XML, which is the version of LINQ that enables you to use LINQ to query and manipulate XML (Extensible Markup Language).
You learned about XML in Chapter 25, so that is not covered again here. You should be familiar with XML documents, elements, attributes, and so on before proceeding further in this chapter, so if you haven’t read the introduction to XML at the beginning of Chapter 25, do so now.
LINQ to XML is not intended to replace the standard XML APIs such as XML DOM (Document Object Model), XPath, XQuery, XSLT, and so on. If you are familiar with these APIs or currently need to use them or learn them, you should continue to do so.
LINQ to XML supplements these standard XML classes and makes working with XML easier. LINQ to XML gives you extra options for creating and querying XML data, resulting in simpler code and quicker development for many common situations, especially if you are already using LINQ to Objects or LINQ to SQL in other parts of your programs.
In learning LINQ to XML, in particular you will look at the following:
How to easily create XML documents with LINQ to XML functional constructor methods
How to format, load, and save XML documents with LINQ to XML
How use LINQ to XML to work with incomplete XML documents (fragments).
How to generate an XML document from a LINQ to SQL or LINQ to Objects query
How to query an XML document with LINQ to XML using standard LINQ query syntax
How use LINQ aggregate operators with LINQ to XML
This chapter introduces the subject of attributes, describing what they are and what they can be used for.... more
This chapter introduces the subject of attributes, describing what they are and what they can be used for. Also included are examples demonstrating several of the attributes available with the .NET Framework. Custom attributesattributes you can write yourself to extend the systemare covered as well, along with several working examples. You’ll also learn how the Intermediate Language Disassembler (Ildasm) can be used to discover the attributes of existing assemblies.
Ildasm
Attributes are one of the most useful features of the .NET Framework, and they are used frequently by Microsoft. To use them effectively, you need to make a significant investment of time, but it is worth the effort. In this chapter, you’ll learn how to do the following:
Use attributes to define sections of code that are only included in Debug builds
Use attributes to define information about an assembly, such as copyright information
Use attributes to mark sections of code as obsolete, so that over time you can revise your assemblies
Create your own attributes and use these to maintain a change history
The final section of this chapter describes in detail how to write your own attributes that extend the system, and it provides a working example of a custom attribute that can be used to maintain change history of your code. By the end of the chapter, you should have enough knowledge of attributes to apply these to your own projects.
Up to this point in this book, you’ve seen the entire C# language and a great many things you can do with it,... more
Up to this point in this book, you’ve seen the entire C# language and a great many things you can do with it, including both Web and Windows programming. Along the way you’ve seen, and made extensive use of, the IntelliSense feature in Visual Studio. This helpful tool dramatically reduces the amount of typing you have to do, because it suggests keywords, type names, variable names, and parameters as you type. It also makes it easier to remember what methods and properties you have at your disposal and often tells you exactly how to use them.
However, the classes you have made have suffered slightly here. While the classes and member names are suggested for you, no handy hints pop up telling you how to do things. To achieve the kind of behavior that you see with the .NET Framework types, you need to use XML documentation. XML documentation enables you to include syntax, help, and examples for the classes you create at the source-code level. This information may then be used to provide IntelliSense information for Visual Studio as discussed previously, but there are other possibilities. You can use XML documentation as a starting point for full, MSDN-link documentation of your projects. You can also style the XML documentation using XSLT to obtain instant HTML documentation with very little effort. You have seen in earlier chapters just how versatile XML is, and you can use all of its power in the development and production life cycle of your applications.
Documentation is particularly important when you are working as part of a team, as it enables you to show exactly how your types work. It can also be very useful to end users if you are creating an SDK or similar product where you expect people to use your classes from their code. Having the facility to create this documentation built into the tool you use to develop code is a very powerful feature. Although adding XML documentation to your code can be a time-consuming process, the result is well worth it. Dropping text in as you develop can make things easier in the long run and provide you with a handy quick reference that will help to avoid confusion when the amount of classes in your project starts getting out of hand.
In this chapter, you will learn two main things:
How to add and view basic XML documentation
How to use XML documentation
Chapter 21 dealt with a high-level technology to communicate across the network: Web Services. You learned how to send... more
Chapter 21 dealt with a high-level technology to communicate across the network: Web Services. You learned how to send messages from the client to the server in a platform-independent way with the SOAP and .NET-specific protocols. In this chapter, you step into lower networking layers, programming with classes from the namespace System.Net. Web Services itself uses this technology.
System.Net
This chapter begins with an overview of programming client and server applications with classes from the namespaces System.Net and System.Net.Sockets, which make use of protocols such as HTTP, TCP, and UDP. You explore both connection-oriented applications with TCP and connectionless applications with the UDP protocol.
System.Net.Sockets
This chapter includes the following topics:
An overview of networking
Networking programming options
Using WebRequest
WebRequest
TcpListener and TcpClient
TcpListener
TcpClient
Socket programming
In the previous chapter, the term GDI+ was briefly introduced when you looked at printing in the .NET Framework.... more
In the previous chapter, the term GDI+ was briefly introduced when you looked at printing in the .NET Framework. This chapter provides a real introduction to programming using the Graphics Device Interface classes (GDI+), the drawing technology of the .NET Framework. Mapping applications, games, computer-aided design/computer-aided manufacturing (CAD/CAM), drawing programs, charting programs, and many other types of applications require developers to write graphics code for their Windows Forms applications. Writing custom controls can also require graphics code. With this latest class library, Microsoft has made writing graphics code easier than ever.
Writing graphics code is one of the most enjoyable programming tasks. It is very rewarding to change your code and immediately see the results in a visible form. Whether you are writing a custom graphics window that presents something in your application in a new and different way or writing a custom control that makes your application more stylish and more usable, your application will be well received by the general public.
This chapter first explains the mechanics of drawing using GDI+, and you write a few simple graphical example programs. Then you take a high-level look at some of the extensive capabilities of GDI+ such as clipping. After an overview of each of these topics, you look at the classes you can use to implement the features. Knowing what you can do and understanding the class hierarchy is half the battle.
This chapter covers the following:
Drawing surfaces as encapsulated by the Graphics class
Graphics
Colors as defined by the Color structure
Color
Drawing lines and shapes
Drawing text and images
Drawing into images (double-buffering)
In this book you have seen two main types of application: desktop applications, which users run directly,... more
In this book you have seen two main types of application: desktop applications, which users run directly, and Web applications, which users access through a browser. You have created these with two different sections of the .NET Framework: Windows Forms and ASP.NET pages. These application types have their advantages and disadvantages. While desktop applications give you more flexibility and responsiveness, Web applications can be accessed remotely by many users at once.
However, in today’s computing environment, the boundaries between applications are becoming increasingly blurred. With the advent of Web services and now the Windows Communication Foundation (WCF, which you’ll look at in Chapter 35), both desktop and Web applications can operate in a more distributed way, exchanging data across local and global networks. In addition, Web client applications (that is, browsers such as Internet Explorer or Firefox) can no longer be seen as so-called “thin” clients that lack any functionality other than the simple display of information. The latest browsers, and the computers that run them, are capable of far more than this.
In recent years there has been a gradual convergence toward a user experience singularity. Web applications now typically use technologies such as JavaScript, Flash, Java applications, and others, and increasingly behave like desktop applications. You only have to look at the capabilities of, for example, Google Docs to see this in action. Conversely, desktop applications have become increasingly “connected,” with capabilities ranging from the simple (automatic updates, online help, and so on) through to the advanced (such as online data sources and peer-to-peer networking). This is illustrated in Figure 34-1.
Windows Presentation Foundation (WPF) is a unifying technology that enables you to write applications that bridge the desktop/Internet gap. A WPF application, as you will see in this chapter, can run as a desktop application or inside a browser as a Web application. There is also a slimmed down version of WPF, Silverlight, that you can use to add dynamic content to Web applications.
In this chapter you learn about WPF and how you can use it to create the next generation of applications. You look at the following topics:
What is WPF?
The anatomy of a basic WPF application
WPF fundamentals
Programming with WPF
In Chapter 21 you learned about Web services and how you can use them to provide simple communication between applications.... more
In Chapter 21 you learned about Web services and how you can use them to provide simple communication between applications. You saw how you could use HTTP GET and POST techniques to exchange data with Web services, and how to use SOAP. Over the years since Web services were first made available to .NET developers, it has become apparent that although Web services are great, there is scope to extend this technology. Microsoft released the Web Service Enhancements (WSE) add-on to address this. WSE enabled Web service developers to include security for messages, routing techniques, and various other policies to improve Web services. Again, though, there was room for improvement.
GET
POST
Another .NET technology, remoting, makes it possible to create instances of objects in one process and use them from another process. Remoting makes this possible even if the object is on a different computer from the one that is using it. However, this technology, despite being a great improvement over previous technologies such as DCOM, still has its problems. Remoting is limited, and it isn’t the easiest thing for a beginner programmer to learn.
Windows Communication Foundation (WCF) is essentially a replacement for both Web services and remoting technology. It takes concepts such as services and platform-independent SOAP messaging from Web services, and combines these with concepts such as host server applications and advanced binding capabilities from remoting. The result is a technology that you can think of as a superset that includes both Web services and remoting, but that is much more powerful that Web services and much easier to use than remoting. By using WCF, you can move from simple applications to applications that use a service-oriented architecture (SOA). SOA means that you decentralize processing and make use of distributed processing by connecting to services and data as you need them across local networks and the Internet.
In this chapter you learn about the principles behind WCF and how you can create and consume WCF services from your application code. Included are the following topics:
What is WCF?
WCF concepts
WCF programming
You cannot create WCF services in VCE, but you can in the full version of VS. You can also create IIS-hosted WCF services in Visual Web Developer 2008 Express Edition, but in this chapter you’ll use VS in order to see the full range of options.
Welcome to the final chapter of the bookand I would like to think that we’ve saved the best until last!... more
Welcome to the final chapter of the bookand I would like to think that we’ve saved the best until last! Many applications need some form of configuration or customization capability, and traditionally this was done by adding in some form of hook to the application so that a third party could add in extra code. A common method was to define an interface in .NET and then ensure that each plug-in supported that interface. The only trouble with this is that it’s all code based, and users without a programming background would find this daunting, if not impossible, to do.
Another way to extend applications is using some form of scripting languagesuch as VBA (Visual Basic for Applications), which is included in Microsoft Word, Excel, and many other applications. The issue here is the barrier to entrythere are licensing costs for VBA, and integrating it with your application isn’t a trivial task.
In .NET 3.0 and above there is anotherand in my opinion much betterway to permit end users to customize an application: Windows Workflow Foundation (referred to as WF throughout the rest of this chapter).
A workflow can be considered simply as a function in C#, which consists of a number of statements (known as activities), optional parameters, and optional return values. That, however, is where the similarity endsas a workflow is defined using a set of graphical building blocks, rather than code.
Activities are the building blocks from which a workflow is constructedthere are 30 built-in activities, some of which are discussed in this chapter. An activity is just a .NET class that is derived from a particular base class, so you can construct your own activities to perform your own processing. Constructing a workflow is similar to designing a form or an ASP.NET pageyou can drag and drop activities from the Toolbox onto the design surface and wire these up into a complete workflow.
When you run a workflow, there is a runtime engine (known as the WorkflowRuntime) that executes the activities in that workflow. This engine knows how to schedule workflows and is used to communicate with running workflow instances. A workflow can be considered in a similar way to a Word templatethe workflow is the template and the running workflow instance is like the document created from that template.
How to create workflows
What an activity is, and how to use several of the built-in activities
How to handle faults in a workflow
How to use the Workflow Persistence Service
How to pass parameters to a workflow
Purchase Before purchasing this product, please be sure you have met all software and system requirements, and that you understand any limits placed upon its use.
Return Policy Wrox Chapters on Demand are non-returnable and non-refundable.
Reader Software Wrox Chapters on Demand are offered as PDFs, and they must be viewed using the Adobe Reader. If you do not have the Reader installed, it can be downloaded for free at Adobe.com.
Test Download As Wrox Chapters on Demand purchases are non-returnable, it is advisable that you test your system and software configurations with a free sample download before you place an order.
Usage Rights for a Wrox Chapter on Demand File Any Wrox Chapter on Demand product you purchase from this site will come with certain restrictions that allow Wiley to protect the copyrights of its products. After you purchase and download this title, you:
If you have any questions about these restrictions, you may contact Customer Care at (877) 762-2974 (8 a.m. - 5 p.m. EST, Monday - Friday). If you have any issues related to Technical Support, please contact us at 800-762-2974 (United States only) or 317-572-3994 (International) 8 a.m. - 8 p.m. EST, Monday - Friday).
Related Books
Visual Basic Resources