Showing posts with label Implementing Accessibility. Show all posts
Showing posts with label Implementing Accessibility. Show all posts

VISUAL STUDIO DOT NET

Microsoft developed Visual Studio .NET (VS.NET) to facilitate the creation of Windows and web applications. You will find that this Integrated Development Environment (IDE) is a very powerful tool that will greatly simplify your work.

Visual Studio .NET offers many advantages to the .NET developer. The following features are discussed in this chapter:

  • A modern interface using a tabbed document metaphor for source code and layout screens, and toolbars and informational windows that dock where you want them

  • Code completion, which allows you to enter code with fewer errors and much less typing

  • IntelliSense, which pops up help on every method and function call as you type

  • Dynamic, context-sensitive help, which allows you to view topics and samples relevant to the code you are writing at the moment

  • Immediate flagging of syntax errors (e.g., missing characters, misplaced braces, etc.), which allows you to fix problems as they are entered

  • The ability to compile and test programs right in the IDE

  • A built-in task list to keep track of changes you need to make

  • A Start Page that provides easy access to new and existing projects

  • Customization capability, which allows you to set user preferences for IDE appearance and behavior

One VS.NET feature will be so important to you, even as a C# novice, that it actually merits its own chapter: an integrated debugger, which allows you to step through code, observe program run-time behavior, and set breakpoints, even across multiple languages.

In addition to these basic capabilities, VS.NET provides a number of advanced features that will simplify the development process. These features include:

  • Convenient access to multiple design and code windows

  • WYSIWYG (What You See Is What You Get) visual design of Windows forms and web forms

  • An HTML editor which provides both Design and HTML views that update each other in real time

  • A Solution Explorer, which displays all the files comprising your solution (a collection of projects) in a hierarchical format

  • A Server Explorer, which allows you to log on to servers to which you have network access, access the data and services on those servers, and perform a variety of other chores

  • Integrated support for source control software


Projects and Solutions :

A C# program is built from source files, which are text files containing the code you write. Source code files are named with the .cs extension.

A typical Visual Studio .NET application can have a number of other files (e.g., assembly information files, references, icons, data connections, etc.). VS.NET organizes these files into a container called a project.

Visual Studio .NET provides two types of containers for your source code, folders, files, and related material: the project and the solution. A project is a set of files that work together to create an executable program (.exe) or a dynamic link library (.dll). Large, complex projects may consist of multiple .dll files called modules.

A solution is a set of one or more related projects. Each time you create a new project, Visual Studio .NET either adds it to an existing solution or creates a new solution.

Solutions are defined within a file named for the solution and have the extension .sln.

There are a number of ways to open an existing solution. The simplest way is to select Open Project from the Start menu (which opens a project and its enclosing solution). Alternatively, you can open a solution in Visual Studio .NET just by double-clicking the .sln file in Windows Explorer.

Typically, the build process results in the contents of a project being compiled into an executable (.exe) file or a dynamic link library (.dll) file.

related links:

VISUAL STUDIO INTRODUCTION

C SHARP INTRODUCTION

C SHARP OUT LOOK

DOT NET AND C SHARP

C SHARP APPLICATION STRICTURE

OOPS INTRODUCTION

OOPS AND C SHARP

IDE AND C SHARP

INSTANTIATING OBJECTS IN C SHARP

CLASSES AND OBJECTS IN C SHARP

OPERATORS IN C SHARP

SWITCH AND ITERATION IN C SHARP

BRANCHING IN C SHARP

CONSTANTS AND STRING

STATIC AND INSTANCE MEMBERS IN DOT NET

Implementing Accessibility

People with accessibility requirements are a significant part of the workforce. In order to meet the needs of today's business application programming, applications must be accessible to people with all kinds of different needs.

Accessibility is facilitated in a variety of ways. Microsoft Windows XP provides a variety of accessibility aids that can interact with your applications.

For example, SoundSentry allows the user to specify a visual cue whenever the system emits a sound. These accessibility aids are designed to integrate seamlessly with your applications to provide an accessible user experience. Additionally, there are accessibility principles you can design into your application.

Accessibility Design

An application begins to be accessible in the design phase. By planning ahead, you can create an application that integrates the principles of accessible design into the user interface. Some of these principles are
  1. Flexibility
  2. Choice of input methods
  3. Choice of output methods
  4. Consistency
  5. Compatibility with accessibility aids
Flexibility is a key principle in accessibility design. Users should be able to customize the user interface to their specific needs. They should also be able to choose from a variety of input methods, such as pointing devices or keyboards. The application should provide keyboard access to the important features of the application and mouse click access for common tasks.

Likewise, users should have a choice of output methods and be able to choose between sound, visual cues, graphics, and text. Your application should interact in a consistent manner with other applications and within its own operation. In addition, your application should be compatible with accessibility aids.

Accessibility and the Certified for Windows Program

In order to provide a standard set of guidelines for designing accessible applications, Microsoft has incorporated five requirements for applications to be certified in the Certified for Windows program. This section discusses the requirements for the Certified for Windows program and how to implement them.

Support Standard System Settings

The first requirement states that applications must support standard system settings for size, color, font, and input. This ensures that all of a user's applications have a consistent user interface that will inherit the look and feel provided by the system settings. Thus, users with accessibility needs can configure their systems once, and all of their applications will automatically adopt a consistent appearance.

