?
Solved

using datareader to output xml in C#

Posted on 2015-02-16
3
Medium Priority
?
141 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 35

Accepted Solution

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

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

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

The Orion Papers

Are you interested in becoming an AWS Certified Solutions Architect?

Discover a new interactive way of training for the exam.

Question has a verified solution.

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

This article introduced a TextBox that supports transparent background.   Introduction TextBox is the most widely used control component in GUI design. Most GUI controls do not support transparent background and more or less do not have the…
Introduction Hi all and welcome to my first article on Experts Exchange. A while ago, someone asked me if i could do some tutorials on object oriented programming. I decided to do them on C#. Now you may ask me, why's that? Well, one of the re…
Do you want to know how to make a graph with Microsoft Access? First, create a query with the data for the chart. Then make a blank form and add a chart control. This video also shows how to change what data is displayed on the graph as well as form…
In this video, Percona Director of Solution Engineering Jon Tobin discusses the function and features of Percona Server for MongoDB. How Percona can help Percona can help you determine if Percona Server for MongoDB is the right solution for …
Suggested Courses
Course of the Month9 days, 15 hours left to enroll

762 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