Solved

using datareader to output xml in C#

Posted on 2015-02-16
3
126 Views
Last Modified: 2015-02-16
Hi Experts,

I'm using Visual Studio 2013 and Sql Server 2008.
I created an example in ASP.net using VB and that one works fine.
Now I'm translating this example to use C# and I'm having problem in the translation.
Below I describe my VB example and then describe the error i'm getting in my C# example.



I'm using the Employees table of the Northwind sql server database.

The Employees table returned by my query in my code looks like this:

employees table
VB Version

I have a ASP.NET page called TestEmployees.aspx. In this example I used Visual Basic as the language.

The page queries the Employees table and returns an (XML with Attributes) representation of that table.

This is my code for it.

TestEmployees.aspx

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="TestEmployees.aspx.vb" Inherits="Map2.TestEmployees" %>

Open in new window


TestEmployees.aspx.vb
Imports System.IO
Imports System.Data
Imports System.Data.SqlClient
Imports System.Xml

Public Class TestEmployees
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load


        Dim dbConnString As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
        Dim dbConn As New SqlConnection(dbConnString)
        Dim strSQL As String, objCommand As SqlCommand
        Dim objDataReader As SqlDataReader
        Dim eventsXMLDoc As XmlTextWriter = New XmlTextWriter(Response.OutputStream, Encoding.UTF8)

        strSQL = "SELECT EmployeeID, LastName, FirstName" _
        & " FROM Employees " _
        & " ORDER BY EmployeeID"

        dbConn.Open()
        objCommand = New SqlCommand(strSQL, dbConn)
        objDataReader = objCommand.ExecuteReader()
        'generate XML
        eventsXMLDoc.Formatting = Formatting.Indented
        Response.ContentType = "text/xml"
        eventsXMLDoc.WriteStartDocument()
        eventsXMLDoc.WriteStartElement("Employees")
        While objDataReader.Read()
            eventsXMLDoc.WriteStartElement("Employee")
            eventsXMLDoc.WriteAttributeString("EmployeeID", objDataReader("EmployeeID"))
            eventsXMLDoc.WriteAttributeString("LastName", objDataReader("LastName"))
            eventsXMLDoc.WriteAttributeString("FirstName", objDataReader("FirstName"))
            eventsXMLDoc.WriteEndElement()
        End While
        eventsXMLDoc.WriteEndElement()
        eventsXMLDoc.Flush()
        eventsXMLDoc.Close()
        objDataReader.Close()
        dbConn.Close()

    End Sub

End Class

Open in new window


So when I run my page it runs just fine and looks like this:

my VB asp page when its run


C# Version

So now I'm doing the same example using C# as the language. This example is where I have a question.


TestEmployeesCS.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="TestEmployeesCS.aspx.cs" Inherits="Map2.TestEmployeesCS" %>

Open in new window


TestEmployeesCS.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Xml;
using System.Configuration;
using System.Text;


    public partial class TestEmployeesCS : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            string strConn = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;

            SqlConnection dbConn = new SqlConnection(strConn);
            string strSQL = null;
            SqlCommand objCommand = default(SqlCommand);

            SqlDataReader objDataReader = default(SqlDataReader);
            XmlTextWriter employeesXMLDoc = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

            strSQL = "SELECT EmployeeID, LastName, FirstName" + " FROM [Northwind].[dbo].[Employees] " + " ORDER BY EmployeeID";

            dbConn.Open();
            objCommand = new SqlCommand(strSQL, dbConn);
            objDataReader = objCommand.ExecuteReader();
            //generate XML
            employeesXMLDoc.Formatting = Formatting.Indented;
            Response.ContentType = "text/xml";
            employeesXMLDoc.WriteStartDocument();
            employeesXMLDoc.WriteStartElement("Employees");
            while (objDataReader.Read())
            {
                employeesXMLDoc.WriteStartElement("Employee");
                
                employeesXMLDoc.WriteAttributeString("EmployeeID", objDataReader["EmployeeID"]);
                employeesXMLDoc.WriteAttributeString("LastName", objDataReader["LastName"]);
                employeesXMLDoc.WriteAttributeString("FirstName", objDataReader["FirstName"]);


                // tested good but not correct formate
                //employeesXMLDoc.WriteStartElement("EmployeeID");
                //employeesXMLDoc.WriteValue(objDataReader["EmployeeID"]);


                employeesXMLDoc.WriteEndElement();
            }
            employeesXMLDoc.WriteEndElement();
            employeesXMLDoc.Flush();
            employeesXMLDoc.Close();
            objDataReader.Close();
            dbConn.Close();


        }
    }

Open in new window


I'm having problem with my C# example. I'm getting the errors underlined in red in the C# image below.

code with error
The output xml should exactly the same as the VB example above.

Anyone know what I'm doing wrong in my c# example?
0
Comment
Question by:maqskywalker
  • 2
3 Comments
 
LVL 34

Accepted Solution

by:
gr8gonzo earned 500 total points
ID: 40612933
Try casting the values as strings. For example:

employeesXMLDoc.WriteAttributeString("EmployeeID", (string)objDataReader["EmployeeID"]);
0
 
LVL 34

Expert Comment

by:gr8gonzo
ID: 40613105
Use (int) instead of (string). If it still has trouble because it's expecting a string, just use the ToString() method after casting:

((int)value).ToString()
0
 
LVL 1

Author Comment

by:maqskywalker
ID: 40613110
thanks gonzo your solution worked.
0

Featured Post

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

We all know that functional code is the leg that any good program stands on when it comes right down to it, however, if your program lacks a good user interface your product may not have the appeal needed to keep your customers happy. This issue can…
This article is for Object-Oriented Programming (OOP) beginners. An Interface contains declarations of events, indexers, methods and/or properties. Any class which implements the Interface should provide the concrete implementation for each Inter…
Email security requires an ever evolving service that stays up to date with counter-evolving threats. The Email Laundry perform Research and Development to ensure their email security service evolves faster than cyber criminals. We apply our Threat…
Finds all prime numbers in a range requested and places them in a public primes() array. I've demostrated a template size of 30 (2 * 3 * 5) but larger templates can be built such 210  (2 * 3 * 5 * 7) or 2310  (2 * 3 * 5 * 7 * 11). The larger templa…

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question