Total Pageviews

Showing posts with label ASP.Net. Show all posts
Showing posts with label ASP.Net. Show all posts

Saturday, January 30, 2010

Reading and Writing XML in C#

In this article, you will see how to read and write XML documents in Microsoft .NET using C# language. First, I will discuss XML .NET Framework Library namespace and classes. Then, you will see how to read and write XML documents. In the end of this article, I will show you how to take advantage of ADO.NET and XML .NET model to read and write XML documents from relational databases and vice versa.

Introduction to Microsoft .NET XML Namespaces and Classes Before start working with XML document
in .NET Framework, It is important to know about .NET namespace and classes provided by .NET Runtime Library. .NET provides five namespace - System.Xml, System.Xml.Schema, System.Xml.Serialization, System.Xml.XPath, and System.Xml.Xsl to support XML classes. The System.Xml namespace contains major XML classes. This namespace contains many classes to read and write XML documents. In this article, we are going to concentrate on reader and write class. These reader and writer classes are used to read and write XMl documents. These classes are - XmlReader, XmlTextReader, XmlValidatingReader, XmlNodeReader, XmlWriter, and XmlTextWriter. As you can see there are four reader and two writer classes. The XmlReader class is an abstract bases classes and contains methods and properties to read a document. The Read method reads a node in the stream. Besides reading functionality, this class also contains methods to navigate through a document nodes. Some of these methods are MoveToAttribute,  MoveToFirstAttribute, MoveToContent, MoveToFirstContent, MoveToElement and  MoveToNextAttribute. ReadString, ReadInnerXml, ReadOuterXml, and ReadStartElement are more read methods. This class also has a method Skip to skip current node and move to next one. We'll see these methods in our sample example. The XmlTextReader, XmlNodeReader and XmlValidatingReader classes are derived from XmlReader class. As their name explains, they are used to read text, node, and schemas. The XmlWrite class contains functionality to write data to XML documents. This class provides many write method to write XML document items. This class is base class for XmlTextWriter class, which we'll be using in our sample example. The XmlNode class plays an important role. Although, this class represents a single node of XML but that could be the root node of an XML document and could represent the entire file. This  class is an abstract base class for many useful classes for inserting, removing, and replacing nodes, navigating through the document. It also contains properties to get a parent or child, name, last child, node type and more. Three major classes derived from XmlNode are XmlDocument, XmlDataDocument and XmlDocumentFragment. XmlDocument class represents an XML document and provides methods and properties to load and save a document. It also provides functionality to add XML items such as attributes, comments, spaces, elements, and new nodes.

The Load and LoadXml methods can be used to load XML documents and Save method to save a document respectively. XmlDocumentFragment class represents a document fragment, which can be used to add to a document. The XmlDataDocument class provides methods and properties to work with ADO.NET data set objects. In spite of above discussed classes, System.Xml namespace contains more classes. Few of them are XmlConvert, XmlLinkedNode, and XmlNodeList. Next namespace in Xml series is  System.Xml.Schema.

It classes  to work with XML schemas such XmlSchema, XmlSchemaAll, XmlSchemaXPath, XmlSchemaType. The System.Xml.Serialization namespace contains classes that are used to serialize objects into XML format documents or streams. The System.Xml.XPath Namespce contains XPath related classes to use XPath specifications. This namespace has following classes  -XPathDocument, XPathExression, XPathNavigator, and XPathNodeIterator. With the help of XpathDocument, XpathNavigator provides a fast
navigation though XML documents. This class contains many Move methods to move through a document. The System.Xml.Xsl namespace contains classes to work with XSL/T transformations. Reading XML Documents In my sample application, I'm using books.xml to read and display its data through XmlTextReader. This file comes with VS.NET samples. You can search this on your machine and change the path of the file in the following line: XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); Or you can use any XML file. The XmlTextReader, XmlNodeReader and XmlValidatingReader classes
are derived from XmlReader class. Besides XmlReader methods and properties, these classes also contain members to read text, node, and schemas respectively. I am using XmlTextReader class to read an XML file. You read a file by passing file name as a parameter in constructor. XmlTextReader textReader = new XmlTextReader("C:\\books.xml"); After creating an instance of XmlTextReader, you call Read method to start reading the document. After read method is called, you can read all information and data stored in a document. XmlReader class has properties such as Name, BaseURI, Depth, LineNumber an so on. List 1 reads a document and displays a node information using these properties. About Sample Example 1 In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of file and display the contents to the console output. Sample Example 1.

using System;

using System.Xml;

namespace ReadXml1

{

    class Class1

    {

        static void Main(string[] args)

        {

            // Create an isntance of XmlTextReader and call Read method to read the file

            XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

            textReader.Read();

            // If the node has value

            while (textReader.Read())

            {

                // Move to fist element

                textReader.MoveToElement();

                Console.WriteLine("XmlTextReader Properties Test");

                Console.WriteLine("===================");

                // Read this element's properties and display them on console

                Console.WriteLine("Name:" + textReader.Name);

                Console.WriteLine("Base URI:" + textReader.BaseURI);

                Console.WriteLine("Local Name:" + textReader.LocalName);

                Console.WriteLine("Attribute Count:" + textReader.AttributeCount.ToString());

                Console.WriteLine("Depth:" + textReader.Depth.ToString());

                Console.WriteLine("Line Number:" + textReader.LineNumber.ToString());

                Console.WriteLine("Node Type:" + textReader.NodeType.ToString());

                Console.WriteLine("Attribute Count:" + textReader.Value.ToString());

            }

        }

    }

}

The NodeType property of XmlTextReader is important when you want to know the content type of a document. The XmlNodeType enumeration has a member for each type of XML item such as Attribute, CDATA, Element, Comment, Document, DocumentType, Entity, ProcessInstruction, WhiteSpace and so on. List 2 code sample reads an XML document, finds a node type and writes information at the end with how many node types a document has. About Sample Example 2 In this sample example, I read an XML file using XmlTextReader and call Read method to read its node one by one until end of the file. After reading a node, I check its NodeType property to find the node and write node contents to the console and keep track of number of particular type of nodes. In the end, I display total number of different types of nodes in the document. Sample Example 2.

using System;

using System.Xml;

namespace ReadingXML2

{

    class Class1

    {

        static void Main(string[] args)

