ASP.NET MVC 3: Razor’s @: and syntax

Razor minimizes the number of characters and keystrokes required when writing a view template, and enables a fast, fluid coding workflow. Unlike most template syntaxes, you do not need to interrupt your coding to explicitly denote the start and end of server blocks within your HTML. The Razor parser is smart enough to infer this from your code. This enables a compact and expressive syntax which is clean, fast and fun to type.

For example, the Razor snippet below can be used to iterate a list of products:

mvc_syntax_1

When run, it generates output like:

mvc_syntax_2

One of the techniques that Razor uses to implicitly identify when a code block ends is to look for tag/element content to denote the beginning of a content region.  For example, in the code snippet above Razor automatically treated the inner <li></li> block within our foreach loop as an HTML content block because it saw the opening <li> tag sequence and knew that it couldn’t be valid C#. 

This particular technique – using tags to identify content blocks within code – is one of the key ingredients that makes Razor so clean and productive with scenarios involving HTML creation.

Using @: to explicitly indicate the start of content

Not all content container blocks start with a tag element tag, though, and there are scenarios where the Razor parser can’t implicitly detect a content block.

Razor addresses this by enabling you to explicitly indicate the beginning of a line of content by using the @: character sequence within a code block.  The @: sequence indicates that the line of content that follows should be treated as a content block:

mvc_syntax_3

As a more practical example, the below snippet demonstrates how we could output a “(Out of Stock!)” message next to our product name if the product is out of stock:

mvc_syntax_4

Because I am not wrapping the (Out of Stock!) message in an HTML tag element, Razor can’t implicitly determine that the content within the @if block is the start of a content block.  We are using the @: character sequence to explicitly indicate that this line within our code block should be treated as content.

Using Code Nuggets within @: content blocks

In addition to outputting static content, you can also have code nuggets embedded within a content block that is initiated using a @: character sequence. 

For example, we have two @: sequences in the code snippet below:

mvc_syntax_5

