Text Reader Classes

As you might expect, there's also a TextReader class that has the subclasses StreamReader and StringReader. This class has fewer methods than TextWriter, although it works in the same way. The methods are summarized in Table 6.9. Closes the TextReader and releases any resources associated with it Looks at the next character without removing it from the input stream Reads characters into a character array Reads characters into a character array and blocks until the right number has been read or...

Implementing Fields and Methods That Belong to the Class

In .NET, you can define members that belong to a class as a whole rather than to any one object. As an example, consider a bank account class. Each Account object has a balance that is unique to the object the Account class may also have an interest rate member, which sets the interest rate for Accounts. This value belongs to every Account rather than to any one Account object, so it makes sense that the interest rate variable belongs to the Account class itself. Members that work like this are...

Opatas

Objwti hofds ruHefwcto objccts A g i 8- QtojcctZ is created as sIiaIIchy copy of Objcctl ijsinq MemberwiicCliiiwii i hii mrans lhal Iho rdcnencre arn DDjiicid. a-nd ia Oh rcli rtfws Ed I he me uiiccli as CHjicctl Note that the MemberwiseClone() method is protected it can only be called from within the derived class. This means that you cannot use the following code Dim obj As New SomeObject() obj.MemberwiseClone() Why not It may not be appropriate for your objects to be copied in this way, but...

Examining an XML Schema

Pull out your scalpels, because it's time to dissect another message. This time you are going to look at an XSD schema file, which closely resembles the XML files you have already looked at. Despite the resemblance, you will not see any actual data surrounded by tags within the schema document. Take a look at the following example < xsd schema id NewDataSet targetNamespace xmlns xmlns xsd _ http www.w3.org 2 0 01 XMLSchema xmlns msdata _ < xsd element name NewDataSet msdata IsDataSet...

The System ServiceProcess Namespace

All service executables tend to be based on the same skeleton code, and writing a service in traditional C++ or C using the Windows API involves a lot of copying and pasting of boilerplate code. The .NET Framework simplifies this greatly by providing the classes in the System.ServiceProcess namespace, which gives you an object-oriented (OO) skeleton that you can use to create and manipulate services. The namespace contains four major classes ServiceBase Used for creating custom services...

Basic Types

The System namespace contains definitions of the basic value types that are supported by a wide variety of .NET languages as shown in Table 3.1. Table 3.1 The .NET basic data types. The System namespace contains definitions of the basic value types that are supported by a wide variety of .NET languages as shown in Table 3.1. Table 3.1 The .NET basic data types. Represents an 8-bit unsigned integer Represents a 16-bit Unicode character Represents a decimal value with 28 significant digits...

Using the Data Grid Web Control

Visual Studio .NET comes with a Web control version of the DataGrid control, which you may be familiar with from Windows Form development projects. This control has the ability to display tables of data to the user and provide view-management features such as the ability to sort columns. This control represents an amazing breakthrough in Web development because before there were server-side Web controls, developers had to create pages and pages of server-side code to draw out database tables...

How Do I Produce Formatted Output

Formatted output is produced by using a version of Console.WriteLine() that takes a string containing a format plus zero or more objects that are going to be inserted into the output string System.WriteLine(format, object1, ) Formats contain static text plus markers that show where items from the argument list are to be substituted and how they are to be formatted. In its simplest form, a marker is a number in curly brackets the number showing which argument is to be substituted Hello world '...

Working with Attributes

You can modify the part of readXml() that handles elements to read attributes like this While xr.Read() ' If it is an element, print its name If xr.NodeType XmlNodeType.Element Then istr indent(level) Console.WriteLine(istr + < + xr.Name + > ) level level + i Console.Write( + xr.Name + + xr.Value) End While ElseIf xr.NodeType XmlNodeType.EndElement Then level level - i istr indent(level) Console.WriteLine(istr + < + xr.Name + > ) End If End While The AttributeCount property tells you...

Working with Delayed Web Control Events

Although the Button's Click event always triggers an immediate postback to the Web server to process its associated code, other Web controls may have events that, by default, do not trigger a postback when they fire. These events will fire, but their associated server-side code will not be processed until another event explicitly causes a postback. By storing these events and delaying their processing, you can avoid unnecessary calls back to the Web server, which could possibly slow down your...

