Monday, June 8, 2009

Boxing and Unboxing in C# .Net

Introduction

In this article I will explain the concepts of Boxing and UnBoxing. C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as unboxing.

Let me explain you little more about Value and Reference Types.

Value Types

Value types are primitive types that are mapped directly to the FCL. Like Int32 maps to System.Int32, double maps to System.double. All value types are stored on stack and all the value types are derived from System.ValueType. All structures and enumerated types that are derived from System.ValueType are created on stack, hence known as ValueType.

Reference Types

Reference Types are different from value types in such a way that memory is allocated to them from the heap. All the classes are of reference type. C# new operator returns the memory address of the object.

Examples

Lets see some examples to have a better understanding of Value Types and Reference Types. Since we know that all ValueTypes are derived from System.Value we can write something like this:

 System.ValueType r = 5;       

So what do you think about the above line of code. Will it compile ? Yes it will compile. But wait what type is it cause I don't remember any type which is called System.ValueType since its a base class from which all value types inherit. So is it Int32, Int64,double, decimal etc. It turns out that the type for variable 'r' is System.Int32. The Question arrises why Int32 and why not Int16. Well its because it is mapped to Int32 by default depending upon the Initial value of the variable.

You cannot write something like this since System.ValueType is not a primitive type its a base class for primitive value types and these mathematical operations can be performed on primitive types.

System.ValueType r = 10;
r++;

In the above example I told you that variable 'r' will be a System.Int32 variable but if you don't believe me than you can find out yourself using the GetType() method:

 System.ValueType r = 5;
Console.WriteLine(r.GetType()) // returns System.Int32;

Here are few samples you can try on your own:


System.ValueType r = 23.45;
Console.WriteLine(r.GetType()); // what does this print
//-------------------------------------------------------
System.ValueType r = 23.45F;
Console.WriteLine(r.GetType()); // What does this print
//-------------------------------------------------------
System.ValueType r = 2U;
Console.WriteLine(r.GetType()); // What does this print
//-------------------------------------------------------
System.ValueType r = 'c';
Console.WriteLine(r.GetType()); // What does this print
//-------------------------------------------------------
System.ValueType r = 'ac';
Console.WriteLine(r.GetType()); // tricky
//-------------------------------------------------------
System.ValueType r = "Hello World";
Console.WriteLine(r.GetType()); // tricky

Boxing

Lets now jump to Boxing. Sometimes we need to convert ValueTypes to Reference Types also known as boxing. Lets see a small example below. You see in the example I wrote "implicit boxing" which means you don't need to tell the compiler that you are boxing Int32 to object because it takes care of this itself although you can always make explicit boxing as seen below right after implicit boxing.


Int32 x = 10;
object o = x ; // Implicit boxing
Console.WriteLine("The Object o = {0}",o); // prints out 10
//-----------------------------------------------------------
Int32 x = 10;
object o = (object) x; // Explicit Boxing
Console.WriteLine("The object o = {0}",o); // prints out 10


Unboxing

Lets now see UnBoxing an object type back to value type. Here is a simple code that unbox an object back to Int32 variable. First we need to box it so that we can unbox.

Int32 x = 5;
object o = x; // Implicit Boxing
x = o; // Implicit UnBoxing

So, you see how easy it is to box and how easy it is to unbox. The above example first boxs Int32 variable to an object type and than simply unbox it to x again. All the conversions are taking place implicitly. Everything seems right in this example there is just one small problem which is that the above code is will not compile. You cannot Implicitly convert a reference type to a value type. You must explicitly specify that you are unboxing as shown in the code below.

Int32 x = 5;
object o = x; // Implicit Boxing
x = (Int32)o; // Explicit UnBoxing

Lets see another small example of unboxing.

Int32 x = 5; // declaring Int32
Int64 y = 0; // declaring Int64 double
object o = x; // Implicit Boxing
y = (Int64)o; // Explicit boxing to double
Console.WriteLine("y={0}",y);

This example will not work. It will compile successfully but at runtime It will generate an exception of System.InvalidCastException. The reason is variable x is boxed as Int32 variable so it must be unboxed to Int32 variable. So, the type the variable uses to box will remain the same when unboxing the same variable. Of course you can cast it to Int64 after unboxing it as Int32 as follows:

Int32 x = 5; // declaring Int32
Int64 y = 0; // declaring Int64 double
object o = x; // Implicit Boxing
y = (Int64)(Int32)o; // Unboxing and than casting to double
Console.WriteLine("y={0}",y);

I am sure that you all have grasp the basic understanding of Boxing and Unboxing. Happy Coding and practice a lot !

All about Unsafe Code in C#

C# .net hides most of memory management, which makes it much easier for the developer. Thanks for the Garbage Collector and the use of references. But to make the language powerful enough in some cases in which we need direct access to the memory, unsafe code was invented.

Commonly while programming in the .net framework we don?t need to use unsafe code, but in some cases there is no way not to, such as the following:

  • Real-time applications, we might need to use pointers to enhance performance in such applications.
  • External functions, in non-.net DLLs some functions requires a pointer as a parameter, such as Windows APIs that were written in C.
  • Debugging, sometimes we need to inspect the memory contents for debugging purposes, or you might need to write an application that analyzes another application process and memory.

Unsafe code is mostly about pointers which have the following advantages and disadvantages.

Advantages of Unsafe Code in C#:

  • Performance and flexibility, by using pointer you can access data and manipulate it in the most efficient way possible.
  • Compatibility, in most cases we still need to use old windows APIs, which use pointers extensively. Or third parties may supply DLLs that some of its functions need pointer parameters. Although this can be done by writing the DLLImport declaration in a way that avoids pointers, but in some cases it?s just much simpler to use pointer.
  • Memory Addresses, there is no way to know the memory address of some data without using pointers.

Disadvantages of Unsafe Code in C#:

  • Complex syntax, to use pointers you need to go throw more complex syntax than we used to experience in C#.
  • Harder to use, you need be more careful and logical while using pointers, miss using pointers might lead to the following:
    • Overwrite other variables.
    • Stack overflow.
    • Access areas of memory that doesn?t contain any data as they do.
    • Overwrite some information of the code for the .net runtime, which will surely lead your application to crash.
  • Your code will be harder to debug. A simple mistake in using pointers might lead your application to crash randomly and unpredictably.
  • Type-safety, using pointers will cause the code to fail in the .net type-safety checks, and of course if your security police don?t allow non type-safety code, then the .net framework will refuse to execute your application.

After we knew all the risks that might face us while using pointer and all the advantages those pointers introduces us of performance and flexibility, let us find now how to use them. The keyword unsafe is used while dealing with pointer, the name reflects the risks that you might face while using it. Let?s see where to place it. We can declare a whole class as unsafe:

unsafe class Class1
{
//you can use pointers here!
}

Or only some class members can be declared as unsafe:

class Class1
{
//pointer
unsafe int * ptr;
unsafe void MyMethod()
{
//you can use pointers here
}
}

The same applies to other members such as the constructor and the properties.

To declare unsafe local variables in a method, you have to put them in unsafe blocks as the following:

static void Main()
{
//can't use pointers here

unsafe
{
//you can declare and use pointer here

}

//can't use pointers here
}

You can?t declare local pointers in a ?safe? method in the same way we used in declaring global pointers, we have to put them in an unsafe block.

static void Main()
{
unsafe int * ptri; //Wrong
}

If you got too excited and tried to use unsafe then when you compile the code just by using

csc test.cs

You will experience the following error:

error CS0227: Unsafe code may only appear if compiling with /unsafe

For compiling unsafe code use the /unsafe

csc test.cs /unsafe

In VS.net go to the project property page and in ?configuration properties>build? set Allow Unsafe Code Blocks to True.

After we knew how to declare a block as unsafe we should now learn how to declare and use pointers in it.

Declaring pointers

To declare a pointer of any type all what you have to do is to put ?*? after the type name such as

int * ptri;

double * ptrd;

NOTE: If you used to use pointer in C or C++ then be careful that in C# int * ptri, i; ?*? applies to the type itself not the variable so ?i? is a pointer here as well, same as arrays.

void Pointers

If you want to declare a pointer, but you do not wish to specify a type for it, you can declare it as void.

void *ptrVoid;

The main use of this is if you need to call an API function than require void* parameters. Within the C# language, there isn?t a great deal that you can do using void pointers.

Using pointers

Using pointers can be demonstrated in the following example:

static void Main()
{

int var1 = 5;

unsafe
{
int * ptr1, ptr2;
ptr1 = &var1;
ptr2 = ptr1;
*ptr2 = 20;
}

Console.WriteLine(var1);
}

The operator ?&? means ?address of?, ptr1 will hold the address of var1, ptr2 = ptr1 will assign the address of var1, which ptr1 was holding, to ptr2. Using ?*? before the pointer name means ?the content of the address?, so 20 will be written where ptr2 points.

Now var1 value is 20.

sizeof operator

As the name says, sizeof operator will return the number of bytes occupied of the given data type

