Sei sulla pagina 1di 84

Q.1.What is .NET Framework?

IT Consist of a primarily of a gigantic library of code thet you use for your client
languages(Such as C#) using OOP techniques.
The Library is Categorized in to different modules you use the portion depending
on the results you want to achieve.
One Module contains the building block of Windows Application while another for
WEB-Development ,Network Programming
.Net Framework library defines some basic types, a types is the representation of
data and specified some of the most fundamentals of these(Such as 32bit signed
integer) facilities interoperability between languages using the .Net Framework.
This is called as the CTS.(Common Type System)
As well as supplying the library, the .Net Framework also includes the .Net
Common Language Runtime(CLR).
The CLR is responsible for maintaining the execution of all application
development using the .NET Framework.
In Order for C# code to execute It must be converted into a language that the
target OS usnderstands Known as Native Code.
This Conversions is called as compiling codes.
An Act that is performed by a compiler under the .NET Framework, this is a Two
Stage Process.
Q.2.CIL and JIT
When you compile code that uses the .NET Framework library, you don t
immediately create operating-system-specific native code.
Instead, you compile your code into Common Intermediate Language (CIL) code.
This code isnt specific to any operating system (OS) and isn t specific to C#.
Other .NET languages Visual Basic .NET, for example also compile to this
language as a first stage.
This compilation step is carried out by VS or VCE when you develop C#
applications.
Obviously, more work is necessary to execute an application. That is the job of a
just-in-time (JIT) compiler, which compiles CIL into native code that is specific to
the OS and machine architecture being targeted.
Only at this point can the OS execute the application.
In the past, it was often necessary to compile your code into several applications,
each of which targeted a specific operating system and CPU architecture.
Typically, this was a form of optimization (to get code to run faster on an AMD
chipset, for example), but at times it was critical (for applications to work in both
Win9x and WinNT/2000 environments, for example).
This is now unnecessary, because JIT compilers (as their name suggests) use
CIL code, which is independent of the machine, operating system, and CPU.
Several JIT compilers exist, each targeting a different architecture, and the
appropriate one is used to create the native code required.

The beauty of all this is that it requires a lot less work on your part in fact, you
can forget about system-dependent details and concentrate on the more
interesting functionality of your code.

Q.3.Explain Assemblies?
When you compile an application, the CIL code created is stored in an assembly.
Assemblies include both executable application files that you can run directly
from Windows without the need for any other programs (these have a .exe file
extension) and libraries (which have a .dll extension) for use by other
applications.
In addition to containing CIL, assemblies also include meta information (that is,
information about the information contained in the assembly, also known as
metadata) and optional resources
The meta information enables assemblies to be fully self-descriptive.
You need no other information to use an assembly, meaning you avoid situations
such as failing to add required data to the system registry and so on, which was
often a problem when developing with other platforms.
This means that deploying applications is often as simple as copying the files into
a directory on a remote computer.
Because no additional information is required on the target systems, you can just
run an executable file from this directory and (assuming the .NET CLR is
installed) youre good to go.
You might write some code that performs tasks required by multiple applications.
In situations like that, it is often useful to place the reusable code in a place
accessible to all applications.
In the .NET Framework, this is the global assembly cache (GAC). Placing code in
the GAC is simple you just place the assembly containing the code in the
directory containing this cache.
Q.4.Managed Code
The role of the CLR doesnt end after you have compiled your code to CIL and a
JIT compiler has compiled that to native code.
Code written using the .NET Framework is managed when it is executed (a stage
usually referred to as runtime).
This means that the CLR looks after your applications by managing memory,
handling security, allowing cross-language debugging, and so on.
By contrast, applications that do not run under the control of the CLR are said to
be unmanaged, and certain languages such as C++ can be used to write such
applications, which, for example, access low-level functions of the operating
system.
However, in C# you can write only code that runs in a managed environment.
You will make use of the managed features of the CLR and allow .NET itself to
handle any interaction with the operating system.
Q.B: Garbage Collection

One of the most important features of managed code is the concept of garbage
collection.
This is the .NET method of making sure that the memory used by an application
is freed up completely when the application is no longer in use.
Prior to .NET this was mostly the responsibility of programmers, and a few simple
errors in code could result in large blocks of memory mysteriously disappearing
as a result of being allocated to the wrong place in memory.
That usually meant a progressive slowdown of your computer followed by a
system crash.
.NET garbage collection works by periodically inspecting the memory of your
computer and removing anything from it that is no longer needed.
Q.5.Introduction to C#
C# is a relatively new language that was unveiled to the world when
Microsoft announced the first version of its .NET Framework in July 2000.
Since then its popularity has rocketed and it has arguably become the
language of choice for both Windows and Web developers who use the
.NET framework.
Part of the appeal of C# comes from its clear syntax, which derives from
C/C++ but simplifies some things that have previously discouraged some
programmers.
Fully object oriented language like java and first component oriented language
Designed to support key features of .NET framework
Its is simple, effective, productive, type-safe
Belongs to family of C/C++
It is designed to build robust, reliable and durable components to handle real
world applications

Linking

Note one additional point concerning this process. The C# code that
compiles into CIL in step 2 neednt be contained in a single file.
Its possible to split application code across multiple source code files,
which are then compiled together into a single assembly.
This extremely useful process is known as linking. It is required because it
is far easier to work with several smaller files than one enormous one.
You can separate out logically related code into an individual file so that it
can be worked on independently and then practically forgotten about when
completed.
This also makes it easy to locate specific pieces of code when you need
them and enables teams of developers to divide the programming burden
into manageable chunks
whereby individuals can check out pieces of code to work on without
risking damage to otherwise satisfactory sections or sections other people
are working on.

Q.6.LOOPING
Looping refers to the repeated execution of statements. This technique
comes in very handy because it means that you can repeat operations as
many times as you want (thousands, even millions, of times) without
having to write the same code each time.
The structure of a do loop is as follows, where <Test> evaluates to a
Boolean value:
do { <code to be looped> } while (<Test>);
Do while loop is also called as exit condition checking loop, means it will
check the condition while exiting loop.
Eg:
int i = 0;//initialization
do
{
System.Console.Write(" " +
i.ToString());
i++; //increment
} while (i != 10); //condition
while Loops
The Boolean test in a while loop takes place at the start of the loop cycle,
not at the end entry level checking
while (<Test>) { <code to be looped> }
Eg: int i = 1; //initialization while (i <= 10) // condition
{ Console.WriteLine(i); i++; // increment }
for Loops
This type of loop executes a set number of times and maintains its own
counter.
for (<initialization>; <condition>; <operation>) { <code to loop> }
Eg:
for (int i = 0; i <= 10; i++) { Console.Write(" " + i.ToString()); }
Interrupting Loops
breakCauses the loop to end immediately
continueCauses the current loop cycle to end immediately (execution
continues with the next loop cycle)

gotoAllows jumping out of a loop to a labeled position


return Jumps out of the loop and its containing function

Q.7.Method or Function Overloading


ASP.NET has lots of classes which provide several methods that offer
overloaded methods. In fact, you will see method overloading all over the place
in ASP.NET classes.
Method or Function Overloading is a programming language feature that is used
in different languages including ASP.NET languages.
Method Overloading means creating and using two or more methods with same
name but different inputs or number of parameters.
It means there can be several versions of the same method with variation in input
and number of parameters.

ASP.NET provides IntelliSense to see different overloaded versions of functions.


The appropriate function is called according to given parameters.

Compiler figures it out that which overloaded method should be called with given
parameters.

It will throw an error if appropriate input is not given or number of parameters


provided is not matched with any overloaded version of the called method.

Overloaded methods can be in the same class or in base and derived


classes.Simple Overloading method in ASP.NET:

C#
string a = "String Value";
int b = 34;
Console.Write(a);
Console.Write(b);
VB.NET
Dim a As String = "String Value"
Dim b As Integer = 34
Console.Write(a)
Console.Write(b)
Write() method of Console class has overloaded versions. It can take string, integer,
decimal or char value. Same is the case with WriteLine() method of Console class.

We can write our own overloaded methods like methods given in ASP.NET
C#
public int Add(int x, int y)
{
return x + y;
}
public int Add(int x, int y, int z)
{
return x + y + z;
}
VB.NET
Public Function Add(ByVal x As Integer, ByVal y As Integer) As Integer
Return x + y
End Function
Public Function Add(ByVal x As Integer, ByVal y As Integer, ByVal z As Integer) As
Integer
Return x + y + z
End Function
I have created two functions with same name but different number of parameters. First
Add() function takes two arguments and second takes three. Now we can call
overloaded function as below.
C#
Add(1, 2);
Add(1, 2, 3);
VB.NET
Add(1, 2)
Add(1, 2, 3)
Compiler will find that first call is for first version of the Add() function and second call is
for second overloaded Add() function with three parameters.
Q.8.Method or Function Overriding

Method or Function Overriding is also a programming feature provided in many


programming languages. Function Overriding means a method created in
derived class with same name, same number of parameters and same return

type as created in base class.


This is in fact a new version of the same method in derived class which has
different implementation than a same method in base class.

Overridden method cannot be in the same class. A method created in base class
can be overridden in derived class for different implementation

. Method overriding is needed when we need to perform different implementation


of the same method in derived class.

We can do Function Overriding like below.


C#
public class A
{
public virtual void showMessage()
{
Console.WriteLine("class A");
}
}
public class B : A
{
public override void showMessage()
{
Console.WriteLine("class B");
}
}
VB.NET
Public Class A
Public Overridable Sub showMessage()
Console.WriteLine("class A")
End Sub
End Class
Public Class B
Inherits A
Public Overrides Sub showMessage()
Console.WriteLine("class B")
End Sub
End Class
In C#, we have to write keyword virtual before the method in base class that we want

to override in inherited class and we have to write override keyword before overridden
method in derived class. In VB.NET Overridable keyword is used in place of virtual
and Overrides keyword is used for Override.
We can call this method as below
C#
A obj1 = new A();
obj1.showMessage();
B obj2 = new B();
obj2.showMessage();
VB.NET
Dim obj1 As New A()
obj1.showMessage()
Dim obj2 As New B()
obj2.showMessage()
Result will be as below.
class A
class B

Q.9.What is a .Net Assembly?


The .NET assembly is the standard for components developed with the Microsoft.NET.
Dot NET assemblies may or may not be executable, i.e., they might exist as the
executable (.exe) file or dynamic link library (DLL) file. All the .NET assemblies contain
the definition of types, versioning information for the type, meta-data, and manifest. The
designers of .NET have worked a lot on the component (assembly) resolution.
There are two kind of assemblies in .NET;
private
shared
Private assemblies are simple and copied with each calling assemblies in the calling
assemblies folder.
Shared assemblies (also called strong named assemblies) are copied to a single
location (usually the Global assembly cache). For all calling assemblies within the same
application, the same copy of the shared assembly is used from its original location.

Hence, shared assemblies are not copied in the private folders of each calling
assembly. Each shared assembly has a four part name including its face name, version,
public key token and culture information. The public key token and version information
makes it almost impossible for two different assemblies with the same name or for two
similar assemblies with different version to mix with each other.
An assembly can be a single file or it may consist of the multiple files. In case of multifile, there is one master module containing the manifest while other assemblies exist as
non-manifest modules. A module in .NET is a sub part of a multi-file .NET assembly.
Assembly is one of the most interesting and extremely useful areas of .NET architecture
along with reflections and attributes, but unfortunately very few people take interest in
learning such theoretical looking topics.
Q.10.Assembly Benefits
Assemblies are designed to simplify application deployment and to solve versioning
problems that can occur with component-based applications.
End users and developers are familiar with versioning and deployment issues that
arise from
today's component-based systems. Some end users have experienced the frustration of
installing a new application on their computer, only to find that an existing application
has
suddenly stopped working. Many developers have spent countless hours trying to keep
all
necessary registry entries consistent in order to activate a COM class.
Many deployment problems have been solved by the use of assemblies in the .NET
Framework. Because they are self-describing components that have no dependencies
on
registry entries, assemblies enable zero-impact application installation. They also
simplify
uninstalling and replicating applications.
Q.11.What are the basic components of .NET platform?
The basic components of .NET platform (framework) are:
.Net Applications
(Win Forms,Web Applications,Web Services)
Data(ADO.Net) and XML Library
FrameWork Class Library(FCL)
(IO,Streams,Sockets,Security,Reflection,UI)
Common Language Runtime(CLR)
(Debugger,Type Checker,JITer,GC)
Operating System
(Windows,Linux,UNIX,Macintosh,etc.,)

Q.12.MSIL (Microsoft Intermediate Language) Code:

When we compile our .Net Program using any .Net compliant language like (C#,
VB.NET, C++.NET)

it does not get converted into the executable binary code but to an intermediate
code, called MSIL or IL in short, understandable by CLR.

MSIL is an OS and H/w independent code. When the program needs to be


executed, this MSIL or intermediate code is converted to binary executable code,
called native code.

The presence of IL makes it possible the Cross Language Relationship as all


the .Net compliant languages produce the similar standard IL code.

Q.13.Just In Time Compilers (JITers):

When our CIL compiled code needs to be executed, CLR invokes JIT compilers
which compile the IL code to native executable code (.exe or .dll) for the specific
machine and OS.

JITers in many ways are different from traditional compilers as they, as their
name suggests, compile the IL to native code only when desired e.g., when a
function is called, IL of function's body is converted to native code;

just in time of need. So, the part of code that is not used by particular run is not
converted to native code.

If some IL code is converted to native code then the next time when its needed to
be used, the CLR uses the same copy without re-compiling.

So, if a program runs for sometime, then it won't have any just in time
performance penalty. As JITers are aware of processor and OS exactly at
runtime, they can optimize the code extremely efficiently resulting in very robust
applications.

Also, since JITer knows the exact current state of executable code, they can also
optimize the code by in-lining small function calls (like replacing body of small
function when its called in a loop, saving the function call time).

Although, Microsoft stated that C# and .Net are not competing with languages
like C++ in efficiency, speed of execution, JITers can make your code even faster
than C++ code in some cases when program is run over extended period of time
(like web-servers).

Q.14.Framework Class Library (FCL):

.NET Framework provides huge set of Framework (or Base) Class Library (FCL)
for common, usual tasks.

FCL contains thousands of classes to provide the access to Windows API and
common functions like String Manipulation, Common Data Structures, IO,
Streams, Threads, Security, Network Programming, Windows Programming,
Web Programming, Data Access, etc.

It is simply the largest standard library ever shipped with any development
environment or programming language.

The best part of this library is they follow extremely efficient OO design (design
patterns) making their access and use very simple and predictable.

You can use the classes in FCL in your program just as you use any other class
and can even apply inheritance and polymorphism on these.

Q.15.Common Type System (CTS):

.NET also defines a Common Type System (CTS). Like CLS, CTS is also a set of
standards. CTS defines the basic data types that IL understands.

Each .NET compliant language should map its data types to these standard data
types.

This makes it possible for the 2 languages to communicate with each other by
passing/receiving parameters to/from each other.

For example, CTS defines a type Int32, an integral data type of 32 bits (4 bytes)
which is mapped by C# through int and VB.Net through its Integer data type.

Q.16:Metadata Overview
Metadata is binary information describing program that is stored either in a
common language
runtime portable executable (PE) file or in memory. When code is complied into a
PE file,
metadata is inserted into one portion of the file, while code is converted to
Microsoft
intermediate language (MSIL) and inserted into another portion of the file. Every
type and
member defined and referenced in a module or assembly is described within
metadata. When
code is executed, the runtime loads metadata into memory and references it to
discover
information about code's classes, members, inheritance, and so on.
Metadata describes every type and member defined in code in a languageneutral manner.
Metadata stores the following information:
Description of the assembly.
Identity (name, version, culture, public key).
The types that are exported.
Other assemblies that this assembly depends on.
Security permissions needed to run.
Description of types.
Name, visibility, base class, and interfaces implemented.
Members (methods, fields, properties, events, nested types).
Attributes.
Additional descriptive elements that modify types and members.
Q.17.Benefits of Metadata
Metadata is the key to a simpler programming model, eliminating the need for
Interface
Definition Language (IDL) files, header files, or any external method of
component reference.
Metadata allows .NET languages to describe themselves automatically in a
language-neutral
manner, unseen by both the developer and the user. Additionally, metadata is
extensible
through the use of attributes. Metadata provides the following major benefits:
Self-describing files. Common language runtime modules and assemblies are selfdescribing. A module's
metadata contains everything needed to interact with another module. Metadata
automatically provides the functionality of IDL in COM, allowing to use one file for
both

definition and implementation.


Language interoperability and easier component-based design.
Metadata provides all the information required about compiled code for
programmer to
inherit a class from a PE file written in a different language. Programmer can
create an
instance of any class written in any managed language (any language that
targets the
common language runtime) without worrying about explicit marshaling or using
custom
interoperability code.
Attributes.
The .NET Framework allows programmer to declare specific kinds of metadata,
called
attributes, in compiled file. Attributes can be found throughout the .NET
Framework and
are used to control in more detail how program behaves at run time.
Microsoft intermediate language(MSIL)
Definition:
It is a set of CPU independent instructions that are generated by the language
compiler
when the project is compiled.
MSIL code is not executable but further processed by CLR/other runtime
environments
before it becomes executable.
MSIL is contained in the assembly of the .NET application.
Features:
MSIL instructions map to the code that is written in .NET Language and are used for
1. loading,
2. storing,
3. initializing,
4. and calling methods on objects,
5. as well as for arithmetic and logical operations,
6. control flow,
7. direct memory access,
8. exception handling,
9. and other operations.
CLS(Common language Specification) provides the infrastructure for MSIL.
Benefits:
MSIL provides language interoperability as the code in any .NET language is compiled
into MSIL.
Q.17.What are the different types of collections in .NET?

At its simplest, an object holds a single value. At its most complex, it holds
references to
many other objects. The .NET Framework provides collectionsthese include
List and
Dictionary. They are often useful.

List
First, the List type provides an efficient and dynamically-allocated array. It does not
provide
fast lookup in the general casethe Dictionary is better for this. List is excellent when
used in
loops.
example::
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
// Use the List type.
List<string> list = new List<string>();
list.Add("cat");
list.Add("dog");
foreach (string element in list)
{
Console.WriteLine(element);
}
}
}
output::
cat
dog
Q.18.Dictionary
The Dictionary type in the base class library is an important one. It is an
implementation of a
hashtable, which is an extremely efficient way to store keys for lookup. The
Dictionary in .NET
is well-designed.
We try to reference items in a table directly by doing arithmetic operations to
transform keys
into table addresses.
code:
using System;
using System.Collections.Generic;
class Program
{

static void Main()


{
// Use the dictionary.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("cat", 1);
dict.Add("dog", 4);
Console.WriteLine(dict["cat"]);
Console.WriteLine(dict["dog"]);
}
}
output::
1
4
Q.19.Hashtable
To continue, the Hashtable is a lookup data structure that uses a hash code to
find elements
quickly. The newer Dictionary collection is usually more appropriate for programs
when
available.
code:
using System;
using System.Collections;
class Program
{
static void Main()
{
Hashtable table = new Hashtable();
table["one"] = 1;
table["two"] = 2;
// ... Print value at key.
Console.WriteLine(table["one"]);
}
}
output::
1

(Q.19.1.1)ASP.NET life cycle specifies, how:

ASP.NET processes pages to produce dynamic output


The application and its pages are instantiated and processed
ASP.NET compiles the pages dynamically

The ASP.NET life cycle could be divided into two groups:

Application Life Cycle


Page Life Cycle

ASP.NET Application Life Cycle


The application life cycle has the following stages:

User makes a request for accessing application resource, a page. Browser


sends this request to the web server.

A unified pipeline receives the first request and the following events take place:
o

An object of the class ApplicationManager is created.

An object of the class HostingEnvironment is created to provide


information regarding the resources.

Top level items in the application are compiled.

Response objects are created. The application objects such as HttpContext,


HttpRequest and HttpResponse are created and initialized.

An instance of the HttpApplication object is created and assigned to the request.

The request is processed by the HttpApplication class. Different events are


raised by this class for processing the request.

(Q.19.B)ASP.NET Page Life Cycle


When a page is requested, it is loaded into the server memory, processed, and sent to
the browser. Then it is unloaded from the memory. At each of these steps, methods

and events are available, which could be overridden according to the need of the
application. In other words, you can write your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the
components on the page, except the directives, are part of this control tree. You can
see the control tree by adding trace= "true" to the page directive. We will cover page
directives and tracing under 'directives' and 'event handling'.
The page life cycle phases are:

Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering

Understanding the page cycle helps in writing codes for making some specific thing
happen at any stage of the page life cycle. It also helps in writing custom controls and
initializing them at right time, populate their properties with view-state data and run
control behavior code.
Following are the different stages of an ASP.NET page:

Page request - When ASP.NET gets a page request, it decides whether to parse
and compile the page, or there would be a cached version of the page;
accordingly the response is sent.

Starting of page life cycle - At this stage, the Request and Response objects
are set. If the request is an old request or post back, the IsPostBack property of
the page is set to true. The UICulture property of the page is also set.

Page initialization - At this stage, the controls on the page are assigned unique
ID by setting the UniqueID property and the themes are applied. For a new
request, postback data is loaded and the control properties are restored to the
view-state values.

Page load - At this stage, control properties are set using the view state and
control state values.

Validation - Validate method of the validation control is called and on its


successful execution, the IsValid property of the page is set to true.

Postback event handling - If the request is a postback (old request), the


related event handler is invoked.

Page rendering - At this stage, view state for the page and all controls are
saved. The page calls the Render method for each control and the output of
rendering is written to the OutputStream class of the Response property of page.

Unload - The rendered page is sent to the client and page properties, such as
Response and Request, are unloaded and all cleanup done.

(Q.19.C)ASP.NET Page Life Cycle Events


At each stage of the page life cycle, the page raises some events, which could be
coded. An event handler is basically a function or subroutine, bound to the event, using
declarative attributes such as Onclick or handle.
Following are the page life cycle events:

PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack
property and determines whether the page is a postback. It sets the themes and
master pages, creates dynamic controls, and gets and sets profile property
values. This event can be handled by overloading the OnPreInit method or
creating a Page_PreInit handler.

Init - Init event initializes the control property and the control tree is built. This
event can be handled by overloading the OnInit method or creating a Page_Init
handler.

InitComplete - InitComplete event allows tracking of view state. All the controls
turn on view-state tracking.

LoadViewState - LoadViewState event allows loading view state information


into the controls.

LoadPostData - During this phase, the contents of all the input fields are
defined with the <form> tag are processed.

PreLoad - PreLoad occurs before the post back data is loaded in the controls.
This event can be handled by overloading the OnPreLoad method or creating a
Page_PreLoad handler.

Load - The Load event is raised for the page first and then recursively for all
child controls. The controls in the control tree are created. This event can be
handled by overloading the OnLoad method or creating a Page_Load handler.

LoadComplete - The loading process is completed, control event handlers are


run, and page validation takes place. This event can be handled by overloading
the OnLoadComplete method or creating a Page_LoadComplete handler

PreRender - The PreRender event occurs just before the output is rendered. By
handling this event, pages and controls can perform any updates before the
output is rendered.

PreRenderComplete - As the PreRender event is recursively fired for all child


controls, this event ensures the completion of the pre-rendering phase.

SaveStateComplete - State of control on the page is saved. Personalization,


control state and view state information is saved. The HTML markup is
generated. This stage can be handled by overriding the Render method or
creating a Page_Render handler.

UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the
UnLoad event for all controls recursively and lastly for the page itself. Final
cleanup is done and all resources and references, such as database
connections, are freed. This event can be handled by modifying the OnUnLoad
method or creating a Page_UnLoad handler.

Q.20.Web.config
The web.config file uses the predefined XML format.The Entire content of the file
is nested in a root<Configuration> elemnt.

Inside this element are several more subsections, some of which youll never
change, and others which are more important.
<?xml version=1.0 ?>
<configuration>
<configSections>.</configSections>
<appSettings>.</appSettings>
<connectionSettings>.</connectionSettings>
<system.web>.</system.web>
<system.codedom>.</system.codedom>
<system.webServer>.</system.webServer>
</cofiguration>

The web.config file is case-sensitive,like all XML documents, and starts every
setting with a lowercase letter.This means you cannot write <AppSetting> instead
of <appSettings>
There are three sections in the web.config file.
The <appSettings> section allows you to add your own miscellaneous pieces of
information.
The<connectionStrings> section allows you to define the connections information
for accessing a database.
Finally, the <system.web> section holds every ASP.NET setting youll need to
configure.
Inside the <system.web> element are separate elements for each aspect of
website configuration. You can incluse as few or as many of these as you want.

Q.21.Global.asax File
The Global.asax file allows you to write the code that responds to global
application events.
These events fire at various points during the lifetime of a web application,
including when the application domain is first created (When the first request is
received for a page in a website folder).
To add an Global.asax file to an application in visual studio, choose Website>Add
New Item, and Select the Global Application Class file type.Then, Click OK.
The Global.asax File looks similar to a normal .aspx file, expect it cant contain
any HTML or ASP.NET tags. Instead, it contains event handlers, This event
handler uses a Write() method of a Built-in Response object.
Each ASP.NET application can have one Global.asax file. Once you place it in the
appropriate website directory, ASP.NET recognizes it and uses it automatically.

Event-Handling Method
Application_Start()

Description
Occurs when the application starts,
which the first time it receives a

Application_End()

Application_BeginRequest()

request from any user, It doesnt occur


on subsequent requests.This event is
commonly used to create or cache
some initial information that will be
reused later.
Occure When the application is
shutting down, generally because the
web server is being restarted. You can
insert cleanup code here.
This event raised at the start of every
request for the web application.

Application_EndRequest()

This event raised at the end of each


request right before the objects
released.

Session_Start()

This event raised for each time a new


session begins, This is a good place
to put code that is session-specific.
This event called when session of
user ends.
This event raised whenever an
unhandled exception occurs in the
application. This provides an
opportunity to implement generic
application-wide error handling.
This event fired after the web
application is destroyed and this event
is used to reclaim the memory it
occupies.

Session_End()
Application_Error()

Application_Disposed()

Example Global.asax implementation: C#


<%@ Application Language="C#" %>
<script runat="server">
static string _pagePath;
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
_pagePath = Server.MapPath("~/Folder/Page.aspx");

}
// ...
</script>

Q.22.DELEGATES
A delegate is a type that enables you to store references to functions. Although this
sounds
quite involved, the mechanism is surprisingly simple.
class Program
{
public delegate void ashok(string letter); // delegate declaration
static void Main(string[] args)
{
Program pp = new Program();
ashok a = new ashok(pp.soniya); // delegate instance
a("increase taxes"); // delegate invokation
}
public void soniya(string msg) // delegate method
{
Console.WriteLine("inside display");
}}
What is the use of Delegates?
Suppose if you have multiple methods with same signature (return type & number of
parameters) and want to call all the methods with single object then we can go for
delegates.
Delegates are two types
- Single Cast Delegates
- Multi Cast Delegates
Single Cast Delegates
Single cast delegate means which hold address of single method like as explained in
above example.
Multicast Delegates

Multi cast delegate is used to hold address of multiple methods in single delegate. To
hold multiple addresses with delegate we will use overloaded += operator and if you
want remove addresses from delegate we need to use overloaded operator -=
Multicast delegates will work only for the methods which have return type only void. If
we want to create a multicast delegate with return type we will get the return type of last
method in the invocation list
Check below sample code for delegate declaration and methods declaration
Syntax of Multicast Delegate & Method Declaration
Check below sample code for multicast delegate declaration and methods declaration
public delegate void MultiDelegate(int a,int b);
public class Sampleclass
{
public static void Add(int x, int y)
{
Console.WriteLine("Addition Value: "+(x + y));
}
public static void Sub(int x, int y)
{
Console.WriteLine("Subtraction Value: " + (x - y));
}
public static void Mul(int x, int y)
{
Console.WriteLine("Multiply Value: " + (x * y));
}
}
class Program
{
static void Main(string[] args)
{
Sampleclass sc=new Sampleclass();
MultiDelegate del = Sampleclass.Add;
del += Sampleclass.Sub;
del += Sampleclass.Mul;
del(10, 5);
Console.ReadLine();
}
}
Output
Whenever we run above code we will get output like as shown below

Addition Value : 15
Subtraction Value : 5
Multiply Value : 50
If you observe above code I declared MultiDelegate method with void return type.
foreach loop is a different kind of looping constructs in C# programming that doesnt
includes initialization, termination and increment/decrement characteristics. It uses
collection to take value one by one and then processes them.
Syntax:
foreach (string name in arr)
{}
Where, name is a string variable that takes value from collection as arr and then
processes them in the body area.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace foreach_loop
{
class Program
{
static void Main(string[] args)
{
string[] arr = new string[5]; // declaring array
//Storing value in array element
arr[0] = "Steven";
arr[1] = "Clark";
arr[2] = "Mark";
arr[3] = "Thompson";
arr[4] = "John";
//retrieving value using foreach loop
foreach (string name in arr)
{

Console.WriteLine("Hello " + name);


}
Console.ReadLine();
}
}
}
Note: You will learn more about array in lateral chapter.
Output
Hello Steven
Hello Clark
Hello Mark
Hello Thompson
Hello John
__
Q.23.Events
Objects may raise (and consume) events as part of their processing. Events are
important
occurrences
that you can act on in other parts of code, similar to (but more powerful than)
exceptions.
The special kind of function that is called when the event occurs. You also need
to configure
this handler to listen for the event you are interested in.
Eg: button click
How to create custom events and attach (wiring) event to function
Code:
private void button1_Click(object sender, EventArgs e)
{
button2.Click += new EventHandler(this.willbecalled);
// line above will add method to call when button2 is clicked
}
private void willbecalled(object sender, EventArgs e)
{
MessageBox.Show("thanks for wiring \n event to me");
}
Q.24.What are the access modifiers available?
There are five different access modifiers:
public: It specifies that it can be accessed by anyone.
private: Private declared variables, classes or functions can be accessed only by the
member functions. No one from outside the class can access them.

protected: This access specifier is useful in a hierarchy wherein an access can be


given only to the child classes.
internal: These limit an access only within an assembly. Its is similar to a friend function
of C++.
protected internal: These limit the access within the assembly and to the child classes
in the hierarchy
public
The public keyword is an access modifier for types and type members. Public access is
the most permissive access level.
There are no restrictions on accessing public members.
Accessibility:
Can be accessed by objects of the class
Can be accessed by derived classes
Example: In the following example num1 is direct access.
using System;
namespace AccessModifiers
{
class Program
{
class AccessMod
{
public int num1;
}
static void Main(string[] args)
{
AccessMod ob1 = new AccessMod();
//Direct access to public members
ob1.num1 = 100;
Console.WriteLine("Number one value in main {0}", ob1.num1);
Console.ReadLine();
}
}
}
private
Private access is the least permissive access level.

Private members are accessible only within the body of the class or the struct in which
they are declared.
Accessibility:
Cannot be accessed by object
Cannot be accessed by derived classes
Example: In the following example num2 is not accessible outside the class.
using System;
namespace AccessModifiers
{
class Program
{
class AccessMod
{
public int num1;
int num2;
}
static void Main(string[] args)
{
AccessMod ob1 = new AccessMod();
//Direct access to public members
ob1.num1 = 100;
//Access to private member is not permitted
ob1.num2 = 20;
Console.WriteLine("Number one value in main {0}", ob1.num1);
Console.ReadLine();
}
}
}
protected
A protected member is accessible from within the class in which it is declared, and from
within any class derived from the class that declared this member.
A protected member of a base class is accessible in a derived class only if the access
takes place through the derived class type.
Accessibility:
Cannot be accessed by object
By derived classes
using System;

namespace AccessModifiers
{
class Program
{
class Base
{
protected int num1;
}
class Derived : Base
{
public int num2;
static void Main(string[] args)
{
Base ob1 = new Base();
Derived ob2 = new Derived();
ob2.num1 = 20;
// Access to protected member as it is inhertited by the Derived class
ob2.num2 = 90;
Console.WriteLine("Number2 value {0}", ob2.num2);
Console.WriteLine("Number1 value which is protected {0}", ob2.num1);
Console.ReadLine();
}
}
}
}
internal
The internal keyword is an access modifier for types and type members. We can
declare a class as internal or its member as internal. Internal members are accessible
only within files in the same assembly (.dll).
In other words, access is limited exclusively to classes defined within the current project
assembly.
Accessibility:
In same assembly (public)
Can be accessed by objects of the class
Can be accessed by derived classes
In other assembly (internal)

Cannot be accessed by object


Cannot be accessed by derived classes
protected internal
The protected internal accessibility means protected OR internal, not protected AND
internal.
In other words, a protected internal member is accessible from any class in the same
assembly, including derived classes.
The protected internal access modifier seems to be a confusing but is a union of
protected and internal in terms of providing access but not restricting. It allows:
Inherited types, even though they belong to a different assembly, have access to
the protected internal members.
Types that reside in the same assembly, even if they are not derived from the
type, also have access to the protected internal members.
Default access
A default access level is used if no access modifier is specified in a member declaration.
The following list defines the default access modifier for certain C# types:
enum: The default and only access modifier supported is public.
class: The default access for a class is private. It may be explicitly defined using any of
the access modifiers.
interface: The default and only access modifier supported is public.
struct: The default access is private with public and internal supported as well.
The default access may suffice for a given situation, but you should specify the access
modifier you want to use to ensure proper application behavior.
Q.25.A.DROP-DOWN-LIST
Nam
e

Description
AccessKey

Gets or sets the access key that


allows you to quickly navigate to the
Web server control.(Inherited

fromWebControl.)
Adapter

Gets the browser-specific adapter for


the control.(Inherited from Control.)

AppendDataBoundItems

Gets or sets a value that indicates


whether list items are cleared before
data binding.(Inherited
fromListControl.)

AppRelativeTemplateSourceDirector
y

Gets or sets the application-relative


virtual directory of
the Page or UserControl object that
contains this control.(Inherited
from Control.)

Attributes

Gets the collection of arbitrary


attributes (for rendering only) that do
not correspond to properties on the
control.(Inherited from WebControl.)

Q.25.B.LIST-BOX
Nam
e

Description
AccessibilityObject

Gets the AccessibleObject assigned to


the control.(Inherited from Control.)

AccessibleDefaultActionDescriptio
n

Gets or sets the default action


description of the control for use by
accessibility client applications.(Inherited
from Control.)

AccessibleDescription

Gets or sets the description of the


control used by accessibility client
applications.(Inherited from Control.)

AccessibleName

Gets or sets the name of the control


used by accessibility client applications.
(Inherited from Control.)

AccessibleRole

Gets or sets the accessible role of the

control (Inherited from Control.)

Q.26.Similarities and difference between Class and structure in .NET.


Similarities:
- Both Class and Structures can have methods, variables and objects.
- Both can have constructor.
- Both are user defined types.
Differences:
- Structure being value type, the variables cannot be assigned to NULL. On the other
hand, classes being reference type, a class variable can be assigned to NULL.
- Structure is allocated on a stack when instantiated, while Class is allocated on a heap.
- When a method is passed to a class, pass by reference is used. Pass by value is used
for struts.
- A class can have a destructor.
Q.27.LINQ
LINQ enables you to query data from a wide variety of data sources, directly from
your
programming code. LINQ is to .NET programming what SQL is to relational
databases. With
straightforward, declarative syntax you can query collections for objects that
match your criteria.
LINQ is not just an add-on that is part of the .NET Framework. On the contrary,
LINQ has been
designed and implemented as a true part of the programming languages in .NET.
This means that
LINQ is truly integrated into .NET, giving you a unified way to query data,
regardless of where that
data comes from. In addition, because it is integrated into the language and not
in a certain project
type, LINQ is available in all kinds of projects including web applications,
Windows Forms
applications, Console applications, and so on. To help developers get familiar
with LINQ, its syntax
is closely modeled after SQL, the most popular query language for relational
databases. This means
that LINQ has keywords such as Select, From, and Where to get data from a
data source.

To give you an idea of what a LINQ query looks like, heres a quick example that
shows a list of
Wrox authors whose names contain the letter S:
LINQ has a great power of querying on any source of data, data source could be
the collections of
objects, database or XML files. We can easily retrieve data from any object that
implements the
IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and
that are give below.
LINQ to Object {Queries performed against the in-memory data}
LINQ to ADO.Net
LINQ to SQL (formerly DLinq) {Queries performed against the
relation database
only Microsoft SQL Server Supported}
LINQ to DataSet {Supports queries by using ADO.NET data sets and
data tables}
LINQ to Entities {Microsoft ORM solution}
LINQ to XML (formerly XLinq) { Queries performed against the XML
so
This sample uses where to find all elements of an array less than 5.
Source Code
C#
public void Linq1()
{
int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };
var lowNums =
from n in numbers
where n < 5
select n;
Console.WriteLine("Numbers < 5:");
foreach (var x in lowNums)
{
Console.WriteLine(x);
}
}
Result
Numbers < 5:
4,0,2,3,1
Q.28.Explain standard query operators Select,From,Order BY,and Where in LINQ?

LINQ supports a large number of query operators keywords that enable you to
select, order, or
filter data that is to be returned from the query.
examples uses the object model and the ObjectContext object called myEntities
Select
var allReviews = from r in myEntities.Reviews
select r;
The r variable in this example is referred to as a range variable that is only available
within
the current query. You typically introduce the range variable in the From clause, and
then
use it again in the Where and Select clauses to filter the data, and to indicate the data
you
want to select. Although you can choose any name you like, you often see single letter
variables like the r (for Review) or you see the singular form of the collection you are
querying
From
Although not considered a standard query operator because it doesnt operate on
the data
but rather points to the data the From clause (from in C#) is an important element in
a LINQ
query, because it defines the collection or data source that the query must act upon.
Order By
With Order By (orderby in C#, without the space that VB.NET uses) you can sort the
items
in the result collection. Order By is followed by an optional Ascending or Descending
(ascending and descending in C#) keyword to specify sort order. You can specify
multiple
criteria by separating them with a comma. The following query returns a list of genres
first
sorted by SortOrder in descending order, then sorted on their Name in ascending order
(the
default):
var allGenres = from g in myEntities.Genres
orderby g.SortOrder descending, g.Name
select g;
Where
Just like the WHERE clause in SQL, the Where clause in LINQ (where in C#) enables
you
to filter the objects returned by the query.
var allReviews = from r in myEntities.Reviews
where r.Authorized == true
select r;
Sum, Min, Max, Average, and Count
These aggregation operators enable you to perform mathematical calculations on the
objects

in the result set. For example, to retrieve the number of reviews, you can execute this
query:
var numberOfReviews = (from r in myEntities.Reviews
select r).Count();
(Q.29.A)LINQ to Objects

Queries in LINQ to Objects return variables of type usually IEnumerable<T>


only. In short, LINQ to Objects offers a fresh approach to collections as earlier,

it was vital to write long coding (foreach loops of much complexity) for retrieval of
data from a collection which is now replaced by writing declarative code which
clearly describes the desired data that is required to retrieve.

There are also many advantages of LINQ to Objects over traditional foreach
loops like more readability, powerful filtering, capability of grouping, enhanced
ordering with minimal application coding.

Such LINQ queries are also more compact in nature and are portable to any
other data sources without any modification or with just a little modification.

This is the purest form of language integration. With LINQ to Objects, you can
query collections in
your .NET applications as you saw in the previous example. Youre not limited to
arrays because
LINQ enables you to query almost any kind of collection that exists in the .NET
Framework.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace LINQtoObjects
{
class Program
{
static void Main(string[] args)
{
string[] tools = { "Tablesaw", "Bandsaw", "Planer", "Jointer", "Drill",
"Sander" };

var list = from t in tools


select t;
StringBuilder sb = new StringBuilder();
foreach (string s in list)
{
sb.Append(s + Environment.NewLine);
}
Console.WriteLine(sb.ToString(), "Tools");
Console.ReadLine();
}
}
}
(Q.29.B)LINQ to XML
LINQ to XML is the new .NET way to read and write XML. Instead of typical XML
query
languages like XSLT or XPath you can now write LINQ queries that target XML
directly in your
application.
While using LINQ to XML, loading XML documents into memory is easy and

more easier is quering and document modification.


It is also possible to save XML documents existing in memory to disk and to

serialize them.
It eliminates the need for a developer to learn the XML query language which is

somwhat complex.
LINQ to XML has its power in the System.Xml.Linq namespace. This has all the

19 necessary classes to work with XML. These classes are the following ones.
Xattribute,XCData,Xcomment,Xcontainer,Xdeclaration,Xdocument,XdocumentTy
pe,Xelement,Xname,Xnamespace,Xnode,XnodeDocumentOrderComparer,Xnod
eEqualityComparer,Xobject,XobjectChange,XobjectChangeEventArgs,XobjectEv
entHandler,XprocessingInstruction,XText

using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;
namespace LINQtoXML
{

class ExampleOfXML
{
static void Main(string[] args)
{
string myXML = @"<Departments>
<Department>Account</Department>
<Department>Sales</Department>
<Department>Pre-Sales</Department>
<Department>Marketing</Department>
</Departments>";
XDocument xdoc = new XDocument();
xdoc = XDocument.Parse(myXML);
var result = xdoc.Element("Departments").Descendants();
foreach (XElement item in result)
{
Console.WriteLine("Department Name - " + item.Value);
}
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

(Q.29.C)LINQ to ADO .NET


ADO.NET is the part of the .NET Framework that enables you to access data and
data services like
SQL Server and many other different kinds of data sources. ADO.NET is also
used under the hood
by the SqlDataSource control and is commonly used in raw data access code;
code written in C#
or VB.NET that connects to a database without using the declarative data
controls. With LINQ to
ADO.NET you can query database-related information sets, including LINQ to
DataSet, LINQ to
SQL, and LINQ to Entities.
LINQ to DataSet enables you to write queries against the DataSet, a class that
represents an in
memory version of a database.

LINQ to SQL enables you to write object-oriented queries in your .NET projects
that target
Microsoft SQL Server databases. The LINQ to SQL implementation translates
your queries into
SQL statements, which are then sent to the database to perform typical CRUD
operations.
For most ASP.NET developers, LINQ to SQL (also known as DLINQ) is an electrifying
part of Langauage Integrated Query as this allows quering data in SQL server database
by using usual LINQ expressions. It also allows to update, delete and insert data, but
the only drawback from which it suffers is its limitation to the SQL server database.
However, there are many benefits of LINQ to SQL over ADO.NET like reduced
complexity, few lines of coding and many more.
Below is a diagram showing the execution architecture of LINQ to SQL.

Querying with LINQ To SQL


The rules for executing a query with LINQ to SQL is similiar to that of a standard LINQ
query i.e. query is executted either deferred or immediate. There are various
components that play a role in execution of a query with LINQ to SQL and these are the
following ones.
LINQ to SQL API requests query execution on behalf of an application and sent it to

LINQ to SQL Provider


LINQ to SQL Provider - converts query to Transact SQL(T-SQL) and sends the new
query to the ADO Provider for execution
ADO Provider - After execution of the query, send the results in the form of a
DataReader to LINQ to SQL Provider which in turn converts it into a form of user object
It should be noted that before executing a LINQ to SQL query, it is vital to connect to the
data source via DataContext class.
C#
using System;
using System.Linq;
namespace LINQtoSQL
{
class LinqToSQLCRUD
{
static void Main(string[] args)
{
string connectString =
System.Configuration.ConfigurationManager.ConnectionStrings["LinqToSQLDBConnect
ionString"].ToString();
LinqToSQLDataContext db = new LinqToSQLDataContext(connectString);
//Create new Employee
Employee newEmployee = new Employee();
newEmployee.Name = "Michael";
newEmployee.Email = "yourname@companyname.com";
newEmployee.ContactNo = "343434343";
newEmployee.DepartmentId = 3;
newEmployee.Address = "Michael - USA";
//Add new Employee to database
db.Employees.InsertOnSubmit(newEmployee);
//Save changes to Database.
db.SubmitChanges();
//Get new Inserted Employee
Employee insertedEmployee = db.Employees.FirstOrDefault(e
=>e.Name.Equals("Michael"));

Console.WriteLine("Employee Id = {0} , Name = {1}, Email = {2}, ContactNo = {3},


Address = {4}",
insertedEmployee.EmployeeId, insertedEmployee.Name, insertedEmployee.Email,
insertedEmployee.ContactNo, insertedEmployee.Address);
Console.WriteLine("\nPress any key to continue.");
Console.ReadKey();
}
}
}

What is CSS? Need of CSS.


CSS (Cascading Style Sheets) is a well established and frequently used technology to
achieve the separation we mentioned above between formatting and content. It's
supported by virtually all of the moderns web browsers. When you employ CSS
techniques, you are always sure that altering the formatting of your web pages will go
as smooth as possible. .
Advantages of CSS

CSS saves time You can write CSS once and then reuse same sheet in
multiple HTML pages. You can define a style for each HTML element and apply it
to as many Web pages as you want.

Pages load faster If you are using CSS, you do not need to write HTML tag
attributes every time. Just write one CSS rule of a tag and apply it to all the
occurrences of that tag. So less code means faster download times.

Easy maintenance To make a global change, simply change the style, and all
elements in all the web pages will be updated automatically.

Superior styles to HTML CSS has a much wider array of attributes than
HTML, so you can give a far better look to your HTML page in comparison to
HTML attributes.

Multiple Device Compatibility Style sheets allow content to be optimized for


more than one type of device. By using the same HTML document, different
versions of a website can be presented for handheld devices such as PDAs and

cell phones or for printing.

Global web standards Now HTML attributes are being deprecated and it is
being recommended to use CSS. So its a good idea to start using CSS in all the
HTML pages to make them compatible to future browsers.

Offline Browsing CSS can store web applications locally with the help of an
offline catche.Using of this, we can view offline websites.The cache also ensures
faster loading and better overall performance of the website.

Platform Independence The Script offer consistent platform independence


and can support latest browsers as well.

Inline CSS
For Inline CSS every style content is in HTML elements. It is used for a limited section.
Whenever our requirements are very small we can use inline CSS.
It will affect only single elements. In HTML we require that various HTML tag's views are
different so then we use inline Cascading Style Sheets. There are disadvantage of inline
Cascading Style Sheets. It must be specified on every HTML tag. There is very much
time consumed by that and it is not the best practice for a good programmer and the
code will be quite large and very complex.
Inline CSS examples are given below:

Internal CSS

In internal CSS the style of CSS is specified in the <head> section. This is internal CSS,
it affects all the elements in the body section. Internal CSS is used in the condition when
we want a style to be used in the complete HTML body. For that we can use style in the
head tag.
This style performs an action in the entire HTML body.

External CSS
In External CSS we create a .css file and use it in our HTML page as per our
requirements. Generally external Cascading Style Sheets are used whenever we have
many of HTML attributes and we can use them as required; there is no need to rewrite
the CSS style again and again in a complete body of HTML that inherits the property of
the CSS file. There are two ways to create a CSS file. The first is to write the CSS code
in Notepad and save it as a .css file, the second one is to directly add the style sheet in
our Solution Explorer and direct Visual Studio to use it on our HTML page.
How to create and use an External CSS.
1.
2.
3.
4.
5.

Right-click on your application name in Visual Studio 2012.


Add a style sheet.
Write your CSS code and save it.
Open your HTML page and drag down the style sheet.
Save and RUN.

(Q.1.1)ASP.NET CONTROLS
Controls are small building blocks of the graphical user interface, which include text
boxes, buttons, check boxes, list boxes, labels, and numerous other tools. Using these
tools, the users can enter data, make selections and indicate their preferences.
Controls are also used for structural jobs, like validation, data access, security, creating
master pages, and data manipulation.
ASP.NET uses five types of web controls, which are:
HTML controls
HTML Server controls
ASP.NET Server controls
ASP.NET Ajax Server controls
User controls and custom controls
ASP.NET server controls are the primary controls used in ASP.NET. These controls can
be grouped into the following categories:
Validation controls - These are used to validate user input and they work by

running client-side script.


Data source controls - These controls provides data binding to different data

sources.
Data view controls - These are various lists and tables, which can bind to data

from data sources for displaying.


Personalization controls - These are used for personalization of a page
according to the user preferences, based on user information.

Login and security controls - These controls provide user authentication.


Master pages - These controls provide consistent layout and interface

throughout the application.


Navigation controls - These controls help in navigation. For example, menus,

tree view etc.


Rich controls - These controls implement special features. For example,

AdRotator, FileUpload, and Calendar control.


The syntax for using server controls is:
<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2]
/>
In addition, visual studio has the following features, to help produce in error-free
coding:
Dragging and dropping of controls in design view
IntelliSense feature that displays and auto-completes the properties
The properties window to set the property values directly
Properties of the Server Controls
ASP.NET server controls with a visual aspect are derived from the WebControl class
and inherit all the properties, events, and methods of this class.
The WebControl class itself and some other server controls that are not visually
rendered are derived from the System.Web.UI.Control class. For example,
PlaceHolder control or XML control.
ASP.Net server controls inherit all properties, events, and methods of the WebControl
and System.Web.UI.Control class.
The following table shows the inherited properties, common to all server controls:
AccessKey

Pressing this key with the Alt key moves focus to the
control.

Attributes

It is the collection of arbitrary attributes (for rendering only)


that do not correspond to properties on the control.

BackColor

Background color.

BindingContainer

The control that contains this control's data binding.

BorderColor

Border color.

BorderStyle

Border style.

BorderWidth

Border width.

CausesValidation

Indicates if it causes validation.

ChildControlCreate
d

It indicates whether the server control's child controls have


been created.

ClientID

Control ID for HTML markup.

Context

The HttpContext object associated with the server control.

Controls

Collection of all controls contained within the control.

ControlStyle

The style of the Web server control.

CssClass

CSS class

Methods of the Server Controls


The following table provides the methods of the server controls:
Method

Description

AddAttributesToRender

Adds HTML attributes and styles that need to be


rendered to the specified HtmlTextWriterTag.

AddedControl

Called after a child control is added to the


Controls collection of the control object.

AddParsedSubObject

Notifies the server control that an element, either


XML or HTML, was parsed, and adds the
element to the server control's control collection.

ApplyStyleSheetSkin

Applies the style properties defined in the page


style sheet to the control.

ClearCachedClientID

Infrastructure. Sets the cached ClientID value to


null.

ClearChildControlState

Deletes the control-state information for the


server control's child controls.

ClearChildState

Deletes the view-state and control-state


information for all the server control's child
controls.

ClearChildViewState

Deletes the view-state information for all the


server control's child controls.

CreateChildControls

Used in creating child controls.

CreateControlCollection

Creates a new ControlCollection object to hold


the child controls.

CreateControlStyle

Creates the style object that is used to implement


all style related properties.

(Q.2.1)ASP.NET State Management


Hyper Text Transfer Protocol (HTTP) is a stateless protocol. When the client
disconnects from the server, the ASP.NET engine discards the page objects. This way,
each web application can scale up to serve numerous requests simultaneously without
running out of server memory.
However, there needs to be some technique to store the information between requests
and to retrieve it when required. This information i.e., the current value of all the
controls and variables for the current user in the current session is called the State.
ASP.NET manages four types of states:

View State
Control State
Session State
Application State

View State
The view state is the state of the page and all its controls. It is automatically maintained
across posts by the ASP.NET framework.

When a page is sent back to the client, the changes in the properties of the page and
its controls are determined, and stored in the value of a hidden input field named
_VIEWSTATE. When the page is again posted back, the _VIEWSTATE field is sent to
the server with the HTTP request.
The view state could be enabled or disabled for:

The entire application by setting the EnableViewState property in the <pages>


section of web.config file.

A page by setting the EnableViewState attribute of the Page directive, as <%@


Page Language="C#" EnableViewState="false" %>

A control by setting the Control.EnableViewState property.

It is implemented using a view state object defined by the StateBag class which defines
a collection of view state items. The state bag is a data structure containing attribute
value pairs, stored as strings associated with objects.
The StateBag class has the following properties:
Properties

Description

Item(name)

The value of the view state item with the specified name.
This is the default property of the StateBag class.

Count

The number of items in the view state collection.

Keys

Collection of keys for all the items in the collection.

Values

Collection of values for all the items in the collection.

The StateBag class has the following methods:


Methods

Description

Add(name, value)

Adds an item to the view state collection and existing


item is updated.

Clear

Removes all the items from the collection.

Equals(Object)

Determines whether the specified object is equal to the

current object.
Finalize

Allows it to free resources and perform other cleanup


operations.

GetEnumerator

Returns an enumerator that iterates over all the key/value


pairs of the StateItem objects stored in the StateBag
object.

GetType

Gets the type of the current instance.

IsItemDirty

Checks a StateItem object stored in the StateBag object


to evaluate whether it has been modified.

Remove(name)

Removes the specified item.

SetDirty

Sets the state of the StateBag object as well as the Dirty


property of each of the StateItem objects contained by it.

SetItemDirty

Sets the Dirty property for the specified StateItem object


in the StateBag object.

ToString

Returns a string representing the state bag object.

Example
The following example demonstrates the concept of storing view state. Let us keep a
counter, which is incremented each time the page is posted back by clicking a button
on the page. A label control shows the value in the counter.
The markup file code is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="statedemo._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
<form id="form1" runat="server">

<div>
<h3>View State demo</h3>
Page Counter:
<asp:Label ID="lblCounter" runat="server" />
<asp:Button ID="btnIncrement" runat="server" Text="Add Count"
onclick="btnIncrement_Click" />
</div>
</form>
</body>
</html>
The code behind file for the example is shown here:
public partial class _Default : System.Web.UI.Page
{
public int counter
{
get
{
if (ViewState["pcounter"] != null)
{
return ((int)ViewState["pcounter"]);
}
else
{
return 0;
}
}
set
{
ViewState["pcounter"] = value;
}
}
protected void Page_Load(object sender, EventArgs e)
{
lblCounter.Text = counter.ToString();
counter++;
}

}
It would produce the following result:

Control State
Control state cannot be modified, accessed directly, or disabled.
Session State
When a user connects to an ASP.NET website, a new session object is created. When
session state is turned on, a new session state object is created for each new request.
This session state object becomes part of the context and it is available through the
page.
Session state is generally used for storing application data such as inventory, supplier
list, customer record, or shopping cart. It can also keep information about the user and
his preferences, and keep the track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from
client to server and back as cookie or a modified URL. The SessionID is globally
unique and random.
The session state object is created from the HttpSessionState class, which defines a
collection of session state items.
The HttpSessionState class has the following properties:
Properties

Description

SessionID

The unique session identifier.

Item(name)

The value of the session state item with the specified


name. This is the default property of the
HttpSessionState class.

Count

The number of items in the session state collection.

TimeOut

Gets and sets the amount of time, in minutes, allowed


between requests before the session-state provider
terminates the session.

The HttpSessionState class has the following methods:


Methods

Description

Add(name, value)

Adds an item to the session state collection.

Clear

Removes all the items from session state collection.

Remove(name)

Removes the specified item from the session state


collection.

RemoveAll

Removes all keys and values from the session-state


collection.

RemoveAt

Deletes an item at a specified index from the sessionstate collection.

The session state object is a name-value pair to store and retrieve some information
from the session state object. You could use the following code for the same:
void StoreSessionInfo()
{
String fromuser = TextBox1.Text;
Session["fromuser"] = fromuser;
}
void RetrieveSessionInfo()
{
String fromuser = Session["fromuser"];
Label1.Text = fromuser;
}
The above code stores only strings in the Session dictionary object, however, it can
store all the primitive data types and arrays composed of primitive data types, as well

as the DataSet, DataTable, HashTable, and Image objects, as well as any user-defined
class that inherits from the ISerializable object.
Application State
The ASP.NET application is the collection of all web pages, code and other files within
a single virtual directory on a web server. When information is stored in application
state, it is available to all the users.
To provide for the use of application state, ASP.NET creates an application state object
for each application from the HTTPApplicationState class and stores this object in
server memory. This object is represented by class file global.asax.
Application State is mostly used to store hit counters and other statistical data, global
application data like tax rate, discount rate etc. and to keep the track of users visiting
the site.
The HttpApplicationState class has the following properties:
Properties

Description

Item(name)

The value of the application state item with the specified


name. This is the default property of the
HttpApplicationState class.

Count

The number of items in the application state collection.

The HttpApplicationState class has the following methods:


Methods

Description

Add(name, value)

Adds an item to the application state collection.

Clear

Removes all the items from the application state


collection.

Remove(name)

Removes the specified item from the application state


collection.

RemoveAll

Removes all objects from an HttpApplicationState

collection.
RemoveAt

Removes an HttpApplicationState object from a collection


by index.

Lock()

Locks the application state collection so only the current


user can access it.

Unlock()

Unlocks the application state collection so all the users


can access it.

Application state data is generally maintained by writing handlers for the events:

Application_Start
Application_End
Application_Error
Session_Start
Session_End

(Q.3.1)ASP.NET validation controls validate the user input data to ensure that
useless, unauthenticated, or contradictory data don't get stored.
ASP.NET provides the following validation controls:

RequiredFieldValidator
RangeValidator
CompareValidator
RegularExpressionValidator
CustomValidator
ValidationSummary

BaseValidator Class
The validation control classes are inherited from the BaseValidator class hence they
inherit its properties and methods. Therefore, it would help to take a look at the
properties and the methods of this base class, which are common for all the validation
controls:

Members

Description

ControlToValidate

Indicates the input control to validate.

Display

Indicates how the error message is shown.

EnableClientScript

Indicates whether client side validation will take.

Enabled

Enables or disables the validator.

ErrorMessage

Indicates error string.

Text

Error text to be shown if validation fails.

IsValid

Indicates whether the value of the control is valid.

SetFocusOnError

It indicates whether in case of an invalid control, the


focus should switch to the related input control.

ValidationGroup

The logical group of multiple validators, where this control


belongs.

Validate()

This method revalidates the control and updates the


IsValid property.

RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty. It is
generally tied to a text box to force input into the text box.
The syntax of the control is as given:
<asp:RequiredFieldValidator ID="rfvcandidate"
runat="server" ControlToValidate ="ddlcandidate"
ErrorMessage="Please choose a candidate"
InitialValue="Please choose a candidate">
</asp:RequiredFieldValidator>
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined
range.
It has three specific properties:

Properties

Description

Type

It defines the type of the data. The available values are:


Currency, Date, Double, Integer, and String.

MinimumValue

It specifies the minimum value of the range.

MaximumValue

It specifies the maximum value of the range.

The syntax of the control is as given:


<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"
ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"
MinimumValue="6" Type="Integer">
</asp:RangeValidator>
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed value or a
value in another control.
It has the following specific properties:
Properties

Description

Type

It specifies the data type.

ControlToCompare

It specifies the value of the input control to compare with.

ValueToCompare

It specifies the constant value to compare with.

Operator

It specifies the comparison operator, the available values


are: Equal, NotEqual, GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, and DataTypeCheck.

The basic syntax of the control is as follows:


<asp:CompareValidator ID="CompareValidator1" runat="server"
ErrorMessage="CompareValidator">
</asp:CompareValidator>

RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a
pattern of a regular expression. The regular expression is set in the
ValidationExpression property.
The following table summarizes the commonly used syntax constructs for regular
expressions:
Character Escapes

Description

\b

Matches a backspace.

\t

Matches a tab.

\r

Matches a carriage return.

\v

Matches a vertical tab.

\f

Matches a form feed.

\n

Matches a new line.

Escape character.

Apart from single character match, a class of characters could be specified that can be
matched, called the metacharacters.
Metacharacters

Description

Matches any character except \n.

[abcd]

Matches any character in the set.

[^abcd]

Excludes any character in the set.

[2-7a-mA-M]

Matches any character specified in the range.

\w

Matches any alphanumeric character and underscore.

\W

Matches any non-word character.

\s

Matches whitespace characters like, space, tab, new line

etc.
\S

Matches any non-whitespace character.

\d

Matches any decimal character.

\D

Matches any non-decimal character.

Quantifiers could be added to specify number of times a character could appear.


Quantifier

Description

Zero or more matches.

One or more matches.

Zero or one matches.

{N}

N matches.

{N,}

N or more matches.

{N,M}

Between N and M matches.

The syntax of the control is as given:


<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"
ValidationExpression="string" ValidationGroup="string">
</asp:RegularExpressionValidator>
CustomValidator
The CustomValidator control allows writing application specific custom validation
routines for both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction
property. The client side validation routine should be written in a scripting language,
such as JavaScript or VBScript, which the browser can understand.

The server side validation routine must be called from the control's ServerValidate
event handler. The server side validation routine should be written in any .Net
language, like C# or VB.Net.
The basic syntax for the control is as given:
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">
</asp:CustomValidator>
ValidationSummary
The ValidationSummary control does not perform any validation but shows a summary
of all errors in the page. The summary displays the values of the ErrorMessage
property of all validation controls that failed validation.
The following two mutually inclusive properties list out the error message:

ShowSummary : shows the error messages in specified format.

ShowMessageBox : shows the error messages in a separate window.

The syntax for the control is as given:


<asp:ValidationSummary ID="ValidationSummary1" runat="server"
DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />
Validation Groups
Complex pages have different groups of information provided in different panels. In
such situation, a need might arise for performing validation separately for separate
group. This kind of situation is handled using validation groups.
To create a validation group, you should put the input controls and the validation
controls into the same logical group by setting their ValidationGroupproperty.

(Q.29.D)LINQ to sql JOINS

A join clause takes two source sequences as input. The elements in each
sequence must either be or contain a property that can be compared to a
corresponding property in the other sequence.

The join clause compares the specified keys for equality by using the
special equals keyword. All joins performed by the join clause are equijoins.

The shape of the output of a join clause depends on the specific type of join you
are performing. The following are three most common join types:

Inner join
The following example shows a simple inner equijoin. This query produces a flat
sequence of "product name / category" pairs. The same category string will appear
in multiple elements. If an element from categories has no matching products, that
category will not appear in the results.
var innerJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID
select new { ProductName = prod.Name, Category = category.Name };
//produces flat sequence

Group join
A group join produces a hierarchical result sequence, which associates elements in
the left source sequence with one or more matching elements in the right side
source sequence. A group join has no equivalent in relational terms; it is essentially
a sequence of object arrays.
var innerGroupJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
select new { CategoryName = category.Name, Products = prodGroup };

Left outer join


In a left outer join, all the elements in the left source sequence are returned, even if
no matching elements are in the right sequence. To perform a left outer join in LINQ,
use the DefaultIfEmpty method in combination with a group join to specify a default
right-side element to produce if a left-side element has no matches. You can

use null as the default value for any reference type, or you can specify a userdefined default type. In the following example, a user-defined default type is shown:
var leftOuterJoinQuery =
from category in categories
join prod in products on category.ID equals prod.CategoryID into prodGroup
from item in prodGroup.DefaultIfEmpty(new Product { Name = String.Empty,
CategoryID = 0 })
select new { CatName = category.Name, ProdName = item.Name };

(Q.30)What is the difference between DataSet and DataReader?


The following are the main difference between DataSet and DataReader.
DataSet :
- Consumer Object
- Provides Disconnected mode
- Forward and backward scanning of data
- Slower access to data
- Can store multiple table simultaneously
- Read/Write access
DataReader :
- Provider Object
- Provides Connected mode
- Forward-only cursor
- Faster access to data
- Supports a single table based on a single SQL query
- Read Only access
(Q.31)SITE NAVIGATIONS
When you think about important parts of a navigation system, the first thing that you
may
come up with is a menu. Menus come in all sorts and sizes, ranging from simple and
static
HTML links to complex, fold-out menus driven by CSS or JavaScript. But there s more
to
navigation than menus alone. ASP.NET comes with a number of useful navigation
controls that
enable you to set up a navigation system in no time. These controls include the Menu,
TreeView, and SiteMapPath

A Sites navigation is used to assist user to browse your site


ASP.Net navigation controls:
Menu
Treeview
breadcrumbs
ASP.Net uses a sitemap to document the sites structure
A sitemap is an XML file
It defines the logical sections of the site
And may tie each section to a URL
After you have your sitemap you can use several ASP.Net controls to navigate the site
SiteMapPath
o Create a breadcrumb
A single line of text showing the user their location in the website
structure
TreeView
o Provides a hierarchical view of the sites structure
o Renders as an expandable/cdollapsible tree
Menu
o Menu items and subitems
Using Breadcrumb Navigation
The siteMapPath control displays a breadcrumb
You can use it to show the user where they are in the site
It also allows the user to move back to higher levels
You must have a sitemap for this control
Drag a siteMapPath control to page1.aspx
Test it
It displays a breadcrumb showing where in the site the user is

Add a siteMapPath control to each page


TreeView
TreeView allows the user to navigate through the entire site
A treeview control requires a siteMapDataSource control which allows the control to
automatically get the data for navigation
Each node in the tree is rendered as a hyperlink to the particular page

Add a SiteMapPathControl to the page


Add a treeView control to the page
Using the smart tag pick the SiteMapDataSource as the dataSource
Test it

There are 4 types of nodes in a treeview

Root Node
o Each siteMapPath has one root node
Selected Node
o The current node matches the page the user is on
Parent Nodes
o A node that has children besides the root node
Leaf Nodes
o Nodes that have a parent but no children
Customizing
Click the autoformat option in the smart tag of the treeView
There are also several property that you can attach a style sheet to
nodeStyle
o default style of all nodes in the treeView
HoverNodeStyle
o Style spplied when the user hovers his mouse over a certain node
levelStyles
o allows you to apply style info for certain levels of the treeview

Menus
The menu will use the sitemap to display each item and it uses submenus for each item
in a lower hierarchy
Add a menu control
Configure it to the siteMapDataAccess Control

The menu control has both static and dynamic parts


The static part is always shown
The dynamic part is shown when the user interacts with it
StaticDisplayLevels property can be used to control how many levels display

Set the staticDisplayLevels to 2


Set the orientation to horizontal

(Q.32)What is the significance of MASTER PAGES?


ASP.NET master pages allow you to create a consistent layout for the pages in
your application.
A single master page defines the look and feel and standard behavior that you
want for all of
the pages (or a group of pages) in your application.
Master pages provide functionality that developers have traditionally created by
copying
existing code, text, and control elements repeatedly; using framesets; using
include files for

common elements; using ASP.NET user controls; and so on. Advantages of


master pages
include the following:
They allow you to centralize the common functionality of your pages so that you
can
make updates in just one place.
They make it easy to create one set of controls and code and apply the results to
a set
of pages. For example, you can use controls on the master page to create a
menu that
applies to all pages.
They give you fine-grained control over the layout of the final page by allowing
you to
control how the placeholder controls are rendered.
They provide an object model that allows you to customize the master page from
individual content pages.

(Q.33)Explain Master Pages in Details?


ASP.NET master pages allow you to create a consistent layout for the pages in
your application.
A single master page defines the look and feel and standard behavior that you
want for all of
the pages (or a group of pages) in your application. You can then create
individual content
pages that contain the content you want to display. When users request the
content pages,
they merge with the master page to produce output that combines the layout of
the master
page with the content from the content page.
A master page is an ASP.NET file with the extension .master (for example,
MySite.master) with
a predefined layout that can include static text, HTML elements, and server
controls. The
master page is identified by a special @ Master directive that replaces the @
Page directive
that is used for ordinary .aspx pages. The directive looks like the following.
<%@ Master Language="C#" %>
The @ Master directive can contain most of the same directives that a @ Control
directive can contain.
For example, the following master-page directive includes the name of a codebehind
file, and assigns a class name to the master page.

<%@ Master Language="C#" CodeFile="MasterPage.master.cs" Inherits="MasterPage"


%>
Replaceable Content Placeholders
the master page also includes one or more ContentPlaceHolder controls. These
placeholder
controls define regions where replaceable content will appear. In turn, the
replaceable content is defined in content pages.
Content Pages
You define the content for the master page's placeholder controls by creating
individual content
pages, which are ASP.NET pages (.aspx files and, optionally, code-behind files)
that are bound to a specific master page. The binding is established in the
content page's @ Page directive by including a MasterPageFile attribute that
points to the master page to be used.
(Q.34)What are the Advantages and Disadvantages of Session?
Following are the basic advantages and disadvantages of using session.
Advantages:
- It stores user states and data to all over the application.
- Easy mechanism to implement and we can store any kind of object.
- Stores every user data separately.
- Session is secure and transparent from user because session object is stored on the
server.
Disadvantages:
- Performance overhead in case of large number of user, because of session data
stored in server memory.
- Overhead involved in serializing and De-Serializing session Data. Because In case of
StateServer and SQLServer session mode we need to serialize the object before store.
(Q.35)How to work with data without using a data adapter
As you can see, you still use command and connection objects to access the
database.
Instead of using a data adapter to execute the commands, though, you execute
the commands directly. When you do that, you also have to provide code to
handle the result of the command.
If you issue a command that contains an Insert, Update, or Delete statement, for
example, the result is an integer that

indicates the number of rows that were affected by the operation. You can use
that information to determine if the operation was successful.
If you execute a command that contains a Select statement, the result is a
result set that contains the rows you requested. To read through the rows in the
result set, you use a data reader object.
Although a data reader provides an efficient way of reading the rows in a result
set, you cant use it to modify those rows. In addition, it only lets you read rows in a
forward direction.
Once you read the next row, the previous row is unavailable. Because of that,
you typically use a data reader to retrieve and work with a single database row at
a time.
Description
Instead of using a data adapter to execute commands to retrieve, insert, update,
and delete data from a database, you can execute those commands directly
To retrieve data from a database, you execute a command object that contains a
Select statement.
Then, the command object uses a connection to connect to the database and
retrieve the data. You can then read the results one row at a time using a data
reader object.
To insert, update, or delete data in a database, you execute a command object
that contains an Insert, Update, or Delete statement. Then, the command object
uses a connection to connect to the database and update the data. You can then
check the value thats returned to determine if the operation was successful.

If you use this technique in an application that maintains the data in a database,
you
typically work with a single row at a time. Because of that, the chance of a
concurrency
error is reduced.

The SqlDataReader class


This class is used to create a data reader object, which provides an efficient
way to read the rows in a result set returned by a database query.
In fact, when you use a data adapter to retrieve data, the data adapter uses a
data reader to read through the rows in the result set and store them in a dataset.
Description
A SqlConnection object is required to establish a connection to a SQL Server
database.
A SqlCommand object is used to execute a SQL command against a SQL Server
database.
A SqlParameter object is used to pass variable information to a SQL command.
Common members of the SqlDataReader class
Indexer Description
[index] Accesses the column with the specified index from the
current row.
[name] Accesses the column with the specified name from the
current row.
Property Description
IsClosed Gets a Boolean value that indicates if the data
reader is closed.
Method Description
Read Reads the next row. Returns True if there are more
rows.
Otherwise, returns False.
Close Closes the data reader.
(Q.36)The SqlDataAdapter class
The job of a data adapter is to provide a link between a
database and a dataset.
The four properties of the SqlDataAdapter class listed in
figure for example, identify The four SQL commands that the data
adapter uses to transfer data from the database to the dataset and vice versa
The selectCommand property identifies the command object that s used to
retrieve data from the database.
And the DeleteCommand, InsertCommand, and UpdateCommand properties
identify the commands that are used to update the database based on changes
made to the data in the dataset.
To execute the command identified by the SelectCommand property and
place the data thats retrieved in a dataset, you use the Fill method.

Then, the application can work with the data in the dataset without affecting
the data in the database. If the application makes changes to the data in the
dataset, it can use ihc data adapters Update method to execute the
commands identified by the
DeleteCommand, InsertCommand, and UpdateCommand properties and post
the changes back to the database.
Common members of the SqlDataAdapter class
Property Description
SelectCommand A SqlCommand object representing the Select
statement used to query the database.
DeleteCommand A SqlCommand object representing the Delete
statement used to delete a row from the database.
InsertCommand A SqlCommand object representing the Insert
statement used to add a row to the database.
UpdateCommand A SqlCommand object representing the Update
statement used to update a row in the database.
Method Description
Fill Executes the command identified by the
SelectCommand property and loads the result into a
dataset object.
Update Executes the commands identified by the
DeleteCommand, InsertCommand, and UpdateCommand
properties for each row in the dataset that was
deleted, added, or updated.
Description
A data reader provides read-only, forward-only access to the data in a database.
Because it doesnt require the overhead of a dataset, it s more efficient than
using a data adapter. However, it cant be used to update data.
When the Fill method of a data adapter is used to retrieve data from a database,
the data adapter uses a data reader to load the results into a dataset.
(Q.37)How to define the connection
The first step in configuring a SqlDataSource control is to create the connection
for th data source click the New Connection button to display the Add Connection
dialog box.
This dialog box helps you identify the database that you want to access and
provide the information you need to access it.
In the Add Connection dialog box, you select the name of the server that
contains the database you want to access, enter the information that s required
to log on to the server, and select the name of the database you want to access.
If youre using SQL Server Express on your own PC, you can type
localhost\sqlexpress for the server name.
For the logon information, you can click on the Use Windows Authentication
option.

Then, SQL Server Express will use the login name and password that you use for
your computer as the name and password for the database too.
As a result, you wont need to provide a separate user name and password in
this dialog box. Last, you select the
name of the database that you want to connect to. When you re done, you can
click on the Test Connection button to be sure that the connection works.
Once you establish a connection to a database, you can use that connection for
all of the applications that use that database.

(Q.38)How to bind a list control to a data source


List control attributes for data binding
Attribute Description
DataSourcelD The ID of the data source to bind the list to.
DataTextField The name of the data source field that should
be displayed in the list.
DataValueField The name of the data source field whose value
should be returned by the SelectedValue
property of the list.
<asp:DropDownList ID="ddlCategory" runat="server"
AutoPostBack="True"
DataSourceID="SqlDataSourcel"
DataTextField="LongName"
DataValueField="CategoryID">
</asp:DropDownList>
Description
You can bind any of the controls that inherit the ListControl class to a data
source.
That includes the list box control, the drop-down list control, the check box list
control, the radio button list control, and the bulleted list control.
You can use the Data Source Configuration Wizard to select the data source for
a list control, the data field to display in the list, and the data value to return for
the selected item.
You can also use the DataTextFormatString attribute of a list control to specify a
format string you want to apply to the text that s displayed in the control.
(Q.39)How to change the data source mode
ADO.NET provides two basic ways to retrieve data from a database. You can either
retrieve the
data into a dataset, which retains a copy of the data in memory so it can be accessed
multiple times and updated if necessary. Or, you can retrieve the data using a
data reader, which lets you retrieve the data in forward-only, read-only fashion.
When you create a SQL data source, the data is retrieved into a dataset by
default. If the data will be readjust once and not updated, though, you can
usually improve the applications performance by retrieving the data using a
data reader. To do that, just set the value of the DataSourceMode attribute

The DataSourceMode attribute


Attribute Description
DataSourceMode DataSet or DataReader. The default is DataSet, but
you can specify DataReader if the data source is
read-only.
A SqlDataSource control that uses a data reader
<asp:SqlDataSource ID="SqlDataSourcel" runat="server"
ConnectionString="<%$ ConnectionStrings:HalloweenConnectionString
%>" DataSourceMode="DataReader" SelectCommand="SELECT [CategorylD],
[LongName] FROM [Categories]ORDER BY [LongName]"
</asp:SqlDataSource>
Description
The DataSourceMode attribute lets you specify that data should be retrieved using a
data reader rather than being stored in a dataset. For read-only data, a data reader is
usually more efficient.
The data source caching attributes let you specify that data should be stored in cache
storage for a specified period of time. For data that changes infrequently, caching can
improve performance.
(Q.40)GridView control
The GridView control. This control lets you display the data from a data source in the
rows and
columns of a table. It includes many advanced features, such as automatic paging and
sorting.
It lets you update and delete data with minimal C# code. And its appearance is fully
customizable.
The GridView control displays data provided by a data source in a row and column
format. In
fact, the GridView control renders its data as an HTML table with one Tr element for
each row
in the data source, and one Td element for each column in the data source.

The aspx code for the GridView control shown above


<asp:GridView ID="GridViewl" runat="server"
AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" DataKeyNames = "CategoryID">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="ID"

Readonly="True" SortExpression="CategorylD">
cltemStyle Widths"10Opx" />
</asp:BoundField>
<asp:BoundField DataField="ShortName" HeaderText="Short Name"
SortExpression="ShortName" >
<ItemStyle Width="150px />
</asp:BoundField>
<asp:BoundField DataField="LongName" HeaderText="Long Name"
SortExpres sion="LongName">
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:CommandField ButtonType="Button ShowEditButton="True"
CausesValidation=False" />
<asp:CommandField ButtonType="Button" ShowDeleteButton="True
CausesValidation="False" />
</Columns>
</asp:GridView>
Basic attributes of the GridView control
ID The ID of the control.
Runat Must specify server.
DataSourceID The ID of the data source to bind to.
DataKeyNames The names of the primary key fields separated
by commas.
AutoGenerateColumns Specifics whether the controls columns should
be
automatically generated.
Selectedlndex Specifies the row to be initially selected.
Description
The GridView control displays data from a data source in a row and column format.
The
data is rendered as an HTML table.
To create a GridView control, drag the GridView icon from the Data group of the
Toolbox.
To bind a GridView control to a data source, use the smart tag menu s Choose Data
Source command.
Q:Attributes of the GridView control that affect paging
Attribute Description
AllowPaging Set to True to enable paging.
PageSize Specifies the number of rows to display on each
page. The default is 10.
Q:Attributes of the PagerSettings element
Attribute Description
Mode Controls what buttons are displayed in the
pager area. You can specify

NextPrevious, NextPreviousFirstLast. Numeric,


or NumericFirstLast.
FirstPageText The text to display for the first page button.
The default is &lt,&lt;,
which displays as <<.
FirstPageImageUrl The URL of an image file used to display the
first page button.
PreviousPageText The text to display for the previous page
button. The default is &lt;,
which displays as <.
PreviousPageImageUrl The URL of an image file used to display the
previous page button.
NextPageText The text to display for the next page button.
The default is &gt;, which
displays as >.
NextPagcImageUrl The URL of an image file used to display the
next page button.
LastPageText The text to display for the last page button.
The default is &gt;&gt;,
which displays as >>.
LastPagelmageUrl The URL of an image file used to display the
last page button.
PageButtonCount The number of page buttons to display if the
Mode is set to Numeric or NumericFirstLast.
Position The location of the pager area. You can specify
Top, Bottom, or TopAndBottom.
Visible Set to False to hide the pager controls.
(Q.41)How to use events raised by the DetailsView control
These events are similar to the events raised by the GridView
control.
Most of these events come in pairs: one thats raised before an operation occurs, and
another
thats raised after the operation completes. For example, the ItemDeleting event is
raised
before an item is deleted, and the IlemDeleted event is raised after an item has been
deleted.
As with the GridView control, the most common reason to handle the before events for
the
DetailsView control is to provide data validation. For example, when the user clicks the
Update
button, you can handle the ItemUpdating event to make sure the user has entered
correct
data. Then, you can set the e arguments Cancel property to True if the user hasn t
entered
correct data. This cancels the update.

The after action events let you check that database operations have completed
successfully. To
do that, you need to check for two types of errors as
illustrated in the example in this figure. First, you should check for database
exceptions by testing the Exception property of the e argument. If it is not null,
database exception has occurred. Then, you should display an appropriate
error message to let the user know about the problem.
If the data source uses optimistic concurrency, you should also check to
make sure there hasnt been a concurrency error. You can do that by testing the
AffectedRows property of the c argument. If a concurrency error has occurred,
this property will be set to zero meaning that no rows have been changed. Then,
you can display an appropriate error message.
If no errors occurred during the update operation, the ItemUpdated event
shown in this figure ends by calling the DataBind method for the drop-down list
control. This is necessary because view state is enabled for this control. As a
result, this control will continue to display the old data unless you call its
DataBind method to refresh its data. If view state were disabled for this control,
the DataBind call wouldn't be necessary.

Events raised by the DetailsView control


Event Description
ItemCommand Raised when a button is clicked.
ItemCreated Raised when an item is created.
DataBound Raised when data binding completes for an item.
ItemDeleted Raised when an item has been deleted.
ItemDeleting Raised when an item is about to be deleted.
Itemlnserted Raised when an item has been inserted.
Itemlnserting Raised when an item is about to be inserted.
ItemUpdated Raised when an item has been updated.
ItemUpdating Raised when an item is about to be updated.
PagelndexChanged Raised when the index of the displayed item has
changed.
PagelndexChanging Raised when the index of the displayed item is
about to change.
How to use the FormView control
The FormView control is designed to display data for a single item from a data source.
the FormView control is similar to the DetailsView control, it differs in several key ways.
Most
importantly, the FormView control isnt restricted by the HTML table layout of the
DetailsView
control, in which each field is rendered as a table row. Instead, the FormView control
uses

templates to render all of the fields as a single row by default. This gives you complete
control
over the layout of the fields within the row.
When you create a FormView control and bind it to a data source, the Web Forms
Designer will
automatically create default templates for you. Then, you can edit the templates to
achieve the
layout you want. To do that, choose Edit Templates from the smart tag menu.
For most applications, youll use just the Item, Editltem, and Insertltem templates.
How the FormView control differs from the DetailsView control
The DetailsView control can be easier to work with, but the FormView control provides
more formatting and layout options.
The DetailsView control can use BoundField elements or TemplateField elements with
templates that use data binding expressions to define bound data fields. The FormView
control can use only templates with data binding expressions to display bound data.
The DetailsView control renders each field as a table row, but the FormView control
renders all the fields in a template as a single table row.
Description
A FormView control is similar to a DetailsView control, but its templates give you more
control over how its data is displayed. To accomplish that, all the columns in the data
source can be laid out within a single template.
After you create a FormView control and assign a data source to it, you can edit the
controls templates so the data is displayed the way you want.
ASP.NET Provider Model

Different types of Selector in Jquery?

jQuery Event Methods


Event methods trigger, or bind a function to an event for all matching elements.

Partitioning Operators: Skip & SkipWhile


Partitioning operators split the sequence (collection) into two parts and return one of the
parts.
Method

Description

Skip

Skips elements up to a specified position starting from the first element in a sequence.

SkipWhile Skips elements based on a condition until an element does not satisfy the condition. If the
first element itself doesn't satisfy the condition, it then skips 0 elements and returns all the
elements in the sequence.
Take

Takes elements up to a specified position starting from the first element in a sequence.

TakeWhile Returns elements from the first element until an element does not satisfy the condition. If t
first element itself doesn't satisfy the condition then returns an empty collection.
Example: Skip() - C#
IList<string> strList = new List<string>(){ "One", "Two", "Three", "Four", "Five" };
var newList = strList.Skip(2);
foreach(var str in newList)
Console.WriteLine(str);
Example: SkipWhile in C#
IList<string> strList = new List<string>() {"One","Two","Three","Four","Five","Six" };
var resultList = strList.SkipWhile(s => s.Length < 4);
foreach(string str in resultList)
Console.WriteLine(str);
Example: Take() in C#
IList<string> strList = new List<string>(){ "One", "Two", "Three", "Four", "Five" };
var newList = strList.Take(2);
foreach(var str in newList)
Console.WriteLine(str);
Example: TakeWhile in C#
IList<string> strList = new List<string>() {"Three","Four","Five","Hundred" };
var result = strList.TakeWhile(s => s.Length > 4);
foreach(string str in result)
Console.WriteLine(str);

Element Operators: First & FirstOrDefault


The First and FirstOrDefault method returns an element from the zeroth index in the
collection i.e. the first element. Also, it returns an element that satisfies the specified
condition.
Element
Operators

Description

First

Returns the first element of a collection, or the first element that satisfies a conditio

FirstOrDefault

Returns the first element of a collection, or the first element that satisfies a conditio
Returns a default value if index is out of range.

Example: LINQ First() - C#


IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
Console.WriteLine("1st Element in intList: {0}", intList.First());
Console.WriteLine("1st Even Element in intList: {0}", intList.First(i => i % 2 == 0));
Console.WriteLine("1st Element in strList: {0}", strList.First());
Console.WriteLine("emptyList.First() throws an InvalidOperationException");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(emptyList.First());
Example: LINQ FirstOrDefault() - C#
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
Console.WriteLine("1st Element in intList: {0}", intList.FirstOrDefault());
Console.WriteLine("1st Even Element in intList: {0}",
intList.FirstOrDefault(i => i % 2 == 0));
Console.WriteLine("1st Element in strList: {0}", strList.FirstOrDefault());
Console.WriteLine("1st Element in emptyList: {0}", emptyList.FirstOrDefault());

Element Operators : Last & LastOrDefault


Element
Operators

Description

Last

Returns the last element from a collection, or the last element that satisfies a condi

LastOrDefault

Returns the last element from a collection, or the last element that satisfies a
condition. Returns a default value if no such element exists.

Example: LINQ Last() - C#


IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
Console.WriteLine("Last Element in intList: {0}", intList.Last());
Console.WriteLine("Last Even Element in intList: {0}", intList.Last(i => i % 2 == 0));
Console.WriteLine("Last Element in strList: {0}", strList.Last());
Console.WriteLine("emptyList.Last() throws an InvalidOperationException");
Console.WriteLine("-------------------------------------------------------------");
Console.WriteLine(emptyList.Last());
Example: LINQ LastOrDefault() - C#
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
Console.WriteLine("Last Element in intList: {0}", intList.LastOrDefault());
Console.WriteLine("Last Even Element in intList: {0}",
intList.LastOrDefault(i => i % 2 == 0));
Console.WriteLine("Last Element in strList: {0}", strList.LastOrDefault());
Console.WriteLine("Last Element in emptyList: {0}", emptyList.LastOrDefault());
Element Operators: Single & SingleOrDefault
Description
single

Returns the only element from a collection, or the only element that satisfies a condition. If
Single() found no elements or more than one elements in the collection then throws
InvalidOperationException.

Single
Or

The same as Single, except that it returns a default value of a specified generic type, instead
throwing an exception if no element found for the specified condition. However, it will thrown
InvalidOperationException if it found more than one element for the specified condition in the
Defaul collection.
t
IList<int> oneElementList = new List<int>() { 7 };
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };

IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };


IList<string> emptyList = new List<string>();
Console.WriteLine("The only element in oneElementList: {0}", oneElementList.Single());
Console.WriteLine("The only element in oneElementList: {0}",
oneElementList.SingleOrDefault());
Console.WriteLine("Element in emptyList: {0}", emptyList.SingleOrDefault());
Console.WriteLine("The only element which is less than 10 in intList: {0}",
intList.Single(i => i < 10));
//Followings throw an exception
//Console.WriteLine("The only Element in intList: {0}", intList.Single());
//Console.WriteLine("The only Element in intList: {0}", intList.SingleOrDefault());
//Console.WriteLine("The only Element in emptyList: {0}", emptyList.Single());
C#: Single() and SingleOrDefault()
IList<int> oneElementList = new List<int>() { 7 };
IList<int> intList = new List<int>() { 7, 10, 21, 30, 45, 50, 87 };
IList<string> strList = new List<string>() { null, "Two", "Three", "Four", "Five" };
IList<string> emptyList = new List<string>();
//following throws error because list contains more than one element which is less than
100
Console.WriteLine("Element less than 100 in intList: {0}", intList.Single(i => i < 100));
//following throws error because list contains more than one element which is less than
100
Console.WriteLine("Element less than 100 in intList: {0}",
intList.SingleOrDefault(i => i < 100));
//following throws error because list contains more than one elements
Console.WriteLine("The only Element in intList: {0}", intList.Single());
//following throws error because list contains more than one elements
Console.WriteLine("The only Element in intList: {0}", intList.SingleOrDefault());
//following throws error because list does not contains any element
Console.WriteLine("The only Element in emptyList: {0}", emptyList.Single());
Equality Operator: SequenceEqual
There is only one equality operator: SequenceEqual. The SequenceEqual method
checks whether the number of elements, value of each element and order of elements
in two collections are equal or not.
If the collection contains elements of primitive data types then it compares the values
and number of elements, whereas collection with complex type elements, checks the

references of the objects. So, if the objects have the same reference then they
considered as equal otherwise they are considered not equal.
The following example demonstrates the SequenceEqual method with the collection of
primitive data types.
Example: SequenceEqual in Method Syntax C#
IList<string> strList1 = new List<string>(){"One", "Two", "Three", "Four", "Three"};
IList<string> strList2 = new List<string>(){"One", "Two", "Three", "Four", "Three"};
bool isEqual = strList1.SequenceEqual(strList2); // returns true
Console.WriteLine(isEqual);
Element Operators: ElementAt, ElementAtOrDefault
Element operators return a particular element from a sequence (collection).
The following table lists all the Element operators in LINQ.
Element Operators
(Methods)
Description
ElementAt

Returns the element at a specified index in a collection

ElementAtOrDefault Returns the element at a specified index in a collection or a default value if the
index is out of range.
First

Returns the first element of a collection, or the first element that satisfies a
condition.

FirstOrDefault

Returns the first element of a collection, or the first element that satisfies a
condition. Returns a default value if index is out of range.

Last

Returns the last element of a collection, or the last element that satisfies a
condition

LastOrDefault

Returns the last element of a collection, or the last element that satisfies a
condition. Returns a default value if no such element exists.

Single

Returns the only element of a collection, or the only element that satisfies a
condition.

SingleOrDefault

Returns the only element of a collection, or the only element that satisfies a
condition. Returns a default value if no such element exists or the collection doe
not contain exactly one element.

The ScriptManager control


You can only have one ScriptManagcr control on a page. This includes master and
content pages. If you put a ScriptManagcr control on a master page, you cant use one
on
a content page. If there is more than one ScriptManager control on a page, an Invalid
Operation exception is generated.
The ScriptManager control can also be used to load and manage additional
JavaScript
files and to register web services or WCF services so they can be accessed by
JavaScript
code on the client.
The ScriptManagerProxy control
The ScriptManagerProxy control lets you load JavaScript files and register WCF
services
or web services. It can be used in a content page if the master page contains a
ScriptManager control.
The UpdatePanel control
The UpdatePanel control is a container control that holds other server controls that will
be updated during an asynchronous postback. All controls inside an UpdatePanel
control
will be updated at the same time. A page can contain multiple UpdatePanel controls,
each with a different set of controls.
The UpdateProgress control
The UpdateProgress control provides a visual indication that an asynchronous
postback
is in progress. Then, the user will know to wait until the postback completes before
doing anything else on the page.
The Timer control
When one or more UpdatePanel controls need to be updated automatically, you can
use
the Timer control to trigger partial-page updates at a set time interval.
Timer controls allow you to do postbacks at certain intervals. If used together
with UpdatePanels, which is the most common approach, it allows for timed partial
updates of your page, but it can be used for posting back the entire page as well. In this

chapter we will focus on using timers with UpdatePanels, so if you haven't already read
the chapter on UpdatePanels, please do so now.
Here is a small example of using the Timer control. It simply updates a timestamp every
5 seconds.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"
Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Timers</title>
</head>
<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server" />
<asp:Timer runat="server" id="UpdateTimer" interval="5000"
ontick="UpdateTimer_Tick" />
<asp:UpdatePanel runat="server" id="TimedPanel" updatemode="Conditional">
<Triggers>
<asp:AsyncPostBackTrigger controlid="UpdateTimer" eventname="Tick" />
</Triggers>
<ContentTemplate>
<asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate>
</asp:UpdatePanel>
</form>
</body>
</html>
We only have a single CodeBehind function, which you should add to your CodeBehind
file:
protected void UpdateTimer_Tick(object sender, EventArgs e)
{
DateStampLabel.Text = DateTime.Now.ToString();
}
This is all very simple. We have a normal UpdatePanel, which carries a Trigger
reference to our new Timer control. This means that the panel is updated when the
Timer "ticks", that is, fires the Tick event. The Timer control uses the interval attribute to
define the number of milliseconds to occur before firing the Tick event. As you can see
from our CodeBehind code listing, we just update the DateStampLabel each time the
Timer fires. This could be done more efficient with a simple piece of JavaScript, which
updates the time on the clientside instead of involving the server. The example is only
used to demonstrate the potential of the Timer control.
Common UpdatePanel Properties

ChildrenAsTriggers This property determines whether controls located within the


UpdatePanelcan cause a refresh of the UpdatePanel. The default value is
True, as you saw in the previous exercise. When you set this
value to False, you have to set the UpdateMode to Conditional.
Note that controls defined within the UpdatePanel still cause a
postback to the server with this property set toFalse; they just don t update the panel
automatically anymore.
Triggers The Triggers collection contains PostBackTrigger and
AsyncPostBackTrigger elements. The first is useful if you want
to force a complete page refresh, whereas the latter is useful if
you want to update an UpdatePanel with a control that is
defined outside the panel.
RenderMode This property can be set to Block or Inline to indicate whether
the UpdatePanel renders itself as a <div> or <span> element.
UpdateMode This property determines whether the control is always
refreshed (the UpdateMode is set to Always) or only under certain conditions,
for example,when one of the controls defined in the <Triggers> element is
causing a postback (the UpdateMode is set to Conditional).
ContentTemplate Although not visible in the Properties Grid for the UpdatePanel,
The <ContentTemplate> is an important property of the
UpdatePanel. Its the container in which you place controls as children of the
UpdatePanel.If you forget this required ContentTemplate, VWD gives you aWarning.
Features of JQueryFeature Description
Cross-browser compatibility Makes it easy to write codc that is compatible with all
modem
web browsers.
Event handling Makes it easy to register functions as event listeners.
DOM selection Makes it easy to select DOM elements.
DOM manipulation Makes it easy to modify DOM elements.
CSS manipulation Makes it easy to modify the CSS for a DOM element.
Effects and animations Makes it easy to apply special effects and animations to DOM
elements such as fading in or out, sliding up or down, and so on.
AJAX Makes it easy to send an AJAX request to the server and use the
data in the AJAX response to update the DOM for a web page.
Extensibility Allows jQuery to work with plug-ins such as the controls in the
jQuery UI library'.

Potrebbero piacerti anche