Working with Controls and Web Form Layout Modes

The following example shows you how to set the Web Form's layout mode and add various control types to the form's surface. The example also examines a control's properties and appearance 1. Create a new ASP.NET Web Application project. The project starts with WebForm1 2. Click once on the surface of the Web Form, and then locate the pageLayout property in the Properties window. By default this is set to GridLayout, and you see tiny dots on the surface of the Web Form. 3. In the Toolbox window,...

Working with Child Nodes

Because the nodes in an XML document are arranged in a tree, you need to process child nodes in order to move from level to level. The following code shows how to read all the nodes in a DOM tree and print it out in XML format ' Import System.Xml and add a project reference to it Imports System.Xml Sub Main() Dim xd As New XmlDocument() Try ' Create a new XmlDocument object xd.Load( XmlFile1.xml) Catch e As XmlException Console.WriteLine(Exception caught + e.ToString) End Try ' Now we've parsed...

Inheritance and Polymorphism

You've already learned two important principles of OO. Encapsulation binds together data and functions into a single construct, whereas data hiding restricts access to the variables that make up the state of your objects. Let's now look at inheritance and polymorphism, two other very important features that are supported by every true OO language. In the real world, objects are classified as belonging to several different types at once. For example, a sports car is a car and also a vehicle, so...

How Do I Store Values by

If you have data that can be identified by a key, such as a list of names and phone numbers, you can use a Hashtable or SortedList to store them. A Hashtable will be more efficient if you only want to search for and retrieve values by key. A SortedList maintains the data items in sorted key order and lets you retrieve them by key or index. SortedList s are not as efficient as Hashtables because of the need to maintain the sort order of the list when adding items, but they basically work the...

Text Boxes

TextBoxBase is the base class that provides common functionality for all text controls. The Windows.Form namespace comes with two text controls, TextBox and RichTextBox, which I'll discuss later in this section. TextBoxBase has a number of commonly used properties, which are listed in Table 10.8. Many of these properties are self-descriptive, so I'll just make special mention of a few. The BorderStyle is the same as that of many other controls and has as its value one of the members of the...

List View and Tree View

Everyone is familiar with the Windows Explorer application, which uses a tree control in the left pane and a list control in the right pane. The .NET ListView and TreeView controls wrap the Windows tree and list controls. Because they're often used together in applications in this way, I'll discuss both in this section. A TreeView is a control that displays a hierarchy of items in the form of a tree. The programmer has to load the control with data items representing the nodes, and the control...

Exceptions

The mechanics of exceptions and the way you use them was discussed in the Exceptions section in Chapter 2. You might want to refer to that section before reading on. System.Exception is the base class for all exceptions. An object cannot be thrown or caught unless it inherits from Exception. The following listing shows all the exception classes that were documented in beta 2 you can see that there is a hierarchy of exception classes ApplicationException SystemException FieldAccessException...

Xml Convert

Because schemas were designed to be universally understood, the data types you will find inside an XML schema file do not directly match up with your .NET data types. Where .NET uses an Integer data type, the XML schema uses an int data type. A String in .NET is also a string in XML, but that is about as close as these two get to agreeing on a data name. In order to deal with their differences, .NET provides a class named XmlConvert to help you convert between the common language runtime (CLR)...

Setting Up a Lifetime Lease

Both server controlled singleton and client controlled CAO objects can have lifetime leases defined for them. These leases decide how long the object will live before its instance is destroyed, requiring the creation of new instances to handle additional object calls. Lifetime leases do not apply to the server-controlled single call object because the object's instance is destroyed at the end of every call, never to be reused again. In contrast to the single call object, a single instance of...

Using a Principal Object

You can also check user identity by using the WindowsIdentity and WindowsPrincipal classes. The following two lines of code show you how to see who the current user is Dim prin As WindowsIdentity WindowsIdentity.GetCurrent() Console.WriteLine(Current user is 0 , prin.Name) The WindowsIdentity class represents a Windows user. The GetCurrent() shared method returns a WindowsIdentity object initialized with the details of the current user. Some other methods and properties of this class are listed...

Introduction to ADONET

Throughout the years, there have been many database access methods made available to the developer community. Most of these technologies have been more closely related to the database they access than to the development tools they can be used in. Open DataBase Connectivity (ODBC), for example, was developed by database vendors to provide access to multiple database types. The major drawbacks of using ODBC are that the API is complex and difficult to work with, and its interfaces are not...

Creating and Using Events

Events are used to provide a standard asynchronous notification mechanism between objects. An event source class can publish details of one or more events that it will fire at appropriate times. Client objects can create callback methods, and then register them with the event object, which will then call them back when the source fires the event. Events are very frequently used in GUI programs to implement communication between the components of the user interface, but in .NET they have much...

Month Calendar

Still on the topic of dates and times, the MonthCalendar class encapsulates the Windows Calendar control. Figure 10.12 shows that this is the same as the drop-down calendar used by the DateTimePicker class. Figure 10.12 A MonthCalendar displayed on a form. Figure 10.12 A MonthCalendar displayed on a form. The MonthCalendar has a number of useful properties, as summarized in Table 10.17. Methods are available to set many of these properties, such as the bolded dates. The MonthCalendar has a...

Classes and Objects in Code

Let's start looking at some common OO concepts and see how they are expressed in code. As mentioned earlier, an object is something that possesses behavior and state. In OO programming languages, the behavior is represented by functions (also known as methods) and the state by variables (also known as fields). A class is the definition of an object type, such as Account or Car, and it lists all the variables and functions that make up an object. The following code shows how you would define a...

Navigating over Attributes

Attributes are held as nodes in the tree in the same way as elements, processing instructions and the other parts of an XML document. Once you are positioned on an element, the HasAttributes property tells you whether there are any attributes. You can then use MoveToFirstAttribute() to position yourself at the first attribute, or MoveToAttribute() to move to a particular attribute by name. The following code shows how I iterate over the immediate children of < dotnet_books> and print out...

Control Styles

The style of a Control can be acquired and set using the GetStyle() and SetStyle() methods, which both use the Windows.Forms.ControlStyles enumeration, as shown in Table 10.3. The style of a Control can be acquired and set using the GetStyle() and SetStyle() methods, which both use the Windows.Forms.ControlStyles enumeration, as shown in Table 10.3. WM_ERASEBKGND is ignored, and both OnPaintBackground and OnPaint are called directly from WM_PAINT. This can reduce flicker. Controls cache a copy...

Using String Builder

As its name implies, the System.Text.StringBuilder class provides you with a way to interactively build and modify strings. This happens on a single copy of the data in situ, in contrast to the methods provided by the System.String class, which always create new String objects whenever any modification is required. The following sample program shows you how to create and use StringBuilder objects Module Modulel Sub Main() ' Create an empty StringBuilder Dim sb As New StringBuilder()...

The Tcp Channel

Similar to DCOM's proprietary transmission method, Remoting's Tcp channel sends the data back and forth between the client and server objects using a proprietary binary format. The objects on both ends of a Tcp channel must be able to understand this binary formatted message, which means you should only plan to use the Tcp channel to communicate from one .NET object to another. The Tcp channel is a two-way street, which means your objects can send and receive data through this channel....

Buttons

Everyone is familiar with buttons in graphical user interface (GUI ) applications controls whose only purpose in life is to be clicked. Some may toggle between the on and off positions, such as checkboxes and radio buttons, whereas normal buttons have a momentary press-and-release action. .NET contains support for these three types of button, all of which inherit from the abstract class ButtonBase. ButtonBase has several useful properties that are shared by all button classes, as shown in Table...

Working with the Win32 API

It may sometimes be necessary to call a function that exists in a DLL outside of .NET. This may be a Win32 API function that doesn't have a .NET equivalent, or it may be a third-party DLL that hasn't been or maybe can't be updated to use .NET. Whatever the reason, the .NET Framework provides the P Invoke mechanism to let you call functions in DLLs from within .NET code. When P Invoke calls an unmanaged function in a DLL, it performs the following steps 1. It locates the DLL containing the...

