Sets

Sets are a uniquely Delphi type that have no equivalent in C or Visual Basic .NET. Sets provide an efficient and convenient means of representing a collection of ordinal, AnsiChar, or enumerated values. You can declare a new set type using the keywords set of followed by an ordinal type or subrange of possible set values. Here's an example TCharSet set of AnsiChar possible members 0 - 255 TEnum Monday, Tuesday, Wednesday, Thursday, Friday TEnumSet set of TEnum can contain any combination of...

LISTING DataGrid Declaration aspx

1 lt Page language c Debug true Codebehind WebForm1.pas Inherits WebForm1.TWebForm1 gt 3 lt DOCTYPE HTML PUBLIC - W3C DTD HTML 4.0 Transitional EN gt 4 8 lt meta name GENERATOR content Borland Package Library 7.1 gt 11 lt body 12 lt form runat server gt 13 lt asp datagrid id DataGrid1 14 style Z-INDEX 1 LEFT 6px POSITION absolute TOP 6px 15 runat server height 243 width 523px font-names Arial borderwidth 1px bordercolor Gray cellspacing 2 cellpadding 2 18 pagesize 5 allowpaging True gt 19 lt...

LISTING webconfig File Schema

lt configuration gt lt location gt lt authentication gt lt forms gt lt credentials gt lt passport gt lt authorization gt lt allow gt lt deny gt lt browserCaps gt lt result gt lt use gt lt filter gt lt case gt lt clientTarget gt lt add gt lt remove gt lt clear gt lt compilation gt lt compilers gt lt compiler gt lt assemblies gt lt add gt lt remove gt lt clear gt lt customErrors gt lt error gt lt globalization gt lt httpHandlers gt lt httpRuntime gt lt identity gt lt machineKey gt lt pages gt lt...

The webconfig File

The web.config file, like the machine.config file, holds specific settings that apply to a specific ASP.NET application. You can also add your own settings to this file that would be needed by the application, such as database connection strings. In a sense, you can think of the web.config file as you would an .ini file. The web.config file is nowhere as wieldy as the machine.config file. The schema for the web.config file is shown in Listing 32.1 with the main sections in bold font.

String Immutability in NET

What exactly is meant by strings being immutable It means that once you instantiate a String type, you cannot change its value. This is not saying that the following code will fail procedure TWinForm.Button1_Click sender System.Object e System.EventArgs var s 'Classic Cars' s s.ToUpper s s.ToLower end It is saying that the preceding code requires two string instances or memory allocations even though they both are being referred to by the same variable. Consider the IL code generated for the...

Creating and Deleting Directories

The following code shows how to create a directory using the Directoryinfo class dirlnfo DirectoryInfo.Create 'c ddgtemp' if not dirlnfo.Exists then dirlnfo. amp Create First, an instance of Directoryinfo is created and assigned to the variable dirinfo. By passing a valid path to the Create constructor, you are associating that directory with the Directoryinfo object however, you are not creating the directory. To actually create the directory, you must call the Create method. Also, note the...

LISTING WebService Proxy Class

1 unit localhost.WebServicel 2 9 System.Web.Services, System.Web.Services.Description 15 Name 'My First Web ServiceSoap', 17 MyFirstWebService 26 function HelloWorld string 27 function BeginHelloWorld callback System.AsyncCallback 28 asyncState System.Object System.IAsyncResult 29 function EndHelloWorld asyncResult System.IAsyncResult string 36 function Add A Integer B Integer Integer 37 function BeginAdd A Integer B Integer callback 38 asyncState System.Object System.IAsyncResult 39 function...

LISTING Filter Output Demo

2 TWebForml class System.Web.UI.Page 4 procedure Page_Load sender System.Object e System.EventArgs 7 TChangeCaseFilter class MemoryStream 11 constructor Create aStream Stream override 12 procedure Write bfr array of byte offset integer CHAPTER 25 ASP.NET Fundamentals LISTING 25.3 Continued 18 procedure TWebForm1.Page_Load sender System.Object e System.EventArgs 20 Response.Filter 21 Response.Write 'Hello Delphi for .NET' 26 constructor TChangeCaseFilter.Create aStream Stream 32 procedure...

Interfaces

The Delphi language contains native support for interfaces, which, simply put, define a set of functions and procedures that can be used to interact with an object. The definition of a given interface is known to both the implementer and the client of the interface acting as a contract of sorts for how an interface will be defined and used. A class can implement multiple interfaces, providing multiple known faces by which a client can control an object. As its name implies, an interface defines...

Variant Records

The Delphi language also supports variant records, which enable different pieces of data to overlay the same portion of memory in the record. Not to be confused with the Variant data type, variant records enable each overlapping data field to be accessed independently. If your background is C, you'll recognize variant records as being the same concept as a union within a C struct. The following code shows a variant record in which a Double, Integer, and Char all occupy the same memory space...

LISTING FileSystemWatcher Example

6 System.Drawing, System.Collections, System.ComponentModel, 7 System.Windows.Forms, System.Data, System.IO 8 10 TWinFormI class System.Windows.Forms.Form 13 procedure OnChanged source System.Object e FileSystemEventArgs 14 procedure OnRenamed source System.Object e RenamedEventArgs 22 constructor TWinForm1.Create 26 fsw 27 fsw.NotifyFilter NotifyFilters.Attributes or 28 NotifyFilters.CreationTime or NotifyFilters.DirectoryName or 29 NotifyFilters.FileName or NotifyFilters.LastAccess or 30...

Paging the DataGrid

One of the nice features of the DataGrid is its capability to display and navigate through divided chunks of large resultsets. The DataGrid itself handles the rendering of each chunk and adds a Pager bar, a row at the bottom of the DataGrid with links to allow the user to move forward or backward through the data chunks. Of course, you have the option of customizing how the DataGrid retrieves chunks to display, and you can also change the look and behavior of the Pager bar. It should be noted,...

LISTING More Interesting Unmanaged Exports

10 BufferLen is the length of the unmanaged buffer, 11 not counting the null terminator, i.e. the number of characters 13 Buffer PWideChar BufferLen Integer Integer unsafe 19 VersionStr System.String.Format 20 '.NET version 0 ', Environment.Version.ToString 21 MinLen Math.Min VersionStr.Length, BufferLen 23 Buffer I VersionStr.Chars I 25 Result VersionStr.Length

Drawing with the Region Class

When creating Regions, you are defining an area in which you will perform drawing operations. Listing 7.13 shows the code that illustrates how to use the Region class. 1 procedure TWinForm.btnCreateRegion_Click sender System.Object 10 MyPen Pen.Create Color.Black, 2 11 r Rectangle.Create 20, 40, 400, 50 12 r2 Rectangle.Create 100, 10, 50, 200 13 rg System.Drawing.Region.Create r 14 15 case ListBox1.SelectedIndex of . Find the code on the CD Code Chapter 07 Ex02. In this example, two Rectangles...

The Data Binding Interfaces

In previous versions of Delphi, the data binding equivalent technology was called data aware, and under this scheme you had data aware controls. Often, component vendors would provide two versions of their controls one that was data aware and one that was not. Additionally, the data awareness of a control was linked to only database-related classes, for the most part. In .NET, data awareness happens as a result of the control being bound to a data source in a decoupled manner. For instance,...

Parameter Collection Editor

The Parameter Collection Editor dialog box allows you to define BdpParameter objects for a parameterized query. This dialog box is shown in Figure 24.4. FIGURE 24.3 The Command Text Editor dialog box. FIGURE 24.3 The Command Text Editor dialog box. FIGURE 24.4 The Parameter Collection Editor dialog box. FIGURE 24.4 The Parameter Collection Editor dialog box. Through this dialog box, you can create new parameters and set the properties that you would normally do programmatically as shown in...

Some Caveats and a Minor Extension of the Example

At this point, our example works on both Windows and Linux. An alternative approach would have been to use a TDateTime variable and the DateToStr function to process the calendar selection. By modifying the Button_ciick event handler to resemble the following procedure TWebForm1.Button1_Click sender System.Object lblResponse.Text lblResponse.Text ' Hello, ' txtbxName.Text ' ' ' You have selected ' DateToStr lDate '.' You will need to add SysUtils to the uses clause. When running the application...

Flow of Execution

After an exception is raised, the flow of execution of your program propagates up to the next exception handler until the exception instance is finally handled and destroyed. This process is determined by the call stack and therefore works program-wide not just within one procedure or unit . Listing 5.7 is a VCL unit that illustrates the flow of execution of a program when an exception is raised. This listing is the main unit of a Delphi application that consists of one form with one button....

LISTING A Raw NET Import Unit for a Simple DLL

5 function SomeFunc InputValue Integer Integer 6 11 15 CallingConvention CallingConvention.StdCall 16 function SomeFunc InputValue Integer Integer external DllImportAttribute supports a variety of fields to tailor its operation of which a few are specified by the compiler and shown in Listing 16.11. The EntryPoint field line 13 specifies the true exported name of the routine in the DLL and is the same as the name modifier on an external clause it is only required if the Delphi identifier for...

IList Interface

Table 10.4 describes the properties and methods in the IList interface. TABLE 10.4 IList Properties and Methods TABLE 10.4 IList Properties and Methods Indicates if the IList has a fixed size. Indicates if the IList grants read-only access to its elements. Returns the IList element by the specified index. Adds the specified item to the IList. Indicates whether the IList contains the specified value. Returns the index of the specified item. Inserts an item into the IList at a specified position....

FIGURE Exception from an HResult

Things to take into consideration for optimizing a P Invoke call include the following Put some work into making the marshaling as efficient or as limited as possible. In particular, try to avoid marshaling .NET Unicode strings to or from unmanaged ANSI strings as this is costly. Selectively use InAttribute and OutAttribute from System.Runtime.InteropServices where possible to help the marshaler know when it does not need to copy data in a given direction. Avoid setting the SetLastError field...

Animation Example

The animation demo for this section is one in which a background, a clear night's sky, is invaded by a flying saucer that bounces about, probably looking for someone to abduct. The program is actually quite simple in fact, much simpler than the Win32 version, which involved using a series of BitBit and masking operations to achieve transparency. The Win32 Version of the application is still around and compiled under VCL.NET. You'll find it under the CD directory Code Chapter 07 AnimateVCL...

IDisposable Example

Consider the TCriticalSection class from the previous section. The following is its reworked definition that implements IDisposable TCriticalSection class TObject, IDisposable private FSection TRTLCriticalSection FCSValid Boolean strict protected procedure Finalize override public constructor Create procedure Dispose end You should notice that the object now implements the IDisposable interface and its Dispose procedure. Also, an FCSValid Boolean field will be initialized to False and set to...

Type Aliases

The Delphi language has the capability to create new names, or aliases, for types that are already defined. For example, if you want to create a new name for an Integer called MyReallyNiftyInteger, you could do so using the following code The newly defined type alias is compatible in all ways with the type for which it's an alias, meaning, in this case, that you could use MyReallyNiftyInteger anywhere in which you could use Integer. It's possible, however, to define strongly-typed aliases that...

LISTING Example of Invoke and InvokeRequired

TMyUpdateDelegate procedure of object procedure TWinForm.UpdateControls var myDelegate TMyUpdateDelegate tmpStr string begin if progBar.InvokeRequired then begin tmpStr System.String.Format ' 0 invoke required ', UpdateTextBox System.Object tmpStr myDelegate self.UpdateControls end progBar.Increment l trackBar.Value trackBar.Value 1 end end . Find the code on the CD Code Chapter i4 Ex08 . Taken from the ThreadingExampies project, the UpdateControis method is called from the main user-interface...

G

G format specifier, 231, 234-237 GAC Global Assembly Cache , 111-112 GC Garbage Collector , 187-189 generational garbage collection, 189-190 invoking, 191 multithreaded applications, 337 roots, 187 System.GC class, 191 GDI library, 125 animation demo implementation, 161165 main form declaration, 160 sprite declaration, 159 Brush classes, 128-130 curves Bezier splines, 135-138 cardinal splines, 134 ellipses, 139 Graphics class, 126 GraphicsPath class, 142-143 images, 147 bitmaps, 148 drawing,...

LISTING Using the BdpCommand Class

2 cnStr ' assembly Borland.Data.Interbase, Version 1.5.0.0, ' w-vendorclient gds32.dll ' 4 ' database C Program Files Common Files Borland Shared Data EMPLOYEE.GDB ' 6 procedure TWinForm.btnOpen_Click sender System.Object 13 bdpCn BdpConnection.Create cnStr 14 Include bdpCn.StateChange, Self.BdpCn_StateChange 18 bdpCmd bdpCn.CreateCommand 19 bdpCmd.CommandText 'SELECT FROM customer' 20 bdpRdr bdpCmd.ExecuteReader . Find the code on the CD Code Chapter 24 Ex02. The BdpConnection must be opened...

LISTING A Simple NET Class to be Exposed to COM

procedure ShowDotNetMessage Msg, Caption String function DotNETVersion String end function DotNETClassForCOM.dotNETVersion String begin Result System.String.Format 'Running .NET 0 on 1 ', Environment.Version, Environment.OSVersion . Find the code on the CD Chapter i6 Ex05 . Figure 16.7 shows the registry entries that enable a .NET class to be used by Win32 COM. The assembly must be placed in a suitable directory to be found at runtime through natural DLL location mechanisms. Generally, it is...

Drawing a Mirror Effect

Ever had your photos developed and found that they were in the wrong direction, rotated that is Fortunately, with digital images, you can rotate them yourself by using the Bitmap.RotateFlip method as shown here g.DrawImage tmpBm, 290, 0 . Find the code on the CD Code Chapter 07 Ex03. The RotateFlip method performs various rotation flipping operations on images based on one of the RotateFlipType enumeration values given it. The possible values are as shown in Table 7.2. FIGURE 7.23 Images drawn...

LISTING Saving Updates Using SqlCommandBuilder

'c windows microsoft.net 17 c_cnstr 18 c_sel_cst 'SELECT FROM Products' 21 sqlCn SqlConnection.Create c_cnstr 22 sqlDA SqlDataAdapter.Create c_sel_cst, sqlCn 23 sqlCB SqlCommandBuilder.Create sqlDA 24 dsNorthWind DataSet.Create 'NorthWind' 'Products' 28 tblProduct dsNorthWind.Tables 'Products' 29 TObject 10 . Find the code on the CD Code Chapter 22 Ex0i. Most of the code in this listing is similar to previous examples you have seen. The first part of this listing basically sets up the...

Using Command and DataReader Objects

The previous chapter covers how to get connected to a database. This chapter discusses how to query database data in a read-only, high-performance manner. Specifically, it covers the Command and DataReader classes. This chapter uses the Microsoft SQL Provider classes SqlCommand and SqlDataReader, which implement the IDbCommand and IDataReader interfaces, respectively. Keep in mind that other providers such as the OLE DB and Borland Data Providers BDP will have slight differences in usage.

TABLE StringBuilder Methods

Append A heavily overloaded method that appends the string representation of the specified object to the string maintained by the StringBuilder. AppendFormat Similar to the Append functionality, but uses the provided format specifiers and culture information. EnsureCapacity Guarantees that the character array is at least of the specified capacity. Equals Compares two StringBuilder classes or objects that have the same MaxCapacity, Capacity, Length, and character array contents. Insert Inserts...

Drawing with the GraphicsPath Class

Earlier, it was said that the GraphicsPath class is used to combine graphical shapes including lines. The following example illustrates how a GraphicsPath can be composed of lines and shapes that might not even be connected. What's convenient about the graphics path is that you can define what you want to draw and then perform the drawing of it in one swoop. Listing 7.12 shows this code. LISTING 7.12 Drawing a Graphics Path 1 procedure TWinForm.btnCreatePath_Click sender System.Object 8 MyPen...

LISTING Using COM Events from the Microsoft Speech API

1 procedure TMainForm.TMainForm_Load sender System.Object 3 Voice SpVoiceClass.Create or 6 Include Voice.Word, VoiceWord 7 Include Voice.EndStream, VoiceEndStream 10 procedure TMainForm.btnSay_Click sender System.Object 12 Speak asynchronously so the events can fire 13 Voice.Speak txtWords.Text, 16 procedure TMainForm.VoiceEndStream StreamNumber Integer 19 When speech stream ends, remove the highlight from the text box 20 txtWords.SelectionLength 0 21 txtWords.SelectionStart Length...

Creating a DataAdapter

The DataAdapter class has four constructors each with a different combination of parameters to specify a select command or connection. For instance, given the following connection and select command strings c_cnstr c_sel_emp 'select from Employees' A DataAdapter can be created without specifying any parameter in which case, the appropriate command property must be specified sqlDA SqlDataAdapter sqlCMD SQLCommand sqlCN SQLConnection begin sqlCN SQLConnection.Create c_cnstr sqlCmd...

Using the SqlDataAdapter Class

The SqlDataAdapter class contains three SqlCommand properties in addition to the SelectCommand property InsertCommand, UpdateCommand, and DeleteCommand. When you invoke SqlDataAdapter's Update method to save changes to the data source, SqlDataAdapter determines which of the three SqlCommand properties it will use to update the data source. To illustrate how SqlDataAdapter works, I'll use the same Transact-SQL statements that were used to demonstrate using the SqlCommand classes to update the...

Structured Exception Handling 1

Structured exception handling SEH is a method centralizing and normalizing error handling, providing both non-invasive error handling within source code as well as the capability to gracefully handle nearly any kind of error condition. The Delphi language's SEH is mapped to that provided in the CLR by .NET. Exceptions are, at the most basic level, merely classes that happen to contain information about the location and nature of a particular error. This makes exceptions as easy to implement and...

Manipulating DataWorking with DataRow

Modifications to data contained in a DataTable are performed at the row level. The DataRow class contains the methods that you would use to perform updates, deletions, and additions to a DataTable. To add a row to a DataTable, first call the DataTable.NewRow method, which returns a DataRow instance containing the schema information for that row. Then, assign column values using the retrieved DataRow instance. The following code illustrates the use of this function drCust dtCust.NewRow drCust...

Example Projects Using DataView and DataViewManager

The following sections illustrate some techniques using the DataView and DataViewManager classes. You will use many of these techniques in designing your own applications. Listing 21.1 illustrates how to bind a user-interface component to a DataView and DataViewManager. LISTING 21.1 Simple DataView Example 2 c_cnstr 3 c_sel 'SELECT FROM customers SELECT FROM employees ' 4 ' SELECT FROM suppliers' 6 constructor TWinForm.Create 7 begin 8 inherited Create 9 InitializeComponent 10...

Creating a Thumbnail

Occasionally, you'll want to generate a thumbnail for an image. Some images have the capability of including their thumbnails. The Bitmap.GetThumbnaiiimage method returns the thumbnail contained in an image. If a thumbnail does not exist, it is created and returned. This code is invoked as shown here procedure TWinForm1.Thumb g Graphics tn MyBitmap.GetThumbnailImage 75, 75, nil, nil tmpBm Bitmap.Create tn g.DrawImage tmpBm, 10, 10 end

Specifying Parameters Using IDbParameter

When executing SQL code, it's highly unlikely that the SQL statement values will be hard-coded as in Listing 19.2, which searched on Canadian customers. What if we wanted to search on German or Mexican customers The query would have to somehow support dynamic specification of the search criteria. This is done through parameterized queries. In a parameterized query, a placeholder is put in the query statement where the hard-coded search criteria initially resided. Consider the following SQL...

Typecasting and Type Conversion 1

Typecasting is a technique by which you can force the compiler to view a variable of one type as another type. Because of Delphi's strongly-typed nature, you'll find that the compiler is very picky about types matching up in the formal and actual parameters of a function call. Hence, you occasionally will be required to cast a variable of one type to a variable of another type to make the compiler happy. Suppose, for example, that you need to assign the value of a character to a Word variable w...

Updating the Data Source Using SQLCommandBuilder

SQLDataAdapter does not automatically create the SQL statements to reconcile changes back to the data source. The SQLCommandBuilder class will perform this task for you. SQLCommandBuilder is easy to use and requires little coding. The SQLCommandBuilder class uses the SelectCommand property of SQLDataAdapter to retrieve metadata about the data set. From this information, SQLCommandBuilder builds the appropriate InsertCommand, UpdateCommand, and DeleteCommand classes. These classes contain the...

Revisiting Coordinate Systems

Listing 7.19 gives a brief example of dealing with the Graphics.TranslateTransform method. Internally, the TranslateTransform method uses a Matrix class to represent the world transformation matrix used in calculating position, angle, and so on of where drawing occurs. A simple example of shifting where point 0, 0 on world coordinates appears on page coordinates is shown in Listing 7.21. LISTING 7.21 Shifting World Origin Using TranslateTransform procedure TWinForm.DrawBasicTransform g Graphics...

Primary Interop Assemblies

If a particular COM server is in widespread use, you can appreciate the problem that might occur in which a variety of developers make their own Interop Assembly for it. As various applications are deployed to target machines, a given machine could end up with several Interop Assemblies for the same COM server installed in various locations. To avoid this situation, there is the notion of a Primary Interop Assembly or PIA. The goal is for vendors of COM servers to create a PIA for their COM...

LISTING HTTPRequest Example

1 procedure TWebForm1.Page_Load sender System.Object e System.EventArgs 3 NameValCol NameValueCollection 7 Client can request server information through the Request Path 0 lt br gt ', Path 0 lt br gt ', Info 0 lt br gt ', Path 0 lt br gt ', Application Path 0 lt br gt ', Host Address 0 lt br gt ', Host Name 0 lt br gt ', 24 Write HTTP Request information Method 0 lt br gt ', 29 NameValCol Request.Headers 30 StrArray NameValCol.AllKeys 31 for i Low StrArray to High StrArray do 0 1 lt br gt ', 33...

Error Handling

COM routines indicate errors by returning HResult status codes. However, you might recall from previous Delphi COM programming that Delphi offers the convenient SafeCall calling convention, which removes the HResult issue from the programmer's eyes and leaves it to the compiled code. Any HResult that is returned by a COM method that represents an error is transparently turned into an exception by the calling code. If the COM method sets extra error information through the IErrorInfo interface...

Parameter Types and Marshaling 1

The key ingredient for success in using P Invoke is getting the marshaling of the parameters correct. Because you will generally be moving code that uses the DLL routines from Win32 to .NET, you can often use the Win32 import declarations supplied with Delphi 7 for Win32 and Delphi for .NET as a guide to help you get the hang of translating the parameter lists across from Win32 to .NET. So let's say that you have a routine in a C DLL that takes a certain type of parameter, a char input...

LISTING Establishing a Connection with BdpConnection

2 cnStr ' assembly Borland.Data.Interbase, Version 1.5.0.0, ' 4 ' database C Program Files Common Files Borland 6 procedure TWinForm.btnOpen_Click sender System.Object 7 e System.EventArgs 8 var 11 bdpCn BdpConnection.Create cnStr 12 Include bdpCn.StateChange, Self.BdpCn_StateChange . Find the code on the CD Code Chapter 24 Ex0i. Lines 2-5 represent the connection string to an Interbase database. The ConnectionString assignment is handled implicitly by the BdpConnection.Create constructor call...

Numeric Format Specifiers

Standard numeric format specifiers are used to format numeric types to string in predefined patterns. The format specifier takes the following form Where a is an alphabetic format specifier and nn is an option precision specifier represented as an integer. The precision specifier, when supplied, might range from 0-99 and typically specifies the number of significant digits to the right of the decimal. Table 11.2 shows the various numeric format specifiers that can be used with formatting...