Web Services

Through Add Web Reference dialog, 635-637 SOAP (Simple Object Access Protocol), 9, 620 UDDI (Universal Description, Discovery, and Integration), 9, 621 WSDL (Web Service Description Language), 9, 620 XML (Extensible Markup Language), 9, 620 web.config file, 721-723 < appSettings> section, 736-737 < authentication> section, 703, 724-725 < authorization> section, 725 < credentials> section, 705-706 custom configuration sections, 737 < customErrors> section, 727 file schema,...

Retrieving Single Values

Oftentimes, you'll need to retrieve a single value from a query, particularly when returning an aggregate value. SqlCommand implements the ExecuteScalar() method, which returns such a value. Examine the following SQL statement SELECT Count(*) AS CanCust FROM customers WHERE country 'Canada' This particular statement will retrieve the total number of records in a table named customers, indicating customers who reside in Canada. The value returned will be returned as a single field named CanCust....

Clipping Regions

You've seen how Regions can be used to define an area in which drawing will be performed. You have also seen how certain operations on a region look when a Region is drawn with another, overlaying shape. Regions can also be used to prohibit drawing outside of, or within, itself. Listing 7.14 illustrates this. FIGURE 7.17 Region intersected with a Rectangle. FIGURE 7.17 Region intersected with a Rectangle. procedure TWinForm.btnClipRegion_Click(sender System.Object gp GraphicsPath r Rectangle...

Format Specifiers

Listing 11.1 illustrates the usage of numeric specifiers. LISTING 11.1 Use of Numeric Format Specifiers 9 MyPercent System.Double 10 0 C2 ', MyCurrency) 18 Console.Writeline('Decimal 0 D4 ', System.Object(MyDecimal)) 0 E10 ', System.Object(MyDouble)) 0 F3 ', System.Object(MyDouble)) 21 Console.Writeline('General 0 G3 ', System.Object(MyDouble)) 22 Console.Writeline('Number 0 N3 ', System.Object(MyDouble)) 23 Console.Writeline('Percent 0 P0 ', System.Object(MyPercent)) 0 R ',...

Joining Lines The Graphics Path Class

The GraphicsPath class is used to combine graphical shapes including lines. I'll get more into the GraphicsPath later. For now, just assume that the lines built in the following example are part of a combined collection. Listing 7.5 shows this. LISTING 7.5 Joining Lines with GraphicsPath 1 procedure TWinForm.PaintLineJoins 9 MyPath.AddLine(10, 10, 300, 10) 10 MyPath.AddLine(300, 10, 10, 200) 11 MyPath.AddLine(10, 200, 300, 200) 12 13 if rbBevel.Checked then MyPen.LineJoin LineJoin.Bevel 14 else...

Listing Continued

Response.Write('< br> ') Response.Write('Browser Information< br> ') 0 < br> ' Request.Browser.Version )) Request.Browser.Platform )) Frames 0 < br> ' 'Version 0 < br> ', 'ClrVersion 0 < br> ' 0 < br> ', Response.Write('< br> ') Request.QueryString )) Request.QueryString 'Name' )) Response.Write(System.String.Format( Request.QueryString 'State' )) Query String ''State'' 0 < br> ' . SEE the entire example on the CD Code Chapter 25 Ex05 . The first portion of...

Dcom

The Distributed Component Object Model (DCOM) was the technology recommended by Microsoft for building distributed applications and, simply put, allows to access COM automation servers from remote computers. DCOM was designed to work using different network transports (that is, TCP IP and HTTP), to be cross platform, and it was based on the Open Group DCE-RPC specification. Although the framework provides support for non-x86 architectures and has been ported to some Unix platforms, it has never...

Listing The Client DPR Files

'SharedPackage.dll' 8 694 CHAPTER 30 .NET Remoting in Action LISTING 30.14 Continued 14 RemotingHelper in 'RemotingHelper.pas' 15 16 var SimpleFactory ISimpleFactory 18 SimpleSrv2 ISimpleServer 19 RemotingHelper TRemotingHelper 21 filename string 'Client.Config.xml' 23 Reads the command line arguments 24 args Environment.GetCommandLineArgs 26 filename args.GetValue(1).ToString+filename 27 28 Configures the remoting infrastructure the client by reading the file '+ filename) 31 32 RemotingHelper...

XCOPY Deployment

The whole idea of xcopy deployment is not only for ASP.NET applications. It refers to how you should be able to install all .NET applications. Prior to .NET, anybody who has had to write an installation program knows the pain and agony involved in just getting started. For the most part, installation is a configuration nightmare. Microsoft dealt with this in how .NET applications are designed. .NET applications, being self-describing, only need to reside in an area from which they can be...

The System ThreadingThread Pool Class

One of the nicest features of threading in the .NET framework is the addition of a thread pooling class. Saving thousands of lines of code, this class provides the means necessary for using threads as easy as calling a single method. Ideal for short-lived tasks, the ThreadPool class hides the underlying Thread class, taking away the flexibility and control that the Thread class provides. Many features of the .NET platform use threads from the thread pool. Examples using the thread pool include...

The Simple StatusBar Control

SimpleStatusBar is a Control that descends from System.Windows.Forms.StatusBar, adding a twist It adds a StatusText property to other controls on the form and monitors the focus change of the other control, setting its own text to be equal to the StatusText property of the focused control. The source code for SimpleStatusBar is shown in Listing 13.10. LISTING 13.10 SimpleStatusBar Source Code 5 uses System.Windows.Forms, System.ComponentModel, System.Collections, 6 System.Windows.Forms.Design,...

The Pen and Brush Classes

You use Pens to draw lines, shapes, and curves. The Pen can draw lines of different widths. You can also apply caps to lines (styles of endpoints to lines), and lines can be joined to form more complex shapes. Brushes are used to fill a drawing surface. The surface area can be filled with a color, pattern, image, and texture. This section covers various line techniques. In the example, there is a helper function that I'll point out before I illustrate the various drawing samples. The first is a...

Listing Get DataAdapter DeleteCommand

1 function GetDataAdapterDeleteCommand SqlCommand 5 sqlCmd SqlCommand.Create('DeleteProduct', sqlCn) 6 sqlCmd.CommandType CommandType.StoredProcedure 7 SqlDbType.Int, 0, 'ProductID') 9 You'll note that the GetDataAdapterDeleteCommandO is quite a bit smaller than the other two functions. The reason here is because the stored procedure for deleting a record uses only the primary key field, ProductID, for locating the record to be deleted in the database. This is shown in Listing 22.21. LISTING...

Adding and Reading Custom Configuration Sections

When you need several items in the web.config file, you can create your own section. The following example shows what this might look like < configuration> < configSections> < section name NewSection System, Version 1.0.5000.0, Culture neutral, < configSections> < NewSection> < add key ConnectionString < NewSection> As shown in this example, you first declare your sections in the < configSection> section of the web.config file. When declaring a section, you must...

Listing Tsimple Server Implementation