Calling a Remoting Server

From the client object's perspective, there are two ways of calling a server object using remote server-side activation and using client-side activation. There is no difference between singleton and single call server objects from the client object's point of view. In the next two sections, I discuss the two ways that client objects can call on remote server objects and explain how this can work using both external client object configuration files and programmatic configuration commands. If...

The SOAP Envelope

If you printed out all of the data in your database and wanted to send it to another company for its review, you couldn't just place that printout into the mailbox and expect it to reach its destination. The mail service prefers that you place items inside an envelope that includes a to and from address along with proper postage. XML messages by themselves are not capable of journeying into the world without first being placed within an envelope. The SOAP protocol provides this encapsulating...

The Thread Function

The class that holds the application code contains a single function, ThreadFunc, which draws a single line on the panel. The line starts at a random point and draws in a random color at 45 degrees, reflecting when it meets a boundary. Figure 12.9 shows what this looks like in action, with only one drawing thread running. Figure 12.9 One thread drawing a line in the threading solution. Figure 12.9 One thread drawing a line in the threading solution. Add a new member function to the class, and...

Code Access Permission

Code access permission is used to protect resources and operations from unauthorized access, such as accessing a file or accessing unmanaged code. Code access permissions form a fundamental part of the CLR's security mechanism. Programs use these classes to declare which permissions they want, and the CLR uses its security policy to decide which if any of them to grant. All the code access permission classes derive from System.Security.CodeAccessPermission and are listed in Table 7.1. All the...

Creating a Client Activated Object and Determining Its Lifetime

CAO objects give the power of activation and lifetime lease control to the client. The server object must explicitly declare that it is allowing CAO activation before a client can use this power. This is a defensive measure on the server object's part because if client objects are allowed to control the server object's lifetime, it is possible that server object lifetimes can be set to some fairly high numbers, thereby keeping those server objects in memory for far longer than they might be...

Setting Up a Print Document

All printing is done through PrintDocument objects, so the first task you need to undertake is to create a PrintDocument and connect it to a printer ' Set its properties, especially the printer name pd.PrinterSettings.PrinterName LaserJet Once you have created the PrintDocument, you can set its properties. There are four properties that you might want to use DefaultPageSettings Gives you access to the page settings DocumentName Represents the name of this document and may be used in printer...

Drawing Implements Pens and Brushes

The Pen and Brush classes encapsulate the line thickness, line styles, fill patterns, and colors that you use for drawing on the screen. Pens are used for drawing the outlines of shapes, lines, and curves, and brushes are used for filling areas. Pens have two basic properties a width and a fill color or pattern. The pattern is provided by one of the Brush classes, so that you can arrange to draw lines with a texture or gradient fill if desired. Table 11.12 lists the most important properties of...

Printing Multipage Documents

If you are printing a form and everything fits on one sheet of paper, the task is simple. You only need one call to the page print handler, and you simply draw everything to the PagePrintEventArgs.Graphics object as you would to the screen. If your output does not fit on one sheet of paper, you'll have to calculate what is to be printed in each call to the handler. Just how you do this depends on the form of your document. The following complete example shows how to print the contents of a text...

How Web Forms Work

Web Forms live in the same realm as the HTML page. When you create an ASP.NET Web Form, you make it available for use by placing it within the directory structure of an IIS Web server. It's important to note that only an ASP.NET-aware Web server, such as IIS 5 running on Windows 2000, is capable of processing and serving ASP.NET applications. This is because, unlike HTML Web pages, an ASP.NET Web Form must be processed before the results can be sent to the requesting browser. You can think of...

Calling XML Web Services

You can call upon XML Web services from within your Windows application, Web application, and class Library projects. Formulating SOAP requests, communicating with remote Web servers using HTTP, and unpackaging the SOAP formatted results might sound like a daunting task, but if you are using Visual Studio .NET to create your projects, it's as simple as can be. All you need to do is to add a reference for a particular remote XML Web service to your project, and then use it like you would any...

Writing an XML Document Using Xml TextWriter