unsafe
{
Console.WriteLine("sbyte: {0}", sizeof(sbyte));
Console.WriteLine("byte: {0}", sizeof(byte));
Console.WriteLine("short: {0}", sizeof(short));
Console.WriteLine("ushort: {0}", sizeof(ushort));
Console.WriteLine("int: {0}", sizeof(int));
Console.WriteLine("uint: {0}", sizeof(uint));
Console.WriteLine("long: {0}", sizeof(long));
Console.WriteLine("ulong: {0}", sizeof(ulong));
Console.WriteLine("char: {0}", sizeof(char));
Console.WriteLine("float: {0}", sizeof(float));
Console.WriteLine("double: {0}", sizeof(double));
Console.WriteLine("decimal: {0}", sizeof(decimal));
Console.WriteLine("bool: {0}", sizeof(bool));

//did I miss something?!
}

The output will be:

sbyte: 1

byte: 1

short: 2

ushort: 2

int: 4

uint: 4

long: 8

ulong: 8

char: 2

float: 4

double: 8

decimal: 16

bool: 1

Great, we don?t have to remember the size of every data type anymore!

Casting Pointers

A pointer actually stores an integer that represents a memory address, and it?s not surprising to know that you can explicitly convert any pointer to or from any integer type. The following code is totally legal.

int x = 10;
int *px;

px = &x;
uint y = (uint) px;
int *py = (int*) y;

A good reason for casting pointers to integer types is in order to display them. Console.Write() and Console.WriteLine() methods do not have any overloads to take pointers. Casting a pointer to an integer type will solve the problem.

Console.WriteLine(?The Address is: ? + (uint) px);

As I mentioned before, it?s totally legal to cast a pointer to any integer type. But does that really mean that we can use any integer type for casting, what about overflows? On a 32-bit machine we can use uint, long and ulong where an address runs from zero to about 4 billion. And on a 64-bit machine we can only use ulong. Note that casting the pointer to other integer types is very likely to cause and overflow error. The real problem is that checked keyword doesn?t apply to conversions involving pointers. For such conversions, exceptions wont be raised when an overflow occur, even in a checked context. When you are using pointers the .net framework will assume that you know what you?re doing and you?ll be happy with the overflows!

You can explicitly convert between pointers pointing to different types. For example:

byte aByte = 8;
byte *pByte = &aByte;
double *pDouble = (double*) pByte;

This is perfectly legal code, but think twice if you are trying something like that. In the above example, the double value pointed to by pDouble will actually contain a byte (which is 8), combined by an area of memory contained a double, which surely won?t give a meaningful value. However, you might want to convert between types in order to implement a union, or you might want to cast pointers to other types into pointers to sbyte in order to examine individual bytes of memory.

Pointers Arithmetic

It?s possible to use the operators +, -, +=, -=, ++ and -- with pointers, with a long or ulong on the right-hand side of the operator. While it?s not permitted to do any operation on a void pointer.

For example, suppose you have a pointer to an int, and you want to add 1 to it. The compiler will assume that you want to access the following int in the memory, and so will actually increase the value by 4 bytes, the size of int. If the pointer was pointing to a double, adding 1 will increase its value by 8 bytes the size of a double.

The general rule is that adding a number X to a pointer to type T with a value P gives the result P + X *sizeof(T).

Let?s have a look at the following example:

uint u = 3;
byte b = 8;
double d = 12.5;
uint *pU = &u;
byte *pB = &b;
double *pD = &d;

Console.WriteLine("Before Operations");
Console.WriteLine("Value of pU:" + (uint) pU);
Console.WriteLine("Value of pB:" + (uint) pB);
onsole.WriteLine("Value of pD:" + (uint) pD);


pU += 5;
pB -= 3;
pD++;

Console.WriteLine("\nAfter Operations");
Console.WriteLine("Value of pU:" + (uint) pU);
Console.WriteLine("Value of pB:" + (uint) pB);
Console.WriteLine("Value of pD:" + (uint) pD);

The result is:


Before Operations
Value of pU:1242784
Value of pB:1242780
Value of pD:1242772


After Operations
Value of pU:1242804
Value of pB:1242777
Value of pD:1242780

5 * 4 = 20, where added to pU.

3 * 1 = 3, where subtracted from pB.

1 * 8 = 8, where added to pD.

We can also subtract one pointer from another pointer, provided both pointers point to the same date type. This will result a long whose value is given by the difference between the pointers values divided by the size of the type that they represent:

double *pD1 = (double*) 12345632;
double *pD2 = (double*) 12345600;
long L = pD1 ? pD2; //gives 4 =32/8(sizeof(double))

Note that the way of initializing pointers in the example is totally valid.

Pointers to Structs and Class members

Pointers can point to structs the same way we used before as long as they don?t contain any reference types. The compiler will result an error if you had any pointer pointing to a struct containing a reference type.

Let?s have an example,

Suppose we had the following struct:

struct MyStruct
{
public long X;
public double D;
}

Declaring a pointer to it will be:

MyStruct *pMyStruct;

Initializing it:

MyStruct myStruct = new MyStruct();
pMyStruct = & myStruct;

To access the members:

(*pMyStruct).X = 18;
(*pMyStruct).D = 163.26;

The syntax is a bit complex, isn?t it?

That?s why C# defines another operator that allows us to access members of structs through pointers with a simpler syntax. The operator ?Pointer member access operator? looks like an arrow, it?s a dash followed by a greater than sign: ->

pMyStruct->X = 18;
pMyStruct->D = 163.26;

That looks better!

Fields within the struct can also be directly accessed through pointer of their type:

long *pL = &(myStruct.X);
double *pD = &(myStruct.D);

Classes and pointers is a different story. We already know that we can?t have a pointer pointing to a class, where it?s a reference type for sure. The Garbage Collector doesn?t keep any information about pointers, it?s only interested in references, so creating pointers to classes could cause the Garbage Collector to not work probably.

On the other hand, class members could be value types, and it?s possible to create pointers to them. But this requires a special syntax. Remember that class members are embedded in a class, which sets in the heap. That means that they are still under the control of the Garbage Collector, which can at any time decide to move the class instance to a new location. The Garbage Collector knows about the reference, and will update its value, but again it?s not interested in the pointers around, and they will still be pointing to the old location.

To avoid the risk of this problem, the compiler will result an error if you tried to create pointers pointing to class members in the same way we are using up to now.

The way around this problem is by using the keyword ?fixed?. It marks out a block of code bounded by braces, and notifies the Garbage Collector that there may be pointers pointing to members of certain class instances, which must not be moved.

Let?s have an example,

Suppose the following class:


class MyClass
{
public long X;
public double D;
}

Declaring pointers to its members in the regular way is a compile-time error:

MyClass myClass = new MyClass();

long *pX = &(myClass.X); //compile-time error.

To create pointers pointing to class members by using fixed keyword:

fixed (long *pX = &(myClass.X))
{

// use *pX here only.
}

The variable *pX is scoped within the fixed block only, and tells the garbage collector that not to move ?myClass? while the code inside the fixed block.

stackalloc

The keyword "stackalloc" commands the .net runtime to allocate a certain amount of memory on the stack. It requires two things to do so, the type (value types only) and the number of variables you?re allocating the stack for. For example if you want to allocate enough memory to store 4 floats, you can write the following:

float *ptrFloat = stackalloc float [4];

Or to allocate enough memory to store 50 shorts:

short *ptrShort = stackalloc short [50];

stackalloc simply allocates memory, it doesn?t initialize it to any value. The advantage of stackalloc is the ultra-high performance, and it?s up to you to initialize the memory locations that were allocated.

A very useful place of stackalloc could be creating an array directly in the stack. While C# had made using arrays very simple and easy, it still suffers from the disadvantage that these arrays are actually objects instantiated from System.Array and they are stored on the heap with all of the overhead that involves.

To create an array in the stack:

int size;
size = 6; //we can get this value at run-time as well.
int *int_ary = stackalloc int [size];

To access the array members, it?s very obvious to use *(int_ary + i), where ?i ?is the index. But it won?t be surprising to know that it?s also possible to use int_ary[i].

*( int_ary + 0) = 5; //or *int_ary = 5;
*( int_ary + 1) = 9; //accessing member #1
*( int_ary + 2) = 16;

int_ary[3] = 19; //another way to access members
int_ary[4] = 7;
int_ary[5] = 10;

In a usual array, accessing a member outside the array bounds will cause an exception. But when using stackalloc, you?re simply accessing an address somewhere on the stack; writing on it could cause to corrupt a variable value, or worst, a return address from a method currently being executed.

int[] ary = new int[6];
ary[10] = 5;//exception thrown

int *ary = stackalloc int [6];
ary[10] = 5;// the address (ary + 10 * sizeof(int)) had 5 assigned to it.

This takes us to the beginning to the article; using pointer comes with a cost. You have to be very certain of what you?re doing, any small error could cause very strange and hard to debug run-time bugs.

Conclusion

Microsoft had chosen the term ?unsafe? to warn programmers of the risk they will go throw after typing that word. Using pointers as we had seen in this article has a lot of advantages from flexibility to high performance, but a very small error, even a simple typing mistake, might cause your entire application to crash. Worst, this could happen randomly and unpredictably, and will make debugging a very harder task to do.

- Article by Mardawi

Introduction to ASP.NET Mobile

The mobile controls provided by ASP .NET target, as the name suggests, mobile devices (cell phones, Palms, etc.). This article will give you an idea of how to develop mobile web applications using ASP .NET and the Microsoft Visual Studio .NET environment. It will describe some of the most important mobile specific controls but won't go deep into the subject. At the end we'll also take a look at the Pocket PC Emulator 2002 which is included in Visual Studio .NET.



The ways mobile pages are organized differ from the classic web pages that you see on your computer. One mobile page is represented by a Form and a typical file (MobileWebForm1.aspx) can contain multiple forms, therefore multiple pages. This way when you open a page with the WAP browser actually multiple pages will be loaded (represented by forms) and when you click a link to one of the other forms there will be no loading time because they are in the same page. There is a good reason for this. Some WAP browsers disconnect after they retrieve the webpage to save the battery of the mobile phone and the money if the connection is charged per minute. This way they won't have to reconnect every time a new form is loaded, if it is located in the same file.



Create a new ASP .NET Mobile Web Application project in Visual Studio .NET.








MobileWebForm1.aspx is created with a form on it:







Also if you look in the HTML code you can see the tags that define this form:





<mobile:Form id=Form1 runat="server">mobile:Form>



If you wish, you can add some content to it and view it on your mobile phone:





<mobile:Form id=Form1 runat="server">

Hello <i>visitori>!

mobile:Form
>



If you don't have one (do you live in a cave?) you can compile and see the result in the IE window. Or you could download a simulator like the popular Openwave. The result is nothing extraordinary, just some simple text.



Earlier in the article I said that an ASP .NET mobile page can contain multiple forms. In the following example we add a second form, Form2 and we link to it from Form1:





<mobile:form id=Form1 runat="server">

Hello <i>visitori>!<br /><br />

<mobile:link id="Link1" Runat="server" NavigateUrl="#Form2">

- About us

mobile:link>


mobile:form
>



<mobile:form id=Form2 runat="server">

<b>About usb
><br /><br />

Here goes some information about the website.

mobile:form
>



The linking is not done with the typical tag. Of course, after the code is compiled the HTML actually uses an tag but that's its job and not ours. As you can see the linking to the other form is done exactly like when using anchors.

The result in the Openwave simulator is the following:








When you click that link you get to Form2 which displays the text "About us. Here goes some information about the website.".



Displaying a graphic on a mobile phone is as easy as displaying it in a usual web browser. You don't use an tag, but this one:





<mobile:Image id="Link2" Runat="server" NavigateUrl="#Form3" ImageUrl="http://www.yourwebsite.com/logo.gif" />

The List control


This is a basic control that you'll be using in almost any WAP website. It provides sufficient functionality to prove itself useful. Let's see it in action.

First add a link to the Form that includes the control:





<mobile:link id="Link2" Runat="server" NavigateUrl="#Form3">

- Get product list

mobile:link>



As you can see here, "Get product list" links to Form3, so let's create this form:






<mobile:form id="Form3" runat="server"><B>Product listB><BR><BR>mobile:form>



Let's add to this form a specific ASP .NET mobile control - List.





<mobile:form id="Form3" runat="server"><B>Product listB><BR><BR>

Currently we have the following products for sale:

<mobile:List id="List1" runat="server">

<Item Text="Microsoft Natural Keyboard" />

<Item Text="Philips 5.1 Surround Sound" />

<Item Text="HP LaserJet Printer" />

mobile:List
>

mobile:form>



If you run this application you can see that the result is just a simple list of the products we entered, if you look at the source code in
Internet Explorer you can see that it's created with the help of a table. So what's so special about this control? Well depending on which device the page containing the control is opened, it will be displayed differently. For example on the web browser the list is created using a HTML table, while on a WML browser it will be created much simpler, by separating the items with
tags.

Another feature of Lists is that you can bind them to different data sources, like databases or XML files.

The AdRotator control


Banner advertisements on WAP page appeared a short while after WAP was born. The AdRotator mobile control acts in the same way as the original AdRotator control does. The mobile control has a very useful feature - you can choose to display one type of image for typical computer browsers and other type of image for WML browsers.

The Calendar control


Let's take a look at another mobile control - the Calendar. Adding a functional calendar to a WAP page was a very difficult task in the past, but with the Calendar control it's just a matter of dragging and dropping.

So add a new link in Form1 that points to a new form, Form4:





<mobile:link id="Link3" Runat="server" NavigateUrl="#Form4">

- Calendar

mobile:link>



Also add Form4 now:





<mobile:form id="Form4" runat="server"><B>CalendarB><BR><BR>mobile:form>



If you drag and drop the Calendar control from the Toolbox inside Form4, the following tag will be added:






<mobile:Calendar id="Calendar1" runat="server">mobile:Calendar>



The calendar control offers great functionality, of course a bit limited for WAP devices. The most important event of this control is called Calendar_SelectionChanged() and, as the name implies, occurs when the visitor selects a date on the calendar.

You could build an entire mobile website based on this control. For example the user picks a day on the calendar and he can see the TV guide for that day, or the movies that run at some cinema.

The SelectionList control


This control acts exactly as a typical DropDown control and also looks like one. Only that it can be made to look like a ListBox also, or like a radio control, or checkbox, or a ListBox that allows multiple items to be selected. This control can change its functionality by changing one of its properties called SelectType:








Also the tags generated by this control are different depending on the devices on which the page is loaded. On an usual computer browser it would display the typical HTML controls. Whereas on a WML browser it would be rendered using WML compatible tags. From a cell phone browser the visitor will have to select the item he wants by using the numeric key pad or by navigating to the wished item.

Pocket PC 2002 Emulator


This emulator comes with the Microsoft Visual Studio .NET package and it's a really nice software to play with if you don't own a Pocket PC. After you're tired of playing with it you can use it for more productive purposes, developing and testing applications and web applications with it. You can fire up this emulator from the Tools menu, Connect to Device item. Choose Pocket PC 2002 Emulator (Default). You probably noticed there's a Windows CE .NET emulator also. Click Connect and the emulator should start in a few seconds. The first thing you'll want to do is set up your internet connection on it. You can do that from the Start menu -> Settings -> Connections tab -> Connections icon.

Aside from the fact that this emulator is a very useful tool for testing your Pocket PC applications, you can also use it to see how your ASP .NET mobile pages look like on the Internet Explorer mobile browser. Open the MobileWebForm we created earlier in this article to see how the forms and controls we added look like on this device. Here's the calendar, for example:








You can apply some stylesheet to it so it will look much better than it does now.

So this emulator can also be used for testing web application, not just Windows mobile applications. A useful tool along with the emulators from Openwave and your WAP enabled cell phone. Using these you can develop flawless mobile applications.

I hope you enjoyed this article !

Site Map and Bread Crumbs for your website

Download the project



In a newly created ASP.NET website project, add two ASP.NET web forms: Contact.aspx and Tutorials.aspx. Along with the Default.aspx web form created by default, we now have three files. Now that we built an website composed of 3 files, let's define its structure so that the site map can be built.

Right click the project and choose Add New Item. Select Site Map as seen in the screenshot below:







We can have multiple Site Maps for our website, but this will be the default one.



After adding Web.sitemap to the file, you can see it contains the following:





xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode url="" title="" description="">

<siteMapNode url="" title="" description="" />

<siteMapNode url="" title="" description="" />

siteMapNode>

siteMap>



Here we'll define our site map, we want to mention the 3 files we have in the project. The Default.aspx will be the root, and the other two files, Tutorials.aspx and Contact.aspx will be situated under Default.aspx (child pages). Here's how we need to set up the Web.sitemap file:





xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode url="Default.aspx" title="Geekpedia Home" description="Geekpedia.com home page">

<siteMapNode url="Tutorials.aspx" title="Programming Tutorials" description="Programming tutorials on .NET Framework languages" />

<siteMapNode url="Contact.aspx" title="Contact Geekpedia" description="Contact Geekpedia.com with questions or comments" />

siteMapNode>

siteMap>



The url attribute is self-explanatory. The title tag defines a title for the page, which will be shown in the bread crumb (and it will be linked to the URL specified in the url attribute). The content of the description attribute will be displayed when hovering the link, in a tooltip.



Open the three files that compose our website, Default.aspx, Contact.aspx and Tutorials.aspx. In each one of them add a SiteMapPath from the Toolbox:








Now all you have to do is compile and run. Open each page and you'll see the result:



Default.aspx:






Contact.aspx:





Tutorials.aspx:






Amazing, considering we only wrote a few lines of XML and dragged a control on the pages.

Now if you add a new page named DotNetTutorials.aspx to the project, mention it in the web.Sitemap XML file as a child of Tutorials.aspx and add a SiteMapPath control to it, you will get the following result:







And here is how you define the DotNetTutorials.aspx page, as a child of Tutorials.aspx:





xml version="1.0" encoding="utf-8" ?>

<siteMap xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >

<siteMapNode url="Default.aspx" title="Geekpedia Home" description="Geekpedia.com home page">

<siteMapNode url="Tutorials.aspx" title="Programming Tutorials" description="Programming tutorials on .NET Framework languages">

<siteMapNode url="DotNetTutorials.aspx" title=".NET Tutorials" description="ASP.NET, C#, VB.NET and other .NET Framework tutorials" />

siteMapNode>

<siteMapNode url="Contact.aspx" title="Contact Geekpedia" description="Contact Geekpedia.com with questions or comments" />

siteMapNode>

siteMap>

I hope you enjoyed this article !

3 Different Ways to Display Progress in an ASP.NET AJAX Application

In this article, we will study three different techniques that allow you to visually display progress to users while performing partial-page updates using the UpdatePanel. For all the three approaches, I have used a .gif image to show a spinning gear kind of a progress bar while the UpdatePanel is performing some action. The image can be found with the source code for this article over here.
Method 1: Using PageRequestManager to display progress in an ASP.NET AJAX application
The PageRequestManager class handles the partial-page updates of the UpdatePanel. This class defines client events that you can use during an asynchronous request cycle. Let us see how to use some events of this class to display progress to the user while the UpdatePanel updates its contents.
Drag and drop a Button(btnInvoke) and Label(lblText) control inside the UpdatePanel. Also add a <div id="divImage" inside the UpdatePanel. This div will contain a .gif image that depicts progress and is initially set to invisible style="display:none". On the button click, perform a time consuming task. In our case, we have set a delay of 3 seconds by using Thread.Sleep(3000).
C#
protected void btnInvoke_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(3000);
lblText.Text = "Processing completed";
}
VB.NET
Protected Sub btnInvoke_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Threading.Thread.Sleep(3000)
lblText.Text = "Processing completed"
End Sub
The markup and code for this sample is as shown below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UsingPageRequestManager.aspx.cs" Inherits="UsingCSS" %>
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>Display Progress Using PageRequestManagertitle>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<script type="text/javascript">
// Get the instance of PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Add initializeRequest and endRequest
prm.add_initializeRequest(prm_InitializeRequest);
prm.add_endRequest(prm_EndRequest);
// Called when async postback begins
function prm_InitializeRequest(sender, args) {
// get the divImage and set it to visible
var panelProg = $get('divImage');
panelProg.style.display = '';
// reset label text
var lbl = $get('<%= this.lblText.ClientID %>');
lbl.innerHTML = '';
// Disable button that caused a postback
$get(args._postBackElement.id).disabled = true;
}
// Called when async postback ends
function prm_EndRequest(sender, args) {
// get the divImage and hide it again
var panelProg = $get('divImage');
panelProg.style.display = 'none';
// Enable button that caused a postback
$get(sender._postBackSettings.sourceElement.id).disabled = false;
}
script>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblText" runat="server" Text="">asp:Label>
<div id="divImage" style="display:none">
<asp:Image ID="img1" runat="server" ImageUrl="~/images/progress.gif" />
Processing...
div>
<br />
<asp:Button ID="btnInvoke" runat="server" Text="Click"
onclick="btnInvoke_Click" />
ContentTemplate>
asp:UpdatePanel>
div>
form>
body>
html>
As shown in the code above, we first get a reference to the PageRequestManager and then wire up the initializeRequest and endRequest events to execute, when an async postback begins and ends respectively.
When the user initiates a postback by clicking on the button kept inside the UpdatePanel, we set a delay of 3 seconds. To display progress to the user, we handle the InitializeRequest at the client side and set the divImage to visible. This shows up the .gif image with the progress as shown below. The button that caused the postback is disabled during this event, so in order to prevent users from hitting the button again.
Progress Bar
Note: Remember that you cannot have simultaneous async postbacks using ASP.NET AJAX.
When the async postback completes (in our case when 3 seconds are over), the endRequest event gets fired. The divImage is set to invisible, there by hiding the gif image and the button is enabled again.
Method 2: Using the UpdateProgress control to display progress in an ASP.NET AJAX application
Another very simple option to display progress during an async postback is to use the UpdateProgress control. You can use this control to display status information to the user, while the UpdatePanel updates its content. In the example below, we use the same .gif to display progress while the UpdatePanel is updating its content. For understanding purposes, we have emulated a time consuming operation by setting a delay of 3 seconds by using Thread.Sleep(3000) on the button click.
C#
protected void btnInvoke_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(3000);
lblText.Text = "Processing completed";
}
VB.NET
Protected Sub btnInvoke_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Threading.Thread.Sleep(3000)
lblText.Text = "Processing completed"
End Sub
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UsingUpdateProgress.aspx.cs" 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:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<asp:UpdateProgress ID="updProgress"
AssociatedUpdatePanelID="UpdatePanel1"
runat="server">
<ProgressTemplate>
<img alt="progress" src="images/progress.gif"/>
Processing...
ProgressTemplate>
asp:UpdateProgress>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblText" runat="server" Text="">asp:Label>
<br />
<asp:Button ID="btnInvoke" runat="server" Text="Click"
onclick="btnInvoke_Click" />
ContentTemplate>
asp:UpdatePanel>
div>
form>
body>
html>
In the code shown above, we use the AssociatedUpdatePanelID property of the UpdateProgress control to associate it with an UpdatePanel control. The ProgressTemplate property that can contain HTML, is used to specify the message displayed by an UpdateProgress control. In our case, we are displaying a .gif image progress as shown below
Progress
Method 3: Using UpdatePanelAnimationExtender to display progress in an ASP.NET AJAX application
The UpdatePanelAnimation control can also be used to visually display progress to the users while the UpdatePanel is performing some operation. As defined in the ASP.NET AJAX documentation “The UpdatePanelAnimationExtender is a simple extender that allows you to utilize the powerful animation framework with existing pages in an easy, declarative fashion. It is used to play animations both while an UpdatePanel is updating and after it has finished updating”. You can read more about the UpdatePanelAnimationExtender over here. For this sample to work, drag and drop a UpdatePanelAnimationExtender from the AJAX Toolkit on to your page.
are declared in the UpdatePanelAnimationExtender to create animation effect. Within the , you can define the sequence of effects for the UpdatePanelAnimation. You can even use definitions to fine-tune and customize the animation.
In this example, we will show how to display an image progress bar using the definition of the UpdatePanelAnimationExtender. In the example given below, we have defined two ; one for while the UpdatePanel is updating(<OnUpdating>) and one for after the UpdatePanel has finished updating(<OnUpdated>).
The two definition tags call two JavaScript methods respectively that are responsible for displaying and hiding the image progress bar while the UpdatePanel performs an update on the control. As shown in the previous methods, we have emulated a time consuming operation by setting a delay of 3 seconds by using Thread.Sleep(3000) on the button click. You can replace this code with any time consuming operation, like fetching records from a remote database or performing any similar resource intensive operation. The technique of hiding and showing the image also remains the same as we had discussed in Method 1. The entire source code and mark up is as shown below:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="UsingUpdatePanelAnimation.aspx.cs" Inherits="UpdPnlAnimation" %>
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %>
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>
<script type="text/javascript">
function onUpdating()
{
// get the divImage
var panelProg = $get('divImage');
// set it to visible
panelProg.style.display = '';
// hide label if visible
var lbl = $get('<%= this.lblText.ClientID %>');
lbl.innerHTML = '';
}
function onUpdated()
{
// get the divImage
var panelProg = $get('divImage');
// set it to invisible
panelProg.style.display = 'none';
}
script>
head>
<body>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server">
asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Label ID="lblText" runat="server" Text="">asp:Label>
<div id="divImage" style="display:none">
<asp:Image ID="img1" runat="server" ImageUrl="~/images/progress.gif" />
Processing...
div>
<br />
<asp:Button ID="btnInvoke" runat="server" Text="Click"
onclick="btnInvoke_Click" />
ContentTemplate>
asp:UpdatePanel>
<cc1:UpdatePanelAnimationExtender ID="UpdatePanelAnimationExtender1"
TargetControlID="UpdatePanel1" runat="server">
<Animations>
<OnUpdating>
<Parallel duration="0">
<ScriptAction Script="onUpdating();" />
<EnableAction AnimationTarget="btnInvoke" Enabled="false" />
Parallel>
OnUpdating>
<OnUpdated>
<Parallel duration="0">
<ScriptAction Script="onUpdated();" />
<EnableAction AnimationTarget="btnInvoke" Enabled="true" />
Parallel>
OnUpdated>
Animations>
cc1:UpdatePanelAnimationExtender>
div>
form>
body>
html>
C#
protected void btnInvoke_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(3000);
lblText.Text = "Processing completed";
}
VB.NET
Protected Sub btnInvoke_Click(ByVal sender As Object, ByVal e As EventArgs)
System.Threading.Thread.Sleep(3000)
lblText.Text = "Processing completed"
End Sub
The progress will look similar to the ones shown in the other methods
progress
Well those were the three different methods of displaying progress to the user while the UpdatePanel updates its contents. The entire source code of this article can be downloaded from here. I hope this article was useful and I thank you for viewing it.

Popular Posts