Overview of XDR Schemas

The example XML document data_dtd.xml used to demonstrate DTDs contains information about the modules in which a given class is articulated. The following listing shows the XDR schema that provides a full description of the class lt xml version 1.0 gt lt AttributeType name title dt type string gt lt AttributeType name company dt type string gt lt AttributeType name author dt type string gt lt AttributeType name total dt type int gt lt AttributeType name expandable dt type enumeration dt values...

The DataRow Error Programming Interface

The tables in this section provide a quick overview of the properties and methods available in the DataRow class for setting and getting error messages. These messages are then tracked in the lt diffgr errors gt section of the DiffGram. Table 10-5 lists the error-related properties of the DataRow class. Table 10-5 Error-Related DataRow Properties Table 10-5 Error-Related DataRow Properties Indicates whether the row contains errors Gets or sets a custom error description for the row The...

Customizing Column Mapping

Each row in a DataTable object originates an XML subtree whose structure depends on the value assigned to the DataColumn object's ColumnMapping property. Table 9-3 lists the allowable column mappings. Table 9-3 The MappingType Enumeration Table 9-3 The MappingType Enumeration The column is mapped to an XML attribute on the row node. The column is mapped to an XML node element. The default setting. Table 9-3 The MappingType Enumeration Table 9-3 The MappingType Enumeration The column is not...

The XmlNode Base Class

When you work with XML DOM parsers, you mainly use the XmlDocument class. The XmlDocument class, however, derives from a base class, XmlNode, which provides all the core functions to navigate and create nodes. XmlNode is the abstract parent class of a handful of node-related classes that are available in the .NET Framework. Figure 5-2 shows the hierarchy of node classes. Figure 5-2 Graphical representation of the hierarchy of node classes and their relationships in the .NET Framework. Figure...

Reading Back DiffGrams

When reading a DiffGram, the DataSet object's ReadXml method first loads the data instance and creates all the necessary tables and rows. Each row is put in the added or modified state, as appropriate. All the diffgr id values are temporarily copied into an internal hash table defined as a property of the DataSet object. Each entry in the hash table references a DataRow object in the table being created. Next ReadXml processes the lt diffgr before gt section and reads the old values for the...

Implementing an ADO Recordset XML Writer

In Microsoft ADO.NET, the OleDbDataAdapter class allows you to import the contents of an ADO Recordset object into one or more DataTable objects. This kind of binding is unidirectional, however. You can import recordsets into ADO.NET objects, but you can't create an ADO Recordset object starting from, say, a DataSet or a DataTable object. The two-way binding between ADO.NET and ADO is important because it can save you from planning hasty porting of Windows Distributed interNet Applications dNa...

Writing Encoded Data

As mentioned in the section Methods of the XmlWriter Class, on page 141, the XML text writer object has two methods that write out XML data in a softly encrypted way using base64 and BinHex algorithms. The methods involved WriteBase64 and WriteBinHex have a rather straightforward interface. They simply take an array of bytes and write it out starting at a specified offset and for the specified number of bytes. As you saw in Chapter 2, XML reader classes have matching ReadBase64 and ReadBinHex...

The WebService Attribute

The WebService attribute is optional and does not affect the activity of the Web service class in terms of what is published and executed. The WebService attribute is represented by an instance of the WebServiceAttribute class and enables you to change three default settings for the Web service the namespace, the name, and the description. The syntax for configuring the WebService attribute is declarative and somewhat self-explanatory. Within the body of the WebService attribute, you simply...

The MarshalByRefObject Class

Inheriting from the MarshalByRefObject class is the key that enables user classes to be accessed across AppDomain boundaries in applications that support remoting. MarshalByRefObject is the base class for objects that communicate across AppDomains. Serializable classes that do not inherit from MarshalByRefObject, when instantiated from a remote assembly, are implicitly marshaled by value. Other classes are simply considered nonremotable. So if you want to write a remote component that uses the...

The XmlRecordsetWriter Programming Interface

The XmlRecordsetWriter class embeds an instance of the XmlTextWriter class but does not inherit from it. All the hard work of creating the XML output is accomplished through the internal writer, but the class programming interface is completely customized and largely simplified. By design, the set of constructors of the XmlRecordsetWriter class is nearly identical to the constructors of the XmlTextWriter class, as shown here public XmlRecordsetWriter string filename Writer new XmlTextWriter...

Schema Information in the DiffGram

In general, the schema and the data should be kept in separate files and handled as truly independent entities. The schema and the data are tightly coupled, and if serialization is involved, you might want to consider putting schema information in-line in the data. In the .NET Framework, the WriteXml method does not provide the capability to include schema information along with the data. This is more of a design choice than an objective difficulty. An indirect confirmation comes from the XML...

Using an Annotated Mapping Schema

A more lightweight alternative to FOR XML EXPLICIT views is the annotated schema. SQL Server 2000 lets you create XML views by defining an XDR schema with special annotations that work like placeholders for selected data. Basically, instead of defining the schema using a new syntax and combining multiple virtual tables, you use a standard XML data definition language and map elements to columns using ad hoc annotations. The base version of SQL Server 2000 supports only XDR. If you want to use...

Supported Validation Types

What are the key differences between the validation mechanisms DTD, XDR, and XSD supported by the XmlValidatingReader class Let's briefly review the main characteristics of each mechanism. DTD A DTD is a text file whose syntax stems directly from the Standard Generalized Markup Language SGML the ancestor of XML as we know it today. A DTD follows a custom, non-XML syntax to define the set of valid tags, the attributes each tag can support, and the dependencies between tags. A DTD allows you to...

The FOR XML RAW Mode

As its name suggests, the FOR XML RAW mode is the least rich mode in terms of features and options. When designed using this mode, the query returns an XML fragment that, at a first glance, might look a lot like the fragment produced by the FOR XML AUTO option. You obtain an XML fragment made of lt row gt nodes with as many attributes as the columns. For example, consider the following simple query SELECT CustomerID, ContactName FROM Customers FOR XML RAW The output is shown here lt row...

The NET XPath Navigation API

The XML DOM support for XPath expressions has a double goal. First, it smooths the transition from MSXML COM code to the .NET Framework. Second, it gives you a built-in and easy-to-use mechanism to search for nodes in a memory-mapped XML document. As mentioned, the core .NET API for processing XPath expressions is built into a tailor-made class named XPathNavigator. You access the navigator object either from the XmlDocument class or from the newest XPathDocument class. Figure 6-5 illustrates...

The XSD keyref Element

In XSD, the keyref element allows you to establish links between elements within a document in much the same way a parent child relationship does. The WriteXml method uses keyref to express a relation within a DataSet object, as shown here lt xs keyref name Emp2Terr refer Constraint1 gt lt xs selector xpath . Territories gt lt xs field xpath employeeid gt The name attribute is set to the name of the DataRelation object. By design, the refer attribute points to the name of a key or unique...

The XML DOM Node Retrieval API

When using XPath queries to query an XML DOM instance, you can use the SelectNodes method of the XmlDocument class. In particular, SelectNodes returns a collection that contains instances of all the XmlNode objects that match the specified expression. If you don't need the entire node-set, but instead plan to use the query to locate the root of a particular subtree, use the SelectSingleNode method. SelectSingleNode takes an XPath expression and returns a reference to the first match found. The...

Mapping Data Structures to XML Nodes

For a long time, INI files have been a fundamental part of Microsoft Windows applications. Although with the advent of Microsoft Win32 they were officially declared obsolete, a lot of applications have not yet stopped using them. Understanding the reasons for this persistence is not of much importance here, but when they were designing the .NET Framework, the Microsoft architects decided not to insert any managed classes to handle INI files. Although overall I agree with their decision, keep in...

The XmlSerializer Classs Constructors

Table 11-1 lists all the public constructors available in the XmlSerializer class. This list does not include the default class constructor because it is declared as protected and, as such, is not intended to be used directly from the user's code. Table 11-1 Constructors of XmlSerializer Serializes objects of the specified type. Allows you to customize the default mapping between properties and XSD elements. Adds type information to elements. Useful if you don't have the source code for the...

The XmlEnum Attribute

If your class definition contains an enumeration type, the XmlEnum attribute lets you modify the named constants used to define each value member, as shown here XmlEnum Name AisleSeat Aisle, XmlEnum Name CentralSeat Central, XmlEnum Name WindowSeat Window You use the Name property to modify the name of the enum member. The XML Schema Definition Tool Installed as part of the .NET Framework SDK, the XML Schema Definition Tool xsd.exe has several purposes. When it comes to XML serialization, the...

