Thursday, August 30, 2007

Creating XML Documents in Memory to read them into String

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
MemoryStream();

XmlTextWriter xmlTextWriterObject = new
XmlTextWriter(memoryStreamObject, System.Text.Encoding.UTF8);

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
StreamReader(memoryStreamObject);

    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!!

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
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:

  • WriteStartDocument() - you should call this method to start creating an XML document. This will create the first line in the XML document, specifying that the file is an XML document and its encoding.
  • WriteStartElement(string) - this method creates a new element in the XML document with the name specified by the string input parameter. (You can also specify a namespace as a second, optional string parameter.)
  • WriteElementString(name, text_value) - If you want to create an XML element with nothing but text content (i.e., no nested elements), you can use this method.
  • WriteAttributeString(name, value) - this method writes an attribute name and value to the current element.
  • WriteEndElement() - this method closes off the element created in the WriteStartElement(string) method call.
  • WriteEndDocument() - this method completes the writing of the XML document.
  • Close() - this method closes the underlying stream, writing the contents of the XML document to the specified file location.

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
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:

<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
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.

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.

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;
}


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.

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];
}
}

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.

. NET Type Safety

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!!! !!!

Microsoft .NET Remoting WebCast

String vs. StringBuilder - How they Work?

 

String objects in .net are immutable. Once the string has been created, the value can't be changed. When you type s = s + "foo";, you actually discard the old s and create a new string object containing the result of the concatenation. When repeated several times, you end up constructing many temporary string objects.

StringBuilder, on the other hand, represents a mutable string. The class itself contains quite a few methods to change the contents of the string. This includes appending new strings to the end - the most common operation by far. Internally, StringBuilder reserves a buffer of memory which is used only partially at first (usually). Concatenations that fit into the buffer are just pasted in and the string length is changed. If the new resulting string wouldn't fit into the buffer, a new buffer is allocated and the old contents are moved in. In no case new objects need to be created.

The sore points of StringBuilder are the construction cost (which makes the "magic number" practically always at least 3) and the cost of allocating a new buffer when the resultant string would exceed the current buffer size. The latter one explains why the preknowledge (or a good estimation) of the resultant string size helps so much: StringBuilder can just allocate a sufficient buffer once.

.net String vs. StringBuilder - concatenation performance

Great articles on Data Structures and Collections in .NET

Hi,

I would recommend reading these below mentioned articles from MSDN for any programmer who wants to develop or is developing using Microsoft .NET Framework technologies.

Part 1: An Introduction to Data Structures
Part 2: The Queue, Stack, and Hashtable
Part 3: Binary Trees and BSTs
Part 4: Building a Better Binary Search Tree
Part 5: From Trees to Graphs
Part 6: Efficiently Representing Sets

Data Structures in .NET

 

Why data structures are important, and their effect on the performance of an algorithm. To determine a data structure's effect on performance, we'll need to examine how the various operations performed by a data structure can be rigorously analyzed. Finally, we'll turn our attention to two similar data structures present in the .NET Framework: the Array and the List. Chances are you've used these data structures in past projects. In this article, we'll examine what operations they provide and the efficiency of these operations.

The Queue and Stack. Like the List, both the Queue and Stack store a collection of data and are data structures available in the .NET Framework Base Class Library. Unlike a List, from which you can retrieve its elements in any order, Queues and Stacks only allow data to be accessed in a predetermined order. We'll examine some applications of Queues and Stacks, and see how these classes are implemented in the .NET Framework. After examining Queues and Stacks, we'll look at hashtables, which allow for direct access like an ArrayList, but store data indexed by a string key.

While arrays and Lists are ideal for directly accessing and storing contents, when working with large amounts of data, these data structures are often sub-optimal candidates when the data needs to be searched. The binary search tree data structure, which is designed to improve the time needed to search a collection of items. Despite the improvement in search time with the binary tree, there are some shortcomings. SkipLists, which are a mix between binary trees and linked lists, and address some of the issues inherent in binary trees.

A graph is a collection of nodes, with a set of edges connecting the various nodes. For example, a map can be visualized as a graph, with cities as nodes and the highways between them as edged between the nodes. Many real-world problems can be abstractly defined in terms of graphs, thereby making graphs an often-used data structure.

Finally, in Part 6 we'll look at data structures to represent sets and disjoint sets. A set is an unordered collection of items. Disjoint sets are a collection of sets that have no elements in common with one another. Both sets and disjoint sets have many uses in everyday programs, which we'll examine in detail in this final part.

Part 1: An Introduction to Data Structures

Saturday, August 25, 2007

Tuesday, August 21, 2007

Delegates in C# .NET


Delegates in C#
are objects which points towards a function which matches its signature. Delegates are reference type used to encapsulate a method with a specific signature. Delegates are similar to function pointers in C++; however, delegates are type-safe and secure.
Here are some features of delegates:

  • A delegate represents a class.
  • A delegate is type-safe.
  • We can use delegates both for static and instance methods
  • We can combine multiple delegates into a single delegate.
  • Delegates are often used in event-based programming, such as publish/subscribe.
  • We can use delegates in asynchronous-style programming.
  • We can define delegates inside or outside of classes.