Notice how within the second @: sequence we are emitting the number of units left within the content block (e.g. - “(Only 3 left!”). We are doing this by embedding a @p.UnitsInStock code nugget within the line of content.

Multiple Lines of Content

Razor makes it easy to have multiple lines of content wrapped in an HTML element.  For example, below the inner content of our @if container is wrapped in an HTML <p> element – which will cause Razor to treat it as content:

mvc_syntax_6

For scenarios where the multiple lines of content are not wrapped by an outer HTML element, you can use multiple @: sequences:

mvc_syntax_7

Alternatively, Razor also allows you to use a <text> element to explicitly identify content:

mvc_syntax_8

The <text> tag is an element that is treated specially by Razor. It causes Razor to interpret the inner contents of the <text> block as content, and to not render the containing <text> tag element (meaning only the inner contents of the <text> element will be rendered – the tag itself will not).  This makes it convenient when you want to render multi-line content blocks that are not wrapped by an HTML element. 

The <text> element can also optionally be used to denote single-lines of content, if you prefer it to the more concise @: sequence:

mvc_syntax_9

The above code will render the same output as the @: version we looked at earlier.  Razor will automatically omit the <text> wrapping element from the output and just render the content within it. 

Five key trends in the developer economy

image

The Developer Megatrends report series distills the major data points and insights from our research into the most important trends in the developer economy. In this 7th edition Megatrends report, we cover app business models and examine how developers can escape the poverty trap. We look at how consumer technology will invade the enterprise, and how data will be at the center of the most interesting apps in the coming years. We’ll also revisit experience roaming – a trend from 2010 that is now in full swing.

One thing is clear. Developers are a driving force in every industry and a critical source of competitive advantage. Every company should master developer ecosystem skills. Developer Megatrends H1 2015 will shed light on the state of the art in the developer economy.

KEY INSIGHTS
  • Developers are a driving force in every industry and a source of competitive advantage. Every company should master developer ecosystem skills.
  • App stores alone cannot sustain developers. e-commerce is and will stay the winning app revenue model.
  • App and IoT developers will take consumer technology and business models to solve the most important enterprise problems (and dodge the poverty trap in the process).
  • Value in tomorrow’s apps will come from making sense of data. Data developers and data platforms will be king.
  • Mobile ecosystem winners are fully leveraging their developer and user bases to win in the Internet of Things.
  • In the future, IoT device selection by consumers and enterprises will be determined by “will it work with my existing services and devices”. We call this experience roaming.
CONTENTS
  • Developers are kingmakers in every industry
  • Developers escape from the app store
  • Developers escape consumer markets
  • Apps escape from screens
  • Platform players escape from mobile

image

Using the UpdateProgress to lock down controls in the browser

If it takes awhile for the server to process the postback (e.g. complex rules or badly written code ), the user may not realize that the server is processing the request. This can lead to all kinds of issues with users that are not savvy or familiar with web applications (multiple clicks, moving off the page, etc.). Consequently, I want to tell the user that the server is processing the request and disable the controls on the page. Let's break this down into two steps: show a message, and disable the user's interaction with the controls.

You can use the UpdateProgress control alone with the UpdatePanel to provide a message to the user during the postback. This is very simple -- put the UpdateProgress control within the UpdatePanel like so:

<asp:UpdateProgress ID="UpdateProgress1" runat="server">
    <ProgressTemplate>
        Update in progress. Please wait ...
    </ProgressTemplate>
</asp:UpdateProgress>
 

This will display the "Update in progress. Please wait ..." message to the the user while the server is processing the request. However, it doesn't prevent the user from continuing to interact with the web application. To provide this type of functionality, we will use the PageRequestManager to invoke some JavaScript while also using CSS and DHTML to lock down the UI.

First, we'll add a little more to our UpdateProgress control:

<ProgressTemplate>
    <div id="blur" />
    <div id="progress">
        Update in progress. Please wait ...
    </div>
</ProgressTemplate>
 

We'll use the "blur" and "progress" controls to _overlay _the controls in the UI while also providing a message to the user. To provide the functionality we require, we need to use the following CSS elements:

#blur
{
    width: 100%;
    background-color: black;
    moz-opacity: 0.5;
    khtml-opacity: .5;
    opacity: .5;
    filter: alpha(opacity=50);
    z-index: 120;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
}

#progress
{
    z-index: 200;
    background-color: White;
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    border: solid 1px black;
    padding: 5px 5px 5px 5px;
    text-align: center;
    width: 100%;
    left: 0px;
    height: 75px;
    padding-top: 40px;
    padding-bottom: 60px;
}
 

The purpose of the "blur" control is to provide a tag that lays over everything in the browser. Since the opacity is 0.5 (and 50), it appears gray while allowing the user to continue to see the controls behind it. However, since the "blur" control exists between the user and the other controls, the user cannot interact with any other controls.

image

Auto Fill Email Subject and Body

If you're using a list management system that requires specific text to be placed within the email subject or body of your email, this HTML code is for you.

Many times, if you request your visitors to type in a specific email subject or body text in order to subscribe to your publication, they may not type the required text correctly. This mistake will cause you to lose your subscriber, as your system will reject the subscription request.

To prevent this problem, you can create an email link that will automatically fill in the subject line and body when clicked on.

<a href="mailto:manish@simplygraphix.com?subject=Feedback for
webdevelopersnotes.com&body=The Tips and Tricks section is great
&cc=anotheremailaddress@anotherdomain.com
&bcc=onemore@anotherdomain.com">Send me an email</a>

Download ReportViewer 2010, ReportViewer 11 and SQLSysClrTypes

Have you tried to install ReportViewer on a server? If you as me receive a similar error, I have a solution.

When you have to install the Report Viewer on a server, it's quite difficult to find the install file and a reference for Report Viewer 11 (SQL System Clear Tyle).

Here you can download the last ReportViewer with its dependencies.

SQLSysClrTypes.zip (1.4MB)
ReportViewer.zip (6.1MB)
ReportViewer2010.zip (4.5MB)

How to roll back from Windows 10 Mobile preview to Windows Phone 8.1

It's the first preview of the universal version of Office apps, and starting with build 10080 the operating system now expands to new phone headsets, including the Lumia Icon/Lumia 930, Lumia 640/Lumia 640 XL, and HTC's One (M8), which is the first non-Lumia phone joining the Windows 10 preview program.

Although, now more users can get access to Windows 10 Mobile preview and get their hands of on the new preview of Word, Excel, PowerPoint, and OneNote, Microsoft warns that there is a significant number of bugs in this particular build for Windows phones, including a bug that could prevent users from receiving MMS messages.

So, if you happen to run into any problems or you simply are done testing the operating system, Microsoft has an application called "Windows Phone Recovery Tool" for PCs that will allow you to rollback to Windows Phone 8.1 from Windows 10 Mobile.

windows-recovery-tool-windows10

Below you'll find all the steps to help you go back safely to your previous version of the mobile operating system:

Note: Before proceeding it is worth pointing that with the release of Windows 10 Mobile build 10080, Microsoft has updated the Windows Phone Recovery Tool, now at version 2.0.3, and it is introducing support for the HTC One (M8) to Windows 10.

  1. Download and install the latest version of the Windows Phone Recovery Tool to your PC.
  2. Launch the recovery tool and connect your phone using a USB cable. If your handset isn't detected, click My phone was not detected to force the application to rescan for and detect the phone.
  3. In the next screen, click your phone, wait a few seconds, and you'll see your phone information and the software available for download to roll back to a previous operating system. To continue, click Reinstall software.
  4. Next, the recovery tool will warn you to backup all your data, settings, and apps before continuing, as the rolling back process will delete all the previous data in your phone. Click Continue to proceed.
  5. Now, the recovery tool will download the image from Microsoft's servers and replace Windows 10 Mobile that is currently on your phone. The process will take some time depending on your internet connection and the hardware in question.

After the tool completes the process, you will receive a message saying "Operation successfully completed". At this point, the phone will reboot and you will have to go through the Out-of-Box-Experience, like on any version of Windows. Then, you'll need to sign-in with your Microsoft account, select to restore your phone from backup (if this is something you prefer), and after a few additional questions, you'll be back to Windows Phone 8.1.

As you can see, Microsoft is making it very convenient to roll back to Windows Phone 8.1from Windows 10 Mobile preview, and the company is starting to add support for non-Lumia devices, which is a big plus. So you don't have to spend time searching on the internet for different tools to go back to the previous operating system.

However, you have to remember that the operating system is far from complete. Not only will you find issues, but you might also stumble upon problems trying to roll back, as I hear many users reporting issues restoring Windows Phone 8.1 on their Lumia 930. As such, you should avoid using Windows 10 Mobile preview as your primary mobile operating system, at least until it hits RTM.

windows-10-recover-download

Reading and Writing XML in C#

In this article, you will see how to read and write XML documents in Microsoft .NET using C# language. 

First, I will discuss XML .NET Framework Library namespace and classes. Then, you will see how to read and write XML documents. In the end of this article, I will show you how to take advantage of ADO.NET and XML .NET model to read and write XML documents from relational databases and vice versa.

Introduction to Microsoft .NET XML Namespaces and Classes

Before start working with XML document in .NET Framework, It is important to know about .NET namespace and classes provided by .NET Runtime Library. .NET provides five namespace - System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, and System.Xml.Xsl to support XML classes. 

The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. In this article, we are going to concentrate on reader and write class. These reader and writer classes are used to read and write XMl documents. These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can see there are four reader and two writer classes. 

The XmlReader class is an abstract bases classes and contains methods and properties to read a document. The Read method reads a node in the stream. Besides reading functionality, this class also contains methods to navigate through a document nodes. Some of these methods are MoveToAttribute, MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and  MoveToNextAttribute. ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement are more read methods. This class also has a method Skip to skip current node and move to next one. We'll see these methods in our sample example. 

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas.

The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items. This class is base class for XmlTextWriter class, which we'll be using in our sample example. 

The XmlNode class plays an important role. Although, this class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. This class is an abstract base class for many useful classes for inserting, removing, and replacing nodes, navigating through the document. It also contains properties to get a parent or child, name, last child, node type and more. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes. The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively. XmlDocumentFragment class represents a document fragment, which can be used to add to a document. The XmlDataDocument class provides methods and properties to work with ADO.NET data set objects.

In spite of above discussed classes, System.Xml namespace contains more classes. Few of them are XmlConvert, XmlLinkedNode, and XmlNodeList. 

Next namespace in Xml series is System.Xml.Schema. It classes  to work with XML schemas such XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType. 

The System.Xml.Serialization namespace contains classes that are used to serialize objects into XML format documents or streams. 

The System.Xml.XPath Namespce contains XPath related classes to use XPath specifications. This namespace has following classes  -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast navigation though XML documents. This class contains many Move methods to move through a document. 

The System.Xml.Xsl namespace contains classes to work with XSL/T transformations.

Reading XML Documents

In my sample application, I'm using books.xml to read and display its data through XmlTextReader. This file comes with VS.NET samples. You can search this on your machine and change the path of the file in the following line: 

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

Or you can use any XML file. 

The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor. 

XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

After creating an instance of XmlTextReader, you call Read method to start reading the document. After read method is called, you can read all information and data stored in a document. XmlReader class has properties such as Name, BaseURI, Depth, LineNumber an so on.

List 1 reads a document and displays a node information using these properties. 

About Sample Example 1

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output. 

Sample Example 1.

using System;

using System.Xml;

namespace ReadXml1

{

    class Class1

    {

        static void Main(string[] args)

        {

            // Create an isntance of XmlTextReader and call Read method to read the file

            XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

            textReader.Read();

            // If the node has value

            while (textReader.Read())

            {

                // Move to fist element

                textReader.MoveToElement();

                Console.WriteLine("XmlTextReader Properties Test");

                Console.WriteLine("===================");

                // Read this element's properties and display them on console

                Console.WriteLine("Name:" + textReader.Name);

                Console.WriteLine("Base URI:" + textReader.BaseURI);

                Console.WriteLine("Local Name:" + textReader.LocalName);

                Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());

                Console.WriteLine("Depth:" + textReader.Depth.ToString());

                Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());

                Console.WriteLine("Node Type:" + textReader.NodeType.ToString());

                Console.WriteLine("Attribute Count:" + textReader.Value.ToString());

            }

        }

    }

}

 

