Blog of a Filipino Developer about C#, VB.NET, ASP.NET, Java, PHP, SQL Server, MySql and Oracle RSS 2.0
 Friday, June 20, 2008

Because of the inspiration from what Chris Williams started I have decided to start Ten Questions - Filipino Developers Edition. Basically, the idea is to interview well-known Filipino developers and ask them 10 questions that would shed light on their persona and their geekiness!

On this first go around we interview Migz Paraz, a fixture in the Philippine IT industry since the 90s. He is well-known for his involvement with the Filipino Java community and for his thoughts posted on his blog at paraz.com among others.

Read more about this interview here.

http://devpinoy.org/blogs/keithrull/archive/2008/06/20/ten-questions-with-migz-paraz.aspx

Friday, June 20, 2008 10:22:03 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
DevConversations | Fun Stuff
 Thursday, June 19, 2008

Just in case you are studying WCF.. You might want to check out the .NET StockTrader Sample Application.

The .NET StockTrader Sample Application is an end-to-end sample application illustrating Windows Communication Foundation and .NET Enterprise Technologies. It is a service-oriented application based on Windows Communication Foundation (.NET 3.0) and ASP.NET, and illustrates many of the .NET enterprise development technologies for building highly scalable, rich "enterprise-connected" applications. It is designed as a benchmark kit to illustrate alternative technologies within .NET and their relative performance.

The application offers full interoperability with J2EE and IBM WebSphere's Trade 6.1 sample application. As such, the application offers an excellent opportunity for developers to learn about .NET and building interoperable, service-oriented applications.

Read more here: http://msdn.microsoft.com/en-us/netframework/bb499684.aspx

I've been diving into WCF lately and I have found this sample application as a great blueprint on how to develop applications using WCF & ASP.NET. The sample includes a smart client and an ASP.NET application that you can jump on and play that showcases as huge list of technologies and approaches when developing an SOA app via WCF and .NET

Below is a list of technologies that's demonstrated in this sample application:

  • Service-oriented, n-tier design with ASP.NET and WCF
    • Clean separation of UI, business services and DB access
    • Design and tuning for performance
    • Horizontally scalable via dynamic clustering
    • Centralized configuration management of clustered service nodes
  • .NET 3.5 with Windows Communication Foundation
    • Interoperability with J2EE/WebSphere Trade 6.1
    • Incorporates alternative designs for performance comparisons
    • Loosely-coupled, message-oriented design with WCF and MSMQ
    • Achieving assured message delivery with transactions
    • Self-hosting WCF Services
    • Custom WCF Behaviors
    • Service host failure detection and automatic restarts
  • .NET Enterprise Application Server Technologies
    • ASP.NET 2.0
    • ADO.NET 2.0
    • .NET Transactions
    • MSMQ 3.5 (Windows XP/Windows Server 2003)
    • MSMQ 4.0 (Windows Vista/"Longhorn Server CTP")
    • Transaction batching with WCF and MSMQ

Try and see for yourself ;) I bet you will enjoy it too!

 

Thursday, June 19, 2008 10:08:05 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | ASP.NET
 Wednesday, June 11, 2008

Do you want to use LINQ but you are still stuck with .NET 2.0 and .NET 3.0? Are you still waiting for your company to upgrade to VS 2008 to get a hold of LINQ? Then wait no more because the good guys who wrote the book C# 3.0 In A Nutshell have created a .NET library that implements all the standard LINQ operators so that you can enjoy the goodness of LINQ in .NET 2.0 and 3.0.

LINQBridge is a reimplementation of all the standard query operators in Framework 3.5's Enumerable class. It's designed to work with the C# 3.0 compiler, as used by Visual Studio 2008. LINQBridge comprises a "LINQ to Objects" API for running local queries. (It doesn't include an implementation of LINQ to SQL, nor LINQ to XML; a good compromise can be to force Framework 3.5 out to just the server machines, allowing LINQ to SQL to be used where it's needed most).

LINQBridge also includes Framework 3.5's generic Func and Action delegates, as well as ExtensionAttribute, allowing you to use C# 3.0's extension methods in Framework 2.0.

In fact LINQBridge lets you use nearly all of the features in C# 3.0 with Framework 2.0—including extension methods, lambda functions and query comprehensions. The only feature it does not support is compiling lambdas to expression trees (i.e., Expression<TDelegate>).

Awesome huh?! Get this goodie here: http://www.albahari.com/nutshell/linqbridge.html

Wednesday, June 11, 2008 12:45:05 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET

I saw this post from Mahesh today and it taught me something that I know I'll put in good use in years to come...

Former President of India APJ Abdul Kalam at Wharton India Economic forum , Philadelphia, United States March 22,2008)

Question: Could you give an example, from your own experience, of how leaders should manage failure?

Kalam:   Let me tell you about my experience. In 1973 I became the project director of India's satellite launch vehicle program, commonly called the SLV-3. Our goal was to put India's "Rohini" satellite into orbit by 1980. I was given funds and human resources -- but was told clearly that by 1980 we had to launch the satellite into space. Thousands of people worked together in scientific and technical teams towards that goal.

By 1979 -- I think the month was August -- we thought we were ready. As the project director, I went to the control center for the launch. At four minutes before the satellite launch, the computer began to go through the checklist of items that needed to be checked. One minute later, the computer program put the launch on hold; the display showed that some control components were not in order. My experts -- I had four or five of them with me -- told me not to worry; they had done their calculations and there was enough reserve fuel. So I bypassed the computer, switched to manual mode, and launched the rocket. In the first stage, everything worked fine. In the second stage, a problem developed. Instead of the satellite going into orbit, the whole rocket system plunged into the Bay of Bengal. It was a big failure.

That day, the chairman of the
Indian Space Research Organization, Prof. Satish Dhawan, had called a press conference. The launch was at 7:00 am, and the press conference -- where journalists from around the world were present -- was at 7:45 am at ISRO's satellite launch range in Sriharikota [in Andhra Pradesh in southern India]. Prof. Dhawan, the leader of the organization, conducted the press conference himself. He took responsibility for the failure -- he said that the team had worked very hard, but that it needed more technological support. He assured the media that in another year, the team would definitely succeed. Now, I was the project director, and it was my failure, but instead, he took responsibility for the failure as chairman of the organization.

The next year, in July 1980, we tried again to launch the satellite -- and this time we succeeded. The whole nation was jubilant. Again, there was a press conference. Prof. Dhawan called me aside and told me, "You conduct the press conference today."

I learned a very important lesson that day. When failure occurred, the leader of the organization owned that failure. When success came, he gave it to his team. The best management lesson I have learned did not come to me from reading a book; it came from that experience
….

Thanks Mahesh for sharing such a wonderful inspiration to us...

Wednesday, June 11, 2008 12:34:36 AM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
All about Keith | Life
 Thursday, April 17, 2008

I know Joel and Jeff are ready. I am ready! Are you?

http://www.stackoverflow.com/

Thursday, April 17, 2008 10:09:41 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
Tech News and Issues

In my previous article I showed you how to add a web service reference in your ASP.NET application, call a webmethod and the display the values returned byt the web service to a Label. This time I'm going to show you how to transform that Xml string into a DataSet.

I suggest that you read the previous article before continuing in reading this post so you'll have a better insight on what we are trying to accomplish on this article.

Let's begin!

To start off this article let's look at how the application that we built for the previous article.

and the HTML code for the UI

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Keith Rull's Consuming Web Services Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <strong>Symbol</strong><br />
            <asp:TextBox ID="symbolTextBox" 
                         runat="server" />
            <asp:Button ID="executeButton" 
                        runat="server" 
                        Text="Execute"
                        OnClick="executeButton_Click" />
            <br />
            <br />
            <strong>Result</strong>
            <br />
            <asp:Label ID="xmlResultLabel" 
                        runat="server" />
        </div>
    </form>
</body>
</html>

and the underlying code for the click event of the "Execute" button

    protected void executeButton_Click(object sender, EventArgs e)
    {
        //get the execution symbol entered in the TextBox
        string executionSymbol = symbolTextBox.Text;

        //get the stock quote information
        string quoteInfo = GetStockQuoteInformation(executionSymbol);

        //HtmlEncode the string to properly render it on the page
        string htmlEncodedResult = System.Web.HttpUtility.HtmlEncode(quoteInfo);
       
        //assign the HtmlEncoded string to our Label control
        xmlResultLabel.Text = htmlEncodedResult;
    }

As you can see the code above does the job of displaying the retuned xml from the webservice. It works. We can understand that XML because we are techie enough but imagine a normal user seeing a xml values on his screen? Yup. Not good. The best way to present data to a user is to show values in tabular form. A lot more pleasing to the eyes and much easier to understand. With that said let's start by replacing the Label control in the form with a DetailsView control. The new aspx page for our form should look like this:

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
                "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Keith Rull's Consuming Web Services Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <strong>Symbol</strong><br />
            <asp:TextBox ID="symbolTextBox" 
                         runat="server" />
            <asp:Button ID="executeButton" 
                        runat="server" 
                        Text="Execute"
                        OnClick="executeButton_Click" />
            <br />
            <br />
            <strong>Result</strong>&nbsp;<br />
            <asp:DetailsView ID="stockQuoteInfoDetailsView" runat="server" Height="50px" Width="125px">
            </asp:DetailsView>
        </div>
    </form>
</body>
</html>

As you can see in the old code for the Click event we are able to get the XML and display it on a Label. What we need to do now is to read that XML string and assign it to a our DetailsView but there is one problem... The XML string needs to be converted to an object that supports IList or IEnumerable first before it could be loaded to our DetailsView.

To solve this problem I've decided to create this method that accepts an XML string and converts it to a DataSet.

    /// <summary>
    /// A function that takes an XML string and converts it into a DataSet
    /// </summary>
    /// <param name="xmlString">The xml string to tranform into a DataSet</param>
    /// <returns>The DataSet representing the values and schema from our xml string</returns>
    private DataSet XmlString2DataSet(string xmlString)
    {
        //create a new DataSet that will hold our values
        DataSet quoteDataSet = null;

        //check if the xmlString is not blank
        if (String.IsNullOrEmpty(xmlString)) {
            //stop the processing
            return quoteDataSet;
        }

        try{
            //create a StringReader object to read our xml string
            using (StringReader stringReader = new StringReader(xmlString))
            {
                //initialize our DataSet
                quoteDataSet = new DataSet();

                //load the StringReader to our DataSet
                quoteDataSet.ReadXml(stringReader);
            }
        }
        catch{
            //return null
            quoteDataSet = null;
        }

        //return the DataSet containing the stock information
        return quoteDataSet;
    }

Now we can modify our our executeButton_Click event

    protected void executeButton_Click(object sender, EventArgs e)
    {
        //get the execution symbol entered in the TextBox
        string executionSymbol = symbolTextBox.Text;

        //get the stock quote information
        string quoteInfo = GetStockQuoteInformation(executionSymbol);

        //create our quote DataTable
        DataSet quoteDataSet = XmlString2DataSet(quoteInfo);

        //assign the quote information to our DetailsView
        stockQuoteInfoDetailsView.DataSource = quoteDataSet;
        stockQuoteInfoDetailsView.DataBind();
    }

All we did was pass the xml string to the XmlString2DataSet function to retrieve a DataSet containing the stock quote information and then assigning that DataSet object to our DetailsView for display. Below is how the final form looks-like after our modification

Now that is more presentable! I hope I was able to share with you something useful. Next stop, we'll be building Master-Detail pages in ASP.NET ;)

Care for the code? Grab it here: KeithRull.ConsumingWebServices.Part2.zip (5.76 KB)

Thursday, April 17, 2008 5:27:06 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | ASP.NET | Tutorial
 Friday, April 11, 2008

I saw this comment on Dustin Campbell's MVP renewal post and it made me smile

That is definetely one proud mama! Congrats Dustin and Happy Birthday too ;)