The XmlTextWriter class provides you with a toolkit for writing XML in its serialized form, complete with angle brackets, processing instructions, and all the other elements you see in XML documents. This class lets you concentrate on the logical structure of your XML, and frees you from having to worry about the formatting. Here's a simple program showing how XmlTextWriter can be used to construct a simple XML document ' Import the namespace so we can use all the XML stuff. Imports System.Xml...

Text Writer Classes

TextWriter is an abstract base class that has a number of subclasses HtmlTextWriter for writing HTML to browser clients HttpWriter for writing text to the HTTP response object in ASP.NET pages IndentedTextWriter for writing text with indentation control StreamWriter for writing characters to a stream StringWriter for writing characters to a string For C programmers, StreamWriter is analogous to printf or fprintf , and StringWriter is analogous to sprintf . TextWriter has three properties...

Creating a Print Handler

The actual printing process is carried out on behalf of the PrintDocument by a PrintController object. If you don't create another PrintController yourself, the PrintDocument will work with a StandardPrintController that is suitable for default output to most printers. If you want to manually specify print preview, you can create a PreviewPrintController object that handles printing to print preview windows. PrintController classes have four methods StartPrint Called at the start of the job...

Finding and Choosing a Printer

The InstalledPrinters property of the PrinterSettings class returns a list of strings containing the names of all installed printers. The following code fragment shows how to use this property to print out a list of all the printers installed on the system Sub Main ' Create a PrinterSettings object Dim ps As New PrinterSettings ' Get the list of installed printers Dim en As IEnumerator ps.InstalledPrinters.GetEnumerator ' Print out all the printer names While en.MoveNext True Console.WriteLine...

Setting Security Policies

In .NET Beta 2 there is no GUI tool, and all policy manipulation is done using the caspol.exe command-line tool. Caspol can be used to edit enterprise-, machine-, and user-level policies using the appropriate switches. The tool is simply run from a command window by giving the command name followed by one or more options A large number of flags can be used with caspol, and Table 7.4 lists some of the most commonly used options. Note that most of the options have one- or two-letter...

Creating the Data Sef s Schema

Although there are many ways to create a DataSet schema, there are two smart ways I want to show you to help you get the job done quickly. The first method involves using an already loaded DataSet. If you have a DataSet loaded with the proper data elements and relationships, all you need to do to create a schema to lock-in this DataSet's format is to use the WriteXmlSchema method like this Dim XMLOut As IO.FileStream New IO.FileMode.OpenOrCreate, IO.FileAccess.Write dsCompany.WriteXmlSchema...

Using the Http Channel to Call Remote Objects

So far in my examples I have used the Tcp channel to create a client and a server object. You can opt to use the Http channel in place of the Tcp channel. Although not as efficient as Tcp, the Http channel uses SOAP to wrap its Remoting messages, which makes your messages universally understandable. Http can also pass through common Internet ports, such as port 80, which allows this protocol to pass through most firewalls unabated. As mentioned earlier, there are two ways to configure your...

Creating a Web Form

Although Web Forms can be created using any of the Visual Studio .NET development languages, you can only add Web Forms to two of the .NET project types the ASP.NET Web Application and the ASP.NET XML Web Service. This restriction to Web Form usage is due to the fact that a Web server is required to process these pages, and non-Web project types do not interface with the Web server. You will not be able to add Web Forms to projects such as the class Library and Windows application projects. The...

Handling a Change oi Drive

Because the user is going to use the ComboBox to select a drive letter, you need to handle this selection process. The ComboBox raises a SelectedIndexChanged event when someone chooses an item, so you need to add a handler for this event to the Form class. In the Visual Studio Designer, you can do this by double-clicking on the ComboBox object Protected Sub ComboBox1_SelectedIndexChanged ByVal sender _ As System.Object, ByVal e As System.EventArgs _ Handles ComboBox1.SelectedIndexChanged If...

Heres C

Where has C come from You can trace its origins back to two facts. It's no secret that Visual J met a rather untimely end, killed off by the bumpy relationship between Microsoft and Sun. Microsoft recognized that Visual J had two unique qualities The first of which was that Java was a simpler language for OO programmers to use than C , and the second was that it was very easy to write COM components in Visual J . C can be a very hard language to use well, so much so that it is overkill for a...