In the previous post on Writing XML Documents with XMLTextWriter Class, I have given sample code for writing the XML to an XML file. But what if you wish to create the XML document in memory and use it as a string. I've also included in the sample the way to create well-formatted(indented) XML document with XmlTextWriter. Here is the trick. You could use MemoryStream class to create the XML document and later use it as a string. MemoryStream memoryStreamObject = new XmlTextWriter xmlTextWriterObject = new xmlTextWriterObject.Formatting = Formatting.Indented; xmlTextWriterObject.IndentChar = '\t'; xmlTextWriterObject.Indentation = 1; xmlTextWriterObject.WriteStartDocument(); //here goes entire code to build the XML document xmlTextWriterObject.WriteEndDocument(); xmlTextWriterObject.Flush(); //write the XML content to MemoryStream and close writer memoryStreamObject.Position = 0; StreamReader sr = new String output = sr.ReadToEnd(); //reads entire content from the stream to string //now use the string into your program That's it. So, you could use the create string representation of XML in your .NET Application like saving it into Database or pass it onto another module. Enjoy Xmling!!
MemoryStream();
XmlTextWriter(memoryStreamObject, System.Text.Encoding.UTF8);
StreamReader(memoryStreamObject);
Thursday, August 30, 2007
Creating XML Documents in Memory to read them into String
Posted by chirag at 6:51 PM 2 comments
Labels: .NET Examples, ASP .NET, C# .NET, XML
Wednesday, August 29, 2007
Creating / Writing XML Documents with the XmlTextWriter Class
The .NET Framework provides a class designed specifically to create XML documents, the System.Xml.XmlTextWriter class. By using this class to create XML documents you don't need to worry about illegal XML characters in the text portion of the XML document, and the end code is much cleaner. In this article we'll look at using the XmlTextWriter class to create XML documents on the fly. The Basics of the XmlTextWriter Class To get started using the XmlTextWriter class you need to specify the file and encoding in the class's constructor. The encoding needs to be of the type System.Text.Encoding; some example encoding values are: System.Text.Encoding.ASCII, System.Text.Encoding.Unicode, and System.Text.Encoding.UTF8. Alternatively, you can specify in the constructor that the output of the XmlTextWriter class should be squirted out to a specified Stream. Creating a Simple XML Document with XmlTextWriter <userInfo> <browserInfo> <urlReferrer>URL referrer info</urlReferrer> <userAgent>User agent referrer info</userAgent> <userLanguages>languages info</userLanguages> </browserInfo> <visitInfo timeVisited="date/time the page was visited"> <ip>visitor's IP address</ip> <rawUrl>raw URL requested</rawUrl> </visitInfo> </userInfo> (This XML file structure was chosen so that it would illustrate using all of the XmlTextWriter methods discussed in the previous section.) The code needed to create this XML document through an ASP.NET Web page is shown below: <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Text" %> <script language="C#" runat="server"> void Page_Load(object sender, EventArgs e) { // Create a new XmlTextWriter instance XmlTextWriter writer = new XmlTextWriter(Server.MapPath("userInfo.xml"), Encoding.UTF8); // start writing! writer.WriteStartDocument(); writer.WriteStartElement("userInfo"); // Creating the <browserInfo> element writer.WriteStartElement("browserInfo"); if (Request.UrlReferrer == null) writer.WriteElementString("urlReferrer", "none"); else writer.WriteElementString("urlReferrer", Request.UrlReferrer.PathAndQuery); writer.WriteElementString("userAgent", Request.UserAgent); writer.WriteElementString("userLanguages", String.Join(", ", Request.UserLanguages)); writer.WriteEndElement(); // Creating the <visitInfo> element writer.WriteStartElement("visitInfo"); writer.WriteAttributeString("timeVisited", DateTime.Now.ToString()); writer.WriteElementString("ip", Request.UserHostAddress); writer.WriteElementString("rawUrl", Request.RawUrl); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); } First, notice that the System.Xml and System.Text namespaces have been imported. The Page_Load event handler begins by creating a new XmlTextWriter instance, indicating that its content should be saved to the file userInfo.xml and that its encoding should be UTF8 (a translation of 16-bit unicode encoding into 8-bits). Note that for each element with nested elements a WriteStartElement(elementName) method is called, along with a matching WriteEndElement() after the inner content has been renderred. Furthermore, the WriteElementString(elementName, textValue) is used for those elements with just text content. Emitting XML Content to the Browser Window Directly A better approach is to have the results of the XmlTextWriter emitted directly to the output stream. This can be accomplished quite easily, by changing one line of code in the previous code sample. In the XmlTextWriter constructor, rather than specifying a file path, we can specify a Stream. Specifically, we want to specify Response.OutputStream. When doing this you will need to make another small change to the ASP.NET Web page. In the <@ Page ... > directive you need to indicate the page's MIME type as text/xml. If you don't do this, some browsers may think the data being sent is for a standard HTML Web page, and will attempt to format the XML document just as they would an HTML page (which will hide the XML elements and remove all whitespace). The following code shows an abbreviated version of the previous code sample, with the changes in bold. <@ Page ContentType="text/xml" %> <%@ Import Namespace="System.Xml" %> <%@ Import Namespace="System.Text" %> <script language="C#" runat="server"> void Page_Load(object sender, EventArgs e) { // Create a new XmlTextWriter instance XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8); // start writing! ... } Notice that by viewing the live demo you are shown an XML document (even though you are visiting an ASP.NET Web page). This is the same XML document that, in the previous code sample, was saved to userInfo.xml.
The XmlTextWriter class contains a number of methods that are useful for starting and completing an XML document and for adding elements and attributes to the XML document. The most important methods are:
To demonstrate using the XmlTextWriter class let's create a simple XML document, saving it to a specified file location. This XML document will contain information about the current user visiting the page, and will have this structure:
The previous example demonstrates how to use the XmlTextWriter class to create an XML document and persist it to a file. While this may be precisely what you are after, oftentimes when creating an XML document in an ASP.NET Web page we want to emit the XML content's to the client requesting the Web page. While this could be done in the previous example by opening the userInfo.xml file after creating it and then Response.Write()ing its contents out, this approach is a bit of a hack.
Posted by chirag at 6:49 PM 0 comments
Labels: .NET EX, .NET Examples, ASP .NET, C# .NET, XML
ObjectDataSource with objects having parameterized constructor
The ObjectDataSource control will create an instance of the source object, call the specified method, and dispose of the object instance all within the scope of a single request, if your object has instance methods instead of static methods (Shared in Visual Basic). Therefore, your object must be stateless. That is, your object should acquire and release all required resources within the span of a single request.
You can control how the source object is created by handling the ObjectCreating event of the ObjectDataSource control. You can create an instance of the source object, and then set the ObjectInstance property of the ObjectDataSourceEventArgs class to that instance. The ObjectDataSource control will use the instance that is created in the ObjectCreating event instead of creating an instance on its own.
<asp:objectdatasource id="ObjectDataSource1" typename="Samples.AspNet.CS.EmployeeLogic" onobjectcreating="NorthwindLogicCreating" selectmethod="GetAllEmployees" runat="server">
</asp:objectdatasource>
and have a method defined as
private void NorthwindLogicCreating(object sender, ObjectDataSourceEventArgs e)
{
// Create an instance of the business object using a non-default constructor.
EmployeeLogic eLogic = new EmployeeLogic("Not created by the default constructor!");
// Set the ObjectInstance property so that the ObjectDataSource uses the created instance.
e.ObjectInstance = eLogic;
}
Posted by chirag at 10:32 AM 0 comments
Labels: .NET Examples, ADO .NET, ASP .NET
Tuesday, August 28, 2007
Formatting GridView Template Data using FormatString in ASP .NET
GridView DataFormatString samples to format the Grid View columns Data e.g. DataFormatString="{0:MM/dd/yy}" HeaderText="date2" HtmlEncode="False" SortExpression="date2">
{0:n}Numbers: Provides formatting with commas for a thousands separator.{0:e4} Numbers:Specifies scientific notation to 4 decimal places{0:ddd, MMM d yyyy}date1 Shows a date as Sat, Jan 14, 2006{0:MM/dd/yy}date2 Shows a date as 01/16/06
As you enter these formatting strings, you also need to change the HtmlEncode property to False for each field. Otherwise, the formatting won't show up properly. This changed from the beta versions of the various Visual Studio 2005 products; in those versions, you didn't have to set HtmlEncode property to false.
Posted by chirag at 9:02 PM 0 comments
How Generic Collections work inside?
public class TypeSafeList<T>
{
T[] innerArray = new T[0];
int currentSize = 0;
int capacity = 0;
public void Add(T item)
{
// see if array needs to be resized
if (currentSize == capacity)
{
// resize array
capacity = capacity == 0 ? 4 : capacity * 2; // double capacity
T[] copy = new T[capacity]; // create newly sized array
Array.Copy(innerArray, copy, currentSize); // copy over the array
innerArray = copy; // assign innerArray to the new, larger array
}
innerArray[currentSize] = item;
currentSize++;
}
public T this[int index]
{
get
{
if (index < 0 index >= currentSize)
throw new IndexOutOfRangeException();
return innerArray[index];
}
set
{
if (index < 0 index >= currentSize)
throw new IndexOutOfRangeException();
innerArray[index] = value;
}
}
public override string ToString()
{
string output = string.Empty;
for (int i = 0; i < currentSize - 1; i++)
output += innerArray[i] + ", ";
return output + innerArray[currentSize - 1];
}
}
Posted by chirag at 8:38 AM 0 comments
Labels: .NET Concepts, .NET Examples, C# .NET, VB .NET
Monday, August 27, 2007
. NET Type Safety
Type safe means preventing programs from accessing memory outside the bounds of an object's public properties A programming language is type safe when the language defines the behavior for when the programmer treats a value as a type to which it does not belong. Type safety requires that well-typed programs have no unspecified behavior (i.e., their semantics are complete). Languages such as C and C++, which allow programmers to access arbitrary memory locations, are not type safe. An unsafe programming language supports operations (such as accessing arbitrary memory locations), which are not defined in terms of the language semantics. Type safety is a property of the programming language, and not of the programs themselves.
Posted by chirag at 9:45 AM 0 comments
Labels: .NET Concepts, .NET Framework, .NET Security, .NET Tips, C# .NET
Sunday, August 26, 2007
Microsoft .NET Remoting - Complete Walkthrough
Remoting enables you to write applications that allow objects in different .NET application domains to communicate with each other. In general, objects living in different application domains cannot access each other directly. They need an infrastructure that makes communication possible. That's what .NET Remoting is for. It's the .NET analogy to DCOM, for those of you who are familiar with DCOM. It allows interprocess and intermachine communication between objects.
Look here for a great power-point presentation and also attached interview transcript of the author about Microsoft .NET Remoting - Complete Walkthrough...Just follow him!!! !!!
Posted by chirag at 11:58 PM 0 comments
Labels: .NET Concepts, .NET Framework, C# .NET