10 TSimpleServer class(MarshalByRefObject, ISimpleServer) 15 function GetValue Integer 16 procedure SetValue(Value Integer) 19 constructor Create overload 20 constructor Create(Value integer) overload 27 constructor TSimpleServer.Create 31 Console.WriteLine('Creating TSimpleServer with empty constructor') 34 constructor TSimpleServer.Create(Value integer) 35 begin 40 Console.WriteLine('Creating TSimpleServer with value '+ 43 function TSimpleServer.GetValue Integer 44 begin 47...

TABLE Continued

StandardClick The control implements the standard mouse click behavior. StandardDoubleClick The control implements the standard mouse double-click behavior. This style must be used in conjunction with the StandardClick style. SupportsTransparentBackColor The control accepts a BackColor with an alpha component of less than 255 to simulate transparency. Transparency will be simulated only if the UserPaint style is included and the parent control descends from System.Windows.Forms.Control....

Overview of the NET Framework

This chapter provides an overview of the core component of the .NET the .NET Framework. The .NET Framework is the technical entity that enables developers to deliver on the business solutions discussed in Chapter 1, Introduction to .NET. In a simplified illustration, the steps to develop and execute a .NET application are 1. Write a program in your .NET language flavor of choice. 2. Compile your code to the Intermediate Language (IL) residing in a managed module. 3. Combine your managed modules...

Windows Coordinate System

The Windows coordinate system is simple. The surface is basically a grid composed of pixels. The origin of this grid is the upper-left pixel. Therefore, its coordinate using the x, y axis would be x 0, y 0 . Figure 7.1 illustrates this concept in an 8x8 grid. It is composed of a line that extends from coordinate 0, 0 to coordinate 7, 7 . FIGURE 7.1 Line extending from 0, 0 to 7, 7 . This explanation is one way to think about a coordinate system. GDI+ actually relies on three different...

Bitwise Operators

Bitwise operators enable you to modify individual bits of a given integral variable. Common bitwise operators enable you to shift the bits to the left or right or to perform bitwise and, not, or, and exclusive or (xor) operations with two numbers. The Shift-left and Shift-right operators are shl and shr, respectively, and they're much like the C < < and > > operators. The remainder of Delphi's bitwise operators is easy enough to remember and, not, or, and xor. Table 5.3 lists the...

String Formatting

The String class has a static Format() function that you use to format strings similar to the Format() function in the Delphi RTL. The type of formatting it uses is called composite formatting. The commonly used version of the overloaded string.Format() function takes a format string and values that it applies to the format string. The format string consists of fixed text and indexed placeholders. The simplest form of string.Format() is declared as Format(format System.String arg0...

Listing The Remoting Helper Class

System.Collections, System.Runtime.Remoting TRemotingHeiper TRemotingHeiper class private fIslnitialized boolean fWellKnownTypes IDictionary function GetRemoteObjectRef(aType system.type) TObject end var entry WellKnownClientTypeEntry if not fIslnitialized then InitTypeCache entry fWellKnownTypes aType as WellKnownClientTypeEntry if (entry NIL) then raise Exception.Create('Type not found ') procedure TRemotingHelper.InitTypeCache var i integer 42 arr array of WellKnownClientTypeEntry 43 entry...

Adding Enumerated Properties to Components

You can edit user-defined enumerated properties and Boolean properties in the Object Inspector by double-clicking in the Value section or by selecting the property value from a drop-down list. An example of such a property is the FlatStyle property found on buttontype controls. To create an enumerated property, you must first define the enumerated type as follows You then define the internal storage field to hold the value specified by the user. Listing 13.3 shows new enumerated property types...

Working with Data Relations

DataReiations are similar to ForeignContraints in that they form a link between a parent table and a child table through which referential integrity can be enforced. In fact, when creating DataReiations, they implicitly create the ForeignConstraint instance in the Constraints collection. DataReiations go beyond the capabilities of ForeignConstraints in that they also support navigability between parent and child tables. This is particularly useful with data-bound controls. Through...

Working with View State

ViewState is the component of ASP.NET pages that keeps track of information such as server control properties. It is handled automatically you typically do nothing with it other than to disable it if you don't need it. It merits discussion here because there are things you can do to improve performance of your Web applications by making adjustments to ViewState. Plus, you can use that state bag to store custom information for these round-trips. Here's how ViewState works. When you fill out a...

Variant Types

The Variant class provides an implementation of a type capable of serving as a kind of container for many other types. This means that a variant can change the kind of data to which it refers at runtime. For example, the following code will compile and run properly Variants support a wide variety of types, including complex types such as arrays and interfaces. The following code from the Boriand.vci.variants unit shows the various supported types, which are identified by values known as...

Creating an Interop Assembly

The IDE does a fine job of creating Interop Assemblies, as you saw previously. However, some developers need to know how to perform these operations by themselves for example, in order to create batch building systems that use command-line tools. The IDE accomplishes its goals by creating a object and calling the ConvertTypeLibToAssembiy() method. This operation is also performed by the command-line Type Library to Assembly Converter tool, Tibimp.exe, installed as part of the .NET Framework SDK...

Value Reference and Optional Parameters

Things are quite straightforward with value parameters as used so far. However, things get messier when the Automation server supports a method that takes reference parameters because you must use an overloaded version of InvokeMember that takes more parameters. One of these parameters is an array containing a single ParameterModifier structure. This object needs to be constructed with a value that indicates how many parameters the method takes whereupon it allocates a Boolean array with that...

Emitting MSIL Through Reflection

The .NET framework provides you with the capability to create code on-the-fly through the System.Reflection.Emit namespace. The code that you create through Emit is MSIL code. Essentially, the functionality in this namespace gives you the ability to dynamically create an assembly and a module within that assembly. You can dynamically define any number of classes and methods within the assembly's module, and then invoke those methods at runtime (which will automatically be JIT compiled to very...

The HTTPCookie Class

The HTTPResponse and HTTPRequest classes have a Cookies property, which is a collection of cookies. Through this property, you would save and manage cookies on the client's computer. The following code demonstrates how to create a cookie in the Cookies collection hc HttpCookie.Create('Name', TextBoxl.Text) hc.Expires DateTime.Now.AddMonths(l) Labell.Text System.String.Format('Hello 0 ', TextBoxl.Text) end . SEE the entire example on the CD Code Chapter 25 Ex06 . In this example, an instance of...

The Data ViewManager Class

The DataViewManager class is basically the same in function as the DataView class except that it provides these capabilities across the entire DataSet. You can also use DataViewManager to create a DataView class for a table within the DataSet contained by the DataViewManager. Table 21.3 lists the key properties of the DataViewManager class. TABLE 21.3 DataViewManager Properties Property Description DataSet Gets or sets the DataSet that the DataViewManager represents. DataViewSettings Returns a...

System ReflectionEmit Example

Listing 15.8 illustrates the tasks involved in using the classes defined in System.Reflection.Emit to generate MSIL code. LISTING 15.8 Example of Using System.Reflection.Emit 11 asmBuilder AssemblyBuilder 14 methBuilder MethodBuilder 20 parms array of System.Type 22 wlTypes array of System.Type 23 SysConsoleType System.Type 26 Parms 0 typeof(System.String) 28 methBuilder typBuilder.DefineMethod('Main', MethodAttributes.Public 29 or MethodAttributes.Static, typeof(integer),...

Impersonization

When ASP.NET executes applications, it does so using the identity aspnet on Windows 2000 and Windows XP or network service under Windows 2003 Server. For non-ASP.NET applications (.html files or ISAPI CGI scripts), the IUSR_machinename account is used. The security level for this particular account is one that has limited access to files and folders required to enable ASP.NET to run properly. Developers of the application are expected to use some form of authentication to prohibit access to...

Dynamically Loading Assemblies

One of the more powerful features of assemblies is that they can be loaded not just statically as a reference from another assembly but also dynamically at runtime. This is accomplished by using .NET reflection to load the file from disk, find and create objects, and invoke methods. Listing 6.8 shows how this is done. LISTING 6.8 Dynamically Loading a Package ' (SystemRoot) microsoft.net framework *v1.1.4322 System.dll' 6 16 load the assembly based on the file name 17 a 18 use reflection to...

The Remoting Configuration Class

The RemotingConfiguration class contains static class methods for interfacing with configuration settings and register objects so that they can be remotely invoked. The following snippet of code registers the class TBankManager typeOf(TBankManager), 'BankManager.soap', WellKnownObjectMode.Singleton) More about this method is explained in the section Server Activation. Remoting settings can be programmatically set or can be read from external configuration files. The...

Changing an Images Resolution

You can change the resolution of an image by calling the SetResolution() method. Listing 7.17 illustrates using this method. LISTING 7.17 Using the SetResolution() Method procedure TWinForm1.ChangeResolution(g Graphics) var Bitmap.Create(MyBitmap) Bitmap.Create(MyBitmap) tmpBm1.SetResolution(600, 600) tmpBm2.SetResolution(120, 120) g.DrawImage(tmpBm1, 0, 0) g.DrawImage(tmpBm2, 100, 0) WriteStats end . Find the code on the CD Code Chapter 07 Ex03. The output from the code used in Listing 7.17 is...

Scalability and Fault Tolerance

The first and most prominent advantage of multitier architectures is scalability. Client server systems depend on a central database server and require permanent connections to be present. The more clients, the worse the server will perform because of the increased resource consumption (that is, network connections constantly open, frequent access to tables, cursors, and so on). Client server systems aren't usually capable of handling more than a couple of hundred concurrent users in an...

Resolving Generic Namespaces

The Delphi compiler must resolve identifiers used from other units to their containing unit. It does this by iterating through the units listed in the uses clauses. For units that have fully qualified namespaces, finding the unit is simple because the unit's scope is known. For generic units, the compiler resolves identifier names by going through the following search order 1. Current unit namespace (if exists) 2. Project default namespace (if exists) 3. The project's namespaces clause (in...

Using Sets

Use square brackets when constructing a literal set value from one or more elements. The following code demonstrates how to declare set type variables and assign them values TCharSet set of AnsiChar possible members 0 - 255 TEnum (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday) TEnumSet set of TEnum can contain any combination of TEnum members CharSet TCharSet EnumSet TEnumSet SubrangeSet set of 1 10 possible members 1 - 10 AlphaSet set of 'A' 'z' possible members 'A' - 'z'...

Role Based Authorization

A role based authorization model would give users entry into the system but would limit their access so that the pages they view would differ based on their role. How roles are stored is really a matter of the system requirements. A typical approach is to store users and roles in a database. The idea is that the ASP.NET application retrieves that information from the database and modifies the pages based on the roles that a user has. We'll examine a simple example that performs this type of...

Automatically Implementing IDisposable

Now that you have seen the long way of implementing IDisposable, this section shows how to do this using the destructor construct, which is familiar to Delphi developers and the method recommended by Borland. By writing a destructor that follows the specific format of destructor Destroy override the Delphi for .NET Compiler will automatically implement the IDisposable interface for your class. Let's take a look at the final version of the TCriticalSection class declaration TCriticalSection...

Listing Insert Product Stored Procedure

CREATE PROCEDURE InsertProduct ProductID int output, QuantityPerUnit nvarchar(20), UnitPrice money, SET NOCOUNT ON INSERT INTO Products ( ProductName, SupplierID, CategoryID, QuantityPerUnit, UnitPrice, UnitsInStock, UnitsOnOrder, ReorderLevel, Discontinued) VALUES ( SET ProductID Scope_Identity() SELECT ProductID ProductID return Find the code on the CD Code Chapter 22 Ex04. Listing 22.18 is the GetDataAdapterUpdateCommand(), which shows the creating of the SqiCommand instance associated with...

TABLE Additional Data List Control Templates Template Description

SelectedltemTemplate Formatting specified in this template is rendered for the item, or row, of the data source when an item is selected. EdititemTemplate Formatting specified in this template is rendered for the item, or row, of the 3 hitp toealhostVRpcater WcbFormi .asp* - Microsoft Internet Explorer f- f 5< 3 P Saarch -f - Favorites r Macia . J- i 13 1 j hHp J1ocahM RpMtcr WebFarmi , p* gj Go Lrte ** V g Search Web 'fi & > f * * & 285 bbcted Table 27.5 lists some key properties and...

Viewing Assembly Contents and Dependencies

The .NET SDK, which is freely available from Microsoft, contains a tool called ILDASM (Intermediate Language Disassembler) that allows you to peer inside an assembly to view its contents and dependencies. An assembly can be opened within ILDASM by passing its name on the command THE .NET FRAMEWORK CLASS LIBRARY DEVELOPMENT CHAPTER 6 Assemblies Libraries and Packages CHAPTER 8 Mono - A Cross Platform .NET Project Viewing Assembly Contents and Dependencies Using Delphi Assemblies in C Installing...

Constructing a Proxy Class

In this section, I discuss how to create a client application that consumes the latter two Web Services created earlier in this chapter. The steps are 1. Create the application and save it to a directory. 2. Add a Web Reference this will create the proxy class. Assuming that step 1 is completed, adding the Web Reference is simple. Simply select the project within the Project Manager in the IDE and invoke the local menu by right-clicking. One of the options is Add Web Reference (see Figure...

Controls ASPNET

ASP.NET Server Controls and Component, 790 list controls, pre-populating, 557-558 < Control > tag, 767-768 creating, 764-765 declaring, 766-767 LoginControl, 769-771 < Register > tag, 768-769 SimpleUserControl example, 764-769 UserControl class, 767 validation controls, 552 BaseValidator, 559 CompareValidator, 560-561 CustomValidator, 564 RangeValidator, 563-564 RegularExpressionValidator, 562-563 RequiredFieldValidator, 559-560 ValidationSummary, 565 Web controls, 552 composite...

The Page Layout

One of the initial considerations in developing a Web page is how it is going to look to the end user. This is not referring to what sort of look and feel from an artistic standpoint, but more from the standpoint of where controls are positioned in what order, and so forth. One must consider that various browsers might render your page differently therefore, you might want to be sure that you use the method that addresses most browsers. There are really three primary approaches to how you lay...

Using Data Reader to Retrieve Schema Information

The DataReader can be used to retrieve schema information using the SqlDataReader.GetSchemaTable() method. This method returns a DataTable that is populated with information about a resultset's columns. Therefore, each row in this schema resultset represents a column in the actual resultset. The schema row contains information about the column, such as its name, uniqueness, data type, and more. Listing 19.11 illustrates using this method. LISTING 19.11 Retrieving Schema Information program...

Comparing Strings

The easy way to compare strings is to simply use the equality operator as shown here if si s2 then Console.WriteLine('Strings are equal') Alternatively, you can use the String.Compare() method if (System.String.Compare(s1, s2) 0) then Console.WriteLine('Strings are equal') The return value of the Compare() method, if less than zero, indicates that s1 is less than s2. A value of zero indicates equality. Finally, a value of greater than zero indicates that s1 is greater than s2. The...

Increment and Decrement Procedures

Increment and decrement operators provide a convenient means to add to or subtract from a given integral variable. Delphi doesn't really provide honest-to-gosh increment and decrement operators similar to the C ++ and -- operators, but Delphi does provide procedures called Inc() and Dec() intended for this very purpose. You can call Inc() or Dec() with one or two parameters. For example, the following two lines of code increment and decrement variable, respectively, by 1 The following two lines...

Writing Threadsafe Code NET Style

Writing a multithreaded application is pointless if multiple threads cannot interact in a predictable and bug-free manner. A body of code is said to be thread-safe if multiple threads can safely execute it without any side effects. One way of making a method or function thread-safe is to serialize access to it, thereby allowing only one thread to execute the code at a time. Thread-safe code can be accomplished by following a few guidelines Avoid variables and objects shared between threads. If...

Early Bound COM

In order to do early binding in COM, you need to have something in addition to the COM server and its type library. The compiler needs to bind directly to some representation of the interfaces. Because we are dealing with a .NET compiler, you will need to manufacture some form of assembly to help it out. Such an assembly is called an Interop Assembly and can be generated from the type library through some support classes provided in the Microsoft .NET Framework. Fortunately, this is...

Web Service Construction

In this section, I will demonstrate the process of creating three types of Web Services. One will be a simple Web Service that returns the sum of two numbers. The second one will return a DataSet containing a table from the Northwind database. A third will demonstrate the use of the WebMethod attribute. For the most part, creating the initial files for the Web Service is a step-by-step process when using the wizard from Delphi for .NET. 1. Select File, New, Other from the main menu to launch...

Advantages Disadvantages

There are several advantages for using strongly-typed DataSets over untyped DataSets. They are Writing code is easier to understand because strong names make sense, and with code completion, it is further simplified. Developers write less code overall because named members are accessed directly rather than using indexer properties. Strongly-typed DataSets already contain schema information improving performance. The strong typing can prevent runtime errors that would occur because they will be...

Application Domains

Application Domains are at the core of the remoting infrastructure and represent the boundaries for Interprocess Communication (IPC). In classical Win32, Windows creates a new process when an executable is launched. Processes are the lowest level of isolation and cannot directly share memory between each other. Memory addresses are process relative Pointers to memory in one process are meaningless to another. Application Domains, or AppDomains, are to .NET what processes are to Win32....

Bezier Spline

The Bezier spline is particularly interesting and has many uses, including CAD CAM, animation, and postscript printing, just to name a few. I will demonstrate a simple curve, two recurves, and a loop using the Bezier. Listing 7.7 shows the code for the various forms of the Bezier curve. 1 procedure TWinForm.paintBezier 3 MyPointsAry array 0 4 of Point 5 if rbtnBSC.Checked then Simple curve 7 MyPointsAry 0 Point.Create(10, 200) 8 MyPointsAry 1 Point.Create(100,100) 9 MyPointsAry 2...

COM Lifetime Control

The lifetime of a COM object is controlled through reference counting, which is managed for you by the RCW. When a RCW gets garbage collected, the COM object reference count will drop to zero and will destroy itself. However, because you don't normally control when a garbage collection will occur, it is indeterminate when the COM object will be destroyed. Sometimes you need to deterministically dispense with a COM object, and this can be achieved by passing it to the static method...

Listing An Example of a Function and a Procedure

5 procedure BiggerThanTen(I Integer) 6 writes something to the screen if I is greater than 10 0 or positive, False if I is negative The local variable Result in the IsPositive() function deserves special attention. Every Delphi function has an implicit local variable called Result that contains the return value of the function. Note that unlike C 's return statement, the function doesn't terminate as soon as a value is assigned to Result. If you want to duplicate the behavior of C 's return...

Application State Management

Application state is different from session state in that data stored at the application level is available to all users of the application. In session state, session data is stored for the user of the session only. Figure 33.4 depicts this difference. Application state is maintained by the HttpApplicationState class. This class is a dictionary, and it is created upon the first request to the application. This is unlike the HttpSessionState class, which is created upon each user's visit to the...

The [Web Method Attribute Explained

In the previous example, you might have noticed the following line above the GetEmployees() method WebMethod(Description 'Gets the employees table') FIGURE 28.7 MySecondWebService output. FIGURE 28.7 MySecondWebService output. .Jbxk Q 3 g i p Search Favorites Media > v C & . http I calh il My5eiiiidweb5er v*e W b5erviee2. ainw GetErr > l ye Google-1 jVj ffcSeard < xml vers on a 1,0 encoding 'utf-B > - < DataSet - < hs schema id ' ew Data Set1 xmlns < xs element...

Listing Tsimple Factory Implementation

9 TSimpleFactory class(MarshalByRefObject, ISimpleFactory) 10 protected 11 function NewInstance ISimpleServer 12 function NewInstanceWithValue(Value Integer) ISimpleServer 23 function TSimpleFactory.NewInstance ISimpleServer 24 begin 28 function TSimpleFactory.NewInstanceWithValue( 29 Value Integer) ISimpleServer 30 begin 31 result TSimpleServer.Create(Value) . Find the code on the CD Chapter 30 Ex02. The concrete class TSimpleFactory is used only in the server application, and it is...

Using the Panel Control for Multiform Simulation

Occasionally, you must create forms that request a lot of data from users, such as a survey. One might be inclined to use multiple .aspx Web forms in order to avoid forcing the user to scroll through a single lengthy form. This might be impractical given that not only must you manage multiple forms, but you must also store all the data the user is entering between forms for later use. An easier approach would be to use sections of a single form, which are toggled between visible and invisible...

System ThreadingApartment State Enumeration

The .NET Framework creates an apartment when it interacts with COM objects. This apartment is specified in one of two ways. For manually created threads, the ApartmentState property can be set to the appropriate ApartmentState enumeration. These values are listed in Table 14.3. TABLE 14.3 Values of the System.Threading.ApartmentState Enumeration Unknown Currently mapped to MTA Once the ApartmentState property has been set, it cannot be changed again. No error or exception will result from...

Another Example of Member Invocation

Listing 15.7 illustrates another example of invoking the members of a type through reflection. LISTING 15.7 Member Invocation 8 TOnWriteEvent procedure of object 9 14 FOnWriteEvent TOnWriteEvent 17 constructor Create(aStr String aInt Integer 21 property IntProp Integer read FIntProp write FIntProp 22 property StrProp String read FStrProp write FStrProp 23 property OnWriteEvent TOnWriteEvent read FOnWriteEvent 27 constructor TMyType.Create(aStr String aInt Integer aStr2 String) 36 procedure...

Nested Transactions

For data providers that support them, nested transactions are an alternative to savepoints. A nested transaction is created by invoking the Begin() method of the transaction object as shown in the following skeleton code oledbTransOuter oleDBConn.BeginTransaction try oledbTranslnner oledbTransOuter.Begin inner updates oledbTransInner.Commit except Note that nested transactions are not supported by the SqlTransaction but are potentially with the OleDBTransaction. Support for transaction nesting...

Listing Alarm ClockEvent Creation

6 System.Drawing, System.Collections, System.ComponentModel, 10 AlarmEventArgs class(EventArgs) 14 property Time DateTime read FTime write FTime 17 AlarmHandler procedure (Sender TObject e AlarmEventArgs) of object 18 19 AlarmClock 21 FTimer Timer internal timer 22 FAlarm AlarmHandler alarm event 24 procedure TimerHandler(Sender TObject e EventArgs) tick handler 25 function GetCurrentTime DateTime 26 procedure SetEnabled(Value Boolean) 27 function GetEnabled Boolean 28 procedure...

Reference Parameters

Delphi enables you to pass variables to functions and procedures by reference parameters passed by reference are also called variable parameters. Passing by reference means that the function or procedure receiving the variable can modify the value of that variable. To pass a variable by reference, use the keyword var in the procedure's or function's parameter list procedure ChangeMe(var x longint) begin x 2 x is now changed in the calling procedure end Instead of making a copy of x, the var...

Windows Authentication

Before getting into how to secure your application through ASP.NET, now is a good time for a primer on the Windows role-based security model. In Windows, you grant users access to the system via an identity. Some refer to this as a user account. You have the ability to grant an identity access to various resources within the system or to the system itself (authentication). After access is granted, you can give each identity varying capabilities (authorization). For instance, an identity may...

Savepoints

In some cases, you might need to roll back only a portion of a transaction. Assuming that the data source supports this, you can use savepoints. A savepoint is equivalent to the following Transact-SQL statement To create a savepoint, you use the transaction's Save() method, passing a name of the savepoint. To roll back a savepoint, call the Rollback() function passing the same name used in the Save() method as shown here sqlTrans sqlcn.BeginTransaction try Note that the exception should not be...

Error Handling

As has been mentioned, many of the regular Win32 APIs already have P Invoke import declarations in import units such as Borland.Vcl.Windows. These are set up appropriately for you to use, but occasionally you might require an API that is not covered by the provided import units. Clearly, you can write your own import declaration, but there are one or two issues with regard to error handling with Win32 routines that need to be addressed. The Windows API is not consistently organized with regard...

Listing Declaration of the System ThreadingReader WriterLock Class

System.Threading.ReaderWriterLock class (System.Object) constructor Create procedure AcquireReaderLock(millisecondsTimeout Integer) overload procedure AcquireReaderLock(timeout TimeSpan) overload procedure AcquireWriterLock(millisecondsTimeout Integer) overload procedure AcquireWriterLock(timeout TimeSpan) overload procedure ReleaseReaderLock procedure ReleaseWriterLock LockCookie overload function UpgradeToWriterLock(timeout TimeSpan) LockCookie overload procedure DowngradeFromWriterLock(var...

Peertopeer

Peer-to-peer indicates networks without a central server in which each computer acts as a client and a server at the same time. A Windows workgroup without a domain server is a peer-to-peer network, for instance. This type of architecture generally only works in local area networks and depends on frequent UDP broadcasts to make each node aware of the status of the others. These broadcasts are normally not possible over the Internet. Figure 29.3 depicts the peer-to-peer network.

How Serialization Works

A class can be serializable by one of two ways. It can be declared with the Seriaiizabie attribute, or it can implement the iSeriaiizabie interface. This chapter discusses the former and easier method of applying the Serializable attribute. You can visit http www. DeiphiGuru.com for an example of iSerializable implementation in Delphi for .NET. Consider the following class Serializable TCiassicCar class(System.Object) public CarName String Manufacturer String Yearlntroduced DateTime In this...

Lifetime Management

Managing the lifetime of a remote object is complex, but having control over when to release server resources is essential to the scalability and efficiency of any distributed system. Historically, DCOM used a combination of reference counting and network pinging in order to determine when to free objects. While this technique worked decently enough in LAN's with few clients, it resulted in problems when the number of clients increased (think in thousands) and was practically unfeasible over...

The System ThreadingWait Handle Class

Before discussing mutexes and monitors, it is necessary to begin with the WaitHandle class as these two locking mechanisms inherit common functionality from it. Listing 14.7 contains the definition of the WaitHandle class. LISTING 14.7 Declaration of the System.Threading.WaitHandle Class System.Threading.WaitHandle class (System.MarshalByRefObject, IDisposable) public constructor Create procedure Close virtual function WaitOne Boolean overload virtual function WaitOne(timeout TimeSpan...

H

H format specifier, 236 H option (XCOPY), 720 HasDefVal() function, 48 HashPasswordForStoringInConfigFile() method, 706 HashTable collection, 209-212 HatchBrush class, 130 headers Headers property (MailMessage class), 576 HeaderText property (ValidationSummary class), 565 Height property (WebControl class), 566 HttpApplicationState class, 760-762 HTTPCookie class, 548-549 HTTPResponse class, 536-537, 544-547

Drawing Lines

When drawing lines, you can give them varying attributes such as color, line width, and so on. Additionally, using different brushes, you can vary the line's texture and color. Listing 7.2 illustrates some of these techniques. lgBrush LinearGradientBrush txBrush TextureBrush img Image begin MyPen.Color Color.Red yPos 10 MyGraphics.DrawLine(MyPen, 10, yPos, Panel1.Width-10, yPos) inc(yPos, 20) end draw a line using a different brush MyPen.Width 20 Point.Create(Panel1.Width-10, 10), Color.Black,...

Using NET Routines in Win Code

The CLR offers support for the opposite of what Platform Invoke offers, which is to expose .NET static methods to the unmanaged Win32 world. These are often referred to as unman-aged exports. Unmanaged exports are implemented by the CLR using the exact inverse of its P Invoke mechanism which is why the support is sometimes referred to as Inverse P Invoke. A Win32 application can import these exposed routines in the same way as with any regular DLL exported routines. The support for this CLR...

Listing Web Service Demonstrating a Data Set Result

Function TWebService2.GetEmployees DataSet const c_cnstr c_sel 'Select * From employees' var sqlcn SqlConnection sqlDA SqlDataAdapter ds DataSet begin try sqlcn SqlConnection.Create(c_cnstr) sqlDA SqlDataAdapter.Create(c_sel, sqlcn) ds DataSet.Create sqlDA.Fill(ds, 'employees') sqlcn.Close Result ds except . Find the code on the CD Code Chapter 28 Ex02. You should recognize this process of retrieving a DataSet from Northwind. Line 17 is the significant line that returns the DataSet class, which...

Using Assemblies in Delphi

Using assemblies similar to the ones just shown is a straightforward process. The first step is to add a reference to the assembly in the project by selecting Project, New Reference from the main menu or right-clicking in the Project Manager and selecting Add Reference After the reference is added, the appropriate namespaces can be added to the uses clause. Listing 6.6 shows a sample project unit that uses both the package and library assemblies created previously. Code from these assemblies is...

Interop Assemblies

Borland Socket Server Com

The act of adding a reference to a type library to a Delphi for .NET project (usually) causes the IDE to generate an Interop Assembly using the type library importing support in the .NET Framework. If you were using the command-line compiler, you would need to perform this step yourself, as discussed next. The SAPI 5.x type library is linked into the in-proc COM server sapi.dll, but the type library specifies that the library name is actually SpeechLib. This can be verified by opening the file...

The [Web Service Attribute

When you create a Web Service, three properties of a Web Service get default values. You should change these values prior to publishing your Web Service. These properties are the description, the name, and the namespace. In Figure 28.3, you'll see that the Web Service name is WebService1 and the namespace is the default of http tempuri.org . You should especially change the default namespace before releasing your Web Service to production. A convention to use is to form the namespace using a...

Listing Transaction Example

1 procedure TWinForm.Button1_Click sender System.Object 7 bdpCn BdpConnection.Create cnStr 10 bdpTrans bdpCn.BeginTransaction . Find the code on the CD Code Chapter 24 Ex06. On line 10, a transaction is created. Any database activities that occur between line 10 and line 13 would occur within the context of the transaction and would be committed on line 13. If a failure occurs an exception is raised , the except block will get invoked and the transaction will roll back all pending actions.

Listing Animation Demo Implementation

Procedure TWinForm.Step1_Click1 sender System.Object procedure TWinForm.Step2_Click sender System.Object e System.EventArgs begin MoveSaucer procedure TWinForm.ClearSky_Click sender System.Object procedure TWinForm.Animate_Click sender System.Object FAnimate not FAnimate if FAnimate then procedure TWinForm.Timer1_Tick sender System.Object if FAnimate then begin Step1_Erase false MoveSaucer Step2_DrawSaucerTrans false Step3_DrawSaucerPos false end end inherited Create InitializeComponent 162...

Listing Hash Table Example

Program d4dnHashTable APPTYPE CONSOLE System.Collections, Borland.Vcl.SysUtils Define a class to store in the HashTable TStateInfo class StateName String StateCapital String Admission TDateTime constructor Create aName, aCapital String aAddmision TDateTime end procedure PrintStateInfo aKey String var First retrieve the TStateInfo item from the HashTable si htDemo aKey as TStateInfo Print out its contents Console.WriteLine Format 'State s, Capital s, Admission si.StateName, si.StateCapital,...

Late Bound Automation

In Delphi for Win32, we orchestrate a late bound Automation session using a Variant. A Variant can be initialized with a call to CreateOleObject from the ComObj unit , which itself is passed an Automation object's class string or ProgID. For example, the entry point to the Microsoft Word Automation hierarchy is the ProgID 'Word.Appiication1. CreateOieObject returns a reference to the IDispatch interface implementation in the instantiated Automation object and this is duly stored in the Variant...

Listing Page Load and Get Data

2 TWebForml class System.Web.UI.Page 4 procedure Page_Load sender System.Object e System.EventArgs 10 function GetSupplierName aSupplierID Integer String 16 c_cnstr 17 c_sel_prod 'SELECT FROM products' 18 c_sel_sup 'SELECT companyname, supplierid FROM suppliers' 19 20 procedure TWebForm1.Page_Load sender System.Object e System.EventArgs 27 Session.Add 'SelStr', SelStr 32 procedure TWebForm1.GetData 610 CHAPTER 27 Building Database Driven ASP.NET Applications LISTING 27.15 Continued 43 SelStr...

Listing Data Grid Page

1 TWebForml class System.Web.UI.Page 2 procedure DataGrid1_PageIndexChanged source System.Object e 606 CHAPTER 27 Building Database Driven ASP.NET Applications LISTING 27.12 Continued 5 procedure Page_Load sender System.Object e System.EventArgs 13 procedure TWebForm1.Page_Load sender System.Object e System.EventArgs 20 e 22 DataGrid1.CurrentPageIndex e.NewPagelndex 26 procedure TWebForm1.GetData 28 c_cnstr 29 c_sel 'select from customers' 36 sqlcn SqlConnection.Create c_cnstr 37 sqlDA...

ADONET with Mono

Our next example application demonstrates a Web application accessing information in a database, combining the capabilities of ASP.NET, ADO.NET, and Mono. The example consists of a Login Web form to establish database access and an Employees Web form to display the information from the database. The example requires access to MS SQL Server and the Northwind database. In the example, the user is asked for SQL server login information. This is purely for illustrative purposes. In a production...

Register WellKnown ServiceType method

RegistrationServices class, 373 regular methods, 89 RegularExpressionValidator class, 562-563 reintroduce statement, 90-91 reintroducing method names, 90-91 ReleaseComObject method, 369 ReleaseMutex method, 323-324 remotable objects activation, 654-655 Context-bound, 653 Marshall-By-Reference objects, 653-654 Marshall-By-Value objects, 654 well-known objects, 654 Remote Procedure Call RPC , 644 RemoteAt method, 439 RemotingConfiguration class, 652 Remove method, 199, 227-229, 439, 744, 761...

Using Win DLL Exports in NET Code

Aside from using COM objects in .NET code, there is a common requirement to use regular Win32 DLL routines. These could be aspects of the Win32 API that are not already made available though the .NET Framework Class Library or could be routines from arbitrary DLLs written by yourself or a third party. Examples of the former might include the high performance timing APIs, QueryPerformanceCounter and QueryPerformanceFrequency. Another example is the simple API that makes a beep Beep. Technically...

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 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 Web Service 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 File SystemWatcher 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...