The NodeType property of XmlTextReader is important when you want to know the content type of a document. The XmlNodeType enumeration has a member for each type of XML item such as Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace and so on.

List 2 code sample reads an XML document, finds a node type and writes information at the end with how many node types a document has. 

About Sample Example 2

In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document.

Sample Example 2.

using System;

using System.Xml;

namespace ReadingXML2

{

    class Class1

    {

        static void Main(string[] args)

        {

            int ws = 0;

            int pi = 0;

            int dc = 0;

            int cc = 0;

            int ac = 0;

            int et = 0;

            int el = 0;

            int xd = 0;

            // Read a document

            XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

            // Read until end of file

            while (textReader.Read())

            {

                XmlNodeType nType = textReader.NodeType;

                // If node type us a declaration

                if (nType == XmlNodeType.XmlDeclaration)

                {

                    Console.WriteLine("Declaration:" + textReader.Name.ToString());

                    xd = xd + 1;

                }

                // if node type is a comment

                if (nType == XmlNodeType.Comment)

                {

                    Console.WriteLine("Comment:" + textReader.Name.ToString());

                    cc = cc + 1;

                }

                // if node type us an attribute

                if (nType == XmlNodeType.Attribute)

                {

                    Console.WriteLine("Attribute:" + textReader.Name.ToString());

                    ac = ac + 1;

                }

                // if node type is an element

                if (nType == XmlNodeType.Element)

                {

                    Console.WriteLine("Element:" + textReader.Name.ToString());

                    el = el + 1;

                }

                // if node type is an entity\

                if (nType == XmlNodeType.Entity)

                {

                    Console.WriteLine("Entity:" + textReader.Name.ToString());

                    et = et + 1;

                }

                // if node type is a Process Instruction

                if (nType == XmlNodeType.Entity)

                {

                    Console.WriteLine("Entity:" + textReader.Name.ToString());

                    pi = pi + 1;

                }

                // if node type a document

                if (nType == XmlNodeType.DocumentType)

                {

                    Console.WriteLine("Document:" + textReader.Name.ToString());

                    dc = dc + 1;

                }

                // if node type is white space

                if (nType == XmlNodeType.Whitespace)

                {

                    Console.WriteLine("WhiteSpace:" + textReader.Name.ToString());

                    ws = ws + 1;

                }

            }

            // Write the summary

            Console.WriteLine("Total Comments:" + cc.ToString());

            Console.WriteLine("Total Attributes:" + ac.ToString());

            Console.WriteLine("Total Elements:" + el.ToString());

            Console.WriteLine("Total Entity:" + et.ToString());

            Console.WriteLine("Total Process Instructions:" + pi.ToString());

            Console.WriteLine("Total Declaration:" + xd.ToString());

            Console.WriteLine("Total DocumentType:" + dc.ToString());

            Console.WriteLine("Total WhiteSpaces:" + ws.ToString());

        }

    }

}

