0% found this document useful (0 votes)
18 views

Awpppp

The document discusses .NET Framework, its architecture and components like CLR. It also explains concepts like boxing, unboxing, properties, inheritance in C# with examples. Key terms like abstract class, sealed class, partial class are defined. The difference between public and private assemblies is explained.

Uploaded by

rexos83460
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

Awpppp

The document discusses .NET Framework, its architecture and components like CLR. It also explains concepts like boxing, unboxing, properties, inheritance in C# with examples. Key terms like abstract class, sealed class, partial class are defined. The difference between public and private assemblies is explained.

Uploaded by

rexos83460
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Q. What is .NET Framework? Explain its architecture with help of What is property ?

at is property ? Explain read-write property with proper syntax and Q. Define each of the following terms: Derived class The functionality of
diagram Ans) .NET Framework is a platform created by Microsoft for example. Ans)  In C# Properties don't have storage locations.  In C# an existing class can be extended by creating a new class from it. The
building, deploying, and running applications and services that use .NET Properties are extensions of fields and accessed like fields.  The new class is then called a child class or derived class. The derived class
technologies, such as desktop applications and Web services.  It is a Properties have accessors that are used to set, get or compute/calculate inherits the properties of the base class. Abstract class An Abstract class
platform for application developers.  It is a Framework that supports their values. ❖ Usage of C# Properties  In C# Properties can be read- is a non-instantiable class which is either partially implemented, or not
Multiple Language and Cross language integration.  It has IDE only or write-only.  We can have logic to implement while setting values at all implemented. It can have abstract methods as well as non-abstract
(Integrated Development Environment).  Framework is a set of utilities in the C# Properties.  In a class fields are private, so that fields can't be methods. Abstract classes require subclasses to provide
or can say building blocks of our application system.  .NET Framework accessed from outside the class.  Now we are forced to use C# implementations for the abstract methods. It provides default
provides interoperability between languages i.e. Common Type System properties for setting or getting values Properties Example : read-only functionality to its sub classes. Static class A static class is class whose
(CTS).  .NET Framework also includes the .NET Common Language property using System; public class Employee { private static int objects cannot be created and must contain only static members. Sealed
Runtime (CLR), which responsible for maintaining the execution of all counter; public Employee() { counter++; } public static int Counter { get { class A sealed class is a class which cannot be inherited. In C#, the sealed
applications developed using the .NET library.  The .NET Framework return counter; } } } class SampleEmployee { public static void modifier is used to define a class as sealed. Partial class It is possible to
consists primarily of a gigantic library of code. Components of the .Net Main(string[] args) { Employee e1 = new Employee(); Employee e2 = split the definition of a class over two or more source files. Each source
Framework: User Interface and Program: We can create various type new Employee(); Employee e3 = new Employee(); //e1.Counter = file contains a section of the type or meth
of application using .net framework such as Console Application 10;//Compile Time Error: Can't set value Console.WriteLine("No. of
Windows Application Web application Base class Library:  Base class Employees: " + Employee.Counter); } } Output: No. of Employees:3 Difference between public assembly and private assembly
library is one of component of .Net Framework. It supplies a library of
base classes that we can use to implement applications quickly. CLR Q. Explain Boxing and Unboxing with reference to value type and Pubic Assembly Private Assembly
(Common Language Runtime)  Common Language Runtime (CLR) is reference type. Ans) Boxing: Any type, value or reference can be Pubic Assembly can be used by Private Assembly can be used
the programming (Virtual Machine component) that manages the assigned to an object without explicit conversion. When a compiler fined multiple applications. by only one applications.
execution of programs written in any language that uses the .NET a value where it needs a reference type, it creates an object ‘box’ into Pubic Assembly is store in GAC Private Assembly will be stored
(global assembly cache) in the specific applications
Framework, for example C#, VB.Net, F# and so on. We can say that it is which it places the value of the value type. Example: - int m = 10; object
directory or sub- directory
heart and soul of .Net Framework or backbone. om = m; When executed, this code creates a temporary reference _type
Pubic Assembly is also termed There is no other name for
‘box’ for the object on heap. We can also use a C-style cast for boxing. int
as shared assembly. private assembly.
Q. Explain CLR in detail. Ans)  Common Language Runtime (CLR) is the m = 10; object om = (object) m; Note that the boxing operation
Strong name has to be created Strong name is not required for
programming (Virtual Machine component) that manages the execution creates a copy of the value of the m integer to the object om. Both the for public assembly. Private assembly.
of programs written in any language that uses the .NET Framework, for variables exist but the value of om resides on the heap. This means that Pubic Assembly should strictly Private Assembly does not have
example C#, VB.Net ,F# and so on.  We can say that it is heart and soul the values are independent of each other. Example int m =10; object om enforce version constraint. any version constraint.
of .Net Framework or backbone.  Programmers write code in any = m; m = 20; Console.WriteLine(m); // m= 20 Console .WriteLine(om); An example to public assembly By default, all assemblies you
language, including VB.Net, C# and F# then they compile their programs //om=10 Unboxing: Unboxing is the process of converting the object is the actuate report classes create are examples of private
into an intermediate form of code called CLI in a portable execution file type back to the value type. Remember that a variable can be unboxed which can be imported in the assembly. Only when you
(PE) that can be managed and used by the CLR and then the CLR only if it has been previously boxed. In contrast to boxing, unboxing is an library and used by any associate a strong name to it
converts it into machine code to be will executed by the processor.  The explicit operation. Example:- int m = 100; object om = m; //boxing int n application that prefers to and store it in GAC, it becomes a
information about the environment, programming language, its version = (int) om; //unboxing When performing unboxing, C# checks the value implement actuate reports. public assembly.
and what class libraries will be used for this code are stored in the form type we request is actually stored in the object under conversion. Only if
of metadata with the compiler that tells the CLR how to handle this code. it is, the value is unboxed.
 The CLR allows an instance of a class written in one language to call a Explain any 5 properties/method of math class in ASP.NET Ans) In
method of the class written in another language. Components of the Q.Explain variable sized array with suitable example. OR Q.Explain ASP.NET, you can use the Math class from the System namespace to
CLR: CTS Common Type System (CTS) describes a set of types that can jagged array with example. Ans) Jagged array is also called Array of perform mathematical operations. Here are five common properties and
be used in different .Net languages in common. That is, the Common Array or variable sized array. In a jagged array, each row may have methods of the Math class along with explanations: 1 Math.PI`
Type System (CTS) ensure that objects written in different .Net different number of columns.  It is equivalent to an array of variable Property:  The Math.PI property provides the mathematical constant π
languages can interact with each other. For Communicating between sized one-dimensional arrays. The Length property is used to get the (pi), which is approximately equal to 3.141592653589793.  You can use
programs written in any .NET complaint language, the types must be length of each one-dimensional array. this property when performing calculations involving circles, angles, and
compatible on the basic level. These types can be Value Types or trigonometric functions. csharp double circleArea = Math.PI *
Reference Types. The Value Types are passed by values and stored in the Math.Pow(radius, 2); 2 Math.Abs()` Method: The Math.Abs() method
stack. The Reference Types are passed by references and stored in the returns the absolute value of a numeric expression, effectively removing
heap. CLS CLS stands for Common Language Specification and it is a the sign of a number. It is commonly used to ensure that a value is
subset of CTS. It defines a set of rules and restrictions that every positive, regardless of its original sign csharp double absoluteValue =
language must follow which runs under .NET framework. The languages Math.Abs(-10.5); // Result: 10.5 3 Math.Sqrt()` Method: The
A jagged array can be declared and initialized as follows:
which follow these set of rules are said to be CLS Compliant. In simple Math.Sqrt() method calculates the square root of a number. It is useful
datatype[][] arrayname=new datatype[rowsize][];
words, CLS enables cross-language integration or Interoperability. MSIL for finding the lengths of sides in right triangles or for other geometric
arrayname[0]=new datatype[]{val1,val2,val3, …};
It is language independent code. When you compile code that uses the calculations. csharp double squareRoot = Math.Sqrt(25.0); // Result:
arrayname[1]=new datatype[]{val1,val2,val3, …};
.NET Framework library, we don't immediately create operating system - 5.0 4 Math.Round()` Method: The Math.Round() method rounds a
arrayname[2]=new datatype[]{val1,val2,val3, …}; Example
specific native code. Instead, we compile our code into Microsoft floating-point number to the nearest integer or a specified number of
Intermediate Language (MSIL) code. The MSIL code is not specific to any decimal places. It is commonly used for rounding numeric values for
class numadd{
operating system or to any language. Advantages -  MSIL provide display or precision control. csharp double roundedValue =
public static void Main(){
language interoperability as code in any .net language is compiled on Math.Round(3.456, 2); // Result: 3.46 5 Math.Max()` and
int[ ][ ] x=new int[4][ ];
MSIL  Same performance in all .net languages  support for different `Math.Min()` Methods: The Math.Max() method returns the larger of
x[0]=new int[2]{5,13};
runtime environments  JIT compiler in CLR converts MSIL code into two numeric values.  The Math.Min() method returns the smaller of two
x[1]=new int[3]{7,8,11};
native machine code which is executed by OS Functions of the CLR  numeric values.  These methods are useful when you need to determine
x[2]=new int[4]{2,3,4,5}; x[3]=new int[1]{9};
Garbage Collector  Exception handling  Type safety  Memory the maximum or minimum value among a set of values. csharp int
for(int i=0;i<4;i++){ for(int j=0;j<x[i].Length;j++){
management (using the Garbage Collector)  Security  Improved maxValue = Math.Max(10, 15); // Result: 15 int minValue =
Console.Write(x[i][j]+"\t"); } Console.Write("\n"); } } }
performance Math.Min(5, 8); // Result: 5 These properties and methods from
the Math class in ASP.NET provide you with essential mathematical
Explain the similarities and differences between Interfaces and Abstract
Q. How Garbage collector works. Ans) Every time our application functionality for various calculations and operations within your
classes Ans)Similarities:  Both abstract classes and interfaces may
instantiates a reference-type object, the CLR allocates space on the applications.
contain members that can be inherited by a derived class.  Neither
managed heap for that object. However, we never need to clear this interfaces nor abstract classes may be directly instantiated, but we can
memory manually.  As soon as our reference to an object goes out of Elaborate Array memory representation with an example or one
declare variables of these types. If we do, we can use polymorphism to
scope (or our application ends), the object becomes available for dimensional and two dimensional array Ans) Array is a reference
assign objects that inherit from these types to variables of these types. 
garbage collection. The garbage collector runs periodically inside the variable, it is a collection of variables having same name, same data
In both cases, we can then use the members of these types through these
CLR, automatically reclaiming unused memory for inaccessible objects types but identified by different index. Index of first element of an array
variables, although we don’t have direct access to the other members of
The .NET Framework provides automatic memory management called is always zero, “0”.  Different types of array supported by C# is Single
the derived object. Differences:  Derived classes may only inherit from
garbage collection. A .NET program that runs in a managed environment dimensional, Multi-dimensional and Jagged array. An example of single
a single base class, which means that only a single abstract class can be
is provided with this facility by .NET CLR The purpose of using dimensional array for string and int data types are given below: string[ ]
inherited directly. Conversely, classes can use as many interfaces as they
Garbage Collector is to clean up memory. In .NET all dynamically cities = {"Mumbai", "Chennai", "Delhi”}; int[ ] myfavnumbers =
want  Abstract classes may possess both abstract members and non-
requested memory is allocated in the heap which is maintained by CLR. {1,2,4,5};  An example of multi-dimensional array for int data types
abstract members. Interface members conversely, must be implemented
The garbage collector continuously looks for heap objects that have are given below: int [,] a = new int [3,4] { {0, 1, 2, 3}, /*
on the class that uses the interface they do not possess code bodies. 
references in order to identify which ones are accessible from the code. initializers for row indexed by 0 */ {4, 5, 6, 7} , /* initializers for row
Moreover, interface members are by definition public but members of
indexed by 1 */ {8, 9, 10, 11} /* initializers for row indexed by 2 */ };
Any objects without reference will be removed at the time of garbage abstract classes may also be private (as long as they aren’t abstract),
collection  The Garbage collection is not deterministic. It is called only  Following code shows how to accept values entered by user and to
protected, internal, or protected internal. In addition, interfaces can’t
store in multidimensional array: class Multi_Array { static void
when the CLR decides that it is most needed  It happens in a situation contain fields, constructors, destructors, static members, or constants
Main(string[] args) { /* an array with 3 rows and 2 columns*/
such as the heap for the given process is becoming full and requires a
int[,] ar = new int[3, 2] {{0,0}, {1,2}, {2,4}}; int i, j;
clean-up. In the common language runtime (CLR), the garbage collector Explain various Types of Constructors in C# Ans) In C#, a constructor is
/* output each array element's value */ for (i = 0; i < 3; i++) {
serves as an automatic memory manager. It provides the following a special method that is used to initialize objects. It is invoked when an
for (j = 0; j < 2; j++) { Console.WriteLine("ar[{0},{1}] = {2}",
benefits:  Enables you to develop your application without having to object of the class is created. Constructors have the same name as the
i, j, ar[i,j]); } } Console.ReadKey(); }
free memory.  Allocates objects on the managed heap efficiently.  class and do not have a return type. There are several types of
Reclaims objects that are no longer being used, clears their memory, and constructors in C#, including: 1) Default Constructor: A constructor
Q. What is namespace? How to create namespace and alias? Ans) A
keeps the memory available for future allocations.  Provides memory without any parameters is called a default constructor. It initializes all
namespace is designed for providing a way to keep one set of names
safety by making sure that an object cannot use the content of another numeric fields in the class to zero and all string and object fields to null.
separate from another. The class names declared in one namespace does
object. GC.Collect () method:  This method is used to call garbage public class Car { public Car( ) { Console.WriteLine("Car
not conflict with the same class names declared in another. Defining a
collector explicitly. It is used to force a garbage collection to occur at any Constructor"); } } 2) Parameterized Constructor: A constructor
Namespace A namespace definition begins with the keyword
time. that accepts parameters is called a parameterized constructor. It allows
namespace followed by the namespace name as follows: namespace
different instances of the class to be initialized with different values.
namespace_name { // code declarations } Example: using System;
Q. What is delegate? Explain multiple delegate with example. Ans) public class Car { public Car(string brand, int price) { this.brand =
namespace first_space{ class namespace_cl{ public void func(){
Delegate: A delegate in C# is similar to a function pointer in C or C++. It brand; this.price = price; } } 3) Copy Constructor: This constructor
Console.WriteLine("Inside first_space"); } } } namespace second_space{
is a reference type object that allows the programmer to encapsulate a creates an object by copying variables from another object. Its purpose is
class namespace_cl{ public void func(){ Console.WriteLine("Inside
reference to a method in it. It defines the return type and signature for a to initialize a new instance to the values of an existing instance. public
second_space"); } } } class TestClass{ static void Main(string[] args){
method and can refer to any methods that are of the same format in the class Car { public Car(Car car) { this.brand = car.brand; this.price =
first_space.namespace_cl fc = new first_space.namespace_cl();
signature. When same delegate is used to call method multiple time then car.price; } } 4) Static Constructor: A static constructor is called
second_space.namespace_cl sc = new second_space.namespace_cl();
it is referred as Multicast delegate or Multiple delegate. Following are automatically to initialize static members of the class. It does not take
fc.func(); sc.func(); Console.ReadKey(); } } The using Keyword The
condition for multicast delegate:  void is used as return type  Out access modifiers or have parameters. public class Car { static Car() {
using keyword states that the program is using the names in the given
parameter is not allowed as arguments Example public delegate void Console.WriteLine("Static Car Constructor"); } } 5) Private
namespace. For example, we are using the System namespace in our
MyDelegate(); class Abc{ public void Show(){ Console.WriteLine (“New Constructor: A private constructor is used to prevent a class from being
programs. The class Console is defined there. We just write:
Delhi”); } public void Display(){ Console.WriteLine (“New York”); } } class instantiated. It is often used in classes that contain only static members.
Console.WriteLine ("Hello there"); We could have written the fully
Xyz{ public static void Main(){ Abc a1=new Abc(); MyDelegate m1=new public class Car { private Car( ) { Console.WriteLine("Private Car
qualified name as: System.Console.WriteLine("Hello there"); Alias of
MyDelegate(a1.Show); MyDelegate m2=new MyDelegate(a1.Display); Constructor"); } } These examples demonstrate the various types of
Namespace: using A=System.Console; class Test{ static void Main(){
m1=m1+m2+m1+m2-m1; m1(); Console.Read(); } } constructors in C#. Each type serves a specific purpose and can be used
A.Write("Craetion of Alias"); A.ReadKey(); } }
based on the requirements of the class and the application.
Unit-2 Explain Calendar control with example in ASP.NET Ans) ASP.NET Explain following validation controls. Ans) RequiredFieldValidator
provides a Calendar control that is used to display a calendar on the Web Control The RequiredFieldValidator control is simple validation control,
Short note on Page class Ans) When an ASP.NET page is requested and page. This control displays a one-month calendar that allows the user to which checks to seeif the data is entered for the input control. We can
renders markup to a browser, ASP.NET creates aninstance of a class that select dates and move to the next and previous months. By default, this have a RequiredFieldValidator control for each form element on which
represents our page. That class is composed not only of the code that we control displays the name of the current month, day headings for the you wish to enforce Mandatory Field rule. The syntax of the control is as
wrote for the page, but also code that is generated by ASP.NET. Page days of the weeks, days of the month and arrow characters for given: <asp:RequiredFieldValidator ID="rfvcandidate" runat="server"
Properties navigation to the previous or next month. The class hierarchy for this ControlToValidate="txtName" ErrorMessage="Please enter name
control is as follows Object- >Control->WebControl->Calendar !!"></asp:RequiredFieldValidator> RangeValidator Control The
Property Description ( Draw a calendar) The Calendar is complex, powerful Web server RangeValidator Server Control is another validator control, which checks
IsPostBack This Boolean property indicates whether this is the control that you can use to add calendar feature toour web page. We can to see if a control value is within a valid range. The attributes that are
first time the page is being run (false) or whether the use calendar control display any date between 0 A.D. and 9999A.D.The necessary to this control are: MaximumValue, MinimumValue, and Type.
page is being resubmittedin response toa Calendar control is represented as: <asp:Calendar ID="Calendar1" It has three specific properties: The syntax of the control is as given:
controlevent, typically with stored view state runat="server"></asp:Calendar> The Calendar control when rendered <asp:RangeValidator ID="rvclass" runat="server"
information (true). to a user browser, it generates an HTML <table> element and a set of ControlToValidate="txtclass"ErrorMessage="Enter your class (6 - 12)"
EnableView When set to false, this overrides the EnableViewState associated JavaScript. The Calendar control can be used to select a MaximumValue="12"MinimumValue="6" Type="Integer">
State property of the contained controls, thereby ensuring </asp:RangeValidator> RegularExpressionValidator The
that no controls will maintai state information.
Property Description RegularExpressionValidator allows validating the input text by matching
Application This collection holds information that’s shared
Day Allow selection of a single date. against apattern of aregular expression. The regular expression is set in
between all users in ourwebsite. For example, we can
use the Application collection to count the number of DayWeek Allows the selection of a single date or a the ValidationExpression property. The syntax of the control is as given:
times a page has been visited. complete week. <asp:RegularExpressionValidator ID="string" runat="server"
Session This collection holds information for a single user, so DayWeekMonth Allow selection of single date, complete week ErrorMessage="string" ValidationExpression="string"
it can be useddifferent pages. For example, we can use or complete month. ValidationGroup="string"> </asp:RegularExpressionValidator>
the Session collection to store the items in the current None Doesn’t allow you to select any date.
user’s shopping basket on an e-commercewebsite. single date or multipledates. The SelectionMode property is used for Explain SiteMapPath control in ASP.NET Ans) The SiteMapPath control
Request This refers to an HttpRequest object that contains this. basically is used to access web pages of the website from one webpage to
information about the current web request. We can another. It is a navigation control and displays the map of the site related
use the HttpRequest object to get information about Q)Explain any five common properties of web server controls Ans) to its web pages. This map includes the pages in the particular website
the user’s browser. Following are common properties of web server controls: and displays the name of thosepages. We can click on that particular
Response This refers to an HttpResponse object that represents page in the Site Map to navigate to that page.We can say that the
the response ASP.NET will send to the user’s browser Property Description SiteMapPath control displays links for connecting to URLs of otherpages.
AccessKey Enables you to set a key with which a control can The SiteMapPath control uses a property called SiteMapProvider for
be accessed at the client by pressing the associated accessing data from databases and it stores the information in a data
What is the difference between List Box and Drop-Down Lists? List and letter. source. The representation of the SiteMapPath control is as follows:
explain any three common properties of these controls. Ans) List boxes BackColor, Enables you to change background color and text Root Node->Child Node Following steps are used to create Menu
are used in cases where there are small numbers of items to be selected. ForeColor color of a control. Control: Toolbox > Navigation >SiteMapPath Following are some
In contrast, dropdown lists are typically used with larger list so that they BorderColor This property is used to change the border color of
important properties that are very useful. ParentLevelsDisplayed :
don’t take up much space on the page. A list box lets a user select one or a control.
It specifies the number of levels of parent nodes and thendisplays the
more items from the list of items. A drop-down list lets a user choose an BorderStyle Using this property border Style can be set to
control accordingly related to the currently displayed node.
item from the drop-down list of items. Following are common none, dotted. dashed, solid double, groove etc.
RenderCurrentNodeAsLink : It specifies whether or not the site
properties of ListBox and DropDownList: BorderWidth Enables you to change border width of a control.
navigation nodethat represents thecurrently displayed page is rendered
CssClass Enables you to set the style sheet class for this
control. as a hyperlink. PathSeperator : It specifies the string that displays the
Properties Description SiteMapPath nodes in therendered navigationpath. Style properties of
Items Gets the collection of items from the Enabled Determines whether the control is enabled or not.
If the control is disabled user cannot interact with the SiteMapPath class CurrentNodeStyle : It specifies the style used for
dropdown box. the display text for the current node.RootNodeStyle : It specifies the style
it.
SelectedValue Get the value of the Selected item for the root node style text. NodeStyle : It specifies the style used for the
from the dropdown box. Font Enables you to change the Font settings.
Height Enables you to set the height of the control. display text for all nodes in the sitenavigation path. Sitemap file has been
SelectedIndex Gets or Sets the index of the selected
Width Enables you to set the width of the control. included in our project and we can see it in the Solution Explorer. And
item in the dropdown box.
SelectedIndex Gets or Sets the index ToolTip This property enables you to set a tooltip for the now wehave to set the URL and title attributes in the sitemap file.
of the selected item in the dropdown control in the browser and is rendered as a title <?xml version="1.0" encoding="utf-8" ?> <siteMap
box. attribute in the HTML, is shown when the user xmlns="http://schemas.microsoft.com/AspNet/SiteMap-File-1.0" >
SelectedItem Gets the selected item from the list. hovers the mouse over the control. <siteMapNode url="Default.aspx" title="myhomepage" description="">
Visible Determines whether the control is visible or not. <siteMapNode url="myweb1.aspx" title="myfirstpage" description="" />
<siteMapNode url="myweb2.aspx" title="mysecondpage" description=""
Explain Table control with example in ASP.NET Ans) Table control is What is user control? How to create and use user control in ASP.NET /> </siteMapNode> </siteMap>
used to structure a web pages. In other words to divide a page into Page Ans) A User Control is a separate, reusable part of a page. We can
several rows and columns to arrange the information or images. When it put a piece of a page in a User Control, and then reuse it from a different Explain each of the following in brief: Ans) i)Web forms Web Forms are
is renderedon the page, it is implemented through <table> HTML tag. We location. A notable difference is that User Controls can be included on pages that your users request using their browser. These pages can be
can simply use HTML <table> control instead of using <asp:Table> multiple pages, while a page can't. User Controls are used much like written using a combination of HTML, client-script, server controls, and
control. However many of one benefits of using <asp:Table> control is regular server controls, and they can be added to a page declaratively, server code. When users request a page, it is compiled and executed on
we can dynamically add rows or columns atthe runtime orchange the just like server controls can. A big advantage of the User Control is that the server by the framework, and then the framework generates the
appearance of the table. Following are some important properties that it can be cached, using the Output Cache functionality described in a HTML markup that the browser can render. An ASP.NET Web Forms page
are very useful. BackImageUrl Used to set background image of the previous chapter, so instead of caching an entire page, we may cache presents information to the user in any browser or client device. ii)Post
tableCaption Used to write the caption of the table. Example: only the User Control, so that the rest of the page is still re-loaded on back When an action is performed by an ASP.Net web server Control ,
ASP.NET code for a table control <asp:Table each request Creation of User Control: Following steps are used to the PostBack event is triggered. When events occur, the application
ID="Table1" runat="server" Height="123px" Width="567px"> create User Control. Open Visual Studio. "File" -> "New" -> should be able to respond to it . For example the data on the page is
<asp:TableRow runat="server"> "Project..." then select ASP.NET Webform Application. Add a new web posted back to the server for processing. PostBack is the name given to
<asp:TableCell runat="server"></asp:TableCell> form. To create a new User Control, in Solution Explorer, Add New the process of submitting an ASP.NET page to the server for processing.
<asp:TableCell runat="server"></asp:TableCell> Item, provide your File Name and click Add Design User Control as per iii)Page rendering At this stage, view state for the page and all controls
<asp:TableCell runat="server"></asp:TableCell> are saved. iv)Page load event At this stage, control properties are set
our requirement. Next step to use User Control in .aspxpage. Add the
</asp:TableRow> <asp:TableRow runat="server"> using the view state and control state values. Syntax:
following line below the standard page declaration:
<asp:TableCell runat="server"></asp:TableCell> protected void Page_Load(object sender, EventArgs e)
<%@RegisterTagPrefix="My"TagName="UserInfoBoxControl"Src="~/Us
<asp:TableCell runat="server"></asp:TableCell> { //Code will come here. } v)Page prerender event
erInfoBoxControl.ascx" %> Make sure that the src value matches the
<asp:TableCell runat="server"></asp:TableCell> ASP.NEt page PreRender event will fire before page start rendering in
path to your User Control file. Now you may use the User Control in your
</asp:TableRow> <asp:TableRow runat="server"> ASP.NET page life cycle. Syntax: protected void
page, like any other control. For instance, like this:
<asp:TableCell runat="server"></asp:TableCell> Page_PreRender(EventArgs e) { //Code will come here. }
<My:UserInfoBoxControlrunat="server"ID="MyUserInfoBoxControl"/>
<asp:TableCell runat="server"></asp:TableCell>
<asp:TableCell runat="server"></asp:TableCell> What are rich controls? Briefly explain about calendar and AdRotator
Why we use validation controls? List various types of controls used in
</asp:TableRow> </asp:Table> controls Ans) The rich data controls include the following:
asp.net Ans)  Validation is important part of any web application. User's
GridView: The GridView is an all-purpose grid control for showing
input must always be validated before sending across different layers of
Explain Adrotator control with example in ASP.NET Ans) The AdRotator large tables of information. The GridView is the heavyweight of ASP.NET
the application. Validation controls are used to: Implement
is one of the rich web server control of asp.net. AdRotator control isused data controls.  DetailsView: The DetailsView is ideal for showing a
presentation logic. To validate user input data. Data format, data type
to display asequence of advertisement images as per given priority of single record at a time, in a table that has one row per field. The
and data range is used for validation. Validation Controls in ASP.NET An
image. Adrotator control display the sequence of images, which is DetailsView also supports editing.  FormView: Like the DetailsView, the
important aspect of creating ASP.NET Web pages for user input is to be
specified in the external XML file. In xml file we indicate the images to FormView shows a single record at a time and supports editing. The
able to check that the information users enter is valid. ASP.NET provides
display with some other attributes like image impressions, difference is that the FormView is based on templates, which allow you
a set of validation controls that provide an easy-to-use but powerful way
NavigateUrl,ImageUrl, AlternateText. In Adrotator control images will to combine fields in a flexible layout that doesn’t need to be table based.
to check for errors and, if necessary, display messages to the user. There
be changed each time while refreshing the web page. AdRotator Control  ListView: The ListView plays the same role as the GridView—it allows
are six types of validation controls in ASP.NET
Example in ASP.Net The basic syntax of adding an AdRotator is as you to show multiple records. The difference is that the ListView is
follows: <asp:AdRotator runat = "server" AdvertisementFile = based on templates. As a result, using the ListView requires a bit more
Validation Control Description
"adfile.xml" /> The advertisement file is an XML file, which contains the work and gives you slightly more layout flexibility. Calendar Control
RequiredFieldValidation Makes an input control a required
information about the advertisements to be displayed. advertisement The Calendar control is used to display a calendar in the browser. The
field
file: The following code illustrates an advertisement file ads.xml: control allows you to select dates and move to the next or previous
CompareValidator Compares the value of one input
<Advertisements> <Ad> <ImageUrl>rose1.jpg</ImageUrl> control to the value of another input month. You can customize the appearance of the Calendar control by
<NavigateUrl>http://www.1800flowers.com</NavigateUrl> control or to a fixed value setting the properties that control the style for different parts of the
<AlternateText> Order flowers, roses, gifts and more </AlternateText> RangeValidator Checks that the user enters a value control. The following ASP.NET program displays the selected Calendar
<Impressions>20</Impressions> <Keyword>flowers</Keyword> that falls between two values date in short date format in a label control. e.g. Default.aspx
<Ad> <ImageUrl>rose2.jpg</ImageUrl> RegularExpressionValidator Ensures that the value of an input <body> <form id=”form1” runat =”server”> <div>
<NavigateUrl>http://www.babybouquets.com.au</NavigateUrl> control matches a specified pattern <asp:Calendar ID=”Calendar1” runnat=’’server’’ onSelectionchanged=”
<AlternateText>Order roses and flowers</AlternateText> CustomValidator Allows you to write a method to Calendar1_ Selectionchanged”></asp:Calendar> <br/>
<Impressions>20</Impressions> <Keyword>gifts</Keyword> handle the validationof the value <asp:Label ID=’’Label1’’ runnat=’’server’’ Text=’’Label’’></asp:Label>
</Ad> <Ad> <ImageUrl>rose3.jpg</ImageUrl> entered </div> </form> </body>
<NavigateUrl>http://www.flowers2moscow.com</NavigateUrl> ValidationSummary Displays a report of all validation
errors occurred in a Web page
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions> <Keyword>russia</Keyword>
</Ad> </Advertisements> Create a new web page and place an
AdRotator control on it. <form id="form1" runat="server"> <div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile
="~/ads.xml" onadcreated="AdRotator1_AdCreated" /> </div>
</form>
What is an event ? How is an event handler added? (Nov 2022) An event List and explain any five template to create ASP.NET application. Ans) In What is user-defined exception? Explain with example. (Ans) We have
in ASP.NET is a specific occurrence or action that takes place during the ASP.NET, you can create web applications using various project seen built-in exception classes however, we often like to raise an
execution of a web application, such as a button click, page load, or templates that provide a starting point for different types of applications. exception when thebusiness rule of our application gets violated. So, for
control interaction. Events are used to trigger specific code or Here are five common project templates for creating ASP.NET this we can create a custom exception class byderiving Exception or
functionality in response to user actions or system events. Events are a applications, along with brief explanations of each: 1. ASP.NET Web ApplicationException class. For example, create
fundamental part of event-driven programming in ASP.NET, allowing Forms Application: - This template is used for creating traditional web InvalidStudentNameException class in a school application, which does
developers to respond to user interactions and control the flow of their applications using Web Forms technology. - Web Forms provide a drag- not allow any special character or numeric value in a name of any of the
applications. In ASP.NET, events follow a publisher-subscriber model, and-drop UI design approach and allow you to build web applications students. class Student { public int StudentID { get; set; }
where an object (the publisher) raises an event, and other objects with server controls. - It's suitable for projects that require a rapid public string StudentName { get; set; } }
(subscribers or event handlers) respond to that event by executing development cycle and are focused on delivering web forms-based user class InvalidStudentNameException : Exception {
predefined code or methods. Adding an event handler in ASP.NET interfaces. 2. ASP.NET MVC (Model-View-Controller) Application: - public InvalidStudentNameException( ) { } public
involves the following steps: 1. Define the Event Handler Method: - MVC is a design pattern that separates the application into three InvalidStudentNameException(string name) :
Create a method in your code-behind file (e.g., .cs file for C# or .vb file for components: Model, View, and Controller. - ASP.NET MVC applications base(String.Format("Invalid Student Name: {0}", name)){ } }
Visual Basic) that will handle the event. This method should have the follow this pattern, making them ideal for building scalable and class Program { static void Main(string[ ] args) {
appropriate signature and logic to respond to the event. csharp maintainable web applications. - They provide greater control over the Student newStudent = null; try {
protected void Button_Click(object sender, EventArgs e) { // Code HTML output and are suitable for developers who prefer a structured newStudent = new Student(); newStudent.StudentName = "James007";
to handle the button click event } 2. Attach the Event Handler to and testable approach to web development. 3. ASP.NET Web API ValidateStudent(newStudent); }
the Control: - In your ASP.NET markup (the .aspx file), locate the control Application: - This template is used for creating RESTful API services in catch(InvalidStudentNameException ex) {
to which you want to attach the event handler. For example, if you want ASP.NET. - Web APIs are designed to expose data and functionality over Console.WriteLine(ex.Message ); } Console.ReadKey(); }
to handle a button click event, find the <asp:Button> control. html HTTP for consumption by various clients, such as web applications, private static void ValidateStudent(Student std) {
<asp:Button ID="btnClick" runat="server" Text="Click Me" mobile apps, and other services. - ASP.NET Web API is a popular choice Regex regex = new Regex("^[a-zA-Z]+$");
OnClick="Button_Click" /> - In the control's attributes, specify the name for building robust and scalable APIs. 4. ASP.NET Core Web if (!regex.IsMatch(std.StudentName))
of the event handler method using the OnClick (for a button click event) Application: - ASP.NET Core is a cross-platform framework for building throw new InvalidStudentNameException(std.StudentName); } }
or the appropriate event attribute for the specific event you are handling. modern web applications. - This template allows you to create web
3. Implement the Event Handler Logic: - In the event handler method applications that can run on Windows, macOS, or Linux. - It provides What is URL mapping ? How is URL mapping and routing
(e.g., Button_Click), write the code that should execute when the event support for various application types, including web applications, APIs, implementation In ASP.NET Ans) URL mapping and routing are
occurs. This code will respond to the user's action or the specific event and Razor Pages applications. 5. ASP.NET Blazor Application: - Blazor techniques used in ASP.NET to provide a way to define and handle URLs
raised by the control. csharp protected void Button_Click(object is a framework for building interactive web applications using C# and for web applications. They enable developers to create user-friendly
sender, EventArgs e) { // Code to handle the button click event .NET, both on the client and server. - The Blazor template enables you to and search engine friendly URLs and map them to specific resources or
LabelResult.Text = "Button Clicked!"; } 4. Compile and Run: Build create single-page applications (SPAs) with a rich user interface. - It uses controllers. Both URL mapping and routing are used to decouple the
your ASP.NET application, and when you run it, the event handler will a component-based architecture similar to React or Angular, but you URL structure from the physical structure of the application, improving
execute when the specified event occurs on the control. In the example write C# code for the components. maintainability and flexibility. Here's an overview of URL mapping
above, we've added an event handler (Button_Click) for a button's click and routing in ASP.NET: 1. URL Mapping: - URL mapping is the process
event. When the button is clicked, the Button_Click method is executed, Unit- 3 of manually specifying how a URL should be mapped to a specific
changing the text of a label control (LabelResult) to indicate that the resource, file, or page in your application. - It typically involves defining
button was clicked. Event handling in ASP.NET allows you to create What is Debugging? Explain in ASP.NET Ans) Debugging allows the rules or patterns for URLs and specifying the corresponding physical file
interactive web applications by responding to user actions and system developers to see how the code works in a step-by-step manner, how the or handler that should process the request. - URL mapping is often used
events effectively. Different controls may have different events, so you values of the variables change, how the objects are created and with ASP.NET Web Forms applications, where you map URLs to .aspx
can handle various actions such as button clicks, page loads, data destroyed, etc. When the site is executed for the first time, Visual Studio pages. Example (Web.config for URL mapping in ASP.NET Web
binding, and more, as needed for your application. displays a prompt asking whether it should be enabled for debugging: Forms): xml <configuration> <system.web> <urlMappings>
 When debugging is enabled, the following lines of codes are shown in <add url="~/about" mappedUrl="~/AboutUs.aspx"/>
Explain any two site navigation controls in ASP.NET Ans) In ASP.NET, the web.config: <system.web> <compilationdebug="true"> <add url="~/contact" mappedUrl="~/ContactUs.aspx"/>
there are several site navigation controls available that help you create <assemblies> .............. </assemblies> </compilation> </urlMappings> </system.web> </configuration> In this
navigation menus and navigate between different pages of your website. </system.web>  The Debug toolbar provides all the tools available for example, URLs like "/about" and "/contact" are mapped to specific .aspx
Here are explanations for two commonly used site navigation controls: debugging: Breakpoints Breakpoints specifies the runtime to run a pages. 2. Routing: - URL routing is a more flexible and pattern-based
1. Menu Control:  The Menu control is used to create hierarchical specific line of code and then stop execution sothat the code could be approach for handling URLs. It is commonly used in ASP.NET MVC and
navigation menus on your web pages. It is rendered as an HTML list examined and perform various debugging jobs such as, changing the ASP.NET Core applications. - Routing allows you to define URL patterns
(typically an unordered list <ul>) with nested list items (<li>) value of the variables, stepthrough the codes, moving in and out of and map them to controller actions or methods, providing a more
representing the menu structure. You can define menu items and their functions and methods etc.  To set a breakpoint, right click on the code structured way to handle requests. - It uses route tables and route
hierarchies declaratively in the markup or programmatically in code- and choose insert break point. A red dot appears on the leftmargin and handlers to determine how incoming URLs should be processed.
behind. The Menu control supports various properties and events for the line of code is highlighted as shown: Next when you execute the Example (ASP.NET MVC RouteConfig.cs): csharp
customizing its appearance and behavior. It can be data-bound to a data code, you can observe its behavior At this stage, you can step through public class RouteConfig {
source, such as a sitemap or a database, to dynamically generate menu the code, observe the execution flow and examinethe value of public static void RegisterRoutes(RouteCollection routes) {
items. - Example usage: html <asp:Menu ID="menuNavigation" thevariables, properties, objects, etc.  We can modify the properties of routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute(
runat="server" DataSourceID="siteMapDataSource" the breakpoint from the Properties menu obtained by right clicking name: "Default", url: "{controller}/{action}/{id}", defaults: new {
Orientation="Horizontal" /> <asp:SiteMapDataSource thebreakpoint glyph: controller = "Home", action = "Index", id = UrlParameter.Optional } ); } }
ID="siteMapDataSource" runat="server" ShowStartingNode="false" /> In this example, the route table is configured to route URLs with the
2. TreeView Control: The TreeView control is used to create Why exception handling is required? Write syntax for user define pattern "{controller}/{action}/{id}" to corresponding controller actions.
hierarchical navigation menus similar to a file explorer or folder exception? Ans) Exception handling: The mechanism of Exception - Routing allows for dynamic and parameterized URLs, making it suitable
structure. It renders a hierarchical tree-like structure of expandable Handling is throwing an exception and catching it C#uses trycatchblock. for RESTful and SEOfriendly URLs.
and collapsible nodes. You can define tree nodes and their hierarchies Code which may give rise to exceptions is enclosed in a try block, and
declaratively in the markup or programmatically in code-behind. The Catch block catches that exception and handles it appropriately. The try Explain relation between content page and master page Ans)  Master
TreeView control is often used for scenarios where you need to display block is followed by one or more catch blocks. { //programming page provides a framework (common content as well as the layout)
data in a hierarchical manner, such as product categories or organization logic(code which may give rise to exceptions) } catch (Exception e) { withinwhich the contentfrom other pages can be displayed.  It provides
charts. It supports properties and events for customizing its //message on exception } Finally { // always executes } Try: elements such as headers, footers, style definitions, or navigation
appearance and behavior, including templates for defining custom node A try block identifies a block of code for which particular exceptions will barsthat are commonto all pages in your web site.  So the Content
content. Example usage: html <asp:TreeView beactivated. It's followed by one or more catch blocks. Catch: A program Pages need not have to duplicate code for shared elements within
ID="treeViewNavigation" runat="server"> <Nodes> catches an exception with an exception handler at the place in a yourWeb site.  It gives a consistent look and feel for all pages in your
<asp:TreeNode Text="Home" Value="Home"> programwhere you want to handle the problem. The catch keyword application.  The master page layout consists of regions where the
<asp:TreeNode Text="Products" Value="Products"> indicates the catching of an exception. Finally: The finally block is used content from each content pageshould bedisplayed.  These regions can
<asp:TreeNode Text="Category 1" Value="Category1" /> to execute a given set of statements, whether an exceptionis thrown or be set using ContentPlaceHolder server controls.  These are the
<asp:TreeNode Text="Category 2" Value="Category2" /> not thrown. For example, if you open a file, it must be closed whether an regions where you are going to have dynamic content in your page  A
</asp:TreeNode> <asp:TreeNode Text="Services" Value="Services" /> exception israised or not. Example: using System; class tryCatch { derived page also known as a content page is simply a collection of
</asp:TreeNode> <asp:TreeNode Text="About" Value="About" /> public static void Main() { int k=0; try { blocks the runtimewill use tofill the regions in the master.  To provide
</Nodes> </asp:TreeView> These site navigation controls simplify int n= 10/k; Console.WriteLine(”n=” + n); } catch(Exception e) content for a ContentPlaceHolder, you use another specialized control,
the creation of navigation menus and hierarchical structures in your { Console .WriteLine (“Division By zero exception”); } called Content.  The ContentPlaceHolder control and the Content
ASP.NET web applications. You can choose the one that best suits your Console.WriteLtne(”Statement executed after Exception because of try
control have a one-to-one relationship.  For each ContentPlaceHolder
navigation requirements, whether you need a simple menu or a catch”); }
in the master page, the content page supplies a matching Contentcontrol
hierarchical tree structure.  ASP.NET links the Content control to the appropriate
What are the three different ways to use style on web page? Explain
ContentPlaceHolder by matching theID of the ContentPlaceHolder with
Brief about graphics class and it’s any 5 methods Ans) In ASP.NET, you various category of style setting in new style dialog box. Ans) Three
the Content ContentPlaceHolderID property of the corresponding
can use the Math class from the System namespace to perform different ways to apply styles to a web page in ASP.NET or web
Content control
mathematical operations. Here are five common properties and methods development in general are: 1. Inline Styles: Inline styles are applied
of the Math class along with explanations: 1. Math.PI Property: - The directly to individual HTML elements using the style attribute. They are
Explain the events in global.asax file with respect to state management
Math.PI property provides the mathematical constant π (pi), which is specified within the HTML tag itself and override any external or
Ans) To manage a session, ASP.NET provides two events: session_start
approximately equal to 3.141592653589793. - You can use this internal styles. Example: html <p style="color: blue; font-size:
and session_end that is written in a special file called Global.asax in the
property when performing calculations involving circles, angles, and 16px;">This is an example of an inline style.</p> - Advantages:
root directory of the project. Session_Start: The Session_start event is
trigonometric functions. csharp double circleArea = Quick and easy to apply styles to specific elements. - Disadvantages: Not
raised every time a new user makes a request without a session ID, i.e.,
Math.PI * Math.Pow(radius, 2); 2. Math.Abs() Method: - The recommended for large-scale styling, and it can make the HTML code
new browser accesses the application, then a session_start event raised.
Math.Abs() method returns the absolute value of a numeric expression, less maintainable. 2. Internal/Embedded Styles: Internal or embedded
Let's see the Global. asax file. void Session_Start(object sender,
effectively removing the sign of a number. - It is commonly used to styles are defined within the section of an HTML document. They apply
EventArgs e) { Session["Count"] = 0; // Code that runs when a
ensure that a value is positive, regardless of its original sign. csharp to elements on the current page. Example: html <head> <style>
new session is started } Session_End: The Session_End event is
double absoluteValue = Math.Abs(-10.5); // Result: 10.5 3. p{ color: green; font-size: 18px; } </style> </head> <body>
raised when session ends either because of a time out expiry or explicitly
Math.Sqrt() Method: - The Math.Sqrt() method calculates the square <p>This is an example of an embedded style.</p> </body> -
by using Session.Abandon(). The Session_End event is raised only in the
root of a number. - It is useful for finding the lengths of sides in right Advantages: Styles are defined within the HTML document, making it
case of In proc mode not in the state server and SQL Server modes.
triangles or for other geometric calculations. csharp double more organized than inline styles. - Disadvantages: Limited reusability,
There are three types of events in ASP.NET. Application event is written
squareRoot = Math.Sqrt(25.0); // Result: 5.0 4. Math.Round() Method: as styles are specific to the current page. 3. External Stylesheets:
in a special file called Global.asax. This file is not created by default, it is
- The Math.Round() method rounds a floating-point number to the External stylesheets are separate CSS (Cascading Style Sheets) files that
created explicitly by the developer in the root directory. An application
nearest integer or a specified number of decimal places. - It is commonly are linked to HTML documents using the <link> element. They allow you
can create more than one Global.asax file but only the root one is read by
used for rounding numeric values for display or precision control. to maintain a consistent style across multiple pages. Example
ASP.NET. void Application_Start(object sender, EventArgs e) {
csharp double roundedValue = (styles.css): css /* styles.css */ p { color: red;
Application["Count"] = 0; } Application_Error: It is raised when
Math.Round(3.456, 2); // Result: 3.46 5. Math.Max() and font-size: 20px; } html <head>
an unhandled exception occurs, and we can manage the exception in this
Math.Min() Methods: - The Math.Max() method returns the larger of <link rel="stylesheet" type="text/css" href="styles.css"> </head>
event. Application_End: The Application_End event is raised just
two numeric values. - The Math.Min() method returns the smaller of two <body> <p>This is an example of an external stylesheet.</p>
before an application domain ends because of any reason, may IIS server
numeric values. - These methods are useful when you need to determine </body> - Advantages: Centralized and reusable styles that can be
restarting or making some changes in an application cycle.
the maximum or minimum value among a set of values. csharp applied to multiple pages. - Disadvantages: Requires an additional
int maxValue = Math.Max(10, 15); // Result: 15 int minValue = HTTP request to load the stylesheet.
Math.Min(5, 8); // Result: 5
Describe features and benefits of master page in asp.net ? Ans)  Significant of ViewState in ASP.NET Or What is ViewState in Unit-4
ASP.NET master pages allow us to create a consistent layout for the ASP.NET?State its advantage and disadvantage Ans) View State  View
pages in our application.  A single master page defines the look and feel State is the method to preserve the Value of the Page and Controls List and Explain ADO .NET objects. Ans) ADO.NET includes many objects
and standard behavior that we wantfor all of the pages(or a group of betweenround trips. It is aPage-Level State Management technique.  we can use to work with data. Some important objects of ADO.NETare:
pages) in our application.  We can then create individual content pages View State is turned on by default and normally serializes the data in Connection To interact with a database, we must have a connection to it.
that contain the content we want to display.  When users request the every control onthe pageregardless of whether it is actually used during The connection helps identify the database server, the database name,
content pages, they merge with the master page to produceoutput a post-back. Features of View State These are the main features of view user name, password, and other parameters that are required for
thatcombines the layout of the master page with the content from the state:  Retains the value of the Control after post-back without using a connecting to the data base. A connection object is used by command
content page.  Master pages actually consist of two pieces, the master session.  Stores the value of Pages and Control Properties defined in objects so they will know which database to execute thecommand on.
page itself and one or more content pages. Use of Master Pages the page.  Creates a custom View State Provider that lets you store Command The command object is one of the basic components of ADO
The master pages can be used to accomplish the following: Creating View State  Information in a SQL ServerDatabase or in another data .NET. The Command Object uses theconnection object to execute SQL
a set of controls that are common across all the web pages and attaching store. Advantages of View State  Easy to Implement.  No server queries. The queries can be in the Form of Inline text, Stored Procedures
them toall theweb pages.  A centralized way to change the above resources are required: The View State is contained in a structure within or direct Table access. An important feature of Command object is that it
created set of controls which willeffectively change all theweb pages.  thepage load.  Enhanced security features: It can be encoded and can be used to execute queries and Stored Procedures withParameters If
To some extent, a master page looks like a normal ASPX page.  It compressed or Unicodeimplementation. Disadvantages of View State  a select query is issued, the result set it returns is usually stored in either
contains static HTML such as the , , and elements, and itcan also Security Risk: The Information of View State can be seen in the page a DataSet or a DataReader object. DataReader Many data operations
containother HTML and ASP.NET server controls.  Inside the master output sourcedirectly. We can manually encrypt and decrypt the require that we only get a stream of data for reading. The data reader
page, you set up the markup that you want to repeat on everypage, like contents of a Hidden Field, but Itrequires extra coding. If security is a object allows us to obtain the results of a SELECT statement from a
command object. For performancereasons, the data returned from a data
thegeneral structure of the page and the menu.  However, a master concern, then consider using a Server-Based State Mechanism so that no
sensitive information issent to the client.  Performance: Performance is reader is a fast forward-only stream of data. This means that we can only
page is not a true ASPX page and cannot be requested in thebrowser
pull the data from the stream in a sequential manner this is good for
directly itonly serves as the template that real web pages called content not good if we use a large amount of data because View State is storedin
speed, but if we need to manipulate data, then a DataSet is a better
pages  One difference is that while web forms start with the Page the page itself and storing a large value can cause the page tobe slow. 
object to work with. DataSet DataSet objects are in-memory
directive, a master page startswith aMaster directive that specifies the Device limitation: Mobile Devices might not have the memory capacity to
representations of data. They contain multiple Datatable objects, which
same information, as shown here store alarge amount ofView State data.  It can store values for the same
contain columns and rows, just like normal database tables. We can even
%@Master Language=”C#” AutoEventWireup=”true” page only. Example: If we want to add one variable in View State,
define relationsbetween tables to create parent-child relationships. The
CodeFile=”MasterPage.master.cs”Inherits=”MasterPage”% ViewState["Var"]=Count; For Retrieving information from View State
DataSet is specifically designed to help manage data in memory and to
string Test=ViewState["TestVal"];
support disconnectedoperations on data, when such a scenario make
What is state management? Explain Application state management Ans)
sense. DataAdapter The data adapter fills a DataSet object when
 A web application is stateless. That means that a new instance of a Explain the four most important selectors present in CSS. Ans)
reading the data and writes in a single batch when persisting changes
page is created everytime when we make a request to the server to get Universal Selector The Universal selector, indicated by an asterisk (*),
back to the database. A data adapter contains a reference to the
the page and after the round trip our page has been lostimmediately. It applies to all elements in your page. The Universalselector can be used to
connection object and opens and closes the connection automatically
only happens because of one server, all the controls of the Web Page are set global settings like a font family. The following rule set changes the
when reading from or writing to the database.
created and after the round trip the server destroys all the instances. So, font for all elements in our page to Arial: *{ font-family: Arial; }
to retain the values of the controls we use state management techniques. Type Selector The Type selector enables us to point to an HTML
What is DataReader in ADO.NET? Explain with example. Ans) 
State Management Techniques They are classified into the following 2 element of a specific type. With a Typeselector allHTML elements of that
DataReader provides an easy way for the programmer to read data from
categories type will be styled accordingly. h1 { color: Green; } This Type
State Management in a database as if it werecoming from a stream. The DataReader is the
selector now applies to all elements in your code and gives them a green
ASP.Net solution for forward streaming data through ADO.NET. 
color. TypeSelectors are not case sensitive, so you can use both h1 and
dataDataReader is also called a firehose cursor or forward read-only
H1 to refer to thesame heading. ID Selector The ID selector is always
prefixed by a hash symbol (#) and enables us to refer to a singleelement cursor because it moves forwardthrough the data.  The DataReader not
Client Side State Server Side State
inthe page. Within an HTML or ASPX page, we can give an element a only allows us to move forward through each record of database, but it
Management Management
unique ID using the id attribute. With the ID selector, we can change the also enables us to parse the data from each column.  The
behavior for that single element, for example: #IntroText { DataReaderclass represents a data reader in ADO.NET. Example: In
1) View State 2) Control sate 1) Application State
font-style: italic; } Because we can reuse this ID across multiple below example we read the all records from customer table using
3) hidden Fields 4) Cookies 2) Session State
pages in our site (it only must be unique within a singlepage), you can DataReader class. string SQL = "SELECT * FROM Customers";
5) Query Strings 3) Profile Properties
use this rule to quickly change the appearance of an elementthat you use SqlConnection conn = new SqlConnection(ConnectionString);
Application State:  If the information that we want to be accessed or
once per page, but more than once in our site, for example with the // create a command object
stored globally throughout the application, even ifmultiple users access
following HTML code: <p id=”IntroText”>I am italic because I have the SqlCommand cmd = new SqlCommand(SQL, conn);conn.Open();
the site or application at the same time, then we can use an Application
right ID. </p> Class Selector  The Class selector enables us to style // Call ExecuteReader to return a DataReader SqlDataReader reader =
Objectfor such purposes.  It stores information as a Dictionary cmd.ExecuteReader(); Console.WriteLine("customer ID,
Collection in key - value pairs. This value is accessible across thepages of multiple HTML elements through the class attribute.  This handy when
Contact Name, " + "Contact Title, Address ");
the application / website.  There are 3 events of the Application which we want to give the same type of formatting to several unrelated HTML
Console.WriteLine("=============================");
are as follows Application_Start Application_Error Application_End elements.  The following rule changes the text to red and bold for all
while (reader.Read()) {
Example - Just for an example, I am setting the Page title in the HTML elements that have their class attributes set to highlight:
Console.Write(reader["CustomerID"].ToString( ) + ", ");
Application Start eventof theGlobal.asax file.  Code for setting value .Highlight { font-weight: bold;color: Red; }  The
Console.Write(reader["ContactName"].ToString( ) + ", ");
to the Application Object - "PageTitle" is the Key and "Welcome to State following code snippet uses the Highlight class to make the
Console.Write(reader["ContactTitle"].ToString( ) + ", ");
Management Application" is the value. void Application_Start(object contents of a <span> element and alink (<a>) appear with a bold
Console.WriteLine(reader["Address"].ToString( ) + ", "); }
sender, EventArgs e) { this.Application[“PageTitle”] = “Welcome typeface: This is normal text but <span class=”Highlight”>this is Red
//Release resourcesreader.Close(); conn.Close( );
to State Management Application”; } and Bold.</span>This is also normal text but <a href=”CssDemo.aspx”
//Release resourcesreader.Close(); conn.Close( );
Code for reading value from the Application Object class=”Highlight”>this link is Red and Bold as well.</a>
protected void Page_Load(object sender, EventArgs e) { Write short note on data binding? Ans) Data binding in ASP.NET is
if (! Page.IsPostBack) { this.Page.Title = Convert.ToString( Explain state management with persistence cookies Ans)  We all know
superficially similar to data binding in the world of desktop or
this.Application [“PageName”]); } } over the Internet communication between client and webserver happens
client/serverapplications, but in truth, it's fundamentally different.  In
through the HTTP protocol.  HTTP is a stateless protocol means
those environments, data bindinginvolves creating a direct connection
Write a short note on cookies in ASP.NET Ans)  A cookie is a small piece whatever communication happens between client and server,whatever
between a data source and a control in an application window. If the
of information stored on the client machine. This file is locatedon data flows among them could not be restored through this protocol. 
user modifies the data in a data-bound control, our program can update
clientmachines "C:\Document and Settings\Currently_Login When client means a browser requests for a particular page to a web
the correspondingrecord in the database, but nothing happens
user\Cookie" path.  It is used to store user preference information like server, Web server processes this requested page, create its object in its
automatically. ASP.NET data binding is much more flexible than old-
Username, Password, City and Phone No etc. on client machines. We own memory, render its HTML form & this requested page’s HTML form
style data binding.  Many of the most powerful data binding controls,
need to import namespace called Systen.Web.HttpCookie before we use will be delivered to client through HTTP protocol.  meanwhile Server
such as the GridView and DetailsView, give us unprecedented control
cookie. Types of Cookies: Persist Cookie - A cookie has not had expired destroys the page object that has been created in its own memory.Now
over thepresentation of our data, allowing us to format it, change its
time which is called as Persist Cookie NonPersist Cookie - A cookie has Server doesn’t have any record of processed page.  Hence various State
layout, embed it in other ASP.NET controls, and so on. Types of ASP.NET
expired time which iscalled as Non-Persist Cookie Creation of cookies: management techniques has been invented to preserve the states(data).
DataBinding Two types of ASP.NET data binding exist: single-value
It’s really easy to create a cookie in the Asp.Net with help of Response Types of State management techniques There are basically two types of
binding and repeated-value binding. Single-Value, or "Simple," Data
object or HttpCookie Creation of cookies: It’s really easy to create a State Management techniques in ASP.NET 1. Client Side state
Binding We can use single-value data binding to add information
cookie in the Asp.Net with help of Response object or HttpCookie management technique: Here it’s a responsibility of browser to keep a
anywhere on an ASP.NET page. We can even place information into a
Example 1: HttpCookie userInfo = new HttpCookie("userInfo"); track of State of controls (Data). There are various ways to implement
control property or as plain text inside an HTML tag. Single-value data
userInfo["UserName"] = "Annathurai"; userInfo["UserColor"] = "Black"; Client side state management. It varies according to the scope. I.
binding doesn't necessarily have anything to do with ADO.NET. Instead,
userInfo.Expires.Add(new TimeSpan(0, 1, 0)); Viewstate II. QueryString III. Cookies  In Viewstate the scope was
single- value data binding allows us to take a variable, a property, or an
Response.Cookies.Add(userInfo); Retrieve from cookie Its easy way limited upto one page.In QueryString the scope was limited from one
expression and insert it dynamically into a page. Repeated-Value, or
to retrieve cookie value form cookes by help of Request object. Example page to another page but there might be a need to store information of "List," Binding Repeated-value data binding allows us to display an
1: string User_Name = string.Empty;string User_Color = string.Empty; entire website altogether at a place. Here Cookies are the solutions.
entire table (or just a single field from a table).Unlike single-value data
User_Name = Request.Cookies["userName"].Value;User_Color = Cookies are small files that are created in the web browser’s memory (if
binding, this type of data binding requires a special control that supports
Request.Cookies["userColor"].Value; When we make request from client they’re temporary) or on the client’s hard drive (if they’re permanent). it. Typically, this will be a list control such as CheckBoxList or ListBox,
to web server, the web server process the request and give the lot of but it can also be a much moresophisticated control such as the
information with big pockets which will have Header information, Explain the different types of CSS present in ASP.NET. Ans) There are GridView.
Metadata, cookies etc., Thenrepose object can do all the things with three types of CSS as follows: External CSS Internal CSS or Embedded
browser. Cookie's common property: Domain: This is used to CSS Inline CSS External Style Sheet The first way to add CSS style What is a GridView control? Explain how to enable row selection, paging
associate cookies to domain. Secure: We can enable secure cookie to set sheets to your web pages is through the <link> element that points to an and sorting eatures of Grid View Ans) GridView control displays the
true (HTTPs). Value: We can manipulate individual cookie. Values: We external CSS file. For example the following <link> shows what options values of a data source in a table. Each column representsa field,while
can manipulate cookies with key/value pair. Expires: Which is used to you have when embedding astyle sheet in yourpage: <link each row represents a record. The GridView control supports the
set expire date for the cookies. Advantages of Cookie:  Its clear text so href=”StyleSheet.css” rel=”Stylesheet” type=”text/css” following features: • Binding to data source controls, such as
user can able to read it.  We can store user preference information on media=”screen” /> The href property points to a file within our site SqlDataSource. • Built-in sort capabilities. • Built-in update and delete
the client machine.  Its easy way to maintain.  Fast accessing. when we create links between twopages. The rel and type attributes tell capabilities. • Built-in paging capabilities. • Built-in row selection
Disadvantages of Cookie  If user clears cookie information we can't the browser that the linked file is in fact a cascading style sheet. The capabilities. • Multiple key fields. • Multiple data fields for the hyperlink
get it back.  No security.  Each request will have cookie information media attribute enables us to target different devices, including the columns. • Customizable appearance through themes and styles Sorting
with page. screen, printer, and handheld devices.The default for the media attribute allows the user to sort the items in the GridView control with respect to
is screen, so it’s OK. Embedded style sheet The second way to include a specific column byclicking on the column's header. To enable sorting,
style sheets is using embedded <style> elements. The <style> set the AllowSorting property to true. AllowSorting="True" Instead of
elementshould be placed at the top of your ASPX or HTML page, displaying all the records in the data source at the same time, the
betweenthe <head> tags. For example, to change the appearance of an GridView control canautomatically break the records up into pages. To
<h1> element in the current pagealone, we can addthe following code to enable paging, set the AllowPaging property to true.
the <head> of our page: <head runat=”server”> AllowPaging="True" Also we can set how many rows we want to see in
<style type=”text/css”>h1 { color: Blue; } </style> Inline style a page. PageSize="4" Example: <asp:gridview
sheet The third way to apply CSS to your HTML elements is to use inline AllowSorting="true" AllowPaging="true" PageSize="5"
styles. Because the styleattribute is already applied to a specific HTML ID="Gridview1" runat="server
element, we don’t need a selector and we canwrite thedeclaration in the DataKeyNames="pid" DataSourceID="SqlDS" > <Columns>
attribute directly: <span style=”color: White; background-color: Black <asp:BoundField DataField="pname" HeaderText="PRODUCT
;”> This is white text on a blackbackground. </span> NAME" SortExpression="pname"></asp:BoundField>
</Columns> </asp:gridview>
Explain various style property of grid view control Ans) The GridView Q17. Explain the ways of formatting the grid view data for display Ans) • Write short notes on data source controls. Or What is the use of data
control in ASP.NET provides various style-related properties that allow DataFormatString property of BoundField column can be used to source control? Explain various type of data source control in ASP.Net
you to customize the appearance of the grid and its elements. These configure the appearance of numbers and dates using a format string. • Ans) A data source control interacts with the data-bound controls and
properties can be set in the markup or programmatically in C#. Here are A format string takes the following form • {0:C} ,where 0 represents the hides the complex data binding processes. These are the tools
some of the commonly used style properties of the GridView control in value that will be formatted, and the letter ‘C’ indicates a predetermined that provide data to the data bound controls and support execution of
C#: 1. HeaderStyle: This property controls the style of the header row format style. <asp:BoundField DataField = "Price" HeaderText = "Price" operations like insertions, deletions, sorting, and updates. Each
of the GridView. csharp myGridView.HeaderStyle.CssClass = DataFormatString = "{0:C}" /> Formatting the grid view using the style: data source control wraps a particular data provider-relational
"header-style"; 2. RowStyle: This property allows you to define the style Style elements databases, XML documents, or custom classes and helps in: • Managing
for data rows in the GridView. csharp connection • Selecting data • Managing presentation aspects like paging,
myGridView.RowStyle.CssClass = "row-style"; 3. AlternatingRowStyle: Element Description caching, etc. • Manipulating data There are many data source
Similar to RowStyle, this property defines the style for alternating data RowStyle The style used for data rows. controls available in ASP.NET for accessing data from SQL Server, from
rows for better readability. csharp AlternativeRowStyle The style used for alternating data rows. ODBC or OLE DB servers, from XML files, and from business objects.
myGridView.AlternatingRowStyle.CssClass = "alt-row-style"; 4. SelectedRowStyle The style used when the row is selected. Based on type of data, these controls could be divided into two
SelectedRowStyle: This property sets the style for the selected row EditRowSttyle The style used when the row is being edited. categories: • Hierarchical data source controls • Table-based data
when a row is selected. csharp EmptyDataRowStyle The style used when the data source is empty. source controls The data source controls used for hierarchical data
myGridView.SelectedRowStyle.CssClass = "selected-row-style"; 5. ItemStyle The style used for an individual field. are: • XML Data Source - It allows binding to XML files and strings with
EditRowStyle: It specifies the style for the row when it's in edit mode. HeaderStyle The style used to format the header row. or without schema information. • Site Map Data Source - It allows
FooterStyle The style used to format the footer row.
csharp myGridView.EditRowStyle.CssClass = "edit-row-style"; binding to a provider that supplies site map information. The data
PagerStyle The style used to format the pager row.
6. PagerStyle: This property controls the style of the pager row, which source controls used for tabular data are:
<asp:GridView ID = "GridView1" runat = "server" DataSourceID =
includes navigation controls like Next, Previous, Page Numbers, etc.
"sourceProducts" AutoGenerateColumns = "False">
csharp myGridView.PagerStyle.CssClass = "pager-style"; Data source Description
<RowStyle BackColor = "#E7E7FF" ForeColor = "#4A3C8C" />
7. FooterStyle: Defines the style for the footer row of the GridView. Control
<HeaderStyle BackColor = "#4A3C8C" Font-Bold = "True" ForeColor =
csharp myGridView.FooterStyle.CssClass = "footer-style"; Sql Data Source It represents a connection to an ADO.NET
"#F7F7F7" /> <Columns>
data provider that returns SQL data, including
<asp:BoundField DataField = "ProductID" HeaderText = "ID" /> data sources accessible via OLEDB and ODBC.
Write any three similarities between FormView and DetailsView
<asp:BoundField DataField = "ProductName" HeaderText = "Product ObjectDataSource It allows binding to a custom .Net business
controls. Explain about item templates of form view Ans) FormView and
Name" /> object that returns data.
DetailsView are two ASP.NET Web Forms controls used for displaying
<asp:BoundField DataField = "UnitPrice" HeaderText = "Price" /> LinqDataSource It allows binding to the results of a Linq-to-
and editing data. Here are three similarities between FormView and
</Columns> </asp:GridView> SQL query (supported by ASP.NET 3.5 only).
DetailsView controls: 1. Data Presentation: - Both FormView and
DetailsView controls are used to display and edit data from a data AccessDataSource It represents connection to a Microsoft Access
Briefly explain FormView control. How is it different from DetailsView? database.
source, such as a database. - They provide a way to view and interact
Or Difference between Form view and details view in ASP.NET Ans) 
with a single record at a time. 2. Template-Based Rendering: - Both
Like DetailsView, FormView also displays a single record from the data
controls use templates for rendering their content. Templates allow you
source at a time. Bothcontrols can be used to display, edit, insert and Unit-5
to customize the layout and appearance of the control. - You can define
delete database records but one at a time. Both have paging feature and
templates for various modes, such as ItemTemplate, EditItemTemplate,
hence support backward and forward traversal.  FormView is a new What is XmlTextWriter? Explain with example Ans) XmlTextWriter is
and InsertItemTemplate, to control how data is presented in different
states. 3. Data Binding: - FormView and DetailsView controls support data-bound control that is nothing but a templated version of one of many useful classes in System.Xml namespace, and it provides
data binding to bind data source fields to various controls within their DetailsViewcontrol. The major difference between DetailsView and several usefulmethods to write a complete XML Document from scratch.
FormView is, here user need to define the rendering template for each Following form is simple ASP.NET web form asking user to input some
templates. - They provide a flexible way to bind data to controls like
labels, textboxes, and buttons within the templates. Now, let's discuss the item.  The FormView control provides more formatting and layout data about the product. I willsave this data in a separate XML document
"Item Templates" of the FormView control in more detail: The FormView options than DetailsView.  The DetailsView control uses elements or named Product.xml using XmlTextWriter object.
control allows you to define templates for different modes, including elements to display bound data whereas FormView can use only
ItemTemplate. The ItemTemplate is used to specify how a single record templates to display bound data.  The FormView control renders all
should be displayed in the read-only (noneditable) mode. Here's how fields in a single table row whereas the DetailsViewcontrol display seach
you can use it in C#: Html: <asp:FormView ID="MyFormView" field as a table row.  When compare to DetailsView, the FormView
runat="server" DataSourceID="MyDataSource" control provides more control overthe layout.  Following are some
DefaultMode="ReadOnly"> <ItemTemplate> important properties that are very useful. Templates of the
<!-- Place data-bound controls or HTML elements here --> FormView Control- 1) EditItem Template- The template that is used
<asp:Label ID="lblEmployeeName" runat="server" Text='<%# when a record is being edited. 2) InsertItem Template- The template
Eval("EmployeeName") %>' /> <asp:Label ID="lblDepartment" that is used when a record is being created. 3) Item Template- The
runat="server" Text='<%# Eval("Department") %>' /> template that is used to render the record to display only.
<!-- Add more controls as needed --> </ItemTemplate> Methods of the FormView Control 1) ChangeMode-
</asp:FormView> In this example, we have a FormView control ReadOnly/Insert/Edit. Change the working mode of the control from the
with an ItemTemplate. Inside the ItemTemplate, we use data-bound current to the defined FormViewMode type. 2)InserItem- used to insert
controls like <asp:Label> to display the values of fields from the data the record /into database. This method must be called when the
Following C# code is saving all the user input values in XML file.
source. The Eval function is used to bind specific data source fields to DetailsView control is in insert mode. 3) UpdateItem- Used to update
protected void Button1_Click(object sender, EventArgs e) {
these controls. the current record into database. This method must be called when
XmlTextWriter writer = null; try {
DetailsView control is in edit mode. 4) DeleteItem- Used to delete the
string filePath = Server.MapPath("~") + "\\Product.xml";
Write a short note on selecting a Grid view row. Ans) • Selecting an item current record from database.
writer = new XmlTextWriter(filePath, System.Text.Encoding.UTF8);
refers to the ability to click a row and have it change color (or become writer.Formatting = Formatting.Indented;
highlighted) to indicate that the user is currently working with this writer.WriteComment("Created On: " + DateTime.Now.ToString("dd-
record. • Adding a Select Button for each row of a GridView • Method 1 • MMM-yyyy"));
By setting AutoGenerateSelectButton attribute of GridView to True. • Differentiate between DataSet and DataReader
writer.WriteComment("===============================");
This SelectedIndexChanged event of the GridView is triggered when a writer.WriteStartElement("Product");
row's Select button is clicked. • • Method 2 • This can aloso be achieved DataSet DataReader writer.WriteAttributeString("ProductID", TextBox1.Text);
by adding a CommandField column with • the ShowSelectButton The DataSet class in ADO.Net DataReader is a connection writer.WriteElementString("ProductName", TextBox2.Text);
property set to true. • <asp:CommandField ShowSelectButton="true" operates in an entirely oriented service. writer.WriteElementString("ProductQuantity", TextBox3.Text);
SelectText="Select College" ButtonType="Link" /> • Method 3 • This can disconnected nature. writer.WriteElementString("ProductPrice", TextBox4.Text);
aloso be achieved by adding a ButtonField column with • the writer.WriteEndElement(); writer.WriteEndDocument();
CommandName property set to “Select”. <asp:ButtonField DataSet is an in-memory DataReader is designed to writer.Flush(); Response.Redirect("Product.xml"); }
CommandName="Select" Text="Select College" ButtonType="Button" /> representation of a collection of retrieve a read-only, forward- catch (Exception ex){ } }
Database objects including only stream of data from data
What is the application services provided in ASP.NET? Explain. Or related tables, constraints, and sources.
What is authorization? Explain adding authorization rules in web.config
Describe asp.net provider model and direct data access method. Ans) relationships among the tables. file Ans) Authentication & Authorization are two interconnected
ASP.NET 4 ships with a number of application services, of which the security concepts. First is process of identifying a user and authorization
most important ones are: Membership: Enables us to manage and work It fetches entire table or tables It fetches one row at a time so is the process of checking whether authenticated user has access to the
with user accounts in our system. Roles: Enables us to manage the roles at a time so greater network very less network cos. resource which they requested Two form of Authorization: File: it is
that your users can be assigned to. Profile: Enables us to store user- cost. performed by the File Authorization Module . It uses the access control
specific data in a back-end database. Figure below gives an list (ACL) of the .aspx file to resolve whether a user should have access to
overview of these services and shows how they are related to our DataSet is not read-only so we DataReader is readonly so we the file. ACL permissions are confirmed for the users windows identity.
website andthe underlying data stores that the services may use. can do any transaction on them. can't do any transaction on 2) URL: in the web.config file you can specify the authorization rules for
them. various directories of files using the element. Syntax is :
<system.web> <authorization> <system.web>
DataAdapter is used to get data DataAdapter is not required <authorization> <allow user =”abc”/> <deny user=”*”/>
in DataSet </authorization> <system.web> <allow user =”abc”/>
<deny user=”*”/> </authorization> <system.web>
Dataset works with the help of DataReader doesn't provide this
xml technology feature Explain the use of Timer control in AJAX. Or Explain about
implementation of timed refresh of update panel using timer Ans) Timer
Example: Dataset ds=new Example: Sqlcommand cmd controls allow us to do postbacks at certain intervals. If used together
Dataset (); =new sqlcommand (select * with UpdatePanel, whichis the most common approach, it allows for
from emptable); timed partial updates of our page, but it can be used for posting back the
A provider is software that provides a standardized interface between a Data Reader dr= entire page as well. •The Timer control uses the interval attribute to
DataAdapter1 Fill(ds,
service and a datasource. ASP.NET providers are as follows:  cmd.ExecuteReader ( ) define the number of milliseconds to occur beforefiring the Tick event.
"newtablename") // where
Membership  Role management  Site map  Profile  Session state newtablename is table alias <asp:Timer ID="Timer1" runat="server" Interval="2000"
etc. At the top of the diagram you see the ASP.NET 4 web sites and web name in dataset OnTick="Timer1_Tick"> </asp:Timer> Example: Here is a
applications that represent theweb sites that you build. These web sites small example of using the Timer control. It simply updates a timestamp
can contain controls like the login controls that in turn cantalk to the every 5 seconds.
ASP.NET application services such as membership and profile. To create <asp:ScriptManager ID="ScriptManager1" runat="server" />
a flexible solution, these services don’t talk to an underlying data source <asp:Timer runat="server" id="UpdateTimer" interval="5000"
directly, but instead talk to a configuredprovider. A provider is an ontick="UpdateTimer_Tick" /> <asp:UpdatePanel
interchangeable piece of software that is designed for a specific task. For runat="server" id="TimedPanel" updatemode="Conditional">
example, in the case of the membership services, the membership <Triggers> <asp:AsyncPostBackTrigger
provider is designed to work with users in the underlying data store. You controlid="UpdateTimer" eventname="Tick" /> </Triggers>
can configure different providers for the same application service <ContentTemplate>
dependingon your needs <asp:Label runat="server" id="DateStampLabel" />
</ContentTemplate> </asp:UpdatePanel> We only have a single
CodeBehind function, which we should add to our CodeBehind file:
protected void UpdateTimer_Tick(object sender, EventArgs e) {
DateStampLabel.Text = DateTime.Now.ToString(); }
Define Authentication and authorization .Give type of Authentication Steps to use Windows authentication with sample code Ans) • When we
Ans) Authentication : It is the process of ensuring the user's identity configure our ASP.NET application as windows authentication it will use
and authenticity. ASP.NET allows three types of authentications: • local windows userand groups to do authentication and authorization
Windows Authentication • Forms Authentication • Windows LiveID for our ASP.NET pages. •In ‘web.config’ file set the authentication mode
Authentication Windows-based authentication: •It causes the browser to ‘Windows’ as shown in the below code snippets. <authentication
to display a login dialog box when the user attempts to access restricted mode="Windows"/> We also need to ensure that all users are
page. •It is supported by most browsers. •It is configured through the IIS denied except authorized users. The below code snippetinside the
management console. •It uses windows user accounts and directory authorization tag that all users are denied. ‘?’ indicates any
rights to grant access to restricted pages I. Forms-based <authorization> <deny users="?"/> </authorization>
authentication: •Developer codes a login form that gets the user name We also need to specify the authorization part. We need to insert the
and password. •The username and password entered by user are below snippet in the ‘web.config’ file .stating that only ‘Administrator’
encrypted if the login page uses a secure connection. •It doesn’t reply on users will have access to <location path="Admin.aspx">
windows user account. II. Windows Live ID authentication: •It is <system.web> <authorization>
centralized authentication service offered by Microsoft. •The advantage <allow roles="questpon-srize2\Administrator"/>
is that the user only has one maintain one username and password. <deny users="*"/> </authorization> </system.web>
Authorization: •Authorization refers to the process that determines </location> The next step is to compile the project and upload the
what a user is able to do. For example, an administrative user is allowed same on an IIS virtual directory. On the IIS virtual directory we need to
to create a document library, add documents, edit documents, and delete ensure to remove anonymous access and check the integrated
them. •A non-administrative user working with the library is only windowsauthentication. Now if we run the web application we will be
authorized to read the documents. •Authorization is orthogonal and popped with a userid and password box.
independent from authentication. However, authorization requires an
authentication mechanism. •Authentication is the process of What do you mean by Impersonation in ASP.NET? Ans) •ASP.NET
ascertaining who a user is. Authentication may create one or more impersonation is used to control the execution of the code in
identities for the current user authenticated and authorized client. It is not a default process in the
ASP.NET application. •It is used for executing the local thread inan
Explain the reading process from an XML document with example Ans) application. •If the code changes the thread, the new thread executes the
The XDocument class contains the information necessary for a valid XML process identity by default. •The impersonation can be enabled in
document. This includes an XML declaration, processing instructions, two ways as mentioned below: Impersonation enabled: ASP.NET
and comments. •The XDocument makes it easy to read and navigate XML impersonates the token passed to it by IIS, can be an authenticated user
content. We can use the static XDocument.Load() method to read XML or an internet user account. The syntax for enabling is as shown below:
documents from a file, URI, or stream. Demo for XDocument: protected <identity impersonate=”true” /> Impersonation enabled for a
void ReadXmlUsingXMLDocument_Click(object sender, EventArgs e) { specific identity: ASP.NET impersonates the token generated using
XmlDocument doc = new XmlDocument(); theidentity specified in the Web.config file. <identity impersonate=”true”
doc.Load(Server.MapPath("~//item_mstr.xml")); userName=”domain\user” password=”password” />
XmlNodeList elemList = Impersonation disabled: It is the default setting for the ASP.NET
doc.GetElementsByTagName("item_name"); application. The process identity of theapplication worker process is the
for (int i = 0; i < elemList.Count; i++) { ASP.NET account. <identity impersonate=”false” />
ListBox2.Items.Add(elemList[i].InnerXml); } }
What is XElement? Explain with example Ans) •The XElement class
Explain Accordion in ASP.NET AJAX Control Toolkit Ans) •Accordion represents an XML element in System.Xml.XLinq. •XElement loads and
control provides us multiple collapsible panes or panels where only one parses XML.It allows us to remove lots of old code and eliminate the
can be expanded at a time. Each AccordionPane control has a template possibility of bugs and typos. •The XAttribute class represents an
for its Header and its content. •Accordion Web Control contains multiple attribute of an element. XElement.Save method saves the contents of
panes and shows one at a time. The panes contain content of images and XElement toa XML file. Example: Authors.xml
text having wide range of supported properties from formatting of the <?xml version="1.0" encoding="utf-8" ?> <Authors>
panes and text, like header and content templates, also it formats the <Author Name="Mahesh Chand">
selected header template. •Accordion contains multiple collapsible <Book>GDI+ Programming</Book> <Cost>$49.95</Cost>
panes while one can be shown at a time and the extended features of <Publisher>Addison-Wesley</Publisher> </Author>
accordion also has support data source which points to the <Author Name="Mike Gold">
DataSourceID and binds through .DataBind() method. •Example we <Book>Programmer's Guide to C#</Book> <Cost>$44.95</Cost>
have lot of paragraphs in a single page and we don’t have much space <Publisher>Microgold Publishing</Publisher> </Author>
and want to summarize in small space then we need to embed to the div <Author Name="Scot t Lysle"> <Book>Custom Controls</Book>
or some container which can hold allthe information in accordion <Cost>$39.95</Cost> <Publisher>C# Corner</Publisher>
collapsible pans. 1. Go to File, New, then Website and Create an Empty </Author> </Authors> Code Behind XElement allData =
Website. Add a webform (Default.aspx) in it. 2. Add ScriptManager from XElement.Load(Server.MapPath("~/App_Data/ Authors.xml")
AJAX Extensions (from v15.1 of AJAX Control Toolkit, ToolScriptManager if (allData != null) {
is removed. Use Standard Script Manager). 3. Go to AJAX Control Toolkit IEnumerable<XElement> authors = allData.Descendants("Author");
in Toolbox and drop Accordion Control on Default.aspx 4. Add foreach(XElement author in authors)
AccordionPane in Panes collection of the Accordion. •AccordionPane Response.Write ((string) author); }
contains two parts i.e. Header and Content. When AccordionPane is
collapsed, only Header part is visible to us. What is XML? List the various XML classes Ans) •Extensible Markup
Language (XML) stores and transports data. If we use a XML file to store
Explain ASP.NET AJAX Control Toolkit. Ans) •The Ajax Control Toolkit is the data then we can do operations with the XML file directly without
an open source library for web development. •The ASP.net Ajax using the database. The XML format is supported for all applications. • It
Controltoolkit contains highly rich web development controls for is independent of all software applications and it is accessible by all
creating responsive and interactive AJAX enabled web applications. applications. •It is a very widely used format for exchanging data, mainly
•ASP.Net Ajax Control Toolkit contains 40 + ready controls which is easy because it's easy readable for both humans and machines. •If we have
to use for fast productivity. •Controls are available in the Visual Studio ever written a website in HTML, XML will look very familiar to us, as it's
Toolbox for easy drag and drop integration with our web application. basically a stricter version of HTML. XML is made up of tags, attributes
•Some of the controls are like AutoComplete, Color Picker, Calendar, and values and looks something like this:
Watermark, Modal Popup Extender, Slideshow Extender and more of the <?xmlversion="1.0"encoding="utf-8"?> <EmployeeInformation>
useful controls. •The ASP.Net AJAX Control toolkit is now maintained by <Details> <Name>Richa</Name> <Emp_id>1</Emp_id>
DevExpress Team. The Current Version ofASP.Net AJAX Toolkit is <Qualification>MCA</Qualification> </Details>
v16.1.0.0. There are lot of new enhancement in the current version from </EmployeeInformation> XML Classes: ASP.NET provides a rich set of
new controls to bug fixes in all controls. The ASP.NET AJAX Control classes for XML manipulation in several namespaces that start with
Toolkit has a lot going for it:  It’s completely free.  It includes full System.Xml. The classes here allow us to read and write XML files,
source code, which is helpful if we’re ambitious enough to want to create manipulate XML data in memory,and even validate XML documents. The
our owncustom controls that use ASP.NET AJAX features.  It uses following options for dealing with XML data: XmlTextWriter The
extenders that enhance the standard ASP.NET web controls. That way, XmlTextWriter class allows us to write XML to a file. This class contains a
we don’t have toreplace all the controls on our web pages. number of methods and properties that will do a lot of the work for us.
To use this class, we create a new XmlTextWriter object. XmlTextReader
What is AJAX? Its Advantages and Disadvantages Ans) •Asynchronous Reading the XML document in our code is just as easy with the
JavaScript and XML (AJAX) is a development technique used to create corresponding XmlTextReader class. The XmlTextReader moves through
interactive webapplications or rich internet applications. •AJAX uses several our document from top to bottom, one node at a time. We call theRead()
existing technologies together, including: XHTML, CSS, JavaScript, Document method to move to the next node. This method returns true if there are
ObjectModel, XML, XSLT, and the XMLHttpRequest object. •With AJAX, web more nodes to read or false once it has read the final node. XDocument
applications can retrieve data from the server asynchronously, in the The XDocument class contains the information necessary for a valid XML
background,without reloading the entire browser page. The use of AJAX has document. This includes an XML declaration, processing instructions,
and comments. The XDocument makes it easy to read and navigate XML
led to an increase in interactive animation on web pages Advantages 
content. We can use the static XDocument.Load() method to read XML
Reduces the traffic travels between the client and the server.  No cross
documents from a file, URI, or stream.
browser pains.  Better interactivity and responsiveness.  With AJAX,
several multipurpose applications and features can be handled using a single
webpage(SPA).  API's are good because those work with HTTP method and
JavaScript. Disadvantages  Search engines like Google would not be able
to index an AJAX application.  It is totally built-in JavaScript code. If any
user disables JS in the browser, it won't work.  The server information
cannot be accessed within AJAX.  Security is less in AJAX applications as all
the files are downloaded at client side  The data of all requests is URL-
encoded, which increases the size of the request.

You might also like