Friday, April 11, 2008 3:51:16 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
All about Keith | Tech News and Issues
 Tuesday, April 08, 2008

I've been meaning to write this tutorial for a month now and finally i found time to write it. As you may have noticed, I have been blogging about accessing files (here, here and here), reading XML, and loading XML data to a GridView lately. The reason behind this is that I am preping you guys up for a much larger article that would span to 5 articles with different demos for each post... something that needs to spend a little bit of time on the lower end of the grid to make the whole thing easier to explain once we start building the big picture... but I won't spill the details about the post yet ;) so better keep up with the site to learn what I've been brewing since early March.

In the meantime let's talk about how to consume XML Web Services in ASP.NET. I don't want to bore you with explanations on what an XML Web Service means so I'll just lead you to a document written by Roger Wolter in 2001 that explains the whole enselada about Web Services. Below is an excerpt from that document:

XML Web services are the fundamental building blocks in the move to distributed computing on the Internet. Open standards and the focus on communication and collaboration among people and applications have created an environment where XML Web services are becoming the platform for application integration. Applications are constructed using multiple XML Web services from various sources that work together regardless of where they reside or how they were implemented.

There are probably as many definitions of XML Web Service as there are companies building them, but almost all definitions have these things in common:

  • XML Web Services expose useful functionality to Web users through a standard Web protocol. In most cases, the protocol used is SOAP.
  • XML Web services provide a way to describe their interfaces in enough detail to allow a user to build a client application to talk to them. This description is usually provided in an XML document called a Web Services Description Language (WSDL) document.
  • XML Web services are registered so that potential users can find them easily. This is done with Universal Discovery Description and Integration (UDDI).

Now that we have nailed the basic definition let's build a simple application that consumes a publicly available web service. There are a lot of sites that list useful public web services and one of those sites is WebServiceX. WebServiceX's website contains 70+ freely available web service that you can use and utilize in your projects. For this demo I've decided to use the StockQuote service which is a web service that allows you to query stock information by using the symbol of the stock. Here's some information about the service taken from their website:

Summary: Get Stock quote for a company symbol by using this web service
Endpoint:
http://www.webservicex.net/stockquote.asmx
Disco: http://www.webservicex.net/stockquote.asmx?Disco
WSDL Location: http://www.webservicex.net/stockquote.asmx?wsdl

Let's begin building!

First, let's start by creating a new ASP.NET Website Project

Once that's done we need to add a Web Reference to our project that would point to the StockQuote service hosted on the WebServiceX website. We can do this by right-clicking on our solution and then selecting the Web Reference menu item.

A new screen will appear that will enable you to specify the URL of the web service. Input http://www.webservicex.net/stockquote.asmx on the URL dropdownlist to create reference to the StockQuote service.

Click "Add Reference" to add the reference to the project. You'll notice that the folder structure of your project has been updated and a new folder called "App_WebReferences" has been added to the project.

Ok, now let's build our UI. My idea for this sample application is to have a TextBox that allows users to enter the symbol, a Button control that will trigger the lookup to the web service via it's Click event and a Label control that will used to display the values returned by the web service. Below is how I envisioned our form to look-like:

And here's the accompanying HTML source for our form

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Keith Rull's Consuming Web Services Sample</title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <strong>Symbol</strong><br />
            <asp:TextBox ID="symbolTextBox" 
                         runat="server" />
            <asp:Button ID="executeButton" 
                        runat="server" 
                        Text="Execute"
                        OnClick="executeButton_Click" />
            <br />
            <br />
            <strong>Result</strong>
            <br />
            <asp:Label ID="xmlResultLabel" 
                        runat="server" />
        </div>
    </form>
</body>
</html>

Now that we have the infrastructure in place it's time to write some code. The first thing that we need to do on the code-behind level is to add the using declaration to include the web service class in our page.