SqIXmlCommand Methods

On instantiation, the SqlXmlCommand class creates an instance of the SQLXMLOLEDB provider. Interestingly, it does not make use of an explicit wrapper assembly but instead gets a COM object type using the static method GetTypeFromCLSID from the Type class. Next it instantiates the COM object using the Activator class. Note The Activator class contains methods to create types of objects locally or remotely, or obtain references to existing remote objects. Functionally equivalent to the new...

XPath Iterators

When the XPath expression originates a node-set, the navigator object always returns it using a new breed of object the node iterator. The node iterator is a relatively simple object that provides an agile, common interface to navigate an array of nodes. The base class for XPath iterators is XPathNodelterator. The node iterator does not cache any information about the identity of the nodes involved. It simply works as an indexer on top of the navigator object that operated the XPath query. All...

Namespace Node Navigation

As you might have noticed in Table 6-4, there are three types of move methods for element, attribute, and namespace nodes. Calling the wrong method on a node causes the whole operation to fail, and there is no change in the position of the navigator. Only MoveTo and MoveToRoot can be called on any node, irrespective of the type. In addition, attributes and namespaces also have ad hoc methods to return their values GetAttribute and GetNamespace. When you call either MoveToFirstNamespace or...

Updategrams and DiffGrams

If you're familiar with ADO.NET, you'll no doubt notice a close similarity, both conceptual and physical, between Updategrams and DiffGrams. Although aDo.NET DiffGrams are a newer format and perhaps the format of the future currently, SQL Server 2000 natively supports only Updategrams. In the section SQLXML Managed Classes, on page 386, we'll take a quick tour of the managed classes in SQLXML 3.0. You'll notice that some of these classes apparently enable you to send DiffGrams to SQL Server....

The SqlXmlAdapter Class

The SqlXmlAdapter class is a shrink-wrapped adapter class. It does not implement the IDataAdapter interface, so technically speaking, it can't be presented as an adapter object. Nevertheless, the class provides adapter-like methods such as Fill and Update, as shown in the following code. These are also the only public methods for the class. The SqlXmlAdapter class also provides three constructors, shown in the following code, whose signatures reinforce the idea that this adapter is a mere...

The Proxy Class

The proxy class generated for a Web service is added to the project and is in effect a local class. The difference in the remoting architecture is that .NET Remoting uses a dynamically generated class whose method information is hard-coded in the object information being marshaled the ObjRef object. With a Web service, there is no dynamic class creation. The following source code represents the proxy for the Sales Report Web Service using System.Xml.Serialization using...

What the XmlWriter Class Cant Do

Although powerful and considerably feature-rich, an XML writer is not perfect it still leaves some margin for errors. To be more precise, the XmlWriter class certainly generates 100-percent well-formed code, but only if you pass on correct information. In particular, an XML writer does not check for invalid characters in element and attribute names. It also does not guarantee that any Unicode characters you use fit into the current encoding schema. As a consequence, any characters outside the...

StringWriter and Unicode Encoding

The XML output generated by the GetSalesReportBarChart method uses the Unicode encoding scheme UTF-16 instead of the default UTF-8. This would be fine if not for the fact that Microsoft Internet Explorer returns an error when you double-click the XML file. The error has nothing to do with the XML itself it is more a bug or perhaps even a feature of Internet Explorer and the internal style sheet Internet Explorer uses to display XML documents. In general, UTF-16 is used whenever you write XML...

Activation Policies

In addition to the remotable object's identity, channels, and ports, the server configuration file also contains another important piece of information the object activation policy. An MBR remotable object can be either server-activated or client-activated. Server-activated objects are created by the server only when the client invokes the first method through the local proxy. Client-activated objects are created on the server as soon as the client instantiates the object using either the new...

The XML Layout of the Configuration Settings

The data corresponding to plug-in modules is stored in a section group named TypicalWinFormsApp. The actual section is named PlugIns. Each plug-in module is identified by an assembly name, a class name, and display text. The display text constitutes the caption of the menu item, whereas the assembly name and the class name provide for a dynamic method call. As mentioned, in a realworld scenario, you might force the class to implement a particular interface so that it's clear to the calling...

Further Reading Owf

Object serialization and ADO.NET are the key topics of this chapter. You'll find a lot of books out there covering ADO.NET from various perspectives. I recommend Microsoft ADO.NET, Core Reference, by David Sceppa Microsoft Press, 2002 . It's more difficult to locate a book that provides thorough coverage of object serialization. Chapter 11 in Programming Microsoft Visual Basic .NET, Core Reference, by Francesco Balena Microsoft Press, 2002 , is an excellent and self-contained reference. If you...

The XslTransform Class

Now that we've seen how the XslTransform class implements the .NET Framework processor to transform XML data into arbitrary text using XSL style sheets, let's look more closely at its programming interface. As shown in the following code, XslTransform has only the default constructor. In addition, it is a sealed class, meaning that you can use it only as is and other classes can't inherit from it. The programming interface of the class is fairly simple and consists of just one public property...

The SoapRpcMethod Attribute

The RPC format is expressed by the SoapRpcMethod attribute and specifies that all parameters are encapsulated within a single XML element named after the Web service method, as shown in the following code. The RPC style does not support the Literal binding mode only the SOAP-encoded binding mode Encoded is accepted. POST salesreport SalesReportService.asmx HTTP 1.1 Content-Type text xml charset utf-8 Content-Length length SOAPAction xmlnet cs 0735618 011 GetSalesReportBarChart lt xml version...

The DiffGram Viewer Application

To fully demonstrate the workings of XML DiffGrams, nothing is better than taking a DataSet object, entering some changes, and seeing how the corresponding DiffGram representation varies. For this purpose, I created the DiffGram Viewer Windows Forms application, shown in Figure 10-3. The application is available in this book's sample files. . rittrsj3 t FCIE iiplayiirtcciccTifi P Ctam rw'id iilniin N jnr lii Ihi D JL Sii P Ctam rw'id iilniin N jnr lii Ihi D JL Sii -.fliffsn 'iLffgiis ti ji...

The FOR XML AUTO Mode

The AUTO mode returns data packed as XML fragments that is, without a root node. The alias of the table determines the name of each node. If the query joins two tables on the value of a column, the resulting XML schema provides nested elements. Let's consider the following simple query SELECT CustomerlD, ContactName FROM Customers FOR XML AUTO The XML result set has the form shown here lt Customers CustomerID ALFKI ContactName Maria Anders gt lt Customers CustomerID ANATR ContactName Ana...

The XPathNavigator Class

The programming interface of the navigator object is defined in the XPathNavigator abstract class. The XPathNavigator class represents a generic interface designed to act as a reader for any data that exposes its contents as XML. Functionally speaking, the XPathNavigator class is not much different from a pseudo-class that simply groups together all the XML DOM methods ChildNodes, SelectNodes, and SelectSingleNode to navigate the document contents. The big difference lies in the fact that...

Validating Against an XDR

An XML document can include its XDR schema as in-line code or simply link it as an external resource. The XmlValidatingReader class determines that a given document requires XDR validation if an x-schema namespace declaration is found. The following sample document, named data_xdr.xml, points to an XDR schema stored in an external resource the schema.xml file lt xml version 1.0 gt lt -- Sample XML document data_xdr.xml using XDR -- gt lt class title Applied XML Programming for .NET 5 expandable...

Adapting Data to Classes

Reading incoming XML data is itself a kind of deserialization. However, as we've seen, the XML deserializer can only re-create an instance of the type you pass when you create the XmlSerializer object. How can you comply with any difference in the schema of the target class and the incoming XML data That task is handled by the attribute overrides process for the XMLSerializer object, shown in Figure 11-2. Attribute overrides and or deserialization hooking Figure 11-2 Attribute overrides are...

Encoding Images as BinHex

Converting a Bitmap object to one of the commonly used image formats is a nonissue. You call the Save method on the Bitmap object, pick up one of the supported formats, and you're done. The real difficulty has to do with the planned use of this helper class. Remember, we designed this class for later use within a .NET Remoting server and a Web service. When Web services in particular are involved, having the helper class save the image to persistent storage just doesn't make sense. An...

Using MSXML in the NET Framework

As with other COM objects, you can import the MSXML type library within the boundaries of a .NET application. The layer of system code providing for COM importation in the .NET Framework is the COM Interop Services CIS . CIS provides access to existing COM components in a codeless and seamless way, without requiring modification of the original component. The CIS consists of two distinct parts one part makes COM components usable from within .NET applications, and the other part does the...