You can implement this requirement in your applications by using System objects exposed through the .NET Framework. The .NET Framework provides a palette of system colors that can be used to set the colors of your application. When the system settings change, the colors of your application's user interface will change. Similarly, you can leave the font determination up to the system by not explicitly setting the Font property for your controls.

If the Font property is not changed from its default value, it will conform to the system font settings. The exception to this is the Font.Size property, which can be changed while maintaining accessibility requirements. Your application should be designed so that it can easily be used on a screen with 640 x 480 resolution and should not require any special methods of input beyond the keyboard and pointing devices.

These properties provide information to accessibility aids about the role of the control in the application. Accessibility aids can then present this information to the user or use this information to make decisions on how to display the control.

The AccessibilityObject property contains the AccessibleObject class instance that provides information to accessibility aids. The AccessibleName, AccessibleDescription, and AccessibleDefaultActionDescription properties contain information that accessibility aids can use to describe your user interface. The AccessibleRole property contains an enum value that determines how an accessibility aid treats your control.

This property is normally set to (Default), which indicates that each control is acting in its usual manner. It is important to set this property, however, when a control is acting in a manner more consistent with another type of control, or for custom controls. For example, if you have a custom control that displays data in a chart form, you would set the AccessibleRole property value to Chart.

Ensure Compatibility Using the High Constrast Option

Users requiring a high degree of legibility will select the High Contrast option. This option sets the Windows color scheme to a scheme that provides maximum contrast between light and dark portions of the user interface.

You can ensure that your application conforms to the High Contrast option requirement by only using system colors or colors chosen by the user. Thus, when the High Contrast option is chosen, your application will conform. You should also avoid using background images for your forms because they decrease contrast and legibility.

Provide Documented Keyboard Access to All Features

Your application should implement keyboard access for all features, and this access should be documented and discoverable. The use of shortcut keys to access controls and menu items, as well as setting the Tab order, allows you to implement keyboard access for your user interface features. The importance of documentation for these features cannot be overlooked. A user must have some means of discovering keyboard access for features and this should be provided through careful, complete, and well-organized documentation.

Provide Notification of the Keyboard Focus Location

The location of the keyboard focus is used by accessibility aids such as Magnifier and Narrator. Thus, it is important that the user and the application always have a clear understanding of where the focus is. For the most part, this is facilitated by the .NET Framework. When designing your program flow, however, you should always incorporate code to set the focus to the first control on a form when the form is first displayed, and the Tab Order should be set to provide logical program flow.

Convey No Information by Sound Alone

Your applications should never rely on sound to convey important information. Although sound is an important cue for some users, other users might be unable to perceive an alert that is communicated by an audio cue. When using sound to convey information, you should combine the notification with visual cues, such as flashing the background color of the active window, displaying a messagebox notification, or using a nonmodal screen that displays information while the application continues to execute.

RELATED POST

DAY 11 OOPS INTRODUCTION

DAY 12 POLYMORPHISM

DAY 13 INHERITANCE AND POLYMORPHISM

DAY 14 EBUGGING TOOLS IN DOT NET

DAY 15 DEBUG AND TRACE IN CLASSES

DAY 16 UNIT TEST PLAN

DAY 17 EXCEPTIONS IN VISUAL STUDIO

DAY 19 ADO.NET INTRODUCTION

DAY 20 DATA ACCESSING IN DOT NET

DAY 21 DATA BASE OBJECTS


Accessing and Invoking Components

You can access any .NET or COM library on your system without much difficulty. These components might represent other development projects you have created, legacy COM components, or business logic that you need to incorporate into your application. The generalized scheme for accessing .NET or COM components is to create a reference to the type library, Import (use) the type library in your application, and then declare and instantiate the class you want to use.

You can obtain a list of available type libraries in the Add Reference dialog box. To display the Add Reference dialog box, right-click References in the Solution Explorer under your project, and choose Add Reference from the shortcut menu.

The Add Reference dialog box has three tabs. Choosing the .NET tab displays available .NET assemblies. Choosing the COM tab displays the available COM type libraries, and choosing the Projects tab displays available projects. If the item you want to add a reference to is not listed, you can browse to the file location by clicking the Browse button. Once you have located the reference you would like to add, you can select it with the Select button. The reference is added to your project in the Solution Explorer.

Once you have added a reference to an assembly or COM type library, you can use the types contained in that reference in your application by using the fully qualified name of the type. If you want to obviate the need to use the fully qualified name, you can use the Imports (Visual Basic .NET) or using (Visual C#) keyword to make members accessible. Chapter 1 describes how to use the Imports and using statements.

Once a reference has been established, you can declare and instantiate the types contained in the type library as you would any other type.

To access a .NET assembly or COM type library

In Solution Explorer, right-click the References node under your project, and choose Add Reference.

The Add Reference dialog box opens.

Select the reference you want to add. COM type libraries are listed under the COM tab, .NET assemblies are listed under the .NET tab, and projects can be found under the Projects tab.

Use the Imports (Visual Basic .NET) or using (Visual C#) keyword to import the reference into your application.

Declare and instantiate the types exposed by your reference as normal.

Instantiating ActiveX Controls

ActiveX is an implementation of COM. As such, you can add a reference to an ActiveX control type library in much the same way as you would add a reference to a COM library. You can then add the ActiveX control to the Toolbox and add it to your applications at design time.

To instantiate an ActiveX control

Add the ActiveX control to the Toolbox by customizing the Toolbox.

Drag an instance of the control from the Toolbox to the designer to add it to your project at design time. Alternatively, you can declare and instantiate the control in code and add it to your application dynamically at run time.

Accessing a Web Service

An integral feature of the .NET Framework is the Web Service. A Web Service is a type of class that is hosted on the Internet. You can declare an instance of the Web Service in your application, and then call its methods either synchronously or asynchronously.

You can create a reference to a Web Service in the Solution Explorer. You can display the Add Web Reference window by right-clicking References under your project and choosing Add Web Reference. This displays a screen that allows you to navigate to the URL of a Web reference or to search online if you do not know the URL.

If you do not know the address of the Web Service you would like to use, the window displays directories in which to search. The Universal Description Discovery Integration (UDDI) directory allows you to search the Web for companies that provide Web Services. When a company is selected, the Web Services it offers will be displayed. Choosing a Web Service will display the XML contract in the left page of the window and the name of the Web Service in the right window.

You can also view a more reader friendly description of the Web Service by removing "?WSDL" from the address displayed in the status bar and reloading the page

Synchronous method calls are made just like regular methods calls. However, because they are accessing resources on the Internet, response time can vary, and application execution will pause until a synchronous call to a Web method is completed.

If you do not want to pause program execution while you wait for a Web Service call to complete, you can make an asynchronous method call. An asynchronous call starts the call to the Web Service on a separate thread, allowing program execution to continue while the Web Service is processing the request. For every method found on a Web Service, there are two additional methods for use asynchronously.

The names of these methods are the name of the Web method prepended with Begin and End. Thus, if a Web Service exposed a method called MyMethod, the asynchronous methods for MyMethod would be BeginMyMethod and EndMyMethod.

You begin an asynchronous method call with the Begin method. In addition to requiring the same parameters as a synchronous method call, a Begin method call requires an AsyncCallback delegate that specifies the method for the Web method to call back on and an Object that allows applications to specify custom state information.

Every Begin method has a return type of IAsyncResult. This interface is used by the corresponding End method to retrieve the data returned by the asynchronous call. The callback method specified by the AsyncCallback delegate must have a signature that takes an IAsyncResult as a parameter.

In the callback method, you can call the End method to retrieve the data. The following example demonstrates how to make an asynchronous call to a method called MyMethod.

To create a reference to a Web Service

In Solution Explorer, right-click References and choose Add Web Reference.

Locate the reference on the Web using either UDDI search or by typing in the address of the Web Service. Click the Add Reference button to add the reference to your project.

After the reference is added, you can instantiate the Web Service just as you would any other class.

To call a method on a Web Service synchronously

Instantiate the Web Service.

Call the method as you would call a method of any other class.

To call a method on a Web Service asynchronously

Create a callback method that takes an IAsyncResult as a parameter.

Call the Begin method of the Web method to invoke the asynchronous call. Supply a delegate to the callback method as a parameter to this method.

Either in the callback method or in another method, call the End method of the Web method to retrieve the data, specifying the IAsyncResult returned by the Begin method as the parameter.

Accessing the Windows API

Accessing native functions of the operating system has become less important with the introduction of the .NET Framework. Most of the important functions exposed by the Windows API are wrapped in .NET classes, which allow you to access their functionality in a type-safe, robust manner.

Nevertheless, you might occasionally want to make a call to an unmanaged function. You can use the Declare keyword in Visual Basic .NET or the DllImportAttribute attribute in Visual C# to import a native function. Once you have imported the function, you can use it like any other function in your application.

To declare an external function in Visual Basic .NET

Use the Declare keyword to specify an external function. The Lib keyword indicates the DLL in which the function is found, and the name and signature must match the name and signature of the external function exactly.

To declare an external function in Visual C#

Use the DllImportAttribute attribute found in the System.Runtime.InteropServices namespace to specify the DLL that contains your function. You must mark your function with both the static and the extern keywords, and the name and signature must match the name and signature of the external function exactly.

related post

DAY 11 OOPS INTRODUCTION

DAY 12 POLYMORPHISM

DAY 13 INHERITANCE AND POLYMORPHISM

DAY 14 EBUGGING TOOLS IN DOT NET

DAY 15 DEBUG AND TRACE IN CLASSES

DAY 16 UNIT TEST PLAN

DAY 17 EXCEPTIONS IN VISUAL STUDIO

DAY 19 ADO.NET INTRODUCTION

DAY 20 DATA ACCESSING IN DOT NET

DAY 21 DATA BASE OBJECTS


Accessing Data in visual studio dot net

Visual Studio .NET provides many built-in wizards and designers to help you build your data access architecture rapidly and efficiently at design time. With a minimum of actual coding, you can implement robust data access for your application. The ADO.NET object model is fully available through code, however, to implement customized features or to fine tune your program.

Connecting to a Database

You can implement a connection to a database in your application in many different ways. The easiest way is to use the graphical tools provided by Visual Studio .NET to create a connection at design time.

Current data connections are managed in the Server Explorer window. This window is normally docked to the left pane of the Integrated Development Environment (IDE) and shares the same space as the Toolbox. If the Toolbox is currently visible, you can view the Server Explorer by clicking the Server Explorer tab located at the bottom of the Toolbox.

Data connections that are currently available to Visual Studio .NET are displayed as child nodes of the Data Connections node in Server Explorer. If you want to add a connection that is already listed under the Data Connections node to your project, all you need to do is drag the connection from the Server Explorer window to the designer.

A new Connection object of the appropriate type (Sql or OleDb) is created and automatically configured to connect to your database.

To add a connection from the Server Explorer

Drag the node that represents a database from the Server Explorer window to the designer.

You can also create a new connection in the Server Explorer. You can create a new connection by right-clicking the Data Connections node and choosing Add Connection. This launches the Data Link Properties dialog box.

The Data Link Properties dialog box is a visual way to configure your data connection. The Providers tab allows you to choose the database provider that you will use in your connection. The Connection tab allows you to configure the specific properties of your connections, and the Advanced tab configures properties not normally needed for every connection.

The All tab allows you to view and edit the current settings of all the properties. Once you have configured your new connection, you can click OK to close the Data Link Properties window. The new connection appears in the Server Explorer window and can be dragged to your designer.

To create a new connection in the Server Explorer

In the Server Explorer, right-click Data Connections and choose Add Connection to open the Data Link Properties window.

On the Provider tab, choose the appropriate provider for your data connection.
On the Connection tab, choose the database you want to connect to. Depending on the provider, you might also have to set additional properties such as the server name or password settings.

When you have entered the appropriate information, click the Test Connection button to verify that the connection is functional.

Drag the new connection from the Server Explorer to the designer surface. A new connection object of the appropriate type is created and correctly configured.
You can also create a database connection manually, either by dragging a Connection object from the Toolbox to the designer or by declaring and instantiating the object in your code.

If you create a connection this way, you will have to manually set the ConnectionString property.

  1. To create a new connection in code
  2. Declare and instantiate the appropriate type of Connection object.
  3. Set the ConnectionString property.
  4. To create a new connection in the designer
  5. Drag the appropriate type of Connection object from the Data tab of the Toolbox to the designer.
  6. In the Properties window, set the ConnectionString property.
  7. Using Data Commands
A Command object contains a reference to a database stored procedure or SQL statement and can execute that statement across an active data connection. A Command object contains all of the information that it requires to execute the command including a reference to the active connection, the specification for the command itself, and any parameters required by the command.

As with other classes represented in Data Providers, there are two types of Command classes. The OleDbCommand class is designed to interact with a wide variety of database types. The SqlCommand class is designed to interact specifically with Microsoft SQL Server 7.0.

Because they only require an active connection and do not need to interact with a DataAdapter, Command objects provide a very fast and efficient way to interact with a database. Command objects can be used to perform the following actions:

Execute commands that do not return values, such as INSERT, UPDATE, and DELETE.
Execute commands that return a single value.

Execute Database Definition Language (DDL) commands, such as CREATE TABLE, or ALTER.
Work with a DataAdapter to return a DataSet.

Return a result set directly through an instance of a DataReader object. This provides the fastest way to access data and is very useful when read-only data is required.

Return a result set as an XML stream. This method is only available with the SqlCommand class.

Return a result set from multiple tables or command statements.

Creating and Configuring a Data Command

You can create a data command in three ways:

By dragging a stored procedure from the Server Explorer window to the designer.
By dragging a SqlCommand or OleDbCommand from the Data tab of the Toolbox to the designer and configuring it in the designer.

By declaring and instantiating the appropriate type of Command object in code and configuring it manually.

The first way to create a data command is the most straightforward. Any stored procedure on a database can automatically be used to create a Command object. When a stored procedure is dragged onto the designer, a Command object of the appropriate type is created. The new command references the stored procedure and can immediately be used to execute the stored procedure as is—no additional configuration is necessary.

To create a Command object that references an existing stored procedure
Drag the stored procedure from the Server Explorer to the designer. An appropriately configured instance of a Command object is created.

Creating a Command object in the designer is almost as easy. You can create a Command object by dragging a SqlCommand or an OleDbCommand from the Data tab of the Toolbox to the designer. This creates an instance of the Command object you have selected. Once created, you must configure your Command object by setting the Connection, CommandType, and CommandText properties.

The CommandType property determines what kind of command is contained by the CommandText property. There are three possible values for the CommandType property:

Text.

A value of Text for this property indicates that the value contained in the CommandText property will be parsed as a SQL text command. In this case, the CommandText property must be set to a valid SQL expression. A Command object can contain multiple SQL statements separated by semicolons (;). If a Command object contains more than one SQL statement, the statements will be executed sequentially when the command is executed.

StoredProcedure.

If the CommandType property is set to StoredProcedure, the value contained in the CommandText property must contain the name of an existing stored procedure on the database. Executing this command will cause the stored procedure of the same name to be executed.

TableDirect.

A CommandType of TableDirect indicates that the name of a table or tables must be indicated by the CommandText property. Executing this command will return all of the columns and all of the rows of the table or tables named in the CommandText property.
The Connection property must be set to an active connection of the appropriate type (that is, a SqlCommand must have a SqlConnection as its connection, and an OleDbCommand must have an OleDbConnection).

Executing Commands

Each type of Command object has three methods to execute the command it represents:

ExecuteNonQuery

ExecuteScalar

ExecuteReader

The SqlCommand class exposes an additional method for executing the command it represents: ExecuteXmlReader.


Each of these methods executes the data command represented by the Command object. The difference between these methods lies in the value(s) they return. The simplest method is ExecuteNonQuery.

This executes the data command, but returns no value. Thus, this is the method typically used to call SQL commands or stored procedures of the INSERT, UPDATE, or DELETE types. Additionally, this is the only way in ADO.NET to execute DDL commands such as CREATE or ALTER. The ExecuteScalar method returns the first column of the first row of data returned by the command, no matter how many rows the command actually selects.

ExecuteReader returns a DataReader object that can iterate through a result set in a forward-only, read-only manner without involving a DataAdapter. This is the fastest way to retrieve data and frequently the most efficient way when you do not need to update or otherwise manipulate the database itself. The SqlCommand class exposes one additional method: ExecuteXmlReader. This class returns an XmlReader object that iterates through the result set and provides data in a forward-only, read-only manner, formatted as XML.


Parameters

Data commands will frequently make use of parameters. Often, the values of some elements of a data command are not known until run time. Consider an application that tracks inventory for a bookstore. It might contain a function that looks up books based on title. You might implement this functionality by querying the database with a SQL statement similar to the following example:

SELECT * FROM Books WHERE (Title LIKE [value])

At design time, you know that you will want to find all the books that have a title similar to a value that will be supplied by the user at run time. Because you do not know what value the user will supply in advance, you must employ some mechanism for supplying that value to the statement at run time.

Parameters are values that fill placeholders left in the command text. Each parameter is an instance of the OleDbParameter or SqlParameter class, as appropriate. Parameters are stored in the Command object's Parameters property, and at run time, the values are read from the property and placed into the SQL statement or supplied to the stored procedure.

Command objects provide a Parameters collection that exposes a collection of Parameter objects of the appropriate type.

The Direction property specifies whether the parameter is for input or output. The possible values for this property are Input, Output, InputOutput, or ReturnValue, which indicates the parameter is to contain a return value from a stored procedure or function.

In code, you can refer to members of the Parameters collection either by their index or by name. The ParameterName property specifies the name that can be used as a key to specify the parameter in code.

The Precision, Scale, and Size properties all affect the size and accuracy of the parameters. Precision and Scale are used with numeric and decimal parameters, and represent the maximum number of digits of the Value property and the number of decimal places that Value resolves to, respectively. Size is used with binary and string parameters and represents the maximum size of data in the column.

SourceColumn and SourceVersion are used when the parameter is bound to a column in a DataTable. The SourceColumn property specifies the column used to look up or map values, and the SourceVersion property specifies which version of the column to use when it is being edited.

The Value property contains the value represented by the parameter.

When the CommandType property of the Command object is set to Text, you must specify a placeholder for any parameters that must be inserted into the SQL statement. With OleDbCommand objects, this placeholder takes the form of a question mark (?).

When multiple parameters are required by the command text, they are inserted in the order that they appear in the Parameters collection.

When using a SqlCommand object, you must use named parameters. Placeholders for a named parameter are created by preceding the name of your parameter (as specified by the ParameterName property) with an @ symbol.

To use a Command object to execute a non-query command

This procedure is used to execute INSERT, UPDATE, and DELETE commands as well as DDL commands such as CREATE TABLE and ALTER.

Set the CommandType property to StoredProcedure if specifying a stored procedure or Text if specifying a SQL string.

Set the CommandText property to the name of the stored procedure or the desired SQL string, as appropriate.

Specify any parameters and their appropriate values.

To use a Command object to return a single value

Set the CommandType property to StoredProcedure if specifying a stored procedure or Text if specifying a SQL string.

Set the CommandText property to the name of the stored procedure or the desired SQL string, as appropriate.

Specify any parameters and their appropriate values.
Call the Command.ExecuteScalar method.

Using DataReaders

Executing non-query or scalar-returning commands with a Command object is relatively straightforward. To use a Command object with queries that return more than one value, however, you must use the ExecuteReader method to return a DataReader.

A DataReader is a lightweight object that provides read-only, forward-only data in a very fast and efficient manner. You can use the DataReader to iterate through the records returned in a result set to expose the values directly to program logic. Using a DataReader is much more efficient than using a DataAdapter to fill a DataSet, but is also more limited. The data provided is read-only; no updates can be performed with a DataReader.

Also, the data access is forward-only; once a record has been read, it cannot be returned to. Additionally, a DataReader is a connected data access structure. A DataReader requires the exclusive use of an active connection for the entire time it is in existence.

Creating a DataReader

DataReaders cannot be created explicitly. Rather, you must instantiate a DataReader by making a call to a Command object's ExecuteReader command. Like other members of the different data providers, each DataProvider has its own class of DataReader. An OleDbCommand object returns an OleDbDataReader, and a SqlCommand object returns a SqlDataReader.

When a Command object's ExecuteReader method is called, the Command object executes the command it represents and builds a DataReader of the appropriate type, which can be assigned to a reference variable.

Simple Data Access with the DataReader

Once you have a reference to a DataReader, you can iterate through the records and read them into memory as needed. When the DataReader is first returned, it is positioned before the first record of the result set. To make the first record available, you must call the Read method. If a record is available, the Read method advances the DataReader to the next record and returns True (true). If a record is not available, the Read method returns False (false).

To access data with a DataReader

Call your Command object's ExecuteReader method and assign the returned DataReader to an appropriately typed variable.

Iterate through the result set within a While (while) loop. You should perform any operations with the data while inside this loop. You must call the DataReader object's Read method before using the data.

When finished, call the DataReader object's Close method to release the connection.

Retrieving Typed Data Using a DataReader

Although the data exposed by a DataReader is typed as objects, the DataReader also exposes methods to retrieve data contained in a result set. These methods are named Get followed by the name of the type to be retrieved. For example, the name of the method to retrieve a Boolean value is called GetBoolean. If you know the type of data in a given column, you can use these methods to return strongly typed data from that column.

Using Multiple Result Sets

If the CommandType property of your Command object is set to Text, you can return multiple result sets with a single command by providing multiple SQL commands in the CommandText property. To indicate multiple commands, separate each command with a semicolon (;). For example:

SELECT * FROM Accounts; SELECT * FROM Creditors

When multiple SQL statements are specified in the CommandText property of a Command object, the statements are executed sequentially. If more than one statement returns a result set, multiple result sets are returned by the DataReader, also sequentially.

The first result set is returned automatically by the DataReader. To access the next result set, you must call the NextResult method.

Like the Read method, the NextResult method returns False (false) when there are no more result sets to be read. Unlike the Read method, however, the DataReader comes into existence positioned at the first result set. If the NextResult method is called before the first result set is read, the first result set is discarded, and the next result set is read.

To read multiple result sets with a DataReader

Set the CommandType property of your Command object to Text.

Specify multiple SQL statements in the CommandText property of your Command object. These should be separated by a semicolon.

Call the ExecuteReader method of your Command object and assign the DataReader to a variable.

Use the DataReader object's NextResult method to iterate through the result sets.

Executing Ad Hoc SQL Queries

At times, you might not know which SQL query you want to execute until run time. You might want to receive a search string through user input, programmatically determine columns to be returned, or even determine the appropriate table at run time. You can create, configure, and execute commands all at run time.

The first step in executing an ad hoc SQL query is to build the command string. When building the command string, you should start by creating the outline of the command string. Where required, add string variables that represent the values to be inserted at run time. Use the concatenation operator to connect the strings.

The Command classes of each Data Provider expose constructors that allow you to set the CommandText and Connection properties at instantiation. After setting these properties, all you need to do is open the connection and execute the command. The following example demonstrates how a method might receive a search string, build an ad hoc SQL command, and execute it against the database.

Creating and Configuring DataAdapters

DataAdapter objects provide the link between a data source and a DataSet by managing the exchange of data. A DataAdapter is responsible for moving data between a data source and a DataSet. In some applications, this movement is strictly one-way. Other applications, however, might require continued querying and updating of the data source. The DataAdapter incorporates the functionality required to retrieve data, populate a DataSet, and perform updates as required.

There are two primary DataAdapters that are included with Visual Studio .NET. The SqlDataAdapter is designed to provide optimal communication with Microsoft SQL Server 7.0 or higher. TheOleDbDataAdapter provides access to any data source that is exposed by an OleDb Provider.

A single DataAdapter is generally used to manage data exchange between a single DataTable object in a DataSet and a single source database table. Because DataSet objects can contain multiple tables, you should create a single DataAdapter for each table you want to add to the DataSet.

There are three ways you can create a DataAdapter. You can drag database elements from the Server Explorer, you can use the new Data Adapter Configuration wizard, or you can create and configure the DataAdapter manually in code. The following sections describe each of these approaches.

Creating a DataAdapter Using Server Explorer

The easiest way to create a DataAdapter is by using the Server Explorer window. The Data Connections node of the Server Explorer window lists each installed data connection. Each Data Connection node, in turn, expands to provide detail about the database it represents, including a list of available Tables, Views, and Stored Procedures.

You can create a DataAdapter that represents a table by dragging a table from the Server Explorer window onto the designer. The resulting DataAdapter is of the correct type (SqlDataAdapter or OleDbDataAdapter) and has correctly configured SelectCommand, UpdateCommand, InsertCommand, and DeleteCommand properties.


You can also configure your DataAdapter to return a subset of the available columns in a table. To do this, expand the node that represents the table that contains the columns you want to select. You can then select individual columns by clicking the column entries while holding down the Ctrl key. When you have selected the columns you want to add, drag them to the designer. This creates a DataAdapter that is configured to manage only these columns.

To create a DataAdapter in Server Explorer

In the Server Explorer window, expand the node that represents the connection to the database you are using in your application.

Expand the Tables node to display the tables present in the database.

Select your table. If you do not want to use the entire table, expand the node represented by the table to display the individual columns. Select columns with the mouse while holding down the Ctrl key.

Drag your selection to the designer. A new instance of the appropriate type of DataAdapter is created and configured.

Creating a DataAdapter with the Data Adapter Configuration Wizard
You can create a new DataAdapter by dragging the appropriate DataAdapter class from the Toolbox to the designer. This launches the Data Adapter Configuration wizard.

To create a DataAdapter with the Data Adapter Configuration Wizard

From the Data tab of the Toolbox, drag the appropriate type of DataAdapter onto the designer.

This launches the Data Adapter Configuration wizard. Click Next to begin configuring your DataAdapter.

In the Choose Your Data Connection page, select the appropriate Data Connection from the drop-down menu. Click Next to continue.


Retrieving Data Using DataAdapters


A DataSet is an in-memory representation of data that is inherently disconnected from the database. A DataSet can represent a complete set of data including multiple tables, data relationships, and constraints. Because a DataSet is a disconnected representation of data, it can include data from multiple data sources. All interactions between DataSet objects and databases are managed by DataAdapter objects.

The DataAdapter encapsulates the functionality required to fill a DataSet with data and to update the database. It acts as a bridge between the connection and DataSet. The DataAdapter maintains a reference to a database connection in its Connection property, which represents the database that any data actions are executed against. The DataAdapter also exposes a SelectCommand property that contains the instructions for selecting data from a data source as a Command object. Like other Data Provider members, there is a DataAdapter implementation for each Data Provider.


You can fill a DataSet with data by calling the DataAdapter's Fill method. The Fill method executes the instructions contained within the SelectCommand property across the connection specified by the Connection property, and fills a specified DataSet with the resultant data. You must specify either a DataSet or a DataTable as the target of a Fill method.

To retrieve data with a DataAdapter

Create an instance of the appropriate type of DataAdapter that specifies the data you want to select.

Create an instance of a DataSet or DataTable object.

Call the Fill method of the DataAdapter, specifying the DataTable or DataSet as the target.

When working with DataAdapter objects, a single DataAdapter is generally used to manage a single table of data. If you want to load multiple tables into a single DataSet, you should use multiple DataAdapter objects. A single DataSet can be the target of multiple Fill commands. When each DataAdapter calls its Fill method, a new DataTable is created, filled with data and added to the DataSet.

To fill a DataSet with multiple tables

Create an instance of a DataSet.

Create a DataAdapter of the appropriate type for each table you want to have represented in your DataSet.

Sequentially call the Fill method of each DataAdapter, specifying your DataSet as the target.


Typed DataSet Objects

Standard DataSet objects are inherently weakly typed. Every data point is exposed as an object and must be converted to the appropriate type to perform any type specific manipulations. Working with weakly typed variables can cause type mismatch errors, which can be difficult to debug. ADO.NET provides an alternative to working with weakly typed variables: the typed DataSet.

A typed DataSet, as the name implies, is a DataSet that implements strong typing for each member. Tables and columns of a typed DataSet are accessible through user-friendly names that represent the names of the tables and columns you are working with, and data is exposed as typed instead of as objects. This provides many advantages to your application. Readability and maintainability of your code is increased.

Type-mismatch errors are discovered at compile time instead of at run time, saving valuable testing cycles. You can use friendly name syntax instead of collection syntax, and your typed data members can be displayed at design time in the Intellisense window.

related post

DAY 11 OOPS INTRODUCTION

DAY 12 POLYMORPHISM

DAY 13 INHERITANCE AND POLYMORPHISM

DAY 14 EBUGGING TOOLS IN DOT NET

DAY 15 DEBUG AND TRACE IN CLASSES

DAY 16 UNIT TEST PLAN

DAY 17 EXCEPTIONS IN VISUAL STUDIO

DAY 19 ADO.NET INTRODUCTION

DAY 20 DATA ACCESSING IN DOT NET

DAY 21 DATA BASE OBJECTS


Implementing Properties in dot net

Properties are members of classes that expose member variables or objects. Properties have similarities to both fields and methods. Values are set and retrieved using the same syntax as fields: getting a value from a property or setting a value with a property actually calls a specialized method that carries out these functions. Properties can contain code that validates values before setting them or carries out any other function that is required by the application.


Properties allow you to expose member values and objects in a more robust way than simply using fields. A property is essentially a specialized method that looks like a field. Property values are set and retrieved in the same manner as fields.

The Value (value) keyword is a special keyword used in the setter of a property. It always represents the value to which the property is being set. Properties can expose any kind of object, array, or collection. The value or object is usually stored in a private local variable (mText in the preceding example) and retrieved when the property is accessed.

The preceding example is a fairly trivial example of a property because it behaves in essentially the same manner as a field. One of the key advantages of properties is that you can provide additional code in the getter and setter of the property to perform calculations or validate the entry. The example below demonstrates how to create a property where the value is validated before being set.

To create a property

  1. Create a private member field or object to hold the value or object that will be returned by the property.
  2. Write the code for the property that will return the value.
  3. Add any validation code in the getter or the setter that is required for the property.
  4. Read-Only and Write-Only Properties

Sometimes you will need to implement a property that can return a value to the client but cannot be changed once the class is initialized. Very infrequently, you might need to create a property that can be changed but not read. These properties are called read-only and write-only properties, respectively.

Creating Read-Only Properties

Read-only properties are created in a manner similar to regular properties. In Visual C#, creating a read-only property is as simple as providing only a getter and omitting the setter from a property. In Visual Basic .NET, the property must be marked with the ReadOnly keyword, and the setter is omitted. In both languages, the private variable that holds the property value must be marked with the ReadOnly (readonly) keyword.

Because the variable holding the data for the property is read-only, it cannot be set or changed in code. You must set an initial value for the variable in the constructor of the class, or when the variable is initialized.

To create a read-only property

  1. Create a private member variable to hold the property value. This variable must be marked ReadOnly in Visual Basic .NET and readonly in Visual C#.
  2. Implement the property, supplying a getter but not a setter. In Visual Basic .NET, the property should also be marked ReadOnly.
  3. Set the value of the private member variable in the constructor of the class for which it is a member.

Write-Only Properties

Although used very infrequently, it is possible to create properties that can be written to but not read by the client. You might implement a write-only property that controls localization properties of a form. When a different locale is set, code in the property would execute to make the appropriate changes to the form, and there would be no need to access the value of the property.

A write-only property is created in a manner analogous to a read-only property. If the value of the write-only property is to be stored, you will need to create a private member variable to hold it. The property itself is implemented as a regular property, but only a setter is supplied. The getter is omitted. In Visual Basic .NET, the property must be marked with the WriteOnly keyword.

To create a write-only property

If needed, create a private member variable to hold the value of the write-only property.

Implement your property supplying only a setter. In the setter, write any code that you want to execute when the property is set. In Visual Basic .NET, you must also mark the property with the WriteOnly keyword.

Parameterized Properties

Most of the properties you create will return a single value or object. In Visual Basic .NET, you can create properties that accept parameters when accessed. These properties usually expose a range, or array of values. For example, a single Engine object might have several Cylinders. Rather than expose each one individually, you could create a Cylinder property that returned or set each cylinder based on a supplied parameter.

You implement a parameterized property just as you would a normal property except that in the property declaration, you declare the parameter. Then, in the getter and setter of the property, you write appropriate code to retrieve the appropriate value or object.

Default Properties and Indexers

In Visual Basic .NET, you can designate a default property for your component. A default property is always a parameterized property and is usually used to expose a range, array, or collection of values. Enabling a default property only makes sense if the primary purpose of the object is to contain and expose other objects. If you mark a property as default, you can use the property name interchangeably with the object name.

The equivalent of a Visual Basic .NET default property in Visual C# is the indexer. The indexer is a specialized property that allows you to expose a group of objects on the name of the object. The name used in the code of the indexer is always this, which indicates that the name of the object itself will be used to access the property.

To create a default property in Visual Basic .NET

Create a parameterized property that returns an object based on the parameter. Use the Default keyword in the property declaration.

To create an indexer in Visual C#

Create a property named this, and designate an index variable for the property. Write code that returns the appropriate object based on the index.

Collection Properties

If your object exposes an undetermined number of objects of the same type, you can expose a collection of objects through a property. Exposing collections of objects as properties allows you to control access to your subordinate objects and validate assignments.

There are a few different ways to implement collection properties. How you choose to do so depends on the kind of functionality you need to implement. Simple collection properties can simply return the collection. This allows clients to add and remove members to the collection as well as use all of the collection's methods.

You would probably expose the collection as a read-only property because you would never want to allow the client to assign the property to a new instance of the collection class itself. The objects in the collection could still be changed with the collection's own methods.


Although this approach is simple and allows you access to the collection's members, there is one fairly significant problem. Most of the collection classes in the System.Collections namespace accept and return their members as objects. This means that any kind of type can be added or removed to the collection. Thus, there is no type checking when members are added to the collection, and retrieved members must be explicitly converted to the correct type. If you want to manage groups of differently typed objects in a single property, this approach will be adequate.

To create a simple collection property

Implement a read-only property that returns the collection.

For more robust collection properties, you should wrap your collection object in the property and provide explicit conversion and validation code within the property. This allows you to access the collection members by index and control the types that are added to the collection. In Visual Basic .NET, you must implement a property of this type as a parameterized property.

This approach allows for properties that are strongly typed and exposes a collection of like-typed items. There are some drawbacks to this approach, however. You lose the ability to iterate through the collection using For Each...Next (foreach), and any other methods of the property that you want to expose to the client must be wrapped as well. Additionally, the syntax concessions required in Visual C# might also be unsuitable.

To create a strongly typed collection property

In Visual Basic .NET, create a parameterized property that returns a member of a private collection based on the index. Use the CType keyword to convert the object returned by the collection to the appropriate type.

In Visual C#, create a pair of methods that get and set the object at the appropriate index in a private collection. In the get method, explicitly convert the object returned by the collection to the appropriate type.

For properties that require an even stronger implementation, you can implement your own strongly typed collection by inheriting from the ystem.Collections.CollectionBase class. This class provides most of the background functionality required by collections and allows you to provide your own implementations of the item property.

With a strongly typed collection, you can expose the collection directly in the property (as shown in the preceding example) and still have access to all the collection functionality. The collection will only accept members of the type you specify and will incorporate any other functionality you require.

related post

DAY 1 MICROSOFT DOT NET FRAME WORK

DAY 2 MICROSOFT DOT NET BASE CLASS LIBRARY

DAY 3 MICROSOFT DOT NET CLASSES AND STRECTURES

DAY 4 METHODS IN FRAME WORK

DAY 5 INPUT VALIDATIONS IN DOT NET PART ONE

DAY 6 INPUT VALIDATIONS IN DOT NET PART TWO

DAY 7 DATA TYPES IN DOT NET

DAY 8 DATA TYPES IN DOT NET PART TWO

DAY 9 IMPLEMENTING PROPERTIES IN DOT NET

DAY 10 DELEGATES AND EVENTS