Syntax of using delegates
//Declaring delegate
delegate void SampleDelegate(string message);
// declare method with same signature:
static void SampleDelegateMethod(string message) { Console.WriteLine(message); }
// create delegate object
SampleDelegate d1 = SampleDelegateMethod;
// Invoke method with delegate
d1("my program");
Technorati Tags: ,

Web Services in ASP .NET


Introduction to web service especially in asp .net

A Web service is a class that allows its methods to be called by methods on other machines via common data formats and protocols, such as XML and HTTP. In .NET, the over-the-network method calls are commonly implemented through the Simple Object Access Protocol (SOAP), an XML-based protocol describing how to mark up requests and responses so that they can be transferred via protocols such as HTTP. Using SOAP, applications represent and transmit data in a standardized XML-based format.
A Web service is a software component stored on one machine that can be accessed by an application (or other software component) on another machine over a network. The machine on which the Web service resides is referred to as a remote machine. The application (i.e., the client) that accesses the Web service sends a method call over a network to the remote machine, which processes the call and returns a response over the network to the application.

Methods in a Web service are invoked through a Remote Procedure Call (RPC). These methods, which are marked with the WebMethod attribute, are often referred to as Web service methods or simply Web methods. Declaring a method with attribute WebMethod makes the method accessible to other classes through RPCs and is known as exposing a Web method.
Web services have important implications for business-to-business (B2B) transactions. They enable businesses to conduct transactions via standardized, widely available Web services rather than relying on proprietary applications. Web services and SOAP are platform and language independent, so companies can collaborate via Web services without worrying about the compatibility of their hardware, software and communications technologies.
Web services are not the best solution for certain performance-intensive applications, because applications that invoke Web services experience network delays. Also, data transfers are typically larger because data is transmitted in text-based XML formats.

Introduction to WebMethods in ASP .NET

Methods of a class that implement a Web service do not automatically have the ability to receive Web service requests and send back responses, but with Web services created using ASP.NET, it is very simple to add that capability. Apply a WebMethod attribute to public methods. Methods of a Web service class that can be communicated with over the Web are called Web service methods.

Web service methods are a key part of the messaging infrastructure employed by Web services. That is, a client and a Web service communicate using messages, specifically SOAP messages, by default. Clients send a SOAP request to a Web service and a Web service method typically returns a SOAP response. Web services define the type of messages they accept using operations, as defined by Web Services Description Language (WSDL). These operations correlate to each of the Web service methods within a Web service.

Even though each of these Web service methods are defined in ASP.NET using a method of a class, it is important to realize that the data that is eventually communicated over the network must be serialized into XML. As such, it is important to remember that Web services are not a replacement for DCOM, but rather a messaging infrastructure for communicating across platforms using industry standards.

Attaching the WebMethod attribute to a Public method indicates that you want the method exposed as part of the XML Web service. The WebMethod attribute tells .NET that a particular public method should be exposed as a web-callable method. The WebMethod attribute has six associated properties to document and change the behavior of your web method. They are:
Description
MessageName
EnableSession
CacheDuration
TransactionOption
BufferResponse
The first two properties are used to document a web method, while the others affect its behavior.

SOAP in .NET Web Services

The Simple Object Access Protocol (SOAP) is a platform-independent protocol that uses XML to make remote procedure calls.
Each request and response is packaged in a SOAP message containing the information that a Web service requires to process the message.

SOAP supports an extensive set of types like the primitive types, DataSet, DateTime, XmlNode and others. SOAP can also transmit arrays of these types and objects of user-defined types.
When a program invokes a Web method, the request and all relevant information are packaged in a SOAP message and sent to the server on which the Web service resides.
A Web service receives a SOAP message and parses its contents (contained in a SOAP envelope) to determine the method that the client wishes to execute and the method's arguments.
After a Web service parses a SOAP message, the proper method is called and the response is sent back to the client in another SOAP message. The client parses the response to retrieve the result.

User Defined Types in Web Services

It is possible to process user-defined types (also known as custom types) in a Web service. These types can be passed to or returned from Web methods. Web service clients also can use these user-defined types, because the proxy class created for the client contains these type definitions

Custom types that are sent to or from a Web service are serialized, enabling them to be passed in XML format. This process is referred to as XML serialization.
Classes that are used to specify Web method return types and parameter types must provide a public default or parameterless constructor. Properties and instance variables that should be serialized in XML format must be declared public. Properties that should be serialized must provide both get and set accessors. Read-only properties are not serialized. Data that is not serialized simply receives its default value when an object of the class is deserialized.

Technorati Tags: ,

Sunday, August 19, 2007

atoi() function in c# .net - convert string to integer

 

public static int atoi(string str)
{
int sign=1;
int TheNumber=0;
int tmp=0;
int x=0;
int l=(str.Length)-1;
char[] c=str.ToCharArray();

if ('-'==c[0]){sign=-1; x=1;}

for(;x < l;x++)
{
if ((c[x]>='0')&&(c[x]<='9'))
{
tmp=(c[x]-'0');//0 is the 0 index
TheNumber=TheNumber*10+tmp; //to enlarge the number by *10 every time
}
}

return TheNumber*sign;

}

Technorati Tags:

Friday, August 10, 2007

Generic Dictionary Class

It's cool.

Here is a scenario. We want to store few Objects or Instances into a collection and then later identify them based on a key. We can use Dictionary class out of System.Collections.Generic.

Dictionary<TKey, TValue>, which is simply a collection of keys and its values.

So, let's say I want to store few objects in 2 different collections, but then retrieve them in particular order. If it was in single collection, it would have been easier to store in the same collection object, but here we need 2 different collections for storing them because, later at the time of retrieval we need to know the type of the object i.e. value we are retrieving.

Here is how we can handle this scenario.

	private Dictionary<int, ClassA> _ClassAObjectCollection;
private Dictionary<int, ClassB> _ClassBObjectCollection;
public void AddClassAObject(int orderNo, ClassA instance)
{
if(instance == null)
throw new ArgumentNullException("instance");
if(_ClassAObjectCollection == null)
_ClassAObjectCollection = new Dictionary();
_ClassAObjectCollection.Add(orderNo, instance);
}

Same way for ClassB.


So, that's just a small and cool example how can we utilize it to store objects and later retrieve these objects based on key from the collection of objects.


Thursday, August 9, 2007

Switch Statement in C# .net

Switch Statement syntax in C# .NET

switch (expression)
{
case constant-expression:
statement
jump-statement
[default:
statement
jump-statement]
}

 


An example is here...

switch (i) {
case 0:
CaseZero();
goto case 1;
case 1:
CaseZeroOrOne();
goto default;
default:
CaseAny();
break;
}
That's pretty simple C# syntax for Switch-case statements.

Technorati Tags:

Wednesday, August 8, 2007

HOW TO: Validating XML Fragments Against an XML Schema in .NET

This step-by-step article describes how to use XmlValidatingReader and XMLSchemaCollection objects to validate an Extensible Markup Language (XML) fragment against an XML schema.
XmlValidatingReader implements the XmlReader class and provides support for XML data validation. The Schemas property of XmlValidatingReader connects the reader to the schema files cached in an XmlSchemaCollection. The ValidationType property of XmlValidatingReader specifies the type of validation the reader should perform. If you set the property to ValidationType.None, you create a nonvalidating reader.
You can only add XML Schema Definition Language (XSD) schemas and XML-Data Reduced (XDR) schemas to XmlSchemaCollection. Use the Add method with a namespace URI to load schemas. For XML schemas, the typical namespace URI is the targetNamespace property of the schema.

HOW TO: Validate XML Fragments Against an XML Schema in Visual Basic .NET

Technorati Tags: ,

Monday, August 6, 2007

Membership Database instead of ASPNETDB.mdf

Creating Membership Database into existing sql server database

Generally, ASPNETDB.mdf, file based database is created in App_Data folder when we start using ASP .NET Membership and Profile features to use Login Controls in our ASP .NET application. But, generally we would like to create these membership database objects in the same database that we have created for our application.

I have created a video that shows how to do that using aspnet_regsql.exe Sql Server Membership database registration tool.



Saturday, August 4, 2007

.NET Framework Class Browser

 

I don't know if you have already used this class browser. But that's an excellent view of Microsoft .NET Framework Namespaces and Classes

It provides details about the namespaces and its classes. Also, provides information about fields, properties and methods in a class.

.NET Framework Class Browser

Thursday, August 2, 2007

A Unit Testing Walkthrough with Visual Studio Team Test

Introduction

With the latest release of Visual Studio Test System (VSTS) comes a full suite of functionality for Visual Studio Team Test (TT). Team Test is a Visual Studio integrated unit-testing framework that enables:

  • Code generation of test method stubs.
  • Running tests within the IDE.
  • Incorporation of test data loaded from a database.
  • Code coverage analysis once the tests have run.

In addition, Team Test includes a suite of testing capabilities not only for the developer, but the test engineer as well.

In this article, we are going to walk through how to create Team Test unit tests. We begin by writing a sample assembly, and then generating the unit test method stubs within that assembly. This will provide readers new to Team Test and unit testing with the basic syntax and code. It also provides a good introduction on how to quickly set up the test project structure. Next, we switch to using a test driven development (TDD) approach in which we write unit tests before writing the production code.

One of the key features of Team Test is the ability to load test data from a database and then use that data within the test methods. After demonstrating basic unit testing, we describe how to create test data and incorporate it into a test.

A Unit Testing Walkthrough with Visual Studio Team Test

Technorati Tags: ,

 
Dotster Domain Registration Special Offer