Writing XML Documents

XmlWriter class contains the functionality to write to XML documents. It is an abstract base class used through XmlTextWriter and XmlNodeWriter classes. It contains methods and properties to write to XML documents. This class has several Writexxx method to write every type of item of an XML document. For example, WriteNode, WriteString, WriteAttributes, WriteStartElement, and WriteEndElement are some of them. Some of these methods are used in a start and end pair. For example, to write an element, you need to call WriteStartElement then write a string followed by WriteEndElement.              

Besides many methods, this class has three properties. WriteState, XmlLang, and XmlSpace. The WriteState gets and sets the state of the XmlWriter class

Although, it's not possible to describe all the Writexxx methods here, let's see some of them.

First thing we need to do is create an instance of XmlTextWriter using its constructor. XmlTextWriter has three overloaded constructors, which can take a string, stream, or a TextWriter as an argument. We'll pass a string (file name) as an argument, which we're going to create in C:\ root.

In my sample example, I create a file myXmlFile.xml in C:\\ root directory. 

// Create a new file in C:\\ dir
XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null) ;

After creating an instance, first thing you call us WriterStartDocument. When you're done writing, you call WriteEndDocument and TextWriter's Close method.

textWriter.WriteStartDocument();
textWriter.WriteEndDocument();
textWriter.Close();  

The WriteStartDocument and WriteEndDocument methods open and close a document for writing. You must have to open a document before start writing to it.  WriteComment method writes comment to a document. It takes only one string type of argument. WriteString method writes a string to a document. With the help of WriteString, WriteStartElement and WriteEndElement methods pair can be used to write an element to a document. The WriteStartAttribute and WriteEndAttribute pair writes an attribute.

WriteNode is more write method, which writes an XmlReader to a document as a node of the document. For example, you can use WriteProcessingInstruction and WriteDocType methods to write a ProcessingInstruction and DocType items of a document. 

//Write the ProcessingInstruction node
string PI= "type='text/xsl' href='book.xsl'"
textWriter.WriteProcessingInstruction("xml-stylesheet", PI);
//'Write the DocumentType node
textWriter.WriteDocType("book", Nothing, Nothing, "<!ENTITY h 'softcover'>");

The below sample example summarizes all these methods and creates a new xml document with some items in it such as elements, attributes, strings, comments and so on. See Listing 5-14. In this sample example, we create a new xml file c:\xmlWriterText.xml. In this sample example, We create a new xml file c:\xmlWriterTest.xml using XmlTextWriter: 

After that, we add comments and elements to the document using Writexxx methods. After that we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter.

About Sample Example 3 

In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items. 

Sample Example 3.

using System;

using System.Xml;

namespace ReadingXML2

{

    class Class1

    {

        static void Main(string[] args)

        {

            // Create a new file in C:\\ dir

            XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);

            // Opens the document

            textWriter.WriteStartDocument();

            // Write comments

            textWriter.WriteComment("First Comment XmlTextWriter Sample Example");

            textWriter.WriteComment("myXmlFile.xml in root dir");

            // Write first element

            textWriter.WriteStartElement("Student");

            textWriter.WriteStartElement("r", "RECORD", "urn:record");

            // Write next element

            textWriter.WriteStartElement("Name", "");

            textWriter.WriteString("Student");

            textWriter.WriteEndElement();

            // Write one more element

            textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");

            textWriter.WriteEndElement();

            // WriteChars

            char[] ch = new char[3];

            ch[0] = 'a';

            ch[1] = 'r';

            ch[2] = 'c';

            textWriter.WriteStartElement("Char");

            textWriter.WriteChars(ch, 0, ch.Length);

            textWriter.WriteEndElement();

            // Ends the document.

            textWriter.WriteEndDocument();

            // close writer

            textWriter.Close();

        }

    }

}

 

Using XmlDocument

The XmlDocument class represents an XML document. This class provides similar methods and properties we've discussed earlier in this article. 

Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter.

About Sample Example 4

This tiny sample example pretty easy to understand. We call LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file. 

Sample Example 4.

//Create the XmlDocument.
XmlDocument doc = new XmlDocument();
doc.LoadXml(("<Student type='regular' Section='B'><Name>Tommy
ex</Name></Student>"));
//Save the document to a file.
doc.Save("C:\\std.xml");
You can also use Save method to display contents on console
if you pass Console.Out as
a
arameter. For example:
doc.Save(Console.Out);

About Sample Example 5 

Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. Passing Console.Out as a Save method argument displays data on the console

Sample Example 5.

XmlDocument doc = new XmlDocument();
//Load the the document with the last book node.
XmlTextReader reader = new
XmlTextReader("c:\\books.xml");
reader.Read();
// load reader
doc.Load(reader);
// Display contents on the console
doc.Save(Console.Out);

Writing Data from a database to an XML Document

Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's data and write the contents to an XML document. 

The DataSet class provides method to read a relational database table and write this table to an XML file. You use WriteXml method to write a dataset data to an XML file.  

In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query. 

About Sample Example 6 

 In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter. 

In this sample example, I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see from Sample Example 6, first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir. 

Sample Example 6. 

using System;

using System.Xml;

using System.Data;

using System.Data.OleDb;

namespace ReadingXML2

{

    class Class1

    {

        static void Main(string[] args)

        {

            // create a connection

            OleDbConnection con = new OleDbConnection();

            con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb";

            // create a data adapter

            OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con);

            // create a new dataset

            DataSet ds = new DataSet();

            // fill dataset

            da.Fill(ds, "Customers");

            // write dataset contents to an xml file by calling WriteXml method

            ds.WriteXml("C:\\OutputXML.xml");

        }

    }

}



Advertsing

125X125_06

TagCloud

MonthList

CommentList