        {

            int ws = 0;

            int pi = 0;

            int dc = 0;

            int cc = 0;

            int ac = 0;

            int et = 0;

            int el = 0;

            int xd = 0;

            // Read a document

            XmlTextReader textReader = new XmlTextReader("C:\\books.xml");

            // Read until end of file

            while (textReader.Read())

            {

                XmlNodeType nType = textReader.NodeType;

                // If node type us a declaration

                if (nType == XmlNodeType.XmlDeclaration)

                {

                    Console.WriteLine("Declaration:" + textReader.Name.ToString());

                    xd = xd + 1;

                }

                // if node type is a comment

                if (nType == XmlNodeType.Comment)

                {

                    Console.WriteLine("Comment:" + textReader.Name.ToString());

                    cc = cc + 1;

                }

                // if node type us an attribute

                if (nType == XmlNodeType.Attribute)

                {

                    Console.WriteLine("Attribute:" + textReader.Name.ToString());

                    ac = ac + 1;

                }

                // if node type is an element

                if (nType == XmlNodeType.Element)

                {

                    Console.WriteLine("Element:" + textReader.Name.ToString());

                    el = el + 1;

                }

                // if node type is an entity\

                if (nType == XmlNodeType.Entity)

                {

                    Console.WriteLine("Entity:" + textReader.Name.ToString());

                    et = et + 1;

                }

                // if node type is a Process Instruction

                if (nType == XmlNodeType.Entity)

                {

                    Console.WriteLine("Entity:" + textReader.Name.ToString());

                    pi = pi + 1;

                }

                // if node type a document

                if (nType == XmlNodeType.DocumentType)

                {

                    Console.WriteLine("Document:" + textReader.Name.ToString());

                    dc = dc + 1;

                }

                // if node type is white space

                if (nType == XmlNodeType.Whitespace)

                {

                    Console.WriteLine("WhiteSpace:" + textReader.Name.ToString());

                    ws = ws + 1;

                }

            }

            // Write the summary

            Console.WriteLine("Total Comments:" + cc.ToString());

            Console.WriteLine("Total Attributes:" + ac.ToString());

            Console.WriteLine("Total Elements:" + el.ToString());

            Console.WriteLine("Total Entity:" + et.ToString());

            Console.WriteLine("Total Process Instructions:" + pi.ToString());

            Console.WriteLine("Total Declaration:" + xd.ToString());

            Console.WriteLine("Total DocumentType:" + dc.ToString());

            Console.WriteLine("Total WhiteSpaces:" + ws.ToString());

        }

    }

}

Writing XML Documents XmlWriter class contains the functionality to write to XML documents. It is an abstract base class used through XmlTextWriter and XmlNodeWriter classes. It contains methods and properties to write to XML documents. This class has several Writexxx method to write every type of item of an XML document. For example, WriteNode, WriteString, WriteAttributes, WriteStartElement, and WriteEndElement are some of them. Some of these methods are used in a start and end pair. For example,
to write an element, you need to call WriteStartElement then write a string followed by WriteEndElement.          

Besides many methods, this class has three properties. WriteState, XmlLang, and XmlSpace. The WriteState gets and sets the state of the XmlWriter class. Although, it's not possible to describe all the Writexxx methods here, let's see some of them. First thing we need to do is create an instance of XmlTextWriter using its  constructor. XmlTextWriter has three overloaded constructors, which can take a string, stream, or a TextWriter as an argument. We'll pass a string (file name) as an argument, which we're going to create in C:\ root. In my sample example, I create a file myXmlFile.xml in C:\\ root directory. // Create a new file in C:\\ dir XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null) ; After creating an instance, first
thing you call us WriterStartDocument. When you're done writing, you call WriteEndDocument and TextWriter's Close method. textWriter.WriteStartDocument(); textWriter.WriteEndDocument(); textWriter.Close(); The WriteStartDocument and WriteEndDocument methods open and close a document for writing. You must have to open a document before start writing to it.  WriteComment method writes comment to a document. It takes only one string type of argument. WriteString method writes a string to a document. With the help of WriteString, WriteStartElement and WriteEndElement methods pair can be used  to write an element to a document. The WriteStartAttribute and WriteEndAttribute pair writes an attribute. WriteNode is more write method, which writes an XmlReader to a document as a node of the document. For example, you can use WriteProcessingInstruction and WriteDocType methods to write a ProcessingInstruction and DocType items of a document. //Write the ProcessingInstruction node string PI= "type='text/xsl' href='book.xsl'" textWriter.WriteProcessingInstruction("xml-stylesheet", PI); //'Write the DocumentType node textWriter.WriteDocType("book", Nothing, Nothing, ""); The below sample example summarizes all these methods and creates a new xml document with some items in it such as elements, attributes, strings, comments and so on. See Listing 5-14. In this sample example, we create a new xml file c:\xmlWriterText.xml. In this sample example, We create a new xml file c:\xmlWriterTest.xml using XmlTextWriter: After that, we add comments and elements to the document using Writexxx methods. After that we read our books.xml xml file using XmlTextReader and add its elements to xmlWriterTest.xml using XmlTextWriter. About Sample Example 3 In this sample example, I create a new file myxmlFile.xml using XmlTextWriter and use its various write methods to write XML items. Sample Example 3.

using System;

using System.Xml;

namespace ReadingXML2

{

    class Class1

    {

        static void Main(string[] args)

        {

            // Create a new file in C:\\ dir

            XmlTextWriter textWriter = new XmlTextWriter("C:\\myXmFile.xml", null);

            // Opens the document

            textWriter.WriteStartDocument();

            // Write comments

            textWriter.WriteComment("First Comment XmlTextWriter Sample Example");

            textWriter.WriteComment("myXmlFile.xml in root dir");

            // Write first element

            textWriter.WriteStartElement("Student");

            textWriter.WriteStartElement("r", "RECORD", "urn:record");

            // Write next element

            textWriter.WriteStartElement("Name", "");

            textWriter.WriteString("Student");

            textWriter.WriteEndElement();

            // Write one more element

            textWriter.WriteStartElement("Address", ""); textWriter.WriteString("Colony");

            textWriter.WriteEndElement();

            // WriteChars

            char[] ch = new char[3];

            ch[0] = 'a';

            ch[1] = 'r';

            ch[2] = 'c';

            textWriter.WriteStartElement("Char");

            textWriter.WriteChars(ch, 0, ch.Length);

            textWriter.WriteEndElement();

            // Ends the document.

            textWriter.WriteEndDocument();

            // close writer

            textWriter.Close();

        }

    }

}

Using XmlDocument The XmlDocument class represents an XML document. This class provides similar methods and properties we've discussed earlier in this article. Load and LoadXml are two useful methods of this class. A Load method loads XML data from a string, stream, TextReader or XmlReader. LoadXml method loads XML document from a specified string. Another useful method of this class is Save. Using Save method you can write XML data to a string, stream, TextWriter or XmlWriter. About Sample Example 4 This tiny sample example pretty easy to understand. We call LoadXml method of XmlDocument to load an XML fragment and call Save to save the fragment as an XML file. Sample Example 4.

//Create the XmlDocument. XmlDocument doc = new XmlDocument();
doc.LoadXml(("Tommyex")); //Save the document to a file. doc.Save("C:\\std.xml");

You can also use Save method to display contents on console if you pass Console.Out as a arameter. For example: doc.Save(Console.Out); About Sample Example 5 Here is one example of how to load an XML document using XmlTextReader. In this sample example, we read books.xml file using XmlTextReader and call its Read method. After that we call XmlDocumetn's Load method to load XmlTextReader contents to XmlDocument and call Save method to save the document. Passing Console.Out as a Save method
argument displays data on the console Sample Example 5. XmlDocument doc = new XmlDocument();
//Load the the document with the last book node.
XmlTextReader reader = new XmlTextReader("c:\\books.xml");
reader.Read(); // load reader doc.Load(reader); // Display contents on the console
doc.Save(Console.Out); Writing Data from a database to an XML Document Using XML and ADO.NET mode, reading a database and writing to an XML document and vice versa is not a big deal. In this section of this article, you will see how to read a database table's data and write the contents to an XML document. The DataSet class provides method to read a relational database table and write this table to an XML file.
You use WriteXml method to write a dataset data to an XML file. In this sample example, I have used commonly used Northwind database comes with Office 2000 and later versions. You can use any database you want. Only thing you need to do is just chapter the connection string and SELECT SQ L query. About Sample Example 6  In this sample, I reate a data adapter object and selects all records of Customers table. After that I can fill method to fill a dataset from the data adapter. In this sample example,I have used OldDb data provides. You need to add reference to the Syste.Data.OldDb namespace to use OldDb data adapters in your program. As you can see from Sample Example 6, first I create a connection with northwind database using OldDbConnection. After that I create a data adapter object by passing a SELECT SQL query and connection. Once you have a data adapter, you can fill a dataset object using Fill method of the data adapter. Then you can WriteXml method of DataSet, which creates an XML document and write its contents to the XML document. In our sample, we read Customers table records and write DataSet contents to OutputXml.Xml file in C:\ dir. Sample Example 6.
using System; using System.Xml; using System.Data; using System.Data.OleDb; namespace ReadingXML2 { class Class1 { static void Main(string[] args) { // create a connection OleDbConnection con = new OleDbConnection(); con.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Northwind.mdb"; // create a data adapter OleDbDataAdapter da = new OleDbDataAdapter("Select * from Customers", con); // create a new dataset DataSet ds = new DataSet(); // fill dataset da.Fill(ds, "Customers"); // write dataset contents to an xml file by calling WriteXml method ds.WriteXml("C:\\OutputXML.xml"); } } }

.NET Framework Library provides a good support to work with XML documents. The XmlReader,
XmlWriter and their derived classes contains methods and properties to read and write XML documents. With the help of the XmlDocument and XmlDataDocument classes, you can read entire document. The Load and Save method of XmlDocument loads a reader or a file and saves document respectively. ADO.NET provides functionality to read a database and write its contents to the XML document using data providers and a DataSet object.

Main Differences between ASP.NET 3.5 and ASP.NET 4.0

As we all know, ASP.NET 3.5 has introduced with the following main new features

1) AJAX integration
2) LINQ
3) Automatic Properties
4) Lambda expressions

I hope it would be useful for everyone to know about the differences about asp.net 3.5 and its next version asp.net 4.0

Because of space consumption I’ll list only some of them here.

1) Client Data access:



ASP.NET 3.5: There is no direct method to access data from client side. We can go for any of these methods

1) Pagemethods of script manager
2) ICallbackEventHandler interface
3) XMLHttphanlder component

ASP.NET 4.0: In this framework there is an inbuilt feature for this. Following are the methods to implement them.

1) Client data controls
2) Client templates
3) Client data context

i.e we can access the data through client data view & data context objects from client side.

2) Setting Meta keyword and Meta description:



Meta keywords and description are really useful for getting listed in search engine.

ASP.NET 3.5: It has a feature to add meta as following tag
&ltmeta name="keywords" content="These, are, my, keywords" /> 
  &ltmeta name="description" content="This is the description of my page" /> 


ASP.NET 4.0: Here we can add the keywords and description in Page directives itself as shown below.
< %@ Page Language="C#"  CodeFile="Default.aspx.cs" 
  Inherits="_Default" 
  Keywords="Keyword1,Key2,Key3,etc" 
  Description="description" %>


3) Enableviewstage property for each control



ASP.NET 3.5: this property has two values “True” or “false”

ASP.NET 4.0: ViewStateMode property takes an enumeration that has three values: Enabled, Disabled, and Inherit.
Here inherit is the default value for child controls of a control.

4) Setting Client IDs



Some times ClientID property creates head ach for the programmers.

ASP.NET 3.5: We have to use ClientID property to find out the id which is dynamically generated

ASP.NET 4.0: The new ClientIDMode property is introduced to minimize the issues of earlier versions of ASP.NET.

It has following values.

AutoID – Same as ASP.NET 3.5
Static – There won’t be any separate clientid generated at run time
Predictable-These are used particularly in datacontrols. Format is like clientIDrowsuffix with the clientid vlaue
Inherit- This value specifies that a control's ID generation is the same as its parent. 



--
happy programming.

Monday, January 25, 2010

.Net Memory Management & Garbage Collection

The Microsoft .NET common language runtime requires that all resources be allocated from the managed heap. Objects are automatically freed when they are no longer needed by the application.
When a process is initialized, the runtime reserves a contiguous region of address space that initially has no storage allocated for it. This address space region is the managed heap. The heap also maintains a pointer. This pointer indicates where the next object is to be allocated within the heap. Initially, the pointer is set to the base address of the reserved address space region.
Garbage collection in the Microsoft .NET common language runtime environment completely absolves the developer from tracking memory usage and knowing when to free memory. However, you’ll want to understand how it works. So let’s do it.
Topics Covered
We will cover the following topics in the article

  1. Why memory matters
  2. .Net Memory and garbage collection
  3. Generational garbage collection
  4. Temporary Objects
  5. Large object heap & Fragmentation
  6. Finalization
  7. Memory problems

1) Why Memory Matters

Insufficient use of memory can impact
  • Performance
  • Stability
  • Scalability
  • Other applications
Hidden problem in code can cause

  • Memory leaks
  • Excessive memory usage
  • Unnecessary performance overhead

2) .Net Memory and garbage collection

.Net manages memory automatically
  • Creates objects into memory blocks(heaps)
  • Destroy objects no longer in use
Allocates objects onto one of two heaps
  • Small object heap(SOH) – objects < 85k
  • Large object heap(LOH) – objects >= 85k
You allocate onto the heap whenever you use the “new” keyword in code
Small object heap (SOH)

  • Allocation of objects < 85k – Contiguous heap – Objects allocated consecutively
  • Next object pointer is maintained – Objects references held on Stack, Globals, Statics and CPU register
  • Objects not in use are garbage collected
Figure-1
SOH_1
Next, How GC works in SOH?
GC Collect the objects based on the following rules:

  • Reclaims memory from “rootless” objects
  • Runs whenever memory usage reaches certain thresholds
  • Identifies all objects still “in use”

    • Has root reference
    • Has an ancestor with a root reference

  • Compacts the heap

    • Copies “rooted” objects over rootless ones
    • Resets the next object pointer

  • Freezes all execution threads during GC

    • Every GC runs it   hit the performance of your app

Figure-2
SOH2

3) Generational garbage collection


Optimizing Garbage collection
  • Newest object usually dies quickly
  • Oldest object tend to stay alive
  • GC groups objects into Generations

    • Short lived – Gen 0
    • Medium – Gen 1
    • Long Lived – Gen 2

  • When an object survives a GC it is promoted to the next generation
  • GC compacts Gen 0 objects most often
  • The more the GC runs the bigger the impact on performance
Figure-3
Generations_3
Figure-4
Generations_4
Here object C is no longer referenced by any one so when GC runs it get destroyed & Object D will be moved to the Gen 1 (see figure-5). Now Gen 0 has no object, so when next time when GC runs it will collect object from Gen 1.

Figure-5
Generations_5
Figure-6
Generations_6
Here when GC runs it will move the object D & B to Gen 2 because it has been referenced by Global objects & Static objects.
Figure-7
Generations_7

Here when GC runs for Gen 2 it will find out that object A is no longer referenced by anyone so it will destroy it & frees his memory. Now Gen 2 has only object D & B.
Garbage collector runs when
  • Gen 0 objects reach ~256k
  • Gen 1 objects reach ~2Meg
  • Gen 2 objects reach ~10Meg
  • System memory is low
Most objects should die in Gen 0.
Impact on performance is very high when Gen 2 run because
  • Entire small object heap is compacted
  • Large object heap is collected

4) Temporary objects

  • Once allocated objects can’t resize on a contiguous heap
  • Objects such as strings are Immutable


    • Can’t be changed, new versions created instead
    • Heap fills with temporary objects

Let us take example to understand this scenario.
Figure – 8
TempObj_8
After the GC runs all the temporary objects are destroyed.
Figure–9

TempObj_9

5) Large object heap & Fragmentation

Large object heap (LOH)
  • Allocation of object >=85k
  • Non contiguous heap

    • Objects allocated using free space table


  • Garbage collected when LOH Threshold Is reached
  • Uses free space table to find where to allocate
  • Memory can become fragmented
Figure-10
LOH_10
After object B is destroyed free space table will be filled with a memory address which has been available now.
Figure-11
LOH_11

Now when you create new object, GC will check out which memory area is free or available for our new object in LOH. It will check out the Free space table & allocate object where it fit.
Figure-12
LOH_12

6) Object Finalization

  • Disk, Network, UI resources need safe cleanup after use by .NET classes
  • Object finalization guarantees cleanup code will be called before collection
  • Finalizable object survive for at least 1 extra GC & often make it to Gen 2
  • Finalizable classes have a

    • Finalize method(c# or vb.net)
    • C++ style destructor (c#)

Here are the guidelines that help you to decide when to use Finalize method:
  • Only implement Finalize on objects that require finalization. There are performance costs associated with Finalize methods.
  • If you require a Finalize method, you should consider implementing IDisposable to allow users of your class to avoid the cost of invoking the Finalize method.
  • Do not make the Finalize method more visible. It should be protected, not public.
  • An object’s Finalize method should free any external resources that the object owns. Moreover, a Finalize method should release only resources that are held onto by the object. The Finalize method should not reference any other objects.
  • Do not directly call a Finalize method on an object other than the object’s base class. This is not a valid operation in the C# programming language.
  • Call the base.Finalize method from an object’s Finalize method.
Note: The base class’s Finalize method is called automatically with the C# and the Managed Extensions for C++ destructor syntax.
Let see one example to understand how the finalization works.
Each figure itself explain what is going on & you can clearly see how the finalization works when GC run.

Figure-13
Final_13
Figure-14
Final_14
Figure-15
Final_15
Figure-16
Final_16
Figure-17

Final_17
For more information on Finalization refer the following links:
http://www.object-arts.com/docs/index.html?howdofinalizationandmourningactuallywork_.htm
http://blogs.msdn.com/cbrumme/archive/2004/02/20/77460.aspx
How to minimize overheads
Object size, number of objects, and object lifetime are all factors that impact your application’s allocation profile. While allocations are quick, the efficiency of garbage collection depends (among other things) on the generation being collected. Collecting small objects from Gen 0 is the most efficient form of garbage collection because Gen 0 is the smallest and typically fits in the CPU cache. In contrast, frequent collection of objects from Gen 2 is expensive. To identify when allocations occur, and which generations they occur in, observe your application’s allocation patterns by using an allocation profiler such as the CLR Profiler.
You can minimize overheads by:
  • Avoid Calling GC.Collect
  • Consider Using Weak References with Cached Data
  • Prevent the Promotion of Short-Lived Objects
  • Set Unneeded Member Variables to Null Before Making Long-Running Calls
  • Minimize Hidden Allocations
  • Avoid or Minimize Complex Object Graphs
  • Avoid Preallocating and Chunking Memory
Read more: http://www.guidanceshare.com/wiki/.NET_2.0_Performance_Guidelines_-_Garbage_Collection

7) Common Memory Problems

  • Excessive RAM footprint

    • App allocates objects too early or for too long using more memory than needed
    • Can affect other app on system

  • Excessive temporary object allocation

    • Garbage collection runs more frequently
    • Executing threads freeze during garbage collection

  • Memory leaks


    • Overlooked root references keep objects alive (collections, arrays, session state, delegates/events etc)
    • Incorrect or absent finalization can cause resource leaks

References & other useful articles related to this topic:
Hope this help

Monday, January 4, 2010

Uploading Multiple Files in ASP.NET 2.0

In ASP.NET We can upload more than one file using the following classes:

HttpFileCollection
HttpPostedFile
Request.Files
System.IO.Path

HttpFileCollection:

HttpFileCollection will provide access to the files uploaded by a client.

HttpPostedFile:

HttpPostedFile will provide access to individual files uploaded by a client. Through this class we can access the content and properties of each individual file, and read and save the files.

Request.Files :

The Request.Files will return collection of all files uploaded by user and store them inside the HttpFileCollection.

Follow these steps mentioned below to do so:

Step 1:

Drag and drop multiple (in our case four) FileUpload controls on to the designer.

Step 2:

Drop a Button control and rename it to “Upload”
<asp:Button ID=”btnUpload” runat=”server” Text=”Upload” />

Step 3:

Double click the Upload Button to add an event hander to the code behind.
protected void btnUpload_Click(object sender, EventArgs e)
{

}

Step 4: Import the System.IO namespace.
using System.IO;

Step 5:

Use the ‘HttpFileCollection’ class to retrieve all the files that are uploaded. Files are encoded and transmitted in the content body using multipart MIME format with an HTTP Content-Type header. ASP.NET extracts
this information from the content body into individual members of an HttpFileCollection.

The code would look as follows:
protected void btnUpload_Click(object sender, EventArgs e)
{
try
{
// Get the HttpFileCollection
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
hpf.SaveAs(Server.MapPath(”MyFiles”) + “\\” +
Path.GetFileName(hpf.FileName));

}
}
}
catch (Exception ex)
{
// Handle your exception here
}

}
Some important points to consider while uploading

1.    To save a file to the server, the account associated with ASP.NET must have sufficient permissions on the folder, where the files are being uploaded. This would usually be the ‘ASPNET’ account for Windows XP or a similar OS. In Windows Server 2003, the account used is ‘NETWORKSERVICE’. So you would be required to explicitly grant write permissions to these accounts on the folder.

2.    While uploading the files to a remote server, the default ASPNET user account used by ASP.NET does not have network permissions by default. The solution is to either give the account such permissions or
use impersonation to have it run under a different account that has the permissions.

3.    By default, you can upload no more than 4096 KB (4 MB) of data. However there is a workaround for this limitation. You can change the maximum file size by changing the maxRequestLength attribute of the
httpRuntime element in the web.config file. You can also increase the ‘executionTimeout’. By default it is 110 seconds. I would encourage you to experiment with the other attributes of the httpRuntime element.

<configuration>
<system.web>
<httpRuntime
executionTimeout=”200″
maxRequestLength=”8192″
requestLengthDiskThreshold=”256″
useFullyQualifiedRedirectUrl=”false”
minFreeThreads=”8″
minLocalRequestFreeThreads=”4″
appRequestQueueLimit=”5000″
enableKernelOutputCache=”true”
enableVersionHeader=”true”
requireRootedSaveAsPath=”true”
enable=”true”
shutdownTimeout=”90″
delayNotificationTimeout=”5″
waitChangeNotification=”0″
maxWaitChangeNotification=”0″
enableHeaderChecking=”true”
sendCacheControlHeader=”true”
apartmentThreading=”false”/>
</system.web>
</configuration>

References

There are a number of good resources I referred to, for this article. A few of them are:

http://www.wrox.com/WileyCDA/Section/id-292160.html
http://msdn2.microsoft.com/en-US/library/aa479405.aspx
http://msdn2.microsoft.com/en-us/library/system.web.httpfilecollection.aspx

Friday, December 18, 2009

Encryption & Decryption : ASCII encoding

The GetByteCount method determines how many bytes result in encoding a set of Unicode characters, and the GetBytes method performs the actual encoding.

Likewise, the GetCharCount method determines how many characters result in decoding a sequence of bytes, and the GetChars and GetString methods perform the actual decoding.

When selecting the ASCII encoding for your applications, consider the following:

    * The ASCII encoding is usually appropriate for protocols that require ASCII.
    * If your application requires 8-bit encoding, the UTF-8 encoding is recommended over the ASCII encoding. For the characters 0-7F, the results are identical, but use

of UTF-8 avoids data loss by allowing representation of all Unicode characters that are representable. Note that the ASCII encoding has an 8th bit ambiguity that can allow malicious use, but the UTF-8 encoding removes ambiguity about the 8th bit.

    * Previous versions of .NET Framework allowed spoofing by merely ignoring the 8th bit. The current version has been changed so that non-ASCII code points fall back during the decoding of bytes.

——————————————————————
Example of ASCII encoding
——————————————————————

SecurityClass.cs
————————–
public static string EnryptString(string strEncrypted)
{
byte[] b = System.Text.ASCIIEncoding.ASCII.GetBytes(strEncrypted);
string encryptedConnectionString = Convert.ToBase64String(b);
return encryptedConnectionString;
}

public static string DecryptString(string encrString)
{
byte[] b = Convert.FromBase64String(encrString);
string decryptedConnectionString = System.Text.ASCIIEncoding.ASCII.GetString(b);
return decryptedConnectionString;
}

Default.aspx.cs
———————
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string Password = “SandeepMRamani”;
lblOriginal.Text = Password;
lblEncryption.Text = SecurityClass.EnryptString(Password);
lblDecryption.Text = SecurityClass.DecryptString(lblEncryption.Text);
}
}
Default.aspx
——————
<div align=”center” style=”font-size:xx-large;”>
<h1> Encryption / Decryption Example </h1>
<hr />

Original String :
<asp:Label ID=”lblOriginal” style=”font-weight:bolder;” runat=”server” Text=”"></asp:Label>
<br />
Encrypted Text :
<asp:Label ID=”lblEncryption” style=”font-weight:bolder;” runat=”server” Text=”"></asp:Label>
<br />
Decrypted Text :
<asp:Label ID=”lblDecryption” style=”font-weight:bolder;” runat=”server” Text=”"></asp:Label>
<hr />
</div>

--

Happy programming

Thursday, December 17, 2009

How to dynamically adjust an iframe’s height?

I was looking to display content of the other aspx page inside iframe but i wasnt able to adjust the height of the iframe. so try out this solution to resolve it.

Insert iframe on page
   <iframe scrolling='no' frameborder='0' id='frmid' src=’getad.aspx'
            onload='javascript:resizeIframe(this);'>
   </iframe>


Use this javascript to resize iframe based on the height & width of child page




<script language="javascript" type="text/javascript">
 function resizeIframe(obj)
 {
   obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
   obj.style.width = obj.contentWindow.document.body.scrollWidth + 'px';
 }
 </script>


What does this code do? When the body of the parent frame loads, it looks up the document element “childframe” which corresponds to the iframe. Then the page calls a function resizeFrame(). The function sets the height of the frame to be the scrollHeight, which effectively removes the scrollbar.

happy programming!

Friday, November 13, 2009

How to Get the Record Count of SQLDataSource?

To get the Record Count or Row Count returned by SQLDataSource control, we have to use DataSourceSelectArgument class.

Create an object to the DataSourceSelectArgument class, set its RetrieveTotalRowCount property to true and by using a DataView we can retrieve the Row Count of the SQLDataSource object. The sample block of code is given below. Try it.


<pre name="code" class="CSharp">

DataSourceSelectArguments dssa = new DataSourceSelectArguments();
dssa.AddSupportedCapabilities(DataSourceCapabilities.RetrieveTotalRowCount);
dssa.RetrieveTotalRowCount = true;
DataView dv = (DataView)SqlDataSource1.Select(dssa);
Response.Write("No of Records : " + dv.Table.Rows.Count);

</pre>

--
happy programming 

Using LINQ to query object hierarchies

I used LINQ to solve the following problem: find all titles of objects at hierarchy level X when you know object ID in hierarchy level Y. I cannot imagine if there is some other solution that is same short and clear as one that LINQ provides. Take a look and decide by yourself.
linq-levels-example Here is simple diagram with my entities. Here are my simple rules. Level1 has no parent level and my contain one ore more Level2 entities. Level2 entities have one Level1 parent and one or more Level3 enitities. Level3 entities have one Level2 parent entity and collection of one or more Items. So there is many-to-many relationship between Level3 and Items.
We cannot use composite pattern here because these classes will be very different and there will be no point where we need one common interface for them. That’s why we have one class per level. Also the number of levels is fixed and there is no plan to expand this hierarchy.
By the way, you can model arbitrary class hierarchies on this model and still use this example (as long as it doesn’t hurt performance and you are really sure what you are doing).
Excercise: having Level1 items collection and knowing Level3 item ID find all Items for specified Level3 item and return string of their titles separated by comma. As you don’t have access to source code of data source you must use IList<Level1> and LINQ.
We will use simple class structure given below and we expect that we already got list of Level1 items from some repository or data context.

public class Level1
{
    public int Id { get; set; }
    public string Title { get; set; }
    public IList<Level2> Level2Items { get; set; }
}

public class Level2
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Level1 Parent { get; set; }
    public IList<Level3> Level3Items { get; set; }
}

public class Level3
{
    public int Id { get; set; }
    public string Title { get; set; }
    public Level2 Parent { get; set; }
    public IList<Item> Items { get; set; }
}

public class Item
{
    public int Id { get; set; }
    public string Title { get; set; }
}

Now it’s time to write some hardcore loops and create a cool code-hell… or maybe it’s time to be elegant and use LINQ as stated before. Using LINQ we can provide the following solution:

public string GetItemsStringForLevel3(IList<Level1> level1Items, int level3Id)
{           
    var items = from l in level1Items
                  from l2 in l.Level2Items
                  from l3 in l2.Level3Items
                  from p in l3.Items
                where l3.Id == level3Id
                select p.Title;

    return string.Join(", ", items.ToArray());
}

--
Happy Programming

Thursday, November 12, 2009

Statement cannot appear within a method body. End of method assumed

Today when I was developing web pages using asp.net,I encountered a problem as below:
Server Error in '/BC30289' Application.
 
Compilation Error Description:
An error occurred during the compilation of a resource required to service  this request. Please review the following specific error details and modify your  source code appropriately.

Compiler Error Message: 
BC30289:  Statement cannot appear within a method body. End of method assumed.

Error Line: Sub showImage(Byval id as string)
I replaced "<% %>" with
<script language="vbscript" runat="server"></script>

And then everything works fine.

That is because we cannot define asp 'sub' or 'function' between the body tag

--
Happy Programming

What is Maximum Request size for asp.net application?

The default max request size is 4MB (4096).
You can change a setting in your web.config to allow larger requests.
Here is the example:
   1: <configuration>
   2:        <system.web>

   3:            <httpRuntime  maxRequestLength="4096"/>
   4:        </system.web>

   5: </configuration>
This is default setting, we have to change this to the size that you want to allow user to request like 10MB, 20MB…

---
Happy Programming

Monday, October 26, 2009

DateTime String Format In Asp.net

Here are some of the string formats that you can try out:
Specifier
type
output
(June 8, 1970 12:30:59)
dd
Day
08
ddd
Short Day Name
Mon
dddd
Full Day Name
Monday
hh
2 digit hour
12
HH
2 digit hour (24 hour)
12
mm
2 digit minute
30
MM
Month
06
MMM
Short Month name
Jun
MMMM
Month name
June
ss
seconds
59
tt
AM/PM
PM
yy
2 digit year
70
yyyy
4 digit year
1970
:
seperator, e.g. {0:hh:mm:ss}
12:30:59
/
seperator, e.g. {0:dd/MM/yyyy}
08/06/1970

Try this way

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:BoundField HeaderText="CheckDateFormat" DataField="Date" DataFormatString="{0:M-dd-yyyy}" />
</Columns>
</asp:GridView>
---
DateTime dt = DateTime.Now;
String strDate="";
strDate = dt.ToString("MM/dd/yyyy");   // 07/21/2007 

strDate = dt.ToString("dddd, dd MMMM yyyy");   //Saturday, 21 July 2007

strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm"); // Saturday, 21 July 2007 14:58

strDate = dt.ToString("dddd, dd MMMM yyyy hh:mm tt"); // Saturday, 21 July 2007 03:00 PM

strDate = dt.ToString("dddd, dd MMMM yyyy H:mm"); // Saturday, 21 July 2007 5:01 

strDate = dt.ToString("dddd, dd MMMM yyyy h:mm tt"); // Saturday, 21 July 2007 3:03 PM

strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:04:10

strDate = dt.ToString("MM/dd/yyyy HH:mm"); // 07/21/2007 15:05

strDate = dt.ToString("MM/dd/yyyy hh:mm tt"); // 07/21/2007 03:06 PM

strDate = dt.ToString("MM/dd/yyyy H:mm"); // 07/21/2007 15:07

strDate = dt.ToString("MM/dd/yyyy h:mm tt"); // 07/21/2007 3:07 PM

strDate = dt.ToString("MM/dd/yyyy HH:mm:ss"); // 07/21/2007 15:09:29

strDate = dt.ToString("MMMM dd"); // July 21

strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss.fffffffK"); // 2007-07-21T15:11:19.1250000+05:30    

strDate = dt.ToString("ddd, dd MMM yyyy HH':'mm':'ss 'GMT'"); // Sat, 21 Jul 2007 15:12:16 GMT

strDate = dt.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss"); // 2007-07-21T15:12:57

strDate = dt.ToString("HH:mm"); // 15:14

strDate = dt.ToString("hh:mm tt"); // 03:14 PM

strDate = dt.ToString("H:mm"); // 5:15

strDate = dt.ToString("h:mm tt"); // 3:16 PM

strDate = dt.ToString("HH:mm:ss"); // 15:16:29

strDate = dt.ToString("yyyy'-'MM'-'dd HH':'mm':'ss'Z'"); // 2007-07-21 15:17:20Z

strDate = dt.ToString("dddd, dd MMMM yyyy HH:mm:ss"); // Saturday, 21 July 2007 15:17:58

strDate = dt.ToString("yyyy MMMM"); // 2007 July




Hence we can format and getting the datetime value.

Saturday, October 24, 2009

Export DataSet or DataTable to Word, Excel, PDF and CSV Formats

using System.Data;
using System.Data.SqlClient;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
Function to get the results in datatable
private DataTable GetData(SqlCommand cmd)
{
DataTable dt = new DataTable();
String strConnString = System.Configuration.ConfigurationManager.
ConnectionStrings["conString"].ConnectionString;
SqlConnection con = new SqlConnection(strConnString);
SqlDataAdapter sda = new SqlDataAdapter();
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
sda.SelectCommand = cmd;
sda.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw ex;
}
finally
{
con.Close();
sda.Dispose();
con.Dispose();
}
}
As you can see above I am passing the query to the GetData function and it returns the results as datatable back.
Export to Word
protected void ExportToWord(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.doc”);
Response.Charset = “”;
Response.ContentType = “application/vnd.ms-word “;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
image
Export to Excel
Below is the code to export the datatable to Excel Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as Excel Workbook. Also you will notice I applied textmode style to all the rows so that it in rendered as text.
protected void ExportToExcel(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.xls”);
Response.Charset = “”;
Response.ContentType = “application/vnd.ms-excel”;
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
for (int i = 0; i < GridView1.Rows.Count; i++)
{
//Apply text style to each Row
GridView1.Rows[i].Attributes.Add(”class”, “textmode”);
}
GridView1.RenderControl(hw);
//style to format numbers to string
string style = @””;
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
image1
Export to Portable Document Format (PDF)
Below is the code to export the datatable to PDF Format. It first fills the datatable using the GetData function and then binds it to a dummy GridView and then the dummy GridView is rendered as PDF document using the iTextSharp Library which is a free open source library and can be downloaded from here.
protected void ExportToPDF(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
//Create a dummy GridView
GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = dt;
GridView1.DataBind();
Response.ContentType = “application/pdf”;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.pdf”);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
image2
Export to Comma Separated Values (CSV)
Below is the code to export the datatable to CSV or Text Format. It first fills the datatable using the GetData function. To export dataset to CSV there is no need of dummy GridView. We just have to loop through the records and append the delimiting character comma.
protected void ExportToCSV(object sender, EventArgs e)
{
//Get the data from database into datatable
string strQuery = “select CustomerID, ContactName, City, PostalCode” +
” from customers”;
SqlCommand cmd = new SqlCommand(strQuery);
DataTable dt = GetData(cmd);
Response.Clear();
Response.Buffer = true;
Response.AddHeader(”content-disposition”,
“attachment;filename=DataTable.csv”);
Response.Charset = “”;
Response.ContentType = “application/text”;
StringBuilder sb = new StringBuilder();
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(dt.Columns[k].ColumnName + ‘,’);
}
//append new line
sb.Append(”\r\n”);
for (int i = 0; i < dt.Rows.Count; i++)
{
for (int k = 0; k < dt.Columns.Count; k++)
{
//add separator
sb.Append(dt.Rows[i][k].ToString().Replace(”,”, “;”) + ‘,’);
}
//append new line
sb.Append(”\r\n”);
}
Response.Output.Write(sb.ToString());
Response.Flush();
Response.End();
}
image3

Master / Detail Editing With a ListView and DetailsView

mplementing a master/detail editing-inserting-deleting interface using the ListView is not much different than doing it with a GridView. Here's a quick tutorial that shows how it's done.
I'm sure you're all familiar with editing records in a master/detail scenario with a GridView and DetailsView. There are probably a thousand tutorials on the 'net that show how to do this. So, when I happened upon a fellow on the ASP.NET forums asking about doing master/detail editing with the ListView instead of the GridView , my first thought was to post a link and tell him to have at it. However, to my surprise, a quick Google search didn't really reveal any good, straightforward examples. That being the case, I decided to work one up, which I'll share with you now.
The ListView is a new databound control introduced with the .NET Framework 3.5. You could think of the ListView as what you might get if a GridView and a Repeater had a baby. Like the GridView, the ListView can display, edit, delete, page, and sort records. And like the Repeater, the ListView is entirely template-driven. Also, the ListView supports inserting new records, functionality provided by neither the GridView nor the Repeater. In fact, due to the extreme flexibility of the ListView, you may find fewer situations in which building a master/detail interface using the DetailsView is needed.

The Solution

The example presented here doesn't show off any of the native data-manipulation prowess of the ListView. Instead, it only displays and allows user selection of individual records, and passes all of the insertion, editing, and deleting functionality to an accompanying DetailsView.
Again, the tricky part is that with a ListView, you need to build your own presentation code. In the example, I'm displaying the records in a table; however, you could display the records however you want: as a bulleted list, a multicolumn grid, or totally free-form; whatever you want. You also need to provide buttons in the template to initiate the functionality you need. Here, in the ItemTemplate of the ListView, you'll see a button with CommandName="Select". That allows the datasource for the DetailsView to pick up the value of the record's primary key and fetch the individual record. Notice that in the SelectedItemTemplate, no button is defined. That means when a record is marked as selected in the ListView, the Select button won't appear.
The example presented here uses selected fields from the Employees table of the Northwind database, and also uses SqlDataSource for simplicity. If you have the Northwind database, you should be able to paste this code into a blank .aspx file and run it locally. Just be sure to change the connection strings in each SqlDataSource to point to your own Northwind database.
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" 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>title>
head>
<body>
<form id="form1" runat="server">
<div>         
<asp:ListView ID="lvwEmployees" runat="server" DataKeyNames="EmployeeID" DataSourceID="SqlDataSourceEmpList">
<ItemTemplate>
<tr>
<td>
<asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' />
td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
td>
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
td>
<td>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
td>
<td>
<asp:Button ID="SelectButton" runat="server" Text="Select" CommandName="Select" />
td>
tr>
ItemTemplate>
<SelectedItemTemplate>
<tr style="background-color: yellow; font-weight: bold;">
<td>
<asp:Label ID="EmployeeIDLabel" runat="server" Text='<%# Eval("EmployeeID") %>' />
td>
<td>
<asp:Label ID="LastNameLabel" runat="server" Text='<%# Eval("LastName") %>' />
td>
<td>
<asp:Label ID="FirstNameLabel" runat="server" Text='<%# Eval("FirstName") %>' />
td>
<td>
<asp:Label ID="TitleLabel" runat="server" Text='<%# Eval("Title") %>' />
td>
tr>
SelectedItemTemplate>
<LayoutTemplate>
<table runat="server">
<tr runat="server">
<td runat="server">
<table id="itemPlaceholderContainer" runat="server" border="1" style="border-collapse: collapse;
border-width: 1px;">
<tr runat="server" style="background-color: #DCDCDC; color: #000000;">
<th runat="server">
EmployeeID
th>
<th runat="server">
LastName
th>
<th runat="server">
FirstName
th>
<th runat="server">
Title
th>
tr>
<tr id="itemPlaceholder" runat="server">
tr>
table>
td>
tr>
table>
LayoutTemplate>
asp:ListView>         
<asp:SqlDataSource ID="SqlDataSourceEmpList" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees] ORDER BY [EmployeeID]">
asp:SqlDataSource>
<br />
<asp:DetailsView ID="dvwEmployee" runat="server" DataSourceID="SqlDataSourceEmp"
AutoGenerateRows="False" DataKeyNames="EmployeeID">
<Fields>
<asp:BoundField DataField="EmployeeID" HeaderText="EmployeeID" InsertVisible="False"
ReadOnly="True" SortExpression="EmployeeID" />
<asp:BoundField DataField="LastName" HeaderText="LastName" SortExpression="LastName" />
<asp:BoundField DataField="FirstName" HeaderText="FirstName" SortExpression="FirstName" />
<asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True" ShowInsertButton="True"
NewText="Add" ButtonType="Button" />
Fields>
asp:DetailsView>
<asp:SqlDataSource ID="SqlDataSourceEmp" runat="server" ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"
DeleteCommand="DELETE FROM [Employees] WHERE [EmployeeID] = @EmployeeID" InsertCommand="INSERT INTO [Employees] ([LastName], [FirstName], [Title]) VALUES (@LastName, @FirstName, @Title)"
SelectCommand="SELECT [EmployeeID], [LastName], [FirstName], [Title] FROM [Employees] WHERE ([EmployeeID] = @EmployeeID)"
UpdateCommand="UPDATE [Employees] SET [LastName] = @LastName, [FirstName] = @FirstName, [Title] = @Title WHERE [EmployeeID] = @EmployeeID">
<SelectParameters>
<asp:ControlParameter ControlID="lvwEmployees" Name="EmployeeID" PropertyName="SelectedValue"
Type="Int32" />
SelectParameters>
<DeleteParameters>
<asp:Parameter Name="EmployeeID" Type="Int32" />
DeleteParameters>
<UpdateParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Title" Type="String" />
<asp:Parameter Name="EmployeeID" Type="Int32" />
UpdateParameters>
<InsertParameters>
<asp:Parameter Name="LastName" Type="String" />
<asp:Parameter Name="FirstName" Type="String" />
<asp:Parameter Name="Title" Type="String" />
InsertParameters>
asp:SqlDataSource>         
div>
form>
body>
html>
Below is an example of the output you can expect:
listview-detailsview
Hey, I didn't say it was gonna be fancy. ;) That part is up to you!

Blog Archive

Ideal SQL Query For Handling Error & Transcation in MS SQL

BEGIN TRY BEGIN TRAN --put queries here COMMIT; END TRY BEGIN CATCH IF @@TRANCOUNT>0 BEGIN SELECT @@ERROR,ERRO...