This enables us to create objects from our web service. The class that we would be using in this exercise is the StockQuote object which has the StockQuote.GetQuote method that returns the XML data containing the information for a specified symbol. Below is the method I wrote to show you how to use this class:

    /// <summary>
    /// A function that retrieves the stock information
    /// from the StockQuote web service
    /// </summary>
    /// <param name="executionSymbol">the execution symbol to lookup</param>
    /// <returns>The string containing the XML information regarding the symbol</returns>
    private string GetStockQuoteInformation(string executionSymbol)
    {
        string quoteInfo = String.Empty;

        //check if the executionSymbol is not blank
        if (String.IsNullOrEmpty(executionSymbol)) {
            //stop the processing
            return quoteInfo;
        }

        try
        {
            //create a StockQuote object
            StockQuote quote = new StockQuote();

            //get the stock quote information for the specified symbol
            quoteInfo = quote.GetQuote(executionSymbol);
        }
        catch (Exception ex) {
            //raise the error
            string errorMessage = String.Format("Error while trying to connect to the Web Service. {0}", ex.Message);
            throw new Exception(errorMessage);
        }

        //return the quote information
        return quoteInfo;
    }

Now that we have the function that will call our web service it's time to hook up our method to the Click event of our button.

    protected void executeButton_Click(object sender, EventArgs e)
    {
        //get the execution symbol entered in the TextBox
        string executionSymbol = symbolTextBox.Text;

        //get the stock quote information
        string quoteInfo = GetStockQuoteInformation(executionSymbol);

        //HtmlEncode the string to properly render it on the page
        string htmlEncodedResult = System.Web.HttpUtility.HtmlEncode(quoteInfo);
        
        //assign the HtmlEncoded string to our Label control
        xmlResultLabel.Text = htmlEncodedResult;
    }

As you can see the whole process was built with little code. Run the application and see how the easy it is to connect to a web service, call a web service method and use it's returned value.

I hope you learned something from this tutorial. On our next article i'll show you howto display the XML returned by the web service to a GridView.

Later ;)

Tuesday, April 08, 2008 4:48:30 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET
 Tuesday, April 01, 2008

Last week I showed you how to read an XML file, load it to a DataSet and assign those values into a GridView. Today I'll show you how you can read an XML file using the XmlDataSource object.

Let's assume that we have an XML file called Symbols.xml in our App_Data folder

that contains the following data

<?xml version="1.0" encoding="utf-8" ?>
<Symbols>
    <Symbol ExecutionSymbol="ATT" Name="AT&amp;T"></Symbol>
    <Symbol ExecutionSymbol="MSFT" Name="Microsoft"></Symbol>
    <Symbol ExecutionSymbol="GOOG" Name="Google"></Symbol>
    <Symbol ExecutionSymbol="CSCO" Name="Cisco"></Symbol>
    <Symbol ExecutionSymbol="IP" Name="International Paper Co."></Symbol>
    <Symbol ExecutionSymbol="MF" Name="MF Global"></Symbol>
    <Symbol ExecutionSymbol="Q" Name="Qwest Communications International Inc."></Symbol>
    <Symbol ExecutionSymbol="BMC" Name="BMC Software Inc."></Symbol>
    <Symbol ExecutionSymbol="WCI" Name="WCI Communities Inc."></Symbol>
    <Symbol ExecutionSymbol="SPY" Name="SDRs"></Symbol>
    <Symbol ExecutionSymbol="LEH" Name="Lehman Brothers Holdings Inc."></Symbol>
    <Symbol ExecutionSymbol="XLF" Name="Financial Select Sector SPDR"></Symbol>
    <Symbol ExecutionSymbol="QQQQ" Name="PowerShares QQQ TR 1"></Symbol>
    <Symbol ExecutionSymbol="IWM" Name="IShare Rus 2000 INDX"></Symbol>
    <Symbol ExecutionSymbol="GE" Name="General Electric Co."></Symbol>
    <Symbol ExecutionSymbol="MER" Name="Merrill Lynch Co., Inc."></Symbol>
    <Symbol ExecutionSymbol="BAC" Name="Bank of America Corporation"></Symbol>
    <Symbol ExecutionSymbol="INTC" Name="Intel Corp"></Symbol>
    <Symbol ExecutionSymbol="F" Name="Ford Motor Co."></Symbol>
    <Symbol ExecutionSymbol="QID" Name="UltraShort QQQ ProShares"></Symbol>
</Symbols>

and we want to load it to a GridView with no server-side code and a quick and easy way. The answer is to use the XmlDataSource object. The XmlDataSource control is an ASP.NET control that allows you to automatically read XML Data and make that data readily available to any ASP.NET control.

To start using this control, go to your Toolbox and drag the XmlDataSource control to your page.

Once the control is on the page it would popup a dialog that has configuration options for our XmlDataSource control. Click the "Configure Data Source" button to configure our XmlDataSource

A popup like below will come up that allows you to select the Xml file you want to your XmlDataSource object to read. It also gives you the option to select the XSL file. You can also specify an XPath expression to use to filter the data in our Xml.

Click the "Browse" button for the "Data File" option to select an XML file.

A new dialog will appear that will let you navigate the folder tree to select your desired XML file

Click "Ok" and you'll be taken back to the "Configure Data Source" screen. Click "Ok" again to finalize the XML data assignment.

Now that we have the file set in to our XmlDataSource control we need assign it to a control. We can do that by dragging a GridView control to our form.

Next, we need to assign the XmlDataSource control as the data source for our GridView. We can do this by selecting our XmlDataSource from the "Choose Data Source" dropdownlist.

Click "XmlDataSource1" and you will notice that our GridView was automatically updated and now shows the contents of our XML file.

Easy huh? Next up, Consuming Web Services in ASP.NET

 

Monday, March 31, 2008 11:15:13 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | ASP.NET | Tutorial
 Thursday, March 27, 2008

Last week I showed you ways on how to read text files. This time around we will be looking at how to load XML files into a DataSet.

Let's assume that we have a file called Symbols.xml which contains some XML data.

<?xml version="1.0" encoding="utf-8" ?>
<Symbols>
    <Symbol ExecutionSymbol="ATT" Name="AT&amp;T"></Symbol>
    <Symbol ExecutionSymbol="MSFT" Name="Microsoft"></Symbol>
    <Symbol ExecutionSymbol="GOOG" Name="Google"></Symbol>
    <Symbol ExecutionSymbol="CSCO" Name="Cisco"></Symbol>
    <Symbol ExecutionSymbol="IP" Name="International Paper Co."></Symbol>
    <Symbol ExecutionSymbol="MF" Name="MF Global"></Symbol>
    <Symbol ExecutionSymbol="Q" Name="Qwest Communications International Inc."></Symbol>
    <Symbol ExecutionSymbol="BMC" Name="BMC Software Inc."></Symbol>
    <Symbol ExecutionSymbol="WCI" Name="WCI Communities Inc."></Symbol>
    <Symbol ExecutionSymbol="SPY" Name="SDRs"></Symbol>
    <Symbol ExecutionSymbol="LEH" Name="Lehman Brothers Holdings Inc."></Symbol>
    <Symbol ExecutionSymbol="XLF" Name="Financial Select Sector SPDR"></Symbol>
    <Symbol ExecutionSymbol="QQQQ" Name="PowerShares QQQ TR 1"></Symbol>
    <Symbol ExecutionSymbol="IWM" Name="IShare Rus 2000 INDX"></Symbol>
    <Symbol ExecutionSymbol="GE" Name="General Electric Co."></Symbol>
    <Symbol ExecutionSymbol="MER" Name="Merrill Lynch Co., Inc."></Symbol>
    <Symbol ExecutionSymbol="BAC" Name="Bank of America Corporation"></Symbol>
    <Symbol ExecutionSymbol="INTC" Name="Intel Corp"></Symbol>
    <Symbol ExecutionSymbol="F" Name="Ford Motor Co."></Symbol>
    <Symbol ExecutionSymbol="QID" Name="UltraShort QQQ ProShares"></Symbol>
</Symbols>

And you want to load that data into a DataSet and display it to a GridView. How would you do it?

There are different ways you can load an XML file to a DataSet and i'm here to show you 4 of them. I don't have alot of time to explain the intrinsicts of each sample or performance comparisson of each technique because of time constraints so i'll leave that part for you to figure out the best among this examples. ;)

SAMPLE 1

//Sample 1
//the code below shows us how to load the XML document
//directly to our dataset by just specifying the file
//location to the DataSet.ReadXml method of the DataSet

using System;
using System.Data;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath(@"App_Data/Symbols.xml");

        if (File.Exists(xmlFilePath))
        {
            //create the Dataset object
            using (DataSet ds = new DataSet())
            {
                //load the xml data to the dataset
                ds.ReadXml(xmlFilePath);

                //bind the values to our GridView
                symbolGridView.Caption = "<h4>Loaded the data using Sample1</h4>";
                symbolGridView.DataSource = ds;
                symbolGridView.DataBind();
            }
        }
    }
}

SAMPLE 2

//Sample 2
//The code below is using the TextReader object to read
//the contents of the file and then assign those values
//to our dataset object

using System;
using System.Data;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath(@"App_Data/Symbols.xml");

        if (File.Exists(xmlFilePath))
        {
            //Create the TextReader object
            using (TextReader sReader = new StreamReader(xmlFilePath))
            {
                //create the Dataset object
                using (DataSet ds = new DataSet())
                {
                    //load the xml data from the TextReader to the Dataset
                    ds.ReadXml(sReader);

                    //bind the values to our GridView
                    symbolGridView.Caption = "<h4>Loaded the data using Sample2</h4>";
                    symbolGridView.DataSource = ds;
                    symbolGridView.DataBind();
                }
            }
        }
    }
}

SAMPLE 3

//Sample 3
//The code below is basically the same as the above code
//but this time we are using the XmlTextReader object
//instead of using the TextReader object. Please note that
//the XmlReader object calls the TextReader internally.

using System;
using System.Data;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath(@"App_Data/Symbols.xml");

        if (File.Exists(xmlFilePath))
        {
            //Create the XmlTextReader object
            using (XmlTextReader xTextReader = new XmlTextReader(xmlFilePath))
            {
                //create the Dataset object
                using (DataSet ds = new DataSet())
                {
                    //load the xml data to dataset
                    ds.ReadXml(xTextReader);

                    //bind the values to our GridView
                    symbolGridView.Caption = "<h4>Loaded the data using Sample3</h4>";
                    symbolGridView.DataSource = ds;
                    symbolGridView.DataBind();
                }
            }
        }
    }
}

SAMPLE 4

//Sample 4
//The code below uses an XmlDocument object and reads a file
//using the XmlDocument.LoadXml method. That data is then
//transfered to a DataSet by using the DataSet.ReadXml method
//and passing a XmlNodeReader object based on our XmlDocument

using System;
using System.Data;
using System.Xml;
using System.IO;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string xmlFilePath = Server.MapPath(@"App_Data/Symbols.xml");

        if (File.Exists(xmlFilePath))
        {
            //Create the Dataset object
            using (DataSet ds = new DataSet())
            {
                //create the XmlDocument object
                XmlDocument xDoc = new XmlDocument();

                //load the contents of the file to our XmlDocument object
                xDoc.LoadXml(File.ReadAllText(xmlFilePath));

                //load the xml data in the XmlDocument object to the Dataset
                ds.ReadXml(new XmlNodeReader(xDoc));

                //bind the values to our GridView
                symbolGridView4.Caption = "<h4>Loaded the data using Sample4</h4>";
                symbolGridView4.DataSource = ds;
                symbolGridView4.DataBind();
            }
        }
    }
}

And that's it. On my next post i'll show you how to load XML data directly to the GridView using the XMLDataSource object.

HTH.

Thursday, March 27, 2008 3:47:22 PM (GMT Standard Time, UTC+00:00)  #    Comments [0] -
.NET | Tutorial
Archive
<June 2008>
SunMonTueWedThuFriSat
25262728293031
1234567
891011121314
15161718192021
22232425262728
293012345
Blogroll