c#asp.net


ASP.NET using C#
Handout
click here to download


















ASP.NET
Using C#






Table
of Contents








  1. Introduction to C# 2



  2. Introduction to ASP.NET 6



  3. Customizing Tables in
    ASP.NET 17



  4. Validation controls in Web
    forms. 19



  5. Using Web Forms List Box
    controls 29



  6. Using ASP.NET Table Control 32



  7. Server Side Repeater Control 34



  8. Using Web Forms Linkbutton
    Control 37



  9. Using Web forms Panel
    Control 40



  10. Using ASP.NET checkboxlist
    Control 42



  11. Debugging an ASP.NET
    Application 46



  12. Webservices using C# 51































Introduction
to C#


Welcome
to the world of C#! This chapter takes you on a tour of C# and
answers questions such as why you should use C#, what the main
differences are between C++ and C#, and why C# will make development
easier and more fun for you.


Why
Another Programming Language?


A good
question that has to be answered is why you should learn another
programming language when you are already doing enterprise
development in C++ or Visual Basic. The marketing-type answer is that
"C# is intended to be the premier language for writing NGWS
(Next Generation Windows Services)applications in the enterprise
computing space." This chapter is about backing up that claim
with arguments, and showcasing a slew of C#'s features. This chapter
is about whetting your appetite.


The
programming language C# derives from C and C++; however, it is
modern, simple, entirely object-oriented, and type-safe. If you are a
C/C++ programmer, your learning curve will be flat. Many C#
statements are directly borrowed from your favorite language,
including expressions and operators. If you don't look too closely at
first, a C# program looks like a C++ program.


An
important point about C# is that it is a modern programming language.
It simplifies and modernizes C++ in the areas of classes, namespaces,
method overloading, and exception handling. Much of the complexity of
C++ was removed from C# to make it easier to use and less error
prone.


Contributing
to the ease of use is the elimination of certain features of C++: no
more macros, no templates, and no multiple inheritance. The
aforementioned features create more problems than they provide
benefit—especially for enterprise developers.


New
features for added convenience are strict type safety, versioning,
garbage collection, and many more. All these features are targeted at
developing component-oriented software. Although you don't have the
sheer power of C++, you become more productive faster.


Before
I get ahead of myself and present too many features, I want to stop
and present the various elements of C# based on key points in the
following sections:







  • Simple


  • Modern


  • Object-oriented


  • Type-safe


  • Versionable


  • Compatible


  • Flexible











Simple


One
thing you definitely wouldn't attribute to C++ is that learning it is
simple. This is not so with C#. The foremost goal for this
programming language was simplicity. Many features—or the lack
thereof—contribute to the overall simplicity of C#.


Pointers
are a prominent feature that is missing in C#. By default, you are
working with managed code, where unsafe operations, such as direct
memory manipulation, are not allowed. I don't think any C++
programmer can claim never to have accessed memory that didn't belong
to him via a pointer.


Closely
related to the pointer "drama" is operator "madness."
In C++, you have ::, ., and -> operators that are used for
namespaces, members, and references. For a beginner, operators make
for yet another hard day of learning. C# does away with the different
operators in favor of a single one: the . (the "dot"). All
that a programmer now has to understand is the notion of nested
names.


You no
longer have to remember cryptic types that originate from different
processor architectures—including varying ranges of integer
types. C# does away with them by providing a unified type system.
This type system enables you to view every type as an object, be it a
primitive type or a full-blown class. In contrast to other
programming languages, treating a simple type as an object does not
come with a performance penalty because of a mechanism called boxing
and unboxing. Boxing and unboxing is explained later in detail, but
basically, this technique provides object access to simple types only
when requested.


At
first, seasoned programmers might not like it, but integer and
Boolean data types are now finally two entirely different types. That
means a mistaken assignment in an if statement is now flagged as an
error by the compiler because it takes a Boolean result only. No more
comparison-versus-assignment errors!


C#
also gets rid of redundancies that crept into C++ over the years.
Such redundancies include, for example, const versus #define,
different character types, and soon. Commonly used forms are
available in C#, whereas the redundant forms were eliminated from the
language.


Modern


The
effort you put into learning C# is a great investment because C# was
designed to be the premier language for writing NGWS applications.
You will find many features that you had to implement yourself in
C++, or that were simply unavailable, are part of the base C#
language implementation.


The
financial types are a welcome addition for an enterprise-level
programming language. You get a new decimal data type that is
targeted at monetary calculations. If you are not fond of the
provided simple types, you can easily create new ones specifically
crafted for your application.


I have
already mentioned that pointers are no longer part of your
programming weaponry. You won't be too surprised then that the entire
memory management is no longer your duty—the runtime of NGWS
provides a garbage collector that is responsible for memory
management in your C# programs. Because memory and your application
are managed, it is imperative that type safety be enforced to
guarantee application stability.


It is
not exactly news to C++ programmers, but exception handling is a main
feature of C#. The difference from C++, however, is that exception
handling is cross-language (another feature of the runtime).Prior to
C#, you had to deal with quirky HRESULTs—this is now over
because of robust error handling that is based on exceptions.


Security
is a top requirement for a modern application. C# won't leave you
alone on this either: It provides metadata syntax for declaring
capabilities and permissions for the underlying NGWS security model.
Metadata is a key concept of the NGWS runtime, and the next chapter
deals with its implications in more depth.


Object-Oriented


You
wouldn't expect a new language to not support object-oriented
features, would you? C#, of course, supports all the key
object-oriented concepts such as encapsulation, inheritance, and
polymorphism. The entire C# class model is built on top of the NGWS
runtime's Virtual Object System(VOS), which is described in the next
chapter. The object model is part of the infrastructure, and is no
longer part of the programming language.


One
thing you will notice right from the start is that there are no more
global functions, variables, or constants. Everything must be
encapsulated inside a class, either as an instance member (accessible
via an instance of a class—an object) or a static member (via
the type). This makes your C# code more readable and also helps to
reduce potential naming conflicts.


The
methods you can define on classes are, by default, non virtual (they
cannot be overridden by deriving classes). The main point of this is
that another source of errors disappears—the accidental
overriding of methods. For a method to be able to be overridden, it
must have the explicit virtual modifier. This behavior not only
reduces the size of the virtual function table, but also guarantees
correct versioning behavior.


When
you are used to programming classes in C++, you know that you can set
different access levels for class members by using access modifiers.
C# also supports the private, protected, and public access modifiers,
and also adds a fourth one: internal. How many of you have ever
created a class that derives from multiple base classes? (ATL
programmers, your vote doesn't count!) In most cases, you need to
derive from only one class. Multiple base classes usually add more
problems than they solve. That is why C# allows only one base class.
If you feel the need for multiple inheritance, you can implement
interfaces.


A
question that might come up is how to emulate function pointers when
there are no pointers in C#. The answer to this question is
delegates, which provide the underpinnings for the NGWS
runtime's event model.


Type-Safe


Once
again, I have to pick on pointers as an example. When you had a
pointer in C++, you were free to cast it to any type, including doing
rather idiotic things such as casting an int* (int pointer) to a
double* (double pointer). As long as memory backed that operation, it
kind of "worked." This is not the kind of type safety you
would envision for an enterprise-level programming language.


Because
of the outlined problems, C# implements strictest type safety to
protect itself and the garbage collector. Therefore, you must abide
by a few rules in C# with regard to variables:



  • You
    cannot use uninitialized variables. For member variables of an
    object, the compiler takes care of zeroing them. For local
    variables, you are incharge. However, if you use an uninitialized
    variable, the compiler will tell you so. The advantage is that you
    get rid of those errors when using an uninitialized variable to
    compute a result and you don't know how these funny results are
    produced.


  • C#
    does away with unsafe casts. You cannot cast from an integer to a
    reference type (object, for example), and when you downcast, C#
    verifies that this cast is okay. (That is, that the derived object
    is really derived from the class to which you are down casting it.)


  • Bounds
    checking is part of C#. It is no longer possible to use that "extra"
    array element n, when the array actually has n-1 elements. This
    makes it impossible to overwrite unallocated memory.


  • Arithmetic
    operations could overflow the range of the result data type. C#
    allows you to check for overflow in such operations on either an
    application level or a statement level. With overflow checking
    enabled, an exception is thrown when an overflow happens.


  • Reference
    parameters that are passed in C# are type-safe.



Versionable


Over
the past few years, almost every programmer has had to deal at least
once with what has become known as "DLL Hell." The problem
stems from the fact that multiple applications install different
versions of the same DLL to the computer. Sometimes, older
applications happily work with the newer version of the DLL; however,
most of the time, they break. Versioning is a real pain today.


As you
will see further the versioning support for applications you write is
provided by the NGWS runtime. C# does its best to support this
versioning. Although C# itself cannot guarantee correct versioning,
it can ensure that versioning is possible for the programmer. With
this support in place, a developer can guarantee that as his class
library evolves, it will retain binary compatibility with existing
client applications.


Compatible


C#
does not live in a closed world. It allows you access to different
APIs, with the foremost being the NGWS Common Language Specification
(CLS). The CLS defines a standard for interoperation between
languages that adhere to this standard. To enforce CLS compliance,
the compiler of C# checks that all publicly exported entities comply,
and raises an error if they do not.


Of
course, you also want to be able to access your older COM objects.
The NGWS runtime provides transparent access to COM. Integration with
legacy code is presented further.OLE Automation is a special kind of
animal. Anyone who ever created an OLE Automation project in C++ will
have come to love the various Automation data types. The good news is
that C# supports them, without bothering you with details.


Finally,
C# enables you to inter operate with C-style APIs. Any entry point in
a DLL—given its C-styledness—is accessible from your
applications. This feature for accessing native APIs is called
Platform Invocation Services (PInvoke),.






Flexible


The
last paragraph of the previous section might have raised an alert
with C programmers. You might ask, "Aren't there APIs to which I
have to pass a pointer?" You are right. There are not only a few
such APIs, but quite a large number (a small understatement). This
access to native WIN32 code sometimes makes using unsafe classic
pointers mandatory (although some of it can be handled by the support
of COM and PInvoke).


Although
the default for C# code is safe mode, you can declare certain classes
or only methods of classes to be unsafe. This declaration enables you
to use pointers, structs, and statically allocated arrays. Both safe
code and unsafe code run in the managed space, which implies that no
marshaling is incurred when calling unsafe code from safe code.


What
are the implications of dealing with your own memory in unsafemode?
Well, the garbage collector, of course, may not touch your memory
locations and move them just as it does for managed code. Unsafe
variables are pinned into the memory block managed by the garbage
collector.


Summary


The C#
language is derived from C and C++, and it was created for the
enterprise developer who is willing to sacrifice a bit of C++'s raw
power for more convenience and productivity. C# is modern, simple,
object-oriented, and type-safe. It borrows a lot from C and C++, but
it is considerably different in specific areas such as namespaces,
classes, methods, and exception handling.


C#
provides you with convenient features such as garbage collection,
type safety, versioning, and more. The only "expense" is
that by default your code operates in safe mode, where no pointers
are allowed. Type safety pays off. However, if you need pointers, you
can still use them via unsafe code--and no marshaling is involved
when calling the unsafe code.


Introduction to ASP.NET


The New ASP.NET Infrastructure (The NGWS
Frameworks and Runtime)


When
I say whole new infrastructure... I mean whole new
infrastructure! This is not just a change for ASP. There's this new
concept of managed code that extends throughout the entire Windows
development platform. This managed code runs in the NGWS Runtime. The
NGWS Runtime is basically a run-time environment, which manages the
execution of the code and helps make programming easier. It does much
of the stuff that programs used to have to do themselves and allows
you to focus on the actual development and not managing your code.
From the ASP developers point of view it's similar to the role
Transaction Server used to play in ASP 2 and 3. It manages the system
level stuff so you can spend more time focusing on building your
application
.


The
runtime automatically handles object references and frees them when
they're no longer being used. It also manages system memory, which
helps eliminate memory leaks and other traditional programming
problems. On top of this the new runtime also allows cross-language
integration and exception handling since all the languages are
running in the same environment. For example you can now derive a
class in any language from a class written in any other language or
pass an instance of a class from one language to another. This is
made possible by the runtime and the new common type system and
environment it provides.


I
can already hear you saying "Enough already... what does this
mean to me?" Well at very least what this means to you is:



  • Increased
    performance



  • Cross-language
    re-use of components



  • Better
    object-oriented programming support



  • Automatic
    memory-management


  • The
    ability for you to work more freely with people who use different
    languages than you



So
basically less work and more free time! That being said, please
remember that I'm greatly over-simplifying this to cover it quickly
and get to the stuff most ASP developers will find more applicable,
but the runtime is important to mention since it's the basis and
environment for ASP.NET.


Increased
Performance


[If
you read the last section let me apologize now and say that this one
is much more interesting and exciting!]


The
one thing you can never have too much of as a programmer (besides
caffinee!) is speed! Once you actually get your code working, the
next most important thing is almost always getting it to run faster.
In ASP you could only tweak your code so far until moving it to a
component was the only way to get that last little performance boost.
Well you'll be happy to know that this wasn't overlooked when
Microsoft built ASP.NET.


ASP.NET
code is now compiled.


Let
me say that again... ASP.NET code is now compiled! Don't
worry... it's not what you think. You don't have to create makefiles
and stop and restart things to re-register components. None of it! It
just works... you write code just like you always have and yet you
still get the benefits of early binding, just-in-time compilation,
native optimization, and caching! How is this possible? Well I'm
going to tell you!


On
it's first request for the script, the runtime compiles the code and
keeps a cached copy of the compiled result. This cached copy can then
be used whenever there is another request for the script. This
results in greatly increased performance because after this first
request, the code can run from the much faster compiled version.


The
natural question is then "How does it know when I've made
changes?" Luckily Microsoft was on top of this one too. The
runtime watches the source file on the file system. When the original
source file changes, it automatically pulls the compiled version out
of the cache so that when the next request comes in it'll be
re-compiled. This means we get all the benefits of compiled code and
none of the headaches of having to compile it ourselves. It doesn't
get much better then that folks! Or does it...






Caching


I'm
not sure where to put this... it's so important that it could go here
or in scalability or in development or even back in infrastructure,
but I guess this is as good a place as any so let's get on with it.
If you couldn't guess by the heading I'm talking about caching.


One
of the common things many developers have found the need to build is
some sort of cache in order to speed things up. Whether it's the
output of an asp page to an html file, a stock quote that you get
from a slow internet link, a recordset of the states and their
abbreviations for your shipping forms, or even a database-driven
dynamic menu that you've found isn't actually all that dynamic, there
are plenty of times when there's no reason to spend the time to get
and/or build these things for every client request. Small amounts of
data that don't continuously change are actually very common in
building web sites, but just because they're not truly dynamic
doesn't mean you want to hard code them so where does that leave you?
Until now it lefts you building a caching system of some sort.


The
basic caching scenario is to first identify the appropriate things to
cache. Then you need to place them in an application variable in some
form or another. Then your code has to be able to understand this
form. Then you've got to determine how long to cache it for and write
a routine to clear the cache. But wait... if you clear the cache then
the routine that uses it has to know how to repopulate it... and
around and around we go.


Well
not anymore... a caching system has been built into ASP.NET and since
the whole system is more object-oriented then before it makes sense
that this caching system caches, you guessed it... objects. So what
you're caching looks like it did when you got it when you actually go
to use it. You can set up all sorts of conditions on how long to
cache things for. You can even link a particular item to a file on
the filesystem so that when the file changes the associated item is
flushed from the cache!


And
that's not all... ASP.NET also does output caching. This is where it
takes the result of your ASP.NET script and saves a copy so that when
the next person requests it it doesn't ever even have to run... the
correct output is waiting to be sent. And it's smart too. It caches
based on the querystring so that a page that is passed parameters
will only return the cached version if the parameters match the
parameters used in the cached version!


Sometimes
figuring out what to cache based on your site can be a little tricky,
but at least now actually caching it won't be.


Greater
Scalability


Unfortunately
scalability often gets lumped in with my last topic, performance, but
it really is a different problem altogether. It's actually fairly
easy to build a really fast site that doesn't handle more than a
handful of users. Unfortunately I already talked about one of the
biggest scalability improvements, caching, in my discussion of
performance... so I guess I'll have to find something else to talk
about here and amazingly this is actually not that hard, which just
goes to show how much has changed!


First
of all the system has been built with a number of features to improve
performance in multi-processor and clustered environments. For
example session state can now be maintained in a separate process, on
a separate machine, or even in a database allowing for cross server
sessions. This allows you to relatively easily add more web servers
as your traffic grows even if you hadn't thought about it and planned
for it during development. (If you haven't tried migrating to a web
farm ask anyone who has and they'll tell you that this alone more
than makes up for any headaches you might have upgrading!)


There's
also something called web gardens that I don't fully understand yet,
but they're supposed to help make multi-processor machines scale so
they can do more work then single processor machines. I know it's a
rather novel idea, but what the heck... someone thought they'd try
and pull it off and apparently they have.


So
you've been given the tools to build a better web farm, but what
about keeping it running? Well processes are now closely monitored
and managed by the ASP.NET runtime. When one leaks or deadlocks it's
automatically shut down, but wait it gets better. A new one is
started in its place to take over the load before the original is
shut down. The runtime then directs new requests to the new process
and drains requests from the old one and shuts it down. So not only
do runaway processes get curbed without you having actually to do it,
the end user never sees any down time because a replacement is
provided! (Now you can't tell me that that's not cool.)


Oh...
and now just so you don't forget... caching. All that stuff about
caching in the last section, well it applies here too. If you've got
a hundred people coming to your site for the same information, what
better way to increase scalability then only having to get that
information once and being able to reuse it? That's all I'm gonna
say... really... well at least on this page!


Quicker
and Easier Development


The
one thing any development platform should do for you is provide you
with a solid foundation that you can build upon. With ASP the
foundation was good, but it was basically just a pile of cinder
blocks. With ASP.NET you get the foundation, plumbing, heating, and
electrical before you write your first line of code! Many of the
repetitive and annoying tasks that you needed to do to build a good
project are now done for you.


Object
Oriented Model


To
begin with, you now get a real event model and can control when your
code runs much better then ever before. It used to be if you wanted
something to run early, you put it near the top of the page and if
you wanted it to run later you put it near the end. While this
usually worked, it didn't make very much sense and you often had to
structure your code in weird ways to obtain the desired effect. This
"spaghetti-code" problem can now be fixed by using a wide
variety of events such as Page_Load, which executes right before a
page is loaded.


It
doesn't stop with page level events either. Each object on a page can
have it's own event model and expose and raise server events that can
be programmed against and handled by your script. Routines like
Button_Click or Listbox_Change can make doing standard form
processing and much of your day-to-day tasks relatively simple.
Reading the code also become possible so that when something goes
wrong six months later, understanding what you did and debugging your
code is actually possible.


ASP.NET
Server Controls


Well
with everything being an object in the new world, there's little
wonder that ASP.NET provides some extremely useful ones built right
in. Many things that used to be components are now ASP.NET Server
Controls. For example the ad rotator has been updated and now uses
XML to store its information, but they didn't stop there. There's a
whole set of controls that do everything from managing your form
state for you to displaying calendars and tables. In fact, for almost
every HTML element there's an ASP.NET Server Control that produces it
and allows you to interact with it programmatically. For instance you
no longer have to do a loop with a conditional to maintain a selected
option in a listbox. You can simply tell the listbox to run at the
server and to manage it for you. Better yet you can programmatically
tell the listbox which item to display as selected.


Perhaps
one of the most interesting of these new controls is the DataGrid.
It's a multi-column data-bound grid that you can easily place a data
set into. It supports paging, sorting, and all the cool stuff you
would expect... and you don't have to write it all! This sort of
naturally leads us into what used to be called ADO...


ADO
has been rewritten and is now ADO+


Let
me just start this off right and scare you by saying recordsets
are gone
! The new central object is the data set. It's basically
an in-memory copy of data and is similar to a recordset, but allows
you to do so much more. We'll cover this a lot in future articles and
code since it's sure to be the central point for much of your
development, but for now I'll just say that it's XML friendly,
relatively easy to use and helps unify and simplify things to make it
easier for you to get your work done. You can still do everything
that you used to... (except server-side cursors)... it's just a
little bit different.


User
Input Validation


Another
extremely handy set of ASP.NET Server Controls are the Validator
controls. Think of all the code you've written trying to validate
user input. Now pretend that you had a tool that made it all easier
and left you just writing the conditions the input should meet. Well
that's basically what you've got and like everything else they're
event driven and can be accessed programmatically or linked to other
objects.


Caching


Once
again we're back to caching! It's basically what I've already said
about everything else... the system is in place, you just have to use
it. You've been given the tools. Now you just have to use them, not
invent them. (Have you figured out that I think this is really cool
yet?!)


Easier
Manageability


Text
File Configuration


Have
you ever tried to find something in the Metabase? What about change a
setting? Well unless you were on the team that wrote IIS it's no
picnic. ASP.NET and the new NGWS framework address this problem by
placing configuration information in an xml file that is easily human
readable and writeable. At the same time this system is still
hierarchical (as it should be) and allows for easy tool integration
so you can still have a nice user interface when you want it. The
fact that the files are in a relatively standard format also allows
you to relatively simply build your own administration tool or even a
limited version of one for your users.


The
best part of this new system however is that since these settings are
stored as plain text with the application, new setting can be applied
without having to pcAnywhere or Terminal Server into the box. This
"zero local administration" strategy allows you to deploy
applications by simply copying the appropriate files to the server,
which is what I call...


XCopy
or FTP deployment - Even of components!


This
is something I've been waiting to come back since the good old days
of DOS. No more registering stuff in different locations so the
system knows it exists. No server restart is needed, even to deploy
or replace running compiled code. The framework simply starts a copy
of the new version and directs all new requests to it. At the same
time it keeps the older version running until the processes using it
have finished. No down time and no deployment headaches of having to
restart the web server just to change one little line of code.


And
it's not just ASP code. This goes for components too! If you don't
get excited about that then you've either got a much more exciting
life then I do or you're still in shock from the caching discussion!
;) I promise I'll stop soon!


Tracing


As
if I haven't said it enough... this is really cool. Tracing is an
option that allows you to do things like Trace.Write or Trace.Warn
and have this information output to a tracing display. It's only
displayed if you turn tracing on so it makes a perfect debugging tool
for checking the value of a variable or asserting that a value should
be in a certain range.


There
are two types of tracing: page-level tracing and application-level
tracing. Page level tracing appends a report to the bottom of the
page you just ran while application logs the same data to a separate
area so you can look at it via a separate interface. This is nice for
debugging live code, but make sure you don't leave this on... it's
really meant as an occasional thing and from what I've been told adds
a lot of overhead to the server.


Here's
an
example

of the output from a very simple page, which has page-level tracing
turned on. Only the drop-down part at the top is the actual ASP.NET
page. All the rest was gathered during execution and added to the
page for your use when there's a problem.


Debugging


Did
you ever try to get Visual Interdev to debug your ASP code? Did it
work?


Real
cross language debugging in one unified debugger. That's all I'm
gonna say! Well that and thank goodness we're not stuck using
Response.Write statements for debugging anymore!


Account
impersonation


You
can now get real account impersonation and have the server execute
code as if the user was sitting right there. You can also
programmatically check to see if the user is in a given role and
conditionally let them do certain things only if they have the
correct permissions.


Most
of the rest is the same... more options... better support. Users and
Roles are cool, but this is what you care about...


Forms-based
authentication


Finally
it's here! Forms-based authentication is where you can do your own
custom login screen and your own credential checking and yet still
have ASP.NET handle authenticating the user, redirecting unauthorized
users to the login page, cookie management, and all the junk you used
to have to build yourself. This sort of authentication extremely
popular on the web already, but you had to build it... well not any
more!


This
is a godsend for anyone doing database-based authentication or if you
just can't justify giving every user a NT account, but you still want
to secure something. Or what about time-based authentication where
you only let users in during work hours. The list of useful
applications goes on and on, but now the implementation time doesn't
have to.


Language
Support


I
stuck this close to the end so that you'd be in a good mood from all
the cool stuff before you read this. It's actually a good thing, but
it does have a downside.


VB
(not VBScript!)


Say
goodbye to VBScript! ASP is now written in full-blown VB. That's not
so bad now is it? Well hold on... VB has some changes!


Major
changes in VB:



  • No
    more Set and Let



  • No
    more default properties



  • Parenthesis
    are now required to call Subs



  • Arguments
    are now ByVal by default



  • Integer
    is now 32 bit, Long is 64 bit


  • "And"
    and "Or" are short-circuited



If
you look at the above list... most of the changes make sense, are
definite improvements, and are probably long overdue. Unfortunately
that doesn't change the fact that much of your existing code isn't
going to work!


C#
(C Sharp)


Moving
right along before the VB changes really sink in... C# is cool!
Pardon the pun. (Microsoft's internal code name for it was "cool".)
I was trying to come up with a good description of the language and I
failed miserably so here you go... taken right from the docs:



NGWS
SDK Documentation - CSharp Reference - 1. Introduction:


C# is a simple, modern, object oriented, and type-safe
programming language derived from C and C++. C# (pronounced "C
sharp") is firmly planted in the C and C++ family tree of
languages, and will immediately be familiar to C and C++ programmers.
C# aims to combine the high productivity of Visual Basic and the raw
power of C++.


If
you're a VB developer there's probably no reason to switch, but the
C++ developers will be jumping for joy. (I don't even use C++ and at
the end of the hour long presentation I was thinking about it. If
you're a VB person you know that's a scary thought!)






JScript


As
far as I know it's the same old JScript. It'll benefit greatly, as VB
has from the NGWS runtime and the fact that it's compiled, but beyond
that I'm not aware of any major language changes here.


Web
Services


Let's
talk about ASP for the moment... (this is probably the only time
you'll even hear me say this, but I mean Application Service
Provider!)


If
you want to provide a service from your servers that people can
program against how would you do it. Maybe develop an XML schema for
it and then have to tell everyone about it? Or set up something using
SOAP? Well like everything else in ASP.NET, Microsoft has done it for
you.


Enter
Web Services. ASP.NET files have a .aspx extension. Web services have
a .asmx extension. The technologies are similar, but instead of
outputting HTML, your service outputs a computer readable answer to
the input it recieved.


What
does this mean? Well imagine if you wanted to validate a credit card.
Until now you were stuck either using an ugly post routine to the
clearing house's web site or you got a CD with their objects on it
and loaded them on your machine. Imagine if you could point to their
server and ask for a URL you could use as if it were a component.
Well you can.


Web
services allow you to create such a service using the same familiar
syntax and languages and it automatically generates all the stuff to
be able to use the service over the internet. And ASP.NET and tools
like the next version of Visual Studio will allow you to use them
just as easily as if they were locally installed components.


Being
an ASP just got a whole lot easier thanks to ASP.NET!


Software
giants and the computer experts thought alike that the next phase
of computing will be centered around internet with more emphasis on
network than devices. Hewlett-Packard has offered E-Speak , IBM has
offered Websphere.When everyone was wondering what Microsoft has up
in its sleeves came the announcement in PDC at Orlando , the .NET
Framework. It has two elements one for developing windows based
applications named WinForms and the other for internet, codenamed
ASP.NET.Both with rich features and Rapid application development
environment with easy to use WYSIWYG editors , a welcome relief for
the developer’s community. Let us see what the asp.net has to
offer.


Before
asp.net came there was a whole lot of incapability regarding running
an application on the web.Microsoft has done well to take note of
these problems from its millions of loyal users and subsequently has
solved it in a grand passion and as a bonus provided some great new
features which a web programmer always dreamed of.


First
let us see what we were lacking before the .net came.



Ø     
The internet itself is considered a stateless environment , i.e. when
a browser requests for a page the server flushes out the required
page and ends its interaction with the server and forgets about it.
When the browser requests for the same page the whole process is
repeated ,hence it is not possible to maintain a interaction between
server and the browser, consequently any values passed cannot be
stored for future reference.



Ø     
Very little information is exchanged between the client and server
machines since they both can be running a different software or even
a different operating systems. In other words there wasn’t a
language which can universally communicate between the client and
server machines.



Ø     
ASP 3.0 is considered a little clumsy and non structured. One had to
write tons of code to program even the basic things like validation
in a WebPages. It was very difficult to manage such huge quantity of
unstructured code.



Ø     
Browser dependency was a big headache for any web programmer.One has
to make adjustments in their program to accommodate some browsers
which may not have the resources to run such applications.



Ø     
Now days every application in the web has a backend database attached
to it. Most of the websites are required to connect to the database
to display the data.But connecting to the database required some
expertise in ADO (ActiveX Data Object ) , ODBC etc.Moreover precious
time as well as resources is consumed before the transaction is
executed.


Microsoft
has solved the above problems in style in their new asp.net .


At
the core of asp.net is Common Language Runtime (CLR). This is the
heart of .net framework which takes care of all the activities like
compiling ,instantiating , safety execution, inheritance from other
components etc. Developers can write codes taking advantage of the
classes and functionality exposed by the compilers and other
development tools in CLR. Besides it supports three languages VB ,
Jscript and C# (see sharp) and third party component support.Let us
see some the features that has made this technology great.



     Now
developers using asp.net can forget about browser dependencies
.ASP.Net takes care of the problem since it verifies with each
browser about the version , capabilities etc before it sends the
requested page and sends output accordingly.



Ø     
Provides a set of management features that maintain the state of a
page between request.These are in the form of state bag
which can be programmatically deployed.



Ø     
Provides a Event based programming model .Each form may consists of
buttons ,radio button, checkbox button etc which raises a events.eg
buttonOn_click .The programmer has to write event handlers keeping in
mind that each event processing makes a round trip to the server.But
the best part is .net acts intelligently and uses the minimum
resource and time to execute this.



Ø     
User control, a new feature which enables one to create controls of
their own or use third party control to enhance their application is
now possible.It throws open a new market for web controls which I am
sure the IT companies would grab with both hands.



Ø     
ADO+ an advanced version of ADO is offered by asp.net with rich
features and easy coding.



Ø     
Advanced caching features which help the programmer to decide on what
and when to cache and when to empty it.



Ø     
An XML based web service for providing online news etc. which
provides a new set of features for the developers is for the taking.



Ø     
It provides an abstract and consistent model .This is much different
from the unstructured code and unwanted spaghetti code used in
ASP3.0.



Ø     
Provides a rich set of built in controls which makes programming in
asp.net a pleasure.


Remember
these are the features available in Beta1, the final version is yet
to be shipped. One can expect some more pleasant features in the
final version. Microsoft has been working on this technology for the
past two years. It is amazing they have made deep inroads in record
time.Hats off to them. And for the Title of this aricle I might be a
little ambitious but I strongly believe that asp.net is more like an
operating system. It allows developers to write components in their
own familiar language and still utilise the good features of .net by
refencing the class and other functionality .ASP.NET is going to be
here for a long time.


  Where
does this take us to?


Software
giants are diverting their resources towards networking the home,
including common household goods like Washing Machines and
refrigerators involving internet.Now the search for Extraterrestrial
Intelligence has begun involving thousands of people lending their
computers to be harnessed to the task of listening for
electromagnetic signals from outerspace.


Sounds
great isn’t , Get set folks for the new revolution has just
begin


Introduction


First
off, let me stress that this is not simply a new version of ASP with
a couple new features and some bug fixes like ASP 3.0 was when you
compared it to ASP 2.0. This is a whole new system built from the
ground up that takes the strong points of ASP and tries to expand on
them 


Lets
explore


ASP.NET files
runs in the NGWS Runtime. The NGWS Runtime is basically a run-time
environment, which manages the execution of the code and helps make
programming easier. It does much of the stuff that programs used to
have to do themselves and allows you to focus on the actual
development and not managing your code.From the ASP developers point
of view it's similar to the role Transaction Server used to play in
ASP 2 and 3. It manages the system level stuff so you can spend more
time focusing on building your application. The runtime automatically
handles object references and frees them when they're no longer being
used. It also manages system memory, which helps eliminate memory
leaks and other traditional programming problems. On top of this the
new runtime also allows cross-language integration and exception
handling since all the languages are running in the same environment.
For example you can now derive a class in any language from a class
written in any other language or pass an instance of a class from one
language to another. This is made possible by the runtime and the new
common type system and environment it provides.


Increased
performance Cross-language re-use of components


Better
object-oriented programming support


Automatic
memory-management


The
ability for you to work more freely with people who use different
languages than you 



ASP+
Platform



The
first thing to notice is that ASP+ pages have a variety of new
extensions. A basic ASP+ page uses .aspx as the filename extension. A
Web Service uses .asmx and a new construct called a "pagelet"
uses .aspc. These new filename extensions are there for a reason.
ASP+ runs side by side with the existing ASP infrastructure. They
don't share session state, application state, or anything else, so
they will peacefully coexist on the same server. These new filename
extensions are therefore required so that IIS can call the
appropriate ISAPI filter to handle processing. Managed code is the
term Microsoft uses for code that sits on top of the new .NET
runtime. This code takes full advantage of the new .NET framework
including garbage collection, simplified deployment, etc. One
interesting thing to note here is that except for some host-specific
code, almost all of the new ASP+ is written using the .NET runtime in
a new language called C#. ASP+ supports multiple hosts. The first
beta will only support IIS5 on Windows 2000. However, upon release it
is expected to run on IIS4 on Windows NT 4.0 as well as in IE 5.5
using a new offline feature called My Web.


Compiled


On
it's first request for the script, the runtime compiles the code and
keeps a cached copy of the compiled result. This cached copy can then
be used whenever there is another request for the script. This
results in greatly increased performance because after this first
request, the code can run from the much faster compiled version. The
runtime watches the source file on the file system. When the original
source file changes, it automatically pulls the compiled version out
of the cache so that when the next request comes in it'll be
re-compiled Initial conservative indications show that these changes,
along with other feature enhancements in ASP+, may yield a raw 250%
performance increase!


ASP+
Page Framework



ASP+
introduces a new page framework that provides an object model on the
server for the contents of the page. This framework includes a new
class of controls termed server controls. Other new features
include the addition of server-side comments that allow you to
comment out an entire block of code, data-binding expressions that
allow you to bind data to server controls, and new directives that
allow you to declaratively set a number of page options. Server
controls are probably the most interesting new advance in the page
framework. A server control is a control on the page that's
instantiated on the server. Its namespace is merged with the page
namespace so that you can manipulate it in code without having to
alter the underlying HTML explicitly.


ASP+
Web Services


Web
Services are one of the coolest new features in Microsoft's .NET
platform. A Web Service allows you to take an object and use HTTP to
invoke it, rather than RPC. The advantages to this are clear. Instead
of tightly coupling your objects with DCOM and relying upon RPC
mechanisms to communicate, you can now use the common HTTP protocol
and extend your services out to the Internet at large and take
advantage of all the infrastructure support for load balancing,
security, etc. that has been built into HTTP. ASP+ provides a
simplified model for creating Web Services. Instead of writing an
.aspx file, you write an .asmx file, which contains a class with
whatever methods the developer wishes to expose. ASP+ compiles the
.asmx file on demand, generating the required SDL contract and
creating a default page that documents the service and provides a
facility for testing it. The Web Service can be consumed in multiple
ways. It supports invocation via HTTP Get requests, HTTP Post
requests, or HTTP Post requests with SOAP XML payloads. The developer
requires no special knowledge of HTTP or XML.


ADO
has been rewritten and is now ADO+


Let
me just start this off right and scare you by saying recordsets are
gone! The new central object is the data set. It's basically an
in-memory copy of data and is similar to a recordset, but allows you
to do so much more.


ASP+
Deployment


If
you have ever tried to deploy a complex ASP application that utilizes
COM objects into a shared multi-application environment, you know how
difficult that really is. ASP+ has simplified the deployment model to
just copying all files which comprise an application into the
appropriate directory. No registration of objects or restarting of
the application is required. All parts of an ASP+ application can be
deployed in this fashion, including pages, Web Services, compiled
components (DLL), and even some configuration data, as shown in the
next section. For compiled components there is now a special
directory under each application root, called "/bin." Any
components placed in this directory are automatically made available
for use within that application. Note that they are only made
available to that specific application. This gives you true
application isolation—that is, each application on the server
could be running a slightly different version of the component with
no effect on other applications! This is a huge win for developers
who host multiple instances of a site on one machine, such as a
development environment, a test environment, and a staging
environment, each with different component versions. ASP+ no longer
locks DLLs to prevent you from updating them. You can just copy the
new DLL on top of the old one. ASP+ automatically detects the change
and migrates to the new version. Currently executing requests are
drained off the old version and new requests are directed to the new
version. You no longer have to reboot or restart the application. To
uninstall, you simply delete any piece of the application and be done
with it—no components to unregister, no Windows Registry
entries to change.


Customizing
Tables in ASP.NET 


Customizing
a table in ASP.NET is one of the basic need of a developer if you
want to display data the way you want. This a very simple example but
it can be enhanced to provide the look and feel to a table the way
you want.


This
sample code customizes a table in the following ways -

1.
Adding ComboBox as a table Cell
2. Adding CheckBox as a table
Cell
3. Changing the color of ComboBox and CheckBox Columns.



The
below sample code does the trick for you. You write this code in
Page_Load event of your ASP.NET page.









 



DropDownList dropDownLst = new DropDownList();



TableRow row = new TableRow();



dropDownLst.Items.Add("First Item");



dropDownLst.Items.Add("Second Item");



dropDownLst.Items.Add("Other Data");



dropDownLst.Items.Add("Ok");



dropDownLst.Items.Add("End");



dropDownLst.BackColor = System.Drawing.Color.Red;



TableCell cell = new TableCell();



cell.Controls.Add(dropDownLst);



row.Cells.Add(cell);



row.BackColor = System.Drawing.Color.Green;



Table1.Rows.Add(row);


 



CheckBox checkBox1 = new CheckBox();



checkBox1.Checked = true;



checkBox1.BackColor =
System.Drawing.Color.Yellow;
TableCell cell2 = new TableCell();



cell2.Controls.Add(checkBox1);



row.Cells.Add(cell2);


 









Validation
Controls in Web Forms


Validation
is one of the less talked about areas – often taken for
granted. As programmers we instinctively know what values not to
enter in our web pages. Real world situations are often different. We
can be proactive and catch the “error” conditions using
validation controls.


What
are Validation Controls ?


Validation
controls allow you to validate user entry on WebForms. These controls
can be very handy tools – Unexpected values can cause the web
page to blow up and result in an error page. We wouldn’t want
that to happen! 


Why
should I use validation Controls ?


It
is still possible to add in the validations within code. Validation
controls provide an easy and object oriented approach for the same
task without sacrificing clarity of code. 


These
controls help in avoiding some negative user experience


What
are the different Validation controls available ?



Following
are the different types of Validation controls and examples for each
of them.


If
you use Visual Studio.Net as your editor, you can just drag-and-drop
the desired Validation Control from the toolbox (from the WebForms
controls section) 


You
can use any combination of validation controls on a single web
control.


The
validations can be performed at the server side or the client side.
If the user is using a browser that supports DHTML, the validation
controls automatically detect and perform the validations at the
client side. 


Common
properties of validation controls 


You
will typically need to set the following properties for Validation
Controls.


ControlToValidate
: Name of the control to be validated 


Text
: This text is displayed for the control. Typically indicated by * or
a hint about the validation. 


ErrorMessage:
This is the message that will be displayed if the validation fails
for that validation control. 














RequiredFieldValidator
control


This
would probably be the most commonly needed validation control –
This control marks a field as mandatory. 









<script
language="C#" runat="server">
void
HiBtn_Click(Object Src, EventArgs E) 
{
lblHello.Text
= "Hi " + txtName.Text + ", Welcome to
ASP.NET!";
}
</script>
<html>
<head> 



<title>RequiredValidator
Control</title></head><body> 



<form
runat="server">
<b><asp:Label
id="lblHello" runat="server" /></b><br
/>
Enter your name: <asp:textbox id="txtName"
runat="server"/>
<asp:button text="Hi"
Onclick="HiBtn_Click"
runat=server/>
<asp:RequiredFieldValidator
id="RequiredFieldValidator1" runat="server"

ControlToValidate="txtName"
ErrorMessage="Name
is a required field."

ForeColor="Red">
</asp:RequiredFieldValidator>

</form>
</body>
</html>



Listing
1 : RequiredFieldValidator Control (Hello.aspx)



Figure
1: RequiredFieldValidator in Action






CompareValidator
control


1.      
Compare
the user entry against a datatype.
Specify the datatype to be
compared by setting the
Type
property of the CompareValidator control using the ValidationDataType
enumeration values (Currency, DateTime, Double, Integer, String)


 Set
the
Operator
property to DataTypeCheck.









<script
language="C#" runat="server">
void
HiBtn_Click(Object Src, EventArgs E) 
{
lblHello.Text
= "Hi " + txtName.Text + ", Welcome to
ASP.NET!";
}
</script> 



<html>
<head> 



<title>CompareValidator
Control</title></head><body> 



<form
runat="server">
Enter your name: <asp:textbox
id="txtName" runat="server"/>
<br/>
Enter
your age in years: <asp:textbox id="txtAgeYrs"
runat="server"/>



<asp:CompareValidator
id="CompareFieldValidator1" runat="server"

ForeColor="Red"

ControlToValidate="txtAgeYrs"
Type="Integer"

Operator="DataTypeCheck"

ErrorMessage="Please enter an integer">

</asp:CompareValidator >

<br/>
<asp:button
text="Enter" Onclick="HiBtn_Click"
runat=server/> 
<asp:RequiredFieldValidator
id="RequiredFieldValidator1" runat="server"

ControlToValidate="txtName"
ErrorMessage="Name
is a required field."

ForeColor="Red">
</asp:RequiredFieldValidator>





<b><asp:Label
id="lblHello" runat="server" /></b><br
/>
</form>
</body>
</html>



 Listing
2: CompareValidator control – Compare for a datatype. 



Figure
2: CompareValidator control – Compare for a datatype. 


2.      
Compare
the user entry against a constant value


Specify
the constant value to be compared against by setting the
ValueToCompare
property.


Set
the
Type
property using the ValidationDataType enumeration.


Set
the
Operator
property using the ValidationCompareOperator enumeration (Equal,
NotEqual, GreaterThan etc)









<script
language="C#" runat="server">  
void
HiBtn_Click(Object Src, EventArgs E)  

lblHello.Text
= "Hi " + txtName.Text + ", Welcome to ASP.NET!";
 
}  
</script>  
   
<html>
 
<head>  
   
<title>CompareValidator
Control</title></head><body>  
 
 
<form runat="server">  
Enter
your name: <asp:textbox id="txtName" runat="server"/>
 
<br/>  
Enter your age in years:
<asp:textbox id="txtAgeYrs" runat="server"/> 


<asp:CompareValidator id="CompareFieldValidator1"
runat="server" 
ForeColor="Red" 

ControlToValidate="txtAgeYrs" 

ValueToCompare=0 
Type="Integer" 

Operator="GreaterThan" 

ErrorMessage="Please enter a whole number greater than
zero."> 
</asp:CompareValidator >

 
<br/>  
<asp:button text="Enter"
Onclick="HiBtn_Click" runat=server/>  
 
<asp:RequiredFieldValidator
id="RequiredFieldValidator1" runat="server" 

ControlToValidate="txtName" 

ErrorMessage="Name is a required field." 

ForeColor="Red">  
</asp:RequiredFieldValidator>
 
   
<b><asp:Label id="lblHello"
runat="server" /></b><br />  
 
 
</form>  
</body>  
</html>
 



Listing
3: CompareValidator control – Compare against a specific value.



Figure
3: CompareValidator control – Compare against a specific value.


3.      
Compare
the user entry against the value of another control.


Specify
the control to be compared against, using the
ControlToCompare
property.


Set
the Type property using the ValidationDataType enumeration and the
Operator property using the ValidationCompareOperator property.









<script
language="C#" runat="server">  
void
HiBtn_Click(Object Src, EventArgs E)  

lblHello.Text
= "Hi " + txtName.Text + ", Welcome to ASP.NET!";
 
}  
</script>  
   
<html>
 
<head>  
   
<title>CompareValidator
Control</title></head><body>  
 
 
<form runat="server">  
Enter
your name: <asp:textbox id="txtName" runat="server"/>
 
<br/>  
Enter your email address:
<asp:textbox id="txtEmail" runat="server"/><br/>
 
Re-enter your email address: <asp:textbox
id="txtEmail1" runat="server"/>
 

<asp:CompareValidator
id="CompareFieldValidator1" runat="server"  

ForeColor="Red"  

ControlToValidate="txtEmail1"  

ControlToCompare="txtEmail"  

Type="String"  
Operator="Equal"
 
ErrorMessage="Please check the email
address.">  
</asp:CompareValidator >  

   
<br/>  
<asp:button
text="Enter" Onclick="HiBtn_Click"
runat=server/>  
   
 
 
<b><asp:Label id="lblHello"
runat="server" /></b><br />  
 
 
</form>  
</body>  
</html>
 



Listing
4: CompareValidator Control – Compare against the value in
another control



Figure
4: CompareValidator Control – Compare against the value in
another control


RangeValidator
Control


As
the name indicates, this control is used to validate that the user
entry falls within a specified range. As with CompareValidator
control, the validation can be against specific values or against
values of controls.


The
minimum value of the range is indicated by setting the
MinimumValue
or
MinimumControl
property. Similarly the maximum value is indicated by setting the
MaximumValue
or
MaximumControl
property


 Set
the Type property using the ValidationDataType enumeration.









<script
language="C#" runat="server">  
void
HiBtn_Click(Object Src, EventArgs E)  

lblHello.Text
= "Hi " + txtName.Text + ", Welcome to ASP.NET!";
 
}  
</script>  
   
<html>
 
<head>  

<title>RangeValidator
Control</title></head><body>  
 
 
<form runat="server">  
Enter
your name: <asp:textbox id="txtName" runat="server"/>
 
<br/>  
On a scale of 1 to 5 (1 being the
lowest), how do you rate this article: <asp:textbox
id="txtRate" runat="server"/>  
 
 

<asp:RangeValidator
id="RangeFieldValidator1" runat="server"  

ForeColor="Red"  

ControlToValidate="txtRate"  

MinimumValue=1  
MaximumValue=5  

Type="Integer"  
ErrorMessage="Please
enter an integer in the range 1 to 5.">
 
</asp:RangeValidator >  

<br/>
 
<asp:button text="Enter"
Onclick="HiBtn_Click" runat=server/>
 
 
<b><asp:Label id="lblHello"
runat="server" /></b><br />  
 
 
</form>  
</body>  
</html>
 



  Listing
5: RangeValidator Control – Validate that the entered value
lies within a range


 


Figure
5: RangeValidator Control – Validate that the entered value
lies within a range


RegularExpression
Control


This
is a customized validation control that validates the user’s
entry matches a predefined pattern such as phone number, email
address.


Visual
Studio.Net provides some predefined patterns. Of course, you can
specify your own expressions. Set the pattern to compare by setting
the ValidationExpression property.









  <script
language="C#" runat="server">  
void
HiBtn_Click(Object Src, EventArgs E)  

lblHello.Text
= "Hi " + txtName.Text + ", Welcome to ASP.NET!";
 
}  
</script>  
   
<html>
 
<head>  
   
<title>RegExValidator
Control</title></head><body>  
 
 
<form runat="server">  
Enter
your name: <asp:textbox id="txtName" runat="server"/>
 

<br/>  
Enter your email address:
<asp:textbox id="txtEmail" runat="server"/>
 
   
<asp:RegularExpressionValidator
id="RegExValidator1" runat="server"
 
ErrorMessage="Please Enter a Valid Email address"
ControlToValidate="txtEmail"
 
ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">
 
</asp:RegularExpressionValidator>  
 
 
<br/>  
<asp:button text="Enter"
Onclick="HiBtn_Click" runat=server/>  
 
 
   
<b><asp:Label id="lblHello"
runat="server" /></b><br />  
 
 
</form>  
</body>  
</html>
 



Listing
6 : Regular Expression Validator Example  



Figure
6 : Regular Expression Validator


CustomValidator
Control


Validation
requirements do not always fall into explicit patterns and can become
complicated for even medium sized systems. The CustomValidator
control is used to validate against any custom validation function
created by you.


Create
a ServerValidate event for the validation control and specify the
custom logic for the validation.









  <script
language="C#" runat="server">  
 
 

protected
void LikeValidate (object source, ServerValidateEventArgs args)
 

try  


string str = Convert.ToString(args.Value); 

args.IsValid = (str != "Yes") ? false : true; 


catch 


args.IsValid = false; 
}  
}  

 
 
   
void HiBtn_Click(Object Src, EventArgs
E)  
{  
if (Page.IsValid) 

lblHello.Text
= "Hi " + txtName.Text + ", Welcome to ASP.NET!";
 
}  
</script>  
   
<html>
 
<head>  
   
<title>CustomValidator
Control</title></head><body>  
 
<form runat="server">  
Enter your name:
<asp:textbox id="txtName" runat="server"/>
 
<br/>  
Do you like validation controls:
<asp:textbox id="txtLike" runat="server"/>
 
   
<asp:CustomValidator
id="CustomValidator1" runat=server  

ControlToValidate = "txtLike" 

ErrorMessage = "You must enter Yes!" 

onservervalidate="LikeValidate" >
 
</asp:CustomValidator>
<br/>
 
<asp:button text="Enter"
Onclick="HiBtn_Click" runat=server/>  
 
 
<b><asp:Label id="lblHello"
runat="server" /></b><br />  
 
 
</form>  
</body>  
</html>
 



Listing
7: CustomValidator control




Figure
7 : CustomValidator control  


How
should I use Validation controls ?


The
Validation Process


When
the user clicks on any button control that has the CausesValidation
property set to true, Page.Validate() gets invoked automatically.
This instructs all the validation controls on the page to validate as
per their property settings. The default value for the
CausesValidation property is true.


You
can also invoke the validation process any time in the code by
calling the Validate function.


Each
validation control sets a flag that can be checked programmatically
and you can decide the logic flow based on the validity of controls.


Page.IsValid
Property


The
IsValid property of the page indicates if the page validation was
successful. Refer to Listing 7 (CustomValidator example). Similarly,
you can also check for the validity of individual controls by looping
through the Page’s Validators collection.


ValidationSummary
control


The
ValidationSummary control is used to summarize the all validation
errors in the page. The DisplayMode property of the control provides
options for formatting the display of the error information.


Summary


Once
you start using Validation controls, you will find that you just
cannot do without them


Using
WebForms ListBox Control


ListBox
Creation

ListBox
is created using the following syntax:
<asp:ListBox
Id="Month">
<asp:ListItem
Value="1">Jan</asp:ListItem>
<asp:ListItem
Value="2">Feb</asp:ListItem>
.....
</asp:ListBox>

Useful
Properties of ListBox Class


1.SelectionMode
- Single,Multiple[Allows multiple items to be selected]
2.Rows -
How many items to show in the ListBox.
3.Selected - To check
whether the Item is selected or not.
4.SelectedItem - To get the
SelectedItem in the ListBox the return type is
ListItem.
5.SelectedIndex - To get the Index of the
SelectedItem
6.Items -To iterate over all the items in the ListBox
each Item is of type ListItem

Useful
Method of ListBox Class


To
add an Item:

lstItem.Items.Add(new
ListItem(<ValueToShow>,<ValueToSubmit>))

To
Removed an Item:

lstItem.Items.Remove(lstItem.SelectedItem)
The
above will remove the SelectedItem in the Listbox


Advantages
over Html <Select>


If
we use HTML <Select> Tag to create ListBox when the form is
submitted we can only get the Value of the ListBox and no way we know
the Text value selected or SelectedIndex of the Control.But using
this ASP.NET control these information can be obtained easily and in
more orgainsed manner.


Example


The
Following source shows how to use Various Properties of ListBox
Control in the Server side like Adding,Deleting,Swapping Items in
ListBox.

Source
Code








<%@
Page Language="C#" %>
<html>
<head>
<script
runat="server">
protected void Button_Click(object
sender,EventArgs
e)
{
if(sender==Add)
{
if(txtItem.Text!="")
{
lstItem.Items.Add(new
ListItem(txtItem.Text));
}
}
if(sender==Del)
{
if(lstItem.SelectedIndex>-1)
{
lstItem.Items.Remove(lstItem.SelectedItem);
}
}
if((sender==Up
&& lstItem.SelectedIndex>0) || (sender==Down &&
lstItem.SelectedIndex<lstItem.Items.Count-1))
{
int
offset;
offset=(sender==Up)?-1:1;
ListItem lstTemp=new
ListItem(lstItem.SelectedItem.Text,lstItem.SelectedItem.Value);
lstItem.Items[lstItem.SelectedIndex].Text=lstItem.Items[lstItem.SelectedIndex+offset].Text;
lstItem.Items[lstItem.SelectedIndex].Value=lstItem.Items[lstItem.SelectedIndex+offset].Value;
lstItem.Items[lstItem.SelectedIndex+offset].Text=lstTemp.Text;
lstItem.Items[lstItem.SelectedIndex+offset].Value=lstTemp.Value;
lstItem.SelectedIndex=lstItem.SelectedIndex+offset;
}
if(sender==First)
{
if(lstItem.Items.Count>0)
{
lstItem.SelectedIndex=0;
}
}
if(sender==Last)
{
if(lstItem.Items.Count>0)
{
lstItem.SelectedIndex=lstItem.Items.Count-1;
}
}
if(sender==Prev)
{
if(lstItem.SelectedIndex>0)
{
lstItem.SelectedIndex=lstItem.SelectedIndex-1;
}
}
if(sender==Next)
{
if(lstItem.SelectedIndex<lstItem.Items.Count-1)
{
lstItem.SelectedIndex=lstItem.SelectedIndex+1;
}

}
</script>
</head>
<body>
<form
runat="server">
<table>
<tr><td
Colspan=2><h1><font color="red">ListBox
Demo</font></h1></td></tr>
<tr>
<td>Enter
Text:</td>
<td>
<asp:TextBox id="txtItem"
TextMode="SingleLine" runat="server"/>&nbsp;
<asp:Button
id=Add Text="Add" runat="server"
onclick="Button_Click"/>
</td>
</tr>
<tr>
<td>ListBox:
<br>
<asp:ListBox id="lstItem"
runat="server">
<asp:ListItem>Sample
Item</asp:ListItem>
</asp:ListBox>
</td>
<td>
<asp:Button
id="Del" Text="Del" runat="server"
onclick="Button_Click"/>&nbsp;
<asp:Button
id="Up" Text=" Up " runat="server"
onclick="Button_Click"/>&nbsp;
<asp:Button
id="Down" Text="Down" runat="server"
onclick="Button_Click"/>&nbsp;
<asp:Button
id="First" Text="<<" runat="server"
onclick="Button_Click"/>&nbsp;
<asp:Button
id="Prev" Text="<" runat="server"
onclick="Button_Click"/>&nbsp;
<asp:Button
id="Next" Text=">" runat="server"
onclick="Button_Click"/>&nbsp;
<asp:Button
id="Last" Text=">>" runat="server"
onclick="Button_Click"/>&nbsp;
</td>
</tr>
</table>
</form>
<body>
</html>






Using
ASP.NET Table Control


The
following article will show how to dynamically build table in
ASP.NET.The Table  control allows us to add Rows,Column in more
orgainsed manner then using the old spaghetti code.

Contains
Relationship
===============
Table
->TableRow->TableCell/TableHeaderCell

Table
Creation
============
Table
is created using the following syntax:
<asp:Table Id="oTable"
runat="server">

</asp:Table>


How
to Manipulate Table Control
========================
1.To
Add a cell to a table first create a instance of TableCell class and
add controls or assign text which is to be displayed in the cell and
add the resulting cell to the TableRow() object.

eg.
TableCell
cell=new TableCell();
cell.Text="Welcome" //This will
show text 'welcome' in the cell
cell.Controls.Add(<Control>)//This
will show the control instead of text
TableRow row=new
TableRow();
row.Cells.Add(cell) //Add the above cell to a table
row.

2.To Add a Row first create instance of TableRow class
and add cells to the TableRow object and then add the Rowobject to
the TableClass.

eg.TableRow row=new
TableRow()
oTable.Rows.Add(row);

Tips
on using Table Control
=====================
1.TableControl
does not maintain ViewState so the value is not postback and
preserved so the developer has to take care of this.

2.TableControl
is mainly used in Custom control Creation.

Example
=======
The
Following source shows assign properties of Table control and add
Rows and Cell using the value specified by the user.


Source
Code








<%@
Page Language="C#"
Debug="true"%>
<html>
<head>
<title>Table
Control Usage</title>
<script
runat="server">
protected void
Generate_Click(object sender,EventArgs
e)
{
try
{
oTable.CellPadding=Int32.Parse(CellPadding.Text);
oTable.CellSpacing=Int32.Parse(CellSpacing.Text);
switch(BorderLines.SelectedItem.Value)
{
case
"0":
oTable.GridLines=GridLines.None;
break;
case
"1":
oTable.GridLines=GridLines.Horizontal;
break; 
case
"2":
oTable.GridLines=GridLines.Vertical;
break; 
case
"3":
oTable.GridLines=GridLines.Both;
break; 
}
for(int
i=0;i<Int32.Parse(Rows.Text);i++)
{
TableRow row=new
TableRow();
for(int
j=0;j<Int32.Parse(Cols.Text);j++)
{
TableCell cell=new
TableCell();
cell.Text="Row#" + i.ToString() +
",Column#" +
j.ToString();
row.Cells.Add(cell);
}
oTable.Rows.Add(row);
}
}
catch(Exception
ex)
{
TableRow row=new TableRow();
TableCell cell=new
TableCell();
cell.Text="<h1><font
color='red'>Invalid Value entered for Table
Properties:</h1><br>" +
ex.ToString();
row.Cells.Add(cell);
oTable.Rows.Add(row);
}
}
</script>
</head>
<form
runat="server">
<table border="0">
<tr>
<td
colspan="2" align="center"><h1><font
color="red">Table
Generation</font></h1></td>
</tr>
<tr>
<td>CellSpacing:</td>
<td><asp:TextBox
id="CellSpacing" MaxLength="2"
runat="server"/></td>
</tr>
<tr>
<td>CellPadding:</td>
<td><asp:TextBox
id="CellPadding" MaxLength="2"
runat="server"/></td>
</tr>
<tr>
<td>GridLines:</td>
<td>
<asp:DropDownList
id="BorderLines" runat="server">
<asp:ListItem
Value="0">None</asp:ListItem>
<asp:ListItem
Value="1">Horizontal</asp:ListItem>
<asp:ListItem
value="2">Vertical</asp:ListItem>
<asp:ListItem
Value="3">Both</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Rows:</td>
<td><asp:TextBox
id="Rows" MaxLength="2"
runat="server"/></td>
</tr>
<tr>
<td>Cols:</td>
<td><asp:TextBox
id="Cols" MaxLength="2"
runat="server"/></td>
</tr>
</table>
<asp:Button
runat="server" id="Generate" Text="Generate"
onclick="Generate_Click"/>
</form>
<asp:Table
id="oTable" runat="server"/>
</html>






Server
Side Repeater Control


Introduction:
The
following article will show you how to use Repeater control in
ASP.NET and how to assign various Properties of the
RepeaterControl.

Repeater
Control Creation:
Repeater
Control is created using the following syntax:


<asp:Repeater
Id="oTable"
runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate></ItemTemplate>
<AlternatingItemTemplate></AlternatingItemTemplate>
<SeparatorTemplate></SeperatorTemplate>
<FooterTemplate></FooterTemplate> 
</asp:Repeater>



Explanation
of the above Properties:

<HeaderTemplate></HeaderTemplate>


The
content between Headertemplate is rendered only once before
showing
the Collection bound to DataSource of the
Repeater.HeaderTemplate should not
bound to any Container
Items.The text between the HeaderTemplate is choosen only
by the
Developer and not by
ASP.NET.

eg. 
<HeaderTemplate><Table><tr><td>Name</td><td>EMail</td></tr></HeaderTemplate>

This
will start a Table and one row is added to the table as
given.

<FooterTemplate></FooterTemplate>

This
is also similar to HeaderTemplate ie it is also rendered only once
and should not
be bounded.It is rendered after finishing the
render of
<ItemTemplate><AlternatingItemTemplate>

eg.
<FooterTemplate></Table></FooterTemplate>

This
will close the table started in the
<HeaderTemplate>

<ItemTemplate></ItemTemplate>

The
content between the tags is rendered repeatedly for each and every
item in the Collection which is bound to the datasource.eg. If an
ArrayList it repeats for as many number of items in the
ArrayList.

eg.
<ItemTemplate>
<tr
bgcolor=cyan>
<td><%#DataContainer.Eval(Container.DataItem,"Name")%></td>
<td><%#DataContainer.Eval(Container.DataItem,"Email")%></td>
</ItemTemplate>
<AlternatingItemTemplate></AlternatingItemTemplate>

This
is also same as ItemTemplate ie rendered for even items in the
collection if it is given. If not even items are rendered by
<ItemTemplate> itself.

eg.
<AlternatingItemTemplate>
<tr
bgcolor=LightGreen>
<td><%#DataContainer.Eval(Container.DataItem,"Name")%></td>
<td><%#DataContainer.Eval(Container.DataItem,"Email")%></td>
</AlternatingItemTemplate>


<SeparatorTemplate></SeparatorTemplate>

This
will be used when we need separator between two items such as <hr>
or <br>

Event
Handling in Repeater Control


1.When
controls are placed in a RepeaterControl we have to right
OnItemCommand() Event for the RepeaterControl and determine which
control has raised the events.Events are bubbled between the controls
ie if as button is placed in Repeater and the Repeater has
OnItemCommand()
Event and also the Button has Click Event then
both the events will be fired so it is always safe to write events
only for Top-Level Controls.


Example
The
Following source shows assign properties of Repeater control and
handle ItemCommand Event for RepeaterControl.

Source
Code








<%@
Page Language="C#" Debug="true"%>
<html>
<head>
<script
runat="server">
protected void Page_Load(object
sender,EventArgs e)
{
ArrayList al=new ArrayList();
for(int
i=1;i<10;i++)
al.Add(new AddressBook("Name#" +
i.ToString(),"mail@mail" +
i.ToString()));
Repeater.DataSource=al;
Repeater.DataBind();
}

protected
void Repeater_Action(object sender,RepeaterCommandEventArgs
re)
{
label1.Text="You Selected: " +
((LinkButton)re.CommandSource).Text;
}

public class
AddressBook
{
private string _Name;
private string
_EMail;

public AddressBook(string name,string
email)
{
this._Name=name;
this._EMail=email;
}

public
string Name
{
get
{
return this._Name;
}
}

public
string Email
{
get
{
return
this._EMail;
}
}
}
</script>
</head>
<body>
<form
runat="server">
<h1><asp:Label
id="label1" runat="server"/></h1>
<asp:Repeater
runat="server" id="Repeater"
OnItemCommand="Repeater_Action">
<HeaderTemplate>
<table
border=1 cellspacing="0" cellpadding="0"
width=100%>
<tr
bgcolor=teal>
<td>Name</td>
<td>eMail</td>
</tr> 
</HeaderTemplate>
<ItemTemplate>
<tr
bgcolor=Cyan>
<td><asp:LinkButton runat="server"
Text=<%#DataBinder.Eval(Container.DataItem,"Name")%>
/></td>
<td><b><%#DataBinder.Eval(Container.DataItem,"Email")%></b></td> 
</tr>
</ItemTemplate>
<AlternatingItemTemplate>
<tr
bgcolor=Lightgreen>
<td><%#DataBinder.Eval(Container.DataItem,"Name")%></td>
<td><asp:LinkButton
Text=<%#DataBinder.Eval(Container.DataItem,"Email")%>
runat="server"/></td> 
</tr> 
</AlternatingItemTemplate>
<FooterTemplate>
</Table>
</FooterTemplate>
</asp:Repeater>
</form>
</body>
</html>






Using
WebForms LinkButton Control


The
following article will show how to use LinkButton Control in
ASP.NET.

The
LinkButton Class

The
LinkButton is similar to Html Submit Button but has <A> tag's
appearance. When the Link is clicked the Form is posted back to the
Server and the corresponding click event is handled on the server
side.

Important
Members 

The
following members are widely used for LinkButton Control. 
1.Text
-This has to be given otherwise we will not be able to see the
control.
2. OnClick - When Click what function should be called on
the server is specified here.
3. CommandName,CommandArgument -
This could be pretty hand property when we need to pass the some
values to the server when the click event fires. 
4.
OnCommand - Same like OnClick but passed CommandName and
CommandArgument to server.

Use
of CommandName,CommandArgument

You
may be bit confused with the use of CommandName and
CommandArgument.It will be useful
in he following
scenario.

Consider we have some 100 Link Buttons in a page and
we need to determine which LinkButton is clicked
on the server
side.One way is to assign different Text properties to different
controls and check the Text
property to determine which control is
clicked.Otherwise name all the controls with different names
[Same
name cannot be given in ASP.NET] and check the sender property of the
EventHandling function. All these seems to be ok but does not look
good.the best way is to assign CommandName and CommandArgument to the
LinkButton(s) and write OnCommand event and we can get the value from
the CommandEventArgs which is shown in the example below.

Advantages
over Html Anchor

The
LinkButton post data to the server but the Html Anchor simply fires a
GET request and the form data has to be passed in the QueryString
explicitly.

DisAdvantages
of Link Button

It
does not work in browsers which does not support javascript.Since it
uses javascript's submit() method to submit the page.

Example

The
Following source code how to use LinkButton control and its
eventhandling.


Source
Code








<%@
Page Language="C#"
Debug="true"%>
<html>
<head>
<title>Link
Button Usage</title>
<script runat="server">
protected
void LinkButton_Command(object sender,CommandEventArgs
e)
{
Message.Text="You born on : " +
e.CommandArgument;
}
</script>
</head>
<body>
<form
runat="server">
<table cellspacing=0
cellpadding=0 border=1>
<tr><td>Choose your Day
of Birth</td></tr>
<tr>
<td
align=center>
<asp:LinkButton
Text="Sun"
runat="server"
CommandName="BirthDay"
CommandArgument="Sunday"
oncommand="LinkButton_Command"
/>
</td>
</tr>
<tr>
<td
align=center>
<asp:LinkButton
Text="Mon"
runat="server"
CommandName="BirthDay"
CommandArgument="Monday"
oncommand="LinkButton_Command"
/>
</td>
</tr>
<tr>
<td
align=center>
<asp:LinkButton
Text="Tue"
runat="server"
CommandName="BirthDay"
CommandArgument="Tuesday"
oncommand="LinkButton_Command"
/>
</td>
</tr>
<tr>
<td
align=center>
<asp:LinkButton
Text="Wed"
runat="server"
CommandName="BirthDay"
CommandArgument="Wednesday"
oncommand="LinkButton_Command"
/>
</td>
</tr>
<tr>
<td
align=center>
<asp:LinkButton
Text="Thu"
runat="server"
CommandName="BirthDay"
CommandArgument="Thursday"
oncommand="LinkButton_Command"
/>
</td>
</tr>
<tr>
<td
align=center>
<asp:LinkButton
Text="Fri"
runat="server"
CommandName="BirthDay"
CommandArgument="Friday"
oncommand="LinkButton_Command"
/>
</td>
</tr>
<tr>
<td
align=center>
<asp:LinkButton
Text="Sat"
runat="server"
CommandName="BirthDay"
CommandArgument="Saturday"
oncommand="LinkButton_Command"
/>
</td>
</tr>
</table>
<asp:Label
id="Message" runat="server"/>
</form>
</body>
</html>






Using
WebForms Panel Control


The
following article will show you how to use a Panel control in
ASP.NET. Panel control can be used as container for other controls
just like a PictureBox or Frame control in VB. The main advantage of
using a panel control is changes applied to the panel control apples
to all the controls on the panel. For example, if you put 10 controls
on a panel and want to hide all controls. Just hide the panel control
and it will hide all the controls on a panel. Other example of panel
control is moving multiple controls. 

For example,
consider we have a screen with 10 controls which should be displayed
when a condition is true and hide when the condition is false. So we
need to hide all controls or show all controls. To implement this
functionality we can make each and every control to be visible or
hidden separately but this will make lot of code and the code
increases with the number of controls. Instead we can simply put
these controls on a panel and show or hide the panel. Showing the
panel will show all the controls and hiding will hide all the
controls.

Usage

<asp:Panel
id=pnl runat="server">
</asp:

How
it is Rendered

The
Panel control is rendered as <div></div>.

Mostly
used Properties

Visible
- This is the Most useful property of the Panel control.
Controls
- To Dynamically add controls to the Panel control.


Example
The
Following source code how to use Panel control.The source code
is 
implemented like TabPage Control in VB.


Source
Code








<%@
Page Language="C#" Debug="true" %>
<%@
Import NameSpace="System.Drawing"
%>

<html>
<head>
<title>Panel
Control Usage</title>
<script
runat="server">
protected void Page_Load(object
sender,EventArgs
e)
{
if(!IsPostBack)
{
Panel1.Visible=true;
}
}

protected
void LinkButton_Click(object sender,EventArgs
e)
{
HideAllPanels();
((LinkButton)sender).ForeColor=Color.Red;
if(sender==Page1)
{
Panel1.Visible=true;
}
if(sender==Page2)
{
Panel2.Visible=true; 
}
if(sender==Page3)
{
Panel3.Visible=true; 
}
}

protected
void
HideAllPanels()
{
Panel1.Visible=false;
Panel2.Visible=false;
Panel3.Visible=false;
Page1.ForeColor=Color.Blue;
Page2.ForeColor=Color.Blue;
Page3.ForeColor=Color.Blue;
}

</script>
</head>
<body>
<form
runat="server">
<table width=100% height=100%
cellspacing=0 cellpadding=0 border=1>
<tr>
<td>
<asp:LinkButton
id=Page1
onclick="LinkButton_Click"
runat="server"
Text=Page1/>&nbsp;
<asp:LinkButton
id=Page2
onclick="LinkButton_Click"
runat="server"
Text=Page2/>&nbsp;
<asp:LinkButton
id=Page3
onclick="LinkButton_Click"
runat="server"
Text=Page3/>
<td>
</tr>
<tr>
<td
width=100% height=100%> 
<asp:Panel BackColor=Red
height=100% width=100% id=Panel1 Visible=false
runat="server">
<h1>Page1</h1>
</asp:Panel>
<asp:Panel
BackColor=Green height=100% width=100% id=Panel2 Visible=false
runat="server">
<h1>Page2</h1>
</asp:Panel>
<asp:Panel
BackColor=Cyan height=100% width=100% id=Panel3 visible=false
runat="server">
<h1>Page3</h1>
</asp:Panel>
</td>
</tr>
</table>
</form>
</body>



Using
ASP.NET CheckBoxList Control


CheckBoxList
Control can be used to display a group of checkboxes. You can use
this control in the cases  for these type of questions:
What
are your Hobbies?
What Products do u have?
which is seen in
most of the sites? 


The
advantage of this control over the CheckBox is that it is much more
easy to mainpulate CheckBoxList than to manipulate to CheckBox since
we have indexers for the items stored in the CheckBoxList which is
not present in CheckBox. 

For example, consider we have a
CheckBoxList with 10 CheckBoxes(Items) and 10 CheckBox controls
in
order to check which checkboxes are selected for CheckBox we have to
use it like this:


if(C1.Checked)
{
}
if(C2.Checked)
{
}
....
if(C10.Checked)
{
}


but
if we use CheckBoxList we can do it like this:

for(int
i=0;i<CHK.Items.Count;i++)
{
if(CHK.Items[i].Selected)
{
//Do
whatever you want
}
}


Usage

<asp:CheckBoxList
runat="server" id=C1>
<asp:ListItem
Value=1>One</asp:ListItem>
<asp:ListItem
Value=2>Two</asp:ListItem>
.....
<asp:ListItem
Value=3>Three</asp:ListItem>
</asp:CheckBoxList>


How
is it Rendered?

Each
ListItem is rendered as CheckBox control as:
<input
type=checkbox value=1><span>One</span>


Mostly
used Properties
TextAlign
- This is used to speicfy where the text should be shown.Possible
values are Left,Right
RepeatLayout - This is to specify whether
the Group of Checkboxes should be displayed in a table or
not.Possible values are:Table,Flow

RepeatColumns - Setting
this property will show up the Checkboxes in the specified no.of
columns
eg.If RepeatColumns is set to 2 and 4 ListItems are added
to the CheckBoxList then the UI is rendered with 2 rows and 2 cols
with each col having a Checkbox.

RepeatDirection - This is to
specify how the arrange the Checkboxes when RepeatColumns
are 
specified.Possible values are:Vertical,Horizontal. For
example, 


Consider
this settings:
RepeatColumns=2
No.of Items in the CheckBoxList
is 4

if RepeatDirection is specified as Vertical then UI is
rendered as:
Item#1 Item#3
Item#2 Item#4

if
RepeatDirection is specified as Horizontal then UI is rendered
as:
Item#1 Item#2
Item#3 Item#4

Selected To Check
whether a checkbox is checked or not

Mostly
used Methods

To
Add an item at runtime :
CHKList.Items.Add(new
ListItem(<text>,<value>))

To Access an
item:
CHKList.Items[<index>]

To Remove an
item:
CHKList.Items.Remove(<index>)

Disadvantage
of this Control

We
will not be able to Control the Layout of the Checkbox since it
always uses
Flow or Table Layout.Also Consider we have table and
in the first Column of each Row we want to
Show Checkbox control
this kind of UI is not shown using CheckBoxList control.In this
circumstances
we have to go only for Checkbox control

Example


The
Following source code how to use CheckBoxList control.

Source
Code








<%@
Page Language="C#"
Debug="true"%>

<html>
<head>
<title>CheckBoxList
Usage</title>
<script runat="server">
protected
void Button_Click(object sender,EventArgs e)
{
//To Set the
Text Alignment
switch(cboAlign.SelectedIndex)
{
case
0:
ChkList.TextAlign=TextAlign.Left;
break;
case
1:
ChkList.TextAlign=TextAlign.Right;
break;
}

//To
Set the Layout
switch(cboRepeatLayout.SelectedIndex)
{
case
0:
ChkList.RepeatLayout=RepeatLayout.Table;
break;
case
1:
ChkList.RepeatLayout=RepeatLayout.Flow;
break;
}

//To
Set the Direction
switch(cboRepeatDirection.SelectedIndex)
{
case
0:
ChkList.RepeatDirection=RepeatDirection.Vertical;
break;
case
1:
ChkList.RepeatDirection=RepeatDirection.Horizontal;
break;
}

//To
Set the RepeatColumns Property
try
{
int
cols=int.Parse(txtRepeatCols.Text);
ChkList.RepeatColumns=cols;
}
catch(Exception)
{
}

lblResult.Text="";
for(int
i=0;i<ChkList.Items.Count;i++)
{
if(ChkList.Items[i].Selected)
{
lblResult.Text+=ChkList.Items[i].Text
+ "<br>";
}
}
}
</script>
</head>
<body>
<form
runat="server">
<h1 align=center>CheckBoxList
Usage
Demo</h1>
<table>
<tr>
<td>TextAlign</td>
<td>
<asp:DropDownList
id=cboAlign
runat="server">
<asp:ListItem>Left</asp:ListItem>
<asp:ListItem>Right</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Repeat
Layout</td>
<td>
<asp:DropDownList
id=cboRepeatLayout
runat="server">
<asp:ListItem>Table</asp:ListItem>
<asp:ListItem>FLow</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Repeat
Direction</td>
<td>
<asp:DropDownList
id=cboRepeatDirection
runat="server">
<asp:ListItem>Vertical</asp:ListItem>
<asp:ListItem>Horizontal</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td>Repeat
Columns</td>
<td><asp:TextBox id="txtRepeatCols"
runat="server"/></td> 
</tr>
</table>
<br>
Choose
Your Favorite Language(s):
<br>
<asp:CheckBoxList
id="ChkList"
runat="server">
<asp:ListItem>C#</asp:ListItem>
<asp:ListItem>VB.NET</asp:ListItem>
<asp:ListItem>JScript.NET</asp:ListItem>
<asp:ListItem>Cobol.NET</asp:ListItem>
<asp:ListItem>J#</asp:ListItem>
<asp:ListItem>Eiffel.NET</asp:ListItem>
<asp:ListItem>CPP.NET</asp:ListItem>
</asp:CheckBoxList>
<br>
<asp:Button
Text="Submit" runat="server"
onclick="Button_Click"/>
<h1><font
color=red>Your Favorite Language(s) are:</font></h1>
<asp:Label
id=lblResult runat=server/>
</form>
</body>
</html>






Debugging
an ASP.NET Application



Fig
1.01 - Web Registration Program


Debugging
a Windows Forms application is similar to debugging in Visual Studio
6.0, but debugging a ASP Web App is not as obvious.  Thanks to
the "BugSlayer" at Tech-Ed, it's not as bad as "all
that".  You can use the debugger like you normally would do
in Visual Studio.  You just need to attach a process.  This
article will bring  you through the steps needed to "get
attached".


The
first step is to simple run the application in Visual Studio by
hitting F5 which will bring up the application in Internet Explorer
as shown in Figure 1.01 above.


Set
a break point in the application where you want to debug.


Once
you've done this you can attach the process.  Go into the Tools
menu and choose
Debug
Processes

as shown in Figure 1.02 below:



Fig
1.02


After
you do this the dialog below will show up:



Fig
1.03



Make
sure you have Show system processes checked.  I made the mistake
of not checking it the first time and I couldn't find the process I
was looking for.  The process you want to attach to is always
the same -
aspnet_wp.exe. 
Click on this in the Available Processes box and Attach it with the
Attach button.  It  will then bring up the dialog in Fig
1.04



Fig
1.04


Check
Common Language Runtime and Script. I'm not sure if you need to check
Script, but checking it doesn't seem to hurt ;-).   Click
Ok and your Web Process will show up in the Debugged Processes box as
in Fig 1.05:



Fig
1.05


Your
ASP.NET application will next trap breakpoints in the debugger. 
In this sample below, I've trapped the breakpoint after hitting the
Submit button in Internet Explorer:


 



Fig
1.06


 


That's
all there is to it!  Now you can use all the powerful watch
features, conditional breaks, stack tracing and other Visual
Studio.NET Debugger goodies.  This is certainly infinitely
easier than popping up alerts and outputting messages in Labels.


Creating
a .NET Web Service


Introduction
Microsoft
.NET marketing has created a huge hype about its Web Services. This
is the first of two articles on Web Services. Here we will create a
.NET Web Service using C#. We will look closely at the Discovery
protocol, UDDI, and the future of the Web Services. In the next
article, we will concentrate on consuming existing Web Services on
multiple platforms (i.e., Web, WAP-enabled mobile phones, and windows
applications).


Why
do we need Web Services?


After
buying something over the Internet, you may have wondered about the
delivery status. Calling the delivery company consumes your time, and
it's also not a value-added activity for the delivery company. To
eliminate this scenario the delivery company needs to expose the
delivery information without compromising its security. Enterprise
security architecture can be very sophisticated. What if we can just
use port 80 (the Web server port) and expose the information through
the Web server? Still, we have to build a whole new Web application
to extract data from the core business applications. This will cost
the delivery company money. All the company wants is to expose the
delivery status and concentrate on its core business. This is where
Web Services come in.


What
is a Web Service?


Web
Services are a very general model for building applications and can
be implemented for any operation system that supports communication
over the Internet. Web Services use the best of component-based
development and the Web. Component-base object models like
Distributed Component Object Model (DCOM), Remote Method Invocation
(RMI), and Internet Inter-Orb Protocol (IIOP) have been around for
some time. Unfortunately all these models depend on an
object-model-specific protocol. Web Services extend these models a
bit further to communicate with the Simple Object Access Protocol
(SOAP) and Extensible Markup Language (XML) to eradicate the
object-model-specific protocol barrier (see Figure 1).


Web
Services basically uses Hypertext Transfer Protocol (HTTP) and SOAP
to make business data available on the Web. It exposes the business
objects (COM objects, Java Beans, etc.) to SOAP calls over HTTP and
executes remote function calls. The Web Service consumers are able to
invoke method calls on remote objects by using SOAP and HTTP over the
Web.



Figure
1. SOAP calls are remote function calls that invoke method executions
on Web Service components at Location B. The output is rendered as
XML and passed back to the user at Location A.


How
is the user at Location A aware of the semantics of the Web Service
at Location B? This question is answered by conforming to a common
standard. Service Description Language (SDL), SOAP Contract Language
(SCL) and Network Accessible Specification Language (NASSL) are some
XML-like languages built for this purpose. However, IBM and Microsoft
recently agreed on the Web Service Description Language (WSDL) as the
Web Service standard.


The
structure of the Web Service components is exposed using this Web
Service Description Language. WSDL 1.1 is a XML document describing
the attributes and interfaces of the Web Service. The new
specification is available at
msdn.microsoft.com/xml/general/wsdl.asp.


The
task ahead


The
best way to learn about Web Services is to create one. We all are
familiar with stock quote services. The NASDAQ, Dow Jones, and
Australian Stock Exchange are famous examples. All of them provide an
interface to enter a company code and receive the latest stock price.
We will try to replicate the same functionality.


The
input parameters for our securities Web service will be a company
code. The Web service will extract the price feed by executing
middle-tier business logic functions. The business logic functions
are kept to a bare minimum to concentrate on the Web service
features.


Tools
to create a Web Service


The
core software component to implement this application will be MS .NET
Framework SDK, which is currently in beta. You can download a version
from Microsoft. I used Windows 2000 Advance Server on a Pentium III
with 300 MB of RAM.


The
preferred Integration Development Environment (IDE) to create Web
Services is Visual Studio .NET. However, you can easily use any text
editor (WordPad, Notepad, Visual Studio 6.0) to create a Web Service
file.


I
assume you are familiar with the following concepts:



  • Basic
    knowledge of .NET platform


  • Basic
    knowledge of C#


  • Basic
    knowledge of object-oriented concepts



Creating
a Web Service


We
are going to use C# to create a Web Service called
"SecurityWebService." A Web Service file will have an .ASMX
file extension. (as opposed to an .ASPX file extension of a ASP.NET
file). The first line of the file will look like



<%@ WebService
Language="C#" class="SecurityWebService" %>



This
line will instruct the compiler to run on Web Service mode and the
name of the C# class. We also need to access the Web Service
namespace. It is also a good practice to add a reference to the
System namespace.



using System;



using
System.Web.Services;


The
SecurityWebService class should inherit the functionality of the Web
Services class. Therefore, we put the following line of code:



public class
SecurityWebService : WebService



Now
we can use our object-oriented programming skills to build a class.
C# classes are very similar to C++ or Java classes. It will be a walk
in the park to create a C# class for anyone with either
language-coding skills.


Dot-net
Web Services are intelligent enough to cast basic data types.
Therefore, if we return "int," "float," or
"string" data types, it can convert them to standard XML
output. Unfortunately, in most cases we need get a collection of data
regarding a single entity. Let's take an example.


Our
SecurityWebService stock quotes service requires the user to enter a
company code, and it will deliver the full company name and the
current stock price. Therefore, we have three pieces of information
for a single company:



  1. Company
    code (data type - string)


  2. Company
    name (data type - string)


  3. Price
    (data type - Double)




We
need to extract all this data when we are referring to a single stock
quote. There are several ways of doing this. The best way could be to
bundle them in an enumerated data type. We can use "structs"
in C# to do this, which is very similar to C++ structs.



public struct
SecurityInfo



{



public string
Code;



public string
CompanyName;



public double
Price;



}


Now
we have all the building blocks to create our Web Service. Therefore,
our code will look like.





<%@
WebService Language="C#" class="SecurityWebService"
%>





using
System;


using
System.Web.Services;





public
struct SecurityInfo


{


public
string Code;


public
string CompanyName;


public
double Price;


}





public
class SecurityWebService : WebService


{


private
SecurityInfo Security;



public
SecurityWebService()


{


Security.Code
= "";


Security.CompanyName
= "";


Security.Price
= 0;


}





private
void AssignValues(string Code)


{


//
This is where you use your business components.


//
Method calls on Business components are used to populate the data.


//
For demonstration purposes, I will add a string to the Code and


// use
a random number generator to create the price feed.



Security.Code
= Code;


Security.CompanyName
= Code + " Pty Ltd";


Random
RandomNumber = new System.Random();


Security.Price
= double.Parse(new
System.Random(RandomNumber.Next(1,10)).NextDouble().Format("##.##",null));


}









[WebMethod(Description="This
method call will get the company name and the price for a given
security code.",EnableSession=false)]


public
SecurityInfo GetSecurityInfo(string Code)


{


AssignValues(Code);


SecurityInfo
SecurityDetails = new SecurityInfo();


SecurityDetails.Code
= Security.Code;


SecurityDetails.CompanyName
= Security.CompanyName;


SecurityDetails.Price
= Security.Price;


return
SecurityDetails;


}





}






Remember,
this Web Service can be accessed through HTTP for any use. We may be
referring to sensitive business data in the code and wouldn't want it
to fall into the wrong hands. The solution is to protect the business
logic function and only have access to the presentation functions.
This is achieved by using the keyword "[Web Method]" in C#.
Let's look at the function headers of our code.



[WebMethod(Description="This......",EnableSession=false)]



public SecurityInfo
GetSecurityInfo(string Code)



This
function is exposed to the public. The "description" tag
can be used to describe the Web Service functionality. Since we will
not be storing any session data, we will disable the session state.



private void
AssignValues(string Code)



This
is a business logic function that should not be publicly available.
We do not want our sensitive business information publicly available
on the Web. (Note:- Even if you change the "private"
keyword to "public," it will still not be publicly
available. You guessed it, the keyword "[Web Method]" is
not used.)


We
can use the business logic in this function to get the newest stock
price quote. For the purpose of this article I have added some text
to the company code to create the company name. The price value is
generated using a random number generator.


We
may save this file as "SampleService.asmx" under an
Internet Information Service (IIS)-controlled directory. I have saved
it under a virtual directory called "/work/aspx." I'll
bring it up on a Web browser.



This
is a Web page rendered by the .NET Framework. We did not create this
page. (The page is generated automatically by the system. I did not
write any code to render it on the browser. This graphic is a
by-product of the previous code.) This ready-to-use functionality is
quite adequate for a simple Web Service. The presentation of this
page can be changed very easily by using ASP.NET pagelets and
config.web files. A very good example can be found at
http://www.ibuyspy.com/store/InstantOrder.asmx.


Notice
a link to "SDL Contract." (Even if we are using WSDL, .NET
Beta still refers to SDL. Hopefully this will be rectified in the
next version). This is the description of the Web Service to create a
proxy object. (I will explain this in the next article.) This
basically gives an overview of the Web Service and it's public
interface. If you look closely, you will only see the "Web-only"
methods being illustrated. All the private functions and attributes
are not described in the SDL contract. The SDL contract for the
SecurityWebService can be found in Appendix A.


How
do we use a Web Service?


Now
we can use this Web Service. Let's enter some values to get a bogus
price feed.



By
clicking the Invoke button a new window will appear with the
following XML document



This
is how the Web Service releases information. We need to write clients
to extract the information from the XML document. Theses clients
could be



  1. A
    Web page


  2. A
    console / Windows application


  3. A
    Wireless Markup Language (WML) / WMLScript to interact with mobile
    phones


  4. A
    Palm / Win CE application to use on Personal Digital Assistants
    (PDAs).



I
will explain this process in the next article.


You
can also call the Web Service directly using the HTTP GET method. In
this case we will not be going through the above Web page and
clicking the Invoke button. The syntax for directly calling the Web
Service using HTTP GET is


http://server/webServiceName.asmx/functionName?parameter=parameterValue


Therefore,
the call for our Web Service will be


http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo?Code=IBM


This
will produce the same result as clicking the Invoke button.


Now
we know how to create a Web Service and use it. But the work is half
done. How will our clients find our Web Service? Is there any way to
search for our Web Service on the Internet? Is there a Web crawler or
a Yahoo search engine for Web Services? In order to answer these
questions we need to create a "discovery" file for our Web
Service.


Creating
a Discovery file


Web
Service discovery is the process of locating and interrogating Web
Service descriptions, which is a preliminary step for accessing a Web
Service. It is through the discovery process that Web Service clients
learn that a Web Service exists, what its capabilities are, and how
to properly interact with it. Discovery file is a XML document with a
.DISCO extension. It is not compulsory to create a discovery file for
each Web Service. Here is a sample discovery file for our securities
Web Service.



<?xml
version="1.0" ?>



<disco:discovery
xmlns:disco="http://schemas.xmlsoap.org/disco/">



<scl:contractRef
ref="http://localhost/work/aspx/SampleService.asmx?SDL"/>



</disco:discovery>



We
can name this file "SampleService.disco" and save it to the
same directory as the Web Service. If we are creating any other Web
Services under the "/work/aspx" directory, it is wise to
enable "dynamic discovery." Dynamic discovery will scan for
all the *.DISCO files in all the subdirectories of "/work/aspx"
automatically.



<?xml
version="1.0" ?>



<dynamicDiscovery
xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17">



</dynamicDiscovery>



An
example of an active discovery file can be found at
http://services3.xmethods.net/dotnet/default.disco. By analyzing the
discovery file we can find where the Web Services reside in the
system. Unfortunately both these methods require you to know the
exact URL of the discovery file. If we cannot find the discovery
file, we will not be able to locate the Web Services. Universal
Description, Discovery, and Integration (UDDI) describes mechanisms
to advertise existing Web Services. This technology is still at the
infant stage. UDDI is an open, Internet-based specification designed
to be the building block that will enable businesses to quickly,
easily, and dynamically find and transact business with one another
using their preferred applications. A reference site for UDDI is
http://uddi.microsoft.com.


There
have been a lot of Web Services written by developers.
www.xmethods.com is one of the sites that has an index of Web
Services. Some developers are building WSDL search engines to find
Web Services on the Web.


Deploying
a Web Service


Deploying
the Web Services from development to staging or production is very
simple. Similar to ASP.NET applications, just copy the .ASMX file and
the .DISCO files to the appropriate directories, and you are in
business.


The
future of the Web Services


The
future looks bright for the Web Service technology. Microsoft is not
alone in the race for Web Service technology. Sun and IBM are very
interested. There are SOAP toolkits available for Apache and Java Web
servers. I believe Web Services needs a bit of work, especially the
Web Service discovery process. It is still very primitive.


On
a positive note, Web Services have the potential to introduce new
concepts to the Web. One I refer to as "pay per view"
architecture. Similar to pay-TV, we can build Web sites that can
generate revenue for each request a user sends (as opposed to a flat,
monthly subscription). In order to get some data, we can sometimes
pay a small fee. Commercially this could be handy for a lot of
people.


Examples



  • Online
    newspaper sites can publish a 10-year-old article with a $2 "pay
    per view" structure.


  • Stock
    market portals can itemize every user portfolio for every single
    stock quote and build pricing and discount structures.



And
the list goes on ...


On
a very optimistic note, Web Services can be described as the "plug
and play" building blocks of enterprise Business to Business
(B2B) Web solutions.


Appendix
A





<?xml
version="1.0" ?>


<serviceDescription
xmlns:s0="http://tempuri.org/" name="SecurityWebService"
targetNamespace="http://tempuri.org/"


xmlns="urn:schemas-xmlsoap-org:sdl.2000-01-25">


<soap
xmlns="urn:schemas-xmlsoap-org:soap-sdl-2000-01-25">


<service>


<addresses>


<address
uri="http://localhost/work/aspx/SampleService.asmx" />


</addresses>


<requestResponse
name="GetSecurityInfo"
soapAction="http://tempuri.org/GetSecurityInfo">


<request
ref="s0:GetSecurityInfo" />


<response
ref="s0:GetSecurityInfoResult" />


<info>This
method call will get the company name and the price for a given
security code.</info>


</requestResponse>


</service>


</soap>


<httppost
xmlns="urn:schemas-xmlsoap-org:post-sdl-2000-01-25">


<service>


<requestResponse
name="GetSecurityInfo"
href="http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo">


<request>


<form>


<input
name="Code" />


</form>


</request>


<response>


<mimeXml
ref="s0:SecurityInfo" />


</response>


<info>This
method call will get the company name and the price for a given
security code.</info>


</requestResponse>


</service>


</httppost>


<httpget
xmlns="urn:schemas-xmlsoap-org:get-sdl-2000-01-25">


<service>


<requestResponse
name="GetSecurityInfo"
href="http://localhost/work/aspx/SampleService.asmx/GetSecurityInfo">


<request>


<param
name="Code" />


</request>


<response>


<mimeXml
ref="s0:SecurityInfo" />


</response>


<info>This
method call will get the company name and the price for a given
security code.</info>


</requestResponse>


</service>


</httpget>


<schema
targetNamespace="http://tempuri.org/"
attributeFormDefault="qualified"


elementFormDefault="qualified"
xmlns="http://www.w3.org/1999/XMLSchema">


<element
name="GetSecurityInfo">


<complexType>


<all>


<element
name="Code" xmlns:q1="http://www.w3.org/1999/XMLSchema"
type="q1:string" nullable="true" />


</all>


</complexType>


</element>


<element
name="GetSecurityInfoResult">


<complexType>


<all>


<element
name="result" type="s0:SecurityInfo" />


</all>


</complexType>


</element>


<complexType
name="SecurityInfo">


<all>


<element
name="Code" xmlns:q2="http://www.w3.org/1999/XMLSchema"
type="q2:string" nullable="true" />


<element
name="CompanyName"
xmlns:q3="http://www.w3.org/1999/XMLSchema"
type="q3:string" nullable="true" />


<element
name="Price" xmlns:q4="http://www.w3.org/1999/XMLSchema"
type="q4:double" />


</all>


</complexType>


<element
name="SecurityInfo" type="s0:SecurityInfo" />


</schema>



</serviceDescription>

























1








0 comments: