asp interview question

59
ASP.NET INTERVIEW QUESTIONS Dategrid filtering and sorting How can we sort all the fields at once? first write one sql query and there include "order by (the column header of the datagrid what you have used"). How many types of page. THREE TYPES OF PAGE can we transfer data from one page to another page using viewstate if so how?if not y? No.from my knowledge can not.Bcos viewstate life time is in single page.So while going to another page first page viewstate end already.[yes we can by sessions, server.transver] How can we prevent an aspx page get refreshed when any information fetch from the database ? Using Update Pannel of Microsoft AJAX or using Simple Ajax What is the best way to search any exact information on google? use AJAX. How many view state can be hold by a aspx page ? A page have only one viewstate object [on the page_load we can increment the objecy and find it] code for inserting images into gridview colomns from database By using item template column in gridview control [It can be done in two ways. *First we maintain a table in database which have a column which would have image path on the server. *Second way to write byte in database for that you have to make byte[] object write in it first through making a class by using Input stream class.] i want to develope a page for online test using asp.net with c#.net. so, how to insert the questions in the database sqlserver2000 and how to pick the questions randomly when user login for test? the query for random selection is select * from tablename order by newid() how to create bin folder in asp.net2.0? By default it will comes under in solution explorer of the current project [In solution explorer by right clicking the website name >>Add Asp.net Folders>>Bin will add the Bin folder] What is the difference between User Controls and Master Pages Master pages and user controils are two different concepts. Master pages are used to provide the consistent layout and common behaviour for multiple pages in your applications.then u can add the Contenetplaceholder to add child pages custom contenet. User Controls:Sometimes u need the functionality in ur web pages which is not possible using the Built-In Web server controls then user can create his own controls called user controls using asp.net builtin controls.User controlsn are those with .aspx extensions and u can share it in the application. What is difference b/w Data Grid in ASP.Net 1.1 and Gridview in 2.0 Gridview is the replacement in .net 2.0 for the datagrid.the differences between them is >>sorting editing and paging are the additional capabilities in gridview which requires no coding while Datgrid requires the user coding .Gridview has improved databinding using smart tag.Additional column types and design time column operations.Customised pager UI using pager template.Customized paging support.[Datagrid has itemdatabound event but in gridview it is replaced by rowdatabound.In datagrid u can show more than one table with their relation while not possible in gridview.] How to use one project files into another project? Simply by copying that files in to current project directory. What is meant by role based security? when we use this one We can use role based security while we use forms authentication to authenticte users and roles are used to authorize i.e grant or deny access to particular pages in ur application depending upon the user role assigned to them. What are generics? why it is used? architecture of ASP.NET? 1

Upload: hemant026

Post on 10-Apr-2015

1.880 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: ASP Interview Question

ASP.NET INTERVIEW QUESTIONS

Dategrid filtering and sorting How can we sort all the fields at once?first write one sql query and there include "order by (the column header of the datagrid what you have used").How many types of page. THREE TYPES OF PAGEcan we transfer data from one page to another page using viewstate if so how?if not y? No.from my knowledge can not.Bcos viewstate life time is in single page.So while going to another page first page viewstate end already.[yes we can by sessions, server.transver]How can we prevent an aspx page get refreshed when any information fetch from the database ?Using Update Pannel of Microsoft AJAX or using Simple AjaxWhat is the best way to search any exact information on google? use AJAX.How many view state can be hold by a aspx page ? A page have only one viewstate object [on the page_load we can increment the objecy and find it]code for inserting images into gridview colomns from databaseBy using item template column in gridview control [It can be done in two ways. *First we maintain a table in database which have a column which would have image path on the server. *Second way to write byte in database for that you have to make byte[] object write in it first through making a class by using Input stream class.]i want to develope a page for online test using asp.net with c#.net. so, how to insert the questions in the database sqlserver2000 and how to pick the questions randomly when user login for test? the query for random selection is select * from tablename order by newid()how to create bin folder in asp.net2.0? By default it will comes under in solution explorer of the current project [In solution explorer by right clicking the website name >>Add Asp.net Folders>>Bin will add the Bin folder]What is the difference between User Controls and Master PagesMaster pages and user controils are two different concepts. Master pages are used to provide the consistent layout and common behaviour for multiple pages in your applications.then u can add the Contenetplaceholder to add child pages custom contenet. User Controls:Sometimes u need the functionality in ur web pages which is not possible using the Built-In Web server controls then user can create his own controls called user controls using asp.net builtin controls.User controlsn are those with .aspx extensions and u can share it in the application.What is difference b/w Data Grid in ASP.Net 1.1 and Gridview in 2.0Gridview is the replacement in .net 2.0 for the datagrid.the differences between them is >>sorting editing and paging are the additional capabilities in gridview which requires no coding while Datgrid requires the user coding .Gridview has improved databinding using smart tag.Additional column types and design time column operations.Customised pager UI using pager template.Customized paging support.[Datagrid has itemdatabound event but in gridview it is replaced by rowdatabound.In datagrid u can show more than one table with their relation while not possible in gridview.]How to use one project files into another project?Simply by copying that files in to current project directory.What is meant by role based security? when we use this oneWe can use role based security while we use forms authentication to authenticte users and roles are used to authorize i.e grant or deny access to particular pages in ur application depending upon the user role assigned to them.What are generics? why it is used? architecture of ASP.NET?

1

Page 2: ASP Interview Question

Generics are new in .NET 2.0.It is used to define a type while leaving some details unspecified.Generics are the replacement of "Objects" in .NET1.1 Generics reduces the run-time error and increases the performance.What is the DLL Hell Problem?As higher version Dll overwrites lower version Dll.This problem is referred to as dllhell .This is a drawback in Vb and eliminated in Dotnet by the concept of assemblies.with which controls you worked in Asp.net 2.0?GridView (Datagrid in asp.net 1.1)How many webforms are possible on a single webpage?n number of webpages u can have in a single webform.for example in a loginpage.aspx u can have 2 different iframes in that u can load 2 different pages.[In a single page n number of pages u take.Using different Layer]how can i insert array values and retreive in asp.net? Take Examplea[10]For i=0 to 9a[i]="value"what is the difference between assemblyinfo and webconfig files?An assemblyinfo contains all information about the manifest of the IL and it also contains the information about the strongname,version number of the assembly created.where the webconfig file contains all the information about the settings of the application including the assemblies information.Is string a value type or a reference type?String in .NET id 'Reference Type'.The reason is quite simple.All classes in the .NET Environment are 'Reference Type' & 'String' is a Class in .NET (not DataType as in VB 6.0)What is boxing?Boxing means convert value type to reference type[converting value type to reference type is called boxing.]How would one do a deep copy in .NET? Two or more pointers have their own Data.class A{string c;}A a;B b;a=b;//deep copy[class A{public A(){};public int i;}class TestPerson{ static void Main() {A a = new A();A b;a.i =5;b=a; // not a deep copyb.i = a.i+6;}}

here a.i=11 and b.i = 11 because a and b both refer same instance of object Deep copy would be implemented in c# using copy constructionclass A

2

Page 3: ASP Interview Question

{public A(){};public A(A previouscopy){i = previouscopy.i;};public int i;}class TestPerson{ static void Main() {A a = new A();a.i =5;// Create another new object, copying a.A b = new A(a); // Deep copy using copy constructorb.i = a.i+6;}}here a.i=5 and b.i = 11 because a and b both refer it's own instance of object]In the context of a comparison, what is object identity versus object equivalence?Object identity: when two things are refers to an instance of object.object Equivalence: when two things refer two instances with same valeWhat is the difference between a.Equals(b) and a == b?[no difference]

The Equals method is just a virtual one defined in System.Object, and overridden by whichever classes choose to do so. The == operator is an operator which can be overloaded by classes, but which usually has identity behaviour.

For reference types where == has not been overloaded, it compares whether two references refer to the same object - which is exactly what the implementation of Equals does in System.Object.

Value types do not provide an overload for == by default. However, most of the value types provided by the framework provide their own overload. The default implementation of Equals for a value type is provided by ValueType, and uses reflection to make the comparison, which makes it significantly slower than a type-specific implementation normally would be. This implementation also calls Equals on pairs of references within the two values being compared.

However, the main difference between the two types of comparison in normal use (where you're unlikely to be defining your own value types very often) is polymorphism. Operators are overloaded, not overridden, which means that unless the compiler knows to call the more specific version, it'll just call the identity version. To illustrate that, here's an example:using System;public class Test{

static void Main(){

// Create two equal but distinct strings string a = new string(new char[] {'h', 'e', 'l', 'l', 'o'}); string b = new string(new char[] {'h', 'e', 'l', 'l', 'o'});

3

Page 4: ASP Interview Question

Console.WriteLine (a==b); Console.WriteLine (a.Equals(b)); // Now let's see what happens with the same tests but // with variables of type object object c = a; object d = b; Console.WriteLine (c==d); Console.WriteLine (c.Equals(d));}}

The results are:True True False True

The third line is False because the compiler can only call the non-overloaded version of == as it doesn't know that the contents of c and d are both string references. As they are references to different strings, the identity operator returns false.

So, when should you use which operator? My rule of thumb is that for almost all reference types, use Equals when you want to test equality rather than reference identity. The exception is for strings - comparing strings with == does make things an awful lot simpler and more readable but you need to remember that both sides of the operator must be expressions of type string in order to get the comparison to work properly.

For value types, I'd normally use == for easier-to-read code. Things would get tricky if a value type provided an overload for == which acted differently to Equals, but I'd consider such a type very badly designed to start with.Contrast the use of an abstract base class against an interface?Abstract classes can provide implementations for methods and properties. Interfaces only provide required declarations.[A class can inherit only one absatract class, whereas the a class can inherit more than one interface.

An abstract class can have abstract as well as non abstract methods whereas the interface can have only the abstract methods.]What is the difference between a Debug and Release build? Is there a significant speed difference? Why or why not?[debug just do debugging the application while release do debugging as well as release the application] - The biggest difference between these is that:

In a debug build the complete symbolic debug information is emitted to help while debugging applications and also the code optimization is not taken into account. While in release build the symbolic debug info is not emitted and the code execution is optimized. Also, because the symbol info is not emitted in a release build, the size of the final executable is lesser than a debug executable.

- Usually they are configured to build differently. The debug build includes building debug symbols (the .pdb files that live next to the .dll assemblies) and doesn't perform code optimization which speeds up compiling a bit.What is the difference between Debug.Write and Trace.Write? When should each be used? Debug.write would not be compiled when the debug symbol is definedTrace.write would be compiled when the debug symbol is definedHow does the XmlSerializer work? What ACL permissions does a process using it require? One of the most powerful XML Schema features is its habilityto validate documents based on element types, instead of element names. That is no matter which element name is used in an instance document, say Customer, customer and CRMCustomer, as far as our XSD Schema makes them all inherit from say CustomerDef, the document will be valid. This is very important in interoperability scenarios, of course.That said, one of the most versatile and performat ways to handle XML in .NET (forget about

4

Page 5: ASP Interview Question

XmlDocument) is using the XmlSerializer class. Coupled with XSD.EXE or the technique I exposed in a previous post, you can easily autogenerate theclasses from that schema. So far so good. + For the curious, here's such a schema (a trivial one here of couse).<?xml version="1.0" encoding="utf-8" ?><xs:schema id="Customers" targetNamespace="http://www.lagash.com/schemas/customers" elementFormDefault="qualified" xmlns="http://www.lagash.com/schemas/customers" xmlns:mstns="http://www.lagash.com/schemas/customers" xmlns:xs="http://www.w3.org/2001/XMLSchema"> <xs:complexType name="CustomerDef"> <xs:sequence> <xs:element name="Name" type="xs:string" /> <xs:element name="EMail" type="xs:string" /> </xs:sequence> </xs:complexType> <xs:element name="customer" type="CustomerDef"></xs:element> <xs:element name="Customer" type="CustomerDef"></xs:element> <xs:element name="CustomerCRM"type="CustomerDef"></xs:element></xs:schema>+ And here are the different instance documents.<?xml version="1.0" encoding="utf-8" ?> <Customer xmlns="http://www.lagash.com/schemas/customers"> <Name>Daniel Cazzulino</Name> <EMail>[email protected]</EMail></Customer><?xml version="1.0" encoding="utf-8" ?> <customer xmlns="http://www.lagash.com/schemas/customers"> <Name>Daniel Cazzulino</Name> <EMail>[email protected]</EMail></customer><?xml version="1.0" encoding="utf-8" ?> <CustomerCRM xmlns="http://www.lagash.com/schemas/customers"> <Name>Daniel Cazzulino</Name> <EMail>[email protected]</EMail></CustomerCRM>

However, only one of the three versions will work, the one with the element "customer". The other versions, which are equally valid according to the schema, and which are of the desired type CustomerDef will fail with an exception saying the element was not expected. As I explained while discussing XmlSerializer speed, it creates a temporary assembly for reading and writing the serialized version of a type. We're interested in the reader now. When the XSD shown above is used to generate the XmlSerializable class, we get a class definition like the following:/// <remarks/>[System.Xml.Serialization.XmlTypeAttribute(Namespace="http://www.lagash.com/schemas/customers")][System.Xml.Serialization.XmlRootAttribute("customer",Namespace="http://www.lagash.com/schemas/customers",IsNullable=false)]public class CustomerDef { /// <remarks/> public string Name; /// <remarks/>

5

Page 6: ASP Interview Question

public string EMail;}From the definition above, the XmlSerializer will create the

temporary reader. The reader will contain a set of Read methods according to those serialization attributes. Using the technique explained in the aforemetioned post, I got the temporary generated class. The reader contains a Read4_customer method which is the one that tries to load the XML. The problem is that this method uses a stored string (taken from the serialization attributes) and performs an element name/namespace string comparison. Therefore, it will always fail with the other two valid rootelements. I found a very interesting thing though, while digginginside the generated reader. It has a method with the signature CustomerDef Read1_CustomerDef(bool isNullable, bool checkType) which is perfectly capable of loading the object. However, getting this far was very difficult. First, I had to add this temporary class to my project and make that method public, as it's private by default, and second, there's no "public" way of initializing this reader. You have to call an internal Init method on the base XmlSerializationReader class. Thanks GOD we still have reflection to test these things!

MethodInfo m = typeof(XmlSerializationReader).GetMethod( "Init", BindingFlags.Instance | BindingFlags.NonPublic);

using (FileStream c = new FileStream(@"C:\CustomerCRM.xml",FileMode.Open)){ XmlValidatingReader vr = new XmlValidatingReader(newXmlTextReader(c)); vr.Schemas.Add(xsd); // Create the temp. reader manuallyMicrosoft.Xml.Serialization.GeneratedAssembly.CustomerDefReadercr = newMicrosoft.Xml.Serialization.GeneratedAssembly.CustomerDefReader(); // Call Init through reflection m.Invoke(cr, new object[] { vr, null, null, null } ); // Read with the method that checks the type object cust = cr.Read1_CustomerDef( false, false ); Console.WriteLine(cust);}

That method will sucessfully load any of the three versions for the root element, either if they have the xsi:type attribute set, in which case the Read1_CustomerDef could use a true for the second parameter (checkType), or not. Another method that is generated and could work is Read2_Object, ifit receives checkType=true and the instance document uses xsi:type to specify that it's a CustomerDef instance (which is not always possible if you're receiving the document from a third party). Unfortunately, like I said above, the code that calls Read1_CustomerDef, and which is the one called by the serializer to load the XML, only checks for names: public object Read4_customer() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { if (((object) Reader.LocalName ==(object)id5_customer && (object) Reader.NamespaceURI ==(object)id2_httpwwwlagashcomschemascustomers)) { o = Read1_CustomerDef(false, true);} else { throw CreateUnknownNodeException();}} else {

6

Page 7: ASP Interview Question

UnknownNode(null);} return (object)o;}

Note the very efficient use of string reference comparison,by casting them to Object.

One way to solve this would be if the XmlRootAttribute couldbe specified multiple times, so that the generated code checks for multiple names.

The other, more XSD-compliant and certainly more flexible as it wouldn't require regeneration of the serializable class (CustomerDef in this case) to reflect new element names, would be to check if the current Reader is actually an XmlValidatingReader and read the customer if the type matches. The previous code can be modified as follows to make this work:

public object Read4_customer() { object o = null; Reader.MoveToContent(); if (Reader.NodeType == System.Xml.XmlNodeType.Element) { // Check for validating reader with schema type determined if (Reader is System.Xml.XmlValidatingReader && ((System.Xml.XmlValidatingReader) Reader).SchemaType!= null) { System.Xml.Schema.XmlSchemaType type =(System.Xml.Schema.XmlSchemaType) ((System.Xml.XmlValidatingReader) Reader).SchemaType; // We would have to check the inheritance chain too. if (((object) type.Name == (object)id1_CustomerDef && (object) type.QualifiedName.Namespace ==(object)id2_httpwwwlagashcomschemascustomers)) { o = Read1_CustomerDef(false, true);}} else if (((object) Reader.LocalName ==(object)id5_customer && (object) Reader.NamespaceURI ==(object)id2_httpwwwlagashcomschemascustomers)) { o = Read1_CustomerDef(false, true);} else { throw CreateUnknownNodeException();}} else { UnknownNode(null);} return (object)o;}

Of course this would require a validating reader with the appropriate schema loaded, by why would you create an XSD otherwise? Would you loose all those powerful validation capabilities and instead use it only to save you some lines of class definition code and Xml serialization attributes? If you do, I urge you to think twice, you're really missingsomething that can greatly improve your code (no more validation of ranges, patterns, etc.).

Another interesting thing I found is that the XmlSerializer can be inherited, and it has a protected method that allows you to deserialize directly from an XmlSerializationReader. That would have solve my previous reflection problems, as I could simply inherit the serializer and make a public method receiving my modified reader and pass it through to it. Thatwould even make for maybe more efficient custom deserialization, for example one where the temporary assemblies are not generated each time the application starts but rather stored in a permanent location for reuse across AppDomains (maybe a DB?). Remember the initial generation and compilation performance hit is significant. Unfortunately, that method implementation throws a NotImplementedException :((((((. But that makes me wonder if

7

Page 8: ASP Interview Question

in Whidbey it's possible.... :)In a future post, maybe here, maybe on MSDN online, I will explain

how to take advantage of IXmlSerializable interface to implement custom serialization but also to gain automatic XSD validation right from your assembly-embedded schema.What does this do? sn -t foo.dllDisplays the public key token of foo.dll. foo.dll must be strong-named.What is FullTrust? Do GACed assemblies have FullTrust?The permissions to run any assembly is based on its trust level.Under Full Trust level all assemblies can be run successfuly. All GAC asemblies have Full Trust as ever strong named assembly is Full Trust assembly.What are PDBs? Where must they be located for debugging to work?A program database (PDB) file contains debug information for the project’s EXE file. The project.PDB contains full debug information, including function prototypes, not just the type information found in VCx0.PDB. Both PDB files allow incremental updates. They should be located at bin\Debug directoryWhat is the difference between an EXE and a DLL?EXE file is a excutable file which runs in a seperate process which is managed by OS,where as a DLL file is a dynamic link library which can be used in exe files and other dll files.In .net frame work both are assemblies.[EXE file has Entry point, but in dll no Entry point.]What is a Windows Service and how does its life cycle differ from a standard EXE? Windows services starts automatically whenever our system starts.windows services runs on a particular portDescribe the difference between a Thread and a Process?- A Process has its own memory space, runtime enivorment and process ID. A Thread runs inside a Process and shares its resources with other threads. - A thread is a path of execution that run on CPU, a proccess is a collection of threads that share the same virtual memory. A process have at least one thread of execution, and a thread always run in a process context.

- Process is unit of allocation while Thread is unit of execution. Each process has one or more threads. Each thread belong to one processIn a webpage if i want to give access to only half page,then what should i do? U can use Iframe to split the webpage and giving access to the particular part.We have 2 sites in which one site allows the user with out asking credentials and second one ask for credentials through a log page. What might be the configurations settings for both sites? We can use IIS and web.config files together. First one using windows authentication as follows.

Set Windows authentication in IIS.And in web.config <authorization>

<deny users=”?”/></authorization>

For the second one.We set IIS authentication as none. And in web.config file we mention as follow.

<authentication mode=”forms”><forms login=”login.aspx”/></authentication><authorization><deny user=”?”/><authorization>** In ASP.NET 2.0 we have lot of new events occur while page loads.

8

Page 9: ASP Interview Question

Page_PreInit()Page_Init()Page_InitComplete()Page_PreLoad()Page_Load()Page_LoadComplete()Page_PreRender()Page_PreRenderComplete()Page_Unload().What is CSS? What is the advantage os using CSS in ASP.NET Web Applications?CSS stands for cascading style sheet. where one can define the style which will be helpful in acheiving uniform look up of the application.Types of optimization and name a few ? For SQL --Heuristic OptimizationSyntactical OptimizationCost-Based OptimizationSemantic OptimizationWhat is view state and how this can be done and was this there in asp?ViewState is a hidden component which is being stored at client side. It is basically used to retain the data of the form during round trip to the server.

Viewstate is introduced in asp.net, it was not in classic asp.What is Http handler? The HTTP handler is used in web services handle theinformation between web browser and web server.Tell about WebService in Asp.Net?Webservice is an application which resides on server and used to share data and information. It provides Platform indpendent service, so any user with any operating system cant use it. it uses SOAP to transfer and receive data. It basically populates data in XML format which can be used by every one.Types of values mode can hold session state in Web.Config?there r three types of values mode can hold session state in we.config<authentication mode="forms"><authentication mode="windows"><authentication mode="passport">[Session mode in web config fiel<session mode ='InProc'> or<session mode ='stateserver'> or<session mode ='sql server'> or]Tell something about state management in asp.net?Give brief Definition for the following1. Application 2. Session 3. Cookies 4. Viewstate5. SqlServer(DataBase) 6. HiddenFeildWhat are Authentication mechanisms in .Net?there are 3 types of authentication mechanisams in .net.there are1)forms authentication 2)windows authentication 3)passport authenticationWhat is Stateless ASP or ASP.Net? In fact HTTP protocol is stateless. so asp and asp.net both are stateless.What are the difference between ASP and ASP.Net?This article explains what is ASP.NET and how different it is from ASP.NET

ASP stands for Active Server Pages. ASP.NET is the next generation of ASP. After the introduction of ASP.NET, old ASP is called 'Classic ASP'.

Classic ASP uses vb script for server side coding. Vb Script is not supported any more in ASP.NET. Instead, ASP.NET supports more languages including C#, VB.NET, J# etc. VB.NET is very similar to vb script, so it should be easy for old Visual Basic or ASP programmers to switch to VB.NET and ASP.NET

9

Page 10: ASP Interview Question

VB Script is a simple scripting language, where as VB.NET or C# are modern, very powerfull, object oriented programming languages. Just for that reason, you will be able to write much more robust and reliable programs in ASP.NET compared to ASP.

In classic ASP, there was no server controls. You have to write all html tags manually. ASP.NET offers a very rich set of controls called Server Controls and Html Controls. It is very easy to drag and drop any controls to a web form. The VS.NET will automatically write the required HTML tags automatically for you. ASP is interpreted, ASP.NET is compiledHow do you register the .Net Component or Assembly?RegAsm is used to register .net assembly.Where does Web.Config Info stored? Will this be stored in the registry?Web Config is a file which contains settings for your application. You can check Web.config file in your application main folder. This information is not stored in registry.DOT NET framework is a way to have a registry free ApplicationWhat is DTS package?Data Transformation Services (DTS) provides a set of tools that lets you extract, transform, and consolidate data from disparate sources into single or multiple destinations.we can create a DTS solution as one or more packages. Each package may contain an organized set of tasks that define work to be performed, transformations on data and objects, workflow constraints that define task execution, and connections to data sources and destinations. DTS packages also provide services, such as logging package execution details, controlling transactions, and handling global variables.What is sequence of code in retrieving data from database?using data.sqlclient;

sqlconnection cn;cn=new sqlconnectin("user id=sa;database=pubs;data source=server");cn.open();[system.data.oledbdim oledb as new oledbconnectionoledbconnection1.open()dim com as new oledbcommand("select empname from emp where empid=100".oledbconnection)dim dr as oledbdatareader=com.executereader()if dr.read() thentextbox1.text=dr(0)end if][SQLConnection conn = newSQLConnection("DataSource=;InitialCatalog=;User Id=;Password=");SQLCommand cmd=new SQLCommand("select * from tablename",conn);DataAdapter da=new DataAdapter(cmd);Dataset ds=new Dataset();da.fill(ds,"tablename");]How do you define authentication in Web.Config?in the authentication tag we have to specify the mode of the authentication. The mode can be Windows, Forms, Passport or None.What are the differences between Dataset and DataReader?Dataset is in memory representation of the Database. where you can create tables, relations between tables, add primary key to tables and also manipulate the data retrieved form the database. It allows us to work in connection less environment.

10

Page 11: ASP Interview Question

Datareader is like forward only readonly cursor, which is used to retrieve data. data manipulation is not possible while using datareader. datareader continously keeps the connection open.What are the types of authentications in ASP.NET?There are main three types of authentications,(1) Windows (2) Forms (3) PassportWhat is Boxing and Unboxing?Boxing is to implicitly converting value type to refrence type,int x = 10;double y = x;

Unboxing is to explicitly converting refrence type to value typedouble y = 10.234;int x = (int)y;What is gacutil.exe? Where do we store assemblies, Shouldsn.exe be used before gacutil.exe?It is one of utility of .net. It is used to register a assemly in global cache. Normally we store this assembly in "C:\WINDOWS\assembly"

Befor we register the assembly we should give strong name using sn.exe utilityHow to write unmanaged code and how to identify whether the code is managed /unmanaged?unmanaged code is not varify by clr,and clr is not varify third party control and pointer.What is shared and private assembly?The assembly which is used only by a single application is called as private assembly. Suppose you created a DLL which encapsulates your business logic. This DLL will be used by your client application only and not by any other application. In order to run the application properly your DLL must reside in the same folder in which the client application is installed. Thus the assembly is private to your application.

Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.What is difference between machine.config and Web.Config?machine.config is for configuration settings of all the applications on a machine. where as web.config is application specific.it contains configuration settings for a application.What is web.config. How many web.config files can be allowed to use in an application?The ASP.NET Web.config file is used to define the configuration settings for an ASP.NET application. ASP.NET and the .NET Framework use .config files to define all configuration options. The .config files, including the ASP.NET Web.config file, are XML files.

Server-wide configuration settings for the .NET Framework are defined in a file called Machine.config. The settings in the Machine.config file can be changed and those settings affect all .NET applications on the server.

Different ASP.NET applications might need different application settings, that’s why defining those settings in the Machine.config file, is usually not practical. The solution for this problem is the ASP.NET Web.config file.

The ASP.NET application configuration settings can be changed by creating a file called Web.config and saving it in the root folder of the application. But what if the Machine.config file defines different settings than the ones defined in your Web.config file? The good news is that the

11

Page 12: ASP Interview Question

settings in the Web.config file override the settings in the Machine.config file. There can be more than one web.config file .How do you relate an aspx page with its code behind Page?Inherits page.aspx.cs.Can we throw exception from catch Block?Yes, we can.Difference between asp and asp.net?1.Scripting is seperated from html2.The coede is compiled as dll3.All controls supports events in asp,net4.Better scalabilitry5.Better security that is authentication and authorization6.Better controls7.Better language supportDifference between Htttppost and Httpget Methods?As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying protocol. Both of these methods encode request parameters as name/value pairs in the HTTP request.The GET method creates a query string and appends it to the script’s URL on the server that handles the request.The POST method creates a name/value pairs that are passed in the body of the HTTP request message.In try catch blocks one is normal catch block and another issqlcatchexception blockyes .but we should mantain the order .first sqlcatchblock then nomal blockwhat is managed and unmanaged code?managed codes are which is supported by CLR, and unmanaged code are those which is not supported.What are clr?cts?cls?All .NET applications are compiled into Intermediate Language code (MSIL). When executed on the CLR, MSIL is converted into native machine code specific to the operating platform. This process is done by a Just In Time (JIT) compiler. The code executed by the CLR is called as Managed Code. This code is type safe and thoroughly checked by the CLR before being deployed. The .NET runtime also provides a facility to incorporate existing COM components and DLL's into a .NET application. Code that is not controlled by the CLR is called Unmanaged Code.

The .NET Framework is further comprised of Common Type System (CTS) and Common Language Specification (CLS). The CTS defines the common data types used by .NET programming languages. The CTS tells you how to represent characters and numbers in a program. The CLS represents the guidelines defined by for the .NET Framework. These specifications are normally used by the compiler developers and are available for all languages, which target the .NET Framework.Can you store dataset in viewstate?No, You cant directly store Dataset in ViewState. You can get XML from dataset store that Xml in ViewState. While getting From ViewState convert to xml and then from xml to dataset[yes.We can store dataset in view state.Not a dataset any serialible object type(datatable,dataset etc..) to be store in view state.]what is Disco?what it will do?DISCO is the discovery file which gives path to the Webservices It contains WSDL(Web Service Description Language) When one searches for the Web Services, it will go to the DISCO whcih gives actual info. about the particular Webserviceswhat is soap? SOAP is Single Object Access Protocol SOAP is simply XML output on HTTP protocol.can we call webservice in Html form?

12

Page 13: ASP Interview Question

yes we can call a webservice from html form. Your web page directory should include the 'webservice.htc' file. This file adds a behavior to html files for calling web services.How can you assign styles to webforms?by using cascading style sheets.what is manifest?Manifest is an XML based, database driven Content Management System (CMS) for satisfying corporate communications needs, including Internet and Intranet. (or)

Assembly manifest is a data structure which stores information about an assembly .The information includes version information, list of constituent files etc.public key?A cryptographic system uses two keys.1.public key -known to every one.2.private or secret key-Known only to the recipient of themessage.if first person want to send message to second person .thefirst person make use of public key to encrypt message andthe second person make use of private key to decrypt message.what is strong name?A strong name consists of the assembly's identity — its simple text name, version number, and culture information (if provided) — plus a public key and a digital signature. In particular, strong names satisfy the following requirements: Strong names guarantee name uniqueness by relying on uniquekey pairs. No one can generate the same assembly name that you can, because an assembly generated with one private key has a different name than an assembly generated with another private key. Strong names protect the version lineage of an assembly. A strong name can ensure that no one can produce a subsequent version of your assembly. Users can be sure that a version of the assembly they are loading comes from the same publisher that created the version the application was built with.

Strong names provide a strong integrity check. Passing the .NET Framework security checks guarantees that the contents of the assembly have not been changed since it was built.Note, however, that strong names in and of themselves do not imply a level of trust like that provided, for example, by a digital signature and supporting certificate.what is shared assembly?Suppose that you are creating a general purpose DLL which provides functionality which will be used by variety of applications. Now, instead of each client application having its own copy of DLL you can place the DLL in 'global assembly cache'. Such assemblies are called as shared assemblies.what is assembly? assembly is a collection of dll,exe files required for running entire application.About Garbage Collector? garbage collection is a form of automatic memory management. The garbage collector attempts to reclaim garbage or memory used by objects that will never be accessed or mutated again by the application.What is viewstate? It maintain the controls data under postback implementation.It is implemented based on hidden field concept.Generally viewstate is disabled for Password type textboxs.What are runtime hosts? Runhosts is a special type where CLR is executed and managed[IE ASP.NET Shell]Types of caching. How to implement caching?ASP.NET Caching Features & ASP.NET Web Applications

When clients access an ASP.NET page, there are basically two ways to provide them with the information they need: the ASP.NET page can either obtain information from server resources, such as from data that has been

13

Page 14: ASP Interview Question

persisted to a database, or the ASP.NET page can obtain information from within the application. Retrieving information from a resource outside the application will require more processing steps, and will therefore require more time and resources on the server than if the information can be obtained from within the application space.

If the information that will be sent to the browser has already been prepared by a previous request, the application will be able to retrieve that information faster if it has been stored in memory, somewhere along the request/response stream. Known as caching, this technique can be used to temporarily store page output or application data either on the client or on the server, which can then be re-used to satisfy subsequent requests and thus avoid the overhead of re-creating the same information. Caching is particularly suitable when you expect to return the same information in the same format for many different requests.

ASP.NET provides the following types of caching that can be used to build highly responsive Web applications:

Output caching, which caches the dynamic response generated by a request.

Fragment caching, which caches portions of a response generated by a request. Data caching, which allows developers to programmatically retain arbitrary data across requests.how to update data using store procedurecreate procedure <pro.name>{@variable declartion,,,,,ASif exist(select the table with condition)BEGINupdate queryENDelseBEGIN //insert new dataENDWHT IS DIFFERENCES BETWEEN HTML CONTROLS AND SERVER CONTROLS.In server controls processing would be done at server side but in html controls would be made to client side only.write a sample code make use of xmltext writerusing System;using System.Data;using System.Configuration;using System.Web;using System.Web.Security;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.WebControls.WebParts;using System.Web.UI.HtmlControls;using System.Xml;

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { try { //creating a apth for writing xml string xml1 = Server.MapPath("test2.xml"); //initialising xmlwriter

14

Page 15: ASP Interview Question

XmlTextWriter xt = new XmlTextWriter(xml1, System.Text.Encoding.UTF8); xt.Formatting = System.Xml.Formatting.Indented; //start writing it xt.WriteStartDocument(); //element xt.WriteStartElement("name"); // attribute xt.WriteAttributeString("my_name", "name"); xt.WriteStartElement("phn"); xt.WriteAttributeString("my_phn", "266549560"); xt.WriteStartElement("id"); xt.WriteAttributeString("my_id", "100"); xt.WriteStartElement("city"); xt.WriteAttributeString("my_city", "city"); xt.WriteElementString ("title","gud girl"); //ending all elements xt.WriteEndElement (); xt.WriteEndElement(); xt.WriteEndElement(); xt.WriteEndElement(); xt.WriteEndDocument(); xt.Close (); } catch { }}}what is the jit? what is the type of jit and purpose of it>JIT IS JUST IN TIME COMPILER Pre-JIT (Compiles entire code into native code at one stretch) Ecno-JIT (Compiles code part by part freeing when required) Normal JIT (Compiles only that part of code when called and places in cache)what are the levels of securities need to be considered for the finincial web application? What is customer control and user control?Custom controls are controls that are developed by the developer or a third party vendor. Custom controls are not provided along with .NET. Difference between Custom Controls and User Controls.1.User Control is a page file with extension .ascx which can only be used within a single application. But custom controls are assemblies (dll files) that can be used in multiple applications.2.User Controls cannot be added to the ToolBox of VS.NET . To use a user Control with in an aspx page u have to drag the user Control from the solution Explorer to designer page. But Custom Controls can be added to ToolBox of VS.NET. 3.User Controls can be viewed as a sort of generic controls during the design time.The proper GUI of user controls can be viewed only during the run time.But Custom Controls can be viewed during the design time. 4. User controls are created from existing Webserver and html server controls .But a developer who creates custom controls have to render every thing from the scratch. 5.Since the dll assembly of a custom control is being used,a custom control developed in C# can be used in a project developed in VB.NET or any other managed code and vice versa.This is not possible with user controls.They are language spefic

We cannot give any examples for custom controls since they are developed either by a developer of a third party vendor.I have a method written in WebForm (means .aspx page) & now I want to call this method in WebUserControl (means .ascx page) what should I have to do?Use the controls page property and typecast it to the page class name.

15

Page 16: ASP Interview Question

eg: Page Default.aspx has a control MyControl.ascxPage Default.aspx.cs has a method MyMethod()in MyControl.ascx.cs((Default)(this.Page)).MyMethod();How we can bind textbox,listbox and datagrid to sql server database in asp.net using visualstudio.net language (vb.net)? use a textbox and a dataset for fetching data from the database,and bind to the textboxtextbox1.text = dataset.Tables(0).Rows(0).Item(1) textbox1.databindIf we add a textbox and give the required field validator,and i add two radio buttons 1 is yes another one is No.And i add another one server control button ,if i click the button ,if the radio button Yes is checked the validation control is fired ,if no the validation control is not fired.So what you used to solve this problem. required field valodator is used to check where a browser has entered a value in atextbox or not.How do you install windows service?First u have to create Windows Service..For install Windows Service , u have to use one Command first Build Windows Service..then use this command..installutil.exe <your service name.exe>installutil.exe/u <your service name.exe> -->For uninstallu have to use this command in visual studio 2005 -> visual studio command Prompt -> write this above command..Go in Particular path where u create Windows Service then go to Bin -->Debug --> then implement this above Command..what are the differences between windows services and web services?a windows service is installed on a Windows box and is very windws platform dependent. it keeps running in the back ground even if the user has logged off. a service is typically use ful where on servers there are long runningprocesses.[An XML Web service is a component that implements program logic and provides functionality for diseparate applications. These applications use standard protocols, such as HTTP, XML, and SOAP, to access the functionality. XML Web services use XML-based messaging to send and receive data, which enables heterogeneous applications to interoperate with each other. You can use XML Web services to integrate applications that are written in different programming languages and deployed on different platforms. In addition, you can deploy XML Web services within an intranet as well as on the Internet. While the Internet brings users closer to organizations, XML Web services allow organizations to integrate their applications.

A Windows service starts much before any user logs in to the system (if it has been setup to start at boot up process). A Windows service can also be setup in such a way that it requires a user to start it manually ? the ultimate customization! Windows services run as background processes. These applications do not have a user interface, which makes them ideal for tasks that do not require any user interaction. You can install a Windows service on any server or computer that is running Windows 2000, Windows XP, or Windows NT. You can also specify a Windows service to run in the security context of a specific user account that is different from the logged on user account or the default computer account. For example, you can create a Windows service to monitor performance counter data and react to threshold values in a database.]One Listbox showing all cities. If you select one city in list box the information related to that particular city should be displayed in Datagrid . How do you do that?protected void ddlcity_SelectedIndexChanged(object sender, EventArgs e) {if (ddlcity.SelectedValue == "Any of the city name") {

16

Page 17: ASP Interview Question

DataSet ds = GetUserInfo(); GridviewCitycity.DataSource = ds; GridviewCity.DataBind();}}[protected void ddlcity_SelectedIndexChanged(object sender, EventArgs e) {sqlConnection con= new sqlConnection(" ");string str="select * from table where city ='" + ddlcity.SelectItem.Text ="'"; sqlDataAdapter da= new slqDataAdapter(str,con)dataset ds = new dataset;da.fill(ds,"City");dgview.datasource=ds.tables["City"];dgview.dataBind();}]accessing a textbox that was created dynamically?for (int i = 0; i < t1; i++) { TextBox t2 = new TextBox(); t2.ID = "adf" + i; PlaceHolder1.Controls.Add(t2); } accessing data entered in the above created controls.for (int i = 0; i < t1; i++) {TextBox t2 =(TextBox) PlaceHolder1.FindControl("adf" + i); string str=t2.Text;}How does Garbage collector(GC) works in .net[Garbege collection are used to handle memory management.]In .NET Garbage Collector maintained by CLR. The process of GC is reclaim the memory of objets which is no longer referenced by our program.Next thing is GC runs undeterministicly because of that we can't assure we the object will be released from the Heap Location.But the CLR maintain a Logical Pointer to every object which referenced by our program. In some amount of time the GC look out the objects which is reachable from Logical Pointer. whatever the object reachable from pointer it create a map those objects. After that it will reclaim the memory of objects those are not reachable from the pointer.This is the process of how the GC clear the memory of Object.what r the Templeats in ASP.net?The repeater,Datalist,Datagrid are templated controls in asp.net Generally speaking, a template is the description of how a certain element will be rendered at runtime. In ASP.NET, a template is property of a server control that describes the static HTML, controls, and script to render within one region of the control. For example, a Repeater control has a HeaderTemplate property that defines the contents of its header region. You normally define a template within the body of an ASP.NET page using declarative syntax. For example, the following code shows how to specify a template to draw the header and each row of a Repeater control.<asp:repeater runat="server"> <HeaderTemplate> <h2>Employees</h2> <table border="0"> </HeaderTemplate> <ItemTemplate> <tr>...</tr> </ItemTemplate>

17

Page 18: ASP Interview Question

</asp:repeater> When it comes to rendering the contents of the Repeater control, the ASP.NET runtime uses the content defined in the templates and processes it?often together with bound data?to create an HTML representation of the region. All the server-side controls within the template individually render themselves as HTML. The Microsoft? .NET Framework utilizes the ITemplate interface at runtime to process the templates into a control hierarchy that can be databound and rendered to populate a part of an ASP.NET control. As long as you define templates in a declarative manner?using inline tags in ASPX pages?you don't strictly need to know about the ITemplate interface. That will become important only when you move one step further and start investigating how to create and assign templates programmatically and dynamically. But before we look at that, let's review the use of templates with a DataGrid control.can sn.exe can be used before gacutil.exeyes sn.exe is an commandline tool which we asign a strong name sn -k and it can be placed into GAC(Global Assembly Catch)what is diff between responseexpires and expiresabsoluteresponse.expires is the lenght of time in minutes before cached response on the browser expires.response.expiresabsolute sets the date/time when a response page stored in browsers cache will expire.what is diffrance between response.write & response.output.writeRespons.Write will display the value/expresion as it is.Response.Output.Write will diaplay the formatted content.what is the auto option in XML ?AUTO mode returns query results as nested XML elementsHow many column in table of sql server?We can add 1024 columns in a table in sql server 2000what is client back feauture ?ClientSideCallback used to avoid form Postback for each and every time .I have posted some sample code also try which is use for Dropdownaspx.cs private string _pricecallbackResult, _pricecallbackResultCAT, _pricecallbackResultClass; public string GetCallbackResult() { return _pricecallbackResult; } public void RaiseCallbackEvent(string eventArgument) { string[] val = eventArgument.Split(','); string id = val[0].ToString(); string k = val[1].ToString(); if (val[1] == "1") { // _pricecallbackResult = objCommonBL.GetProgramNameForRebate(); } else if (val[1] == "2") { _pricecallbackResult = objCommonBL.GetCategoryNameForRebate(Convert.ToInt32(id)); } else if (val[1] == "3") { _pricecallbackResult = objCommonBL.GetClassNameForRebate(Convert.ToInt32(id));}}

18

Page 19: ASP Interview Question

in Aspx Java Script********************* function PriceClientCallbackError(result, context) { alert(result); } function PriceClientCallback(result, context) { ClassClear(); if (!result) { return; } var resultValue = result.split(','); for (var i = 0; i < resultValue.length; ++i) { var val = resultValue[i].split('~~'); for(var j=0;j<val.length; ++j) { var values = val[j].split('~'); var option = document.createElement("OPTION"); option.value = values[0]; option.innerHTML = values[1]; document.forms[0].ctl00$ContentPlaceHolder1$frmRebate$ddlCategory.appendChild(option);}}}what is the MSIL assembler do?MSIL is also called as Microsoftintermediatelanguage and it converts IL code to cpu native code with the help of JIT compilerdiffrance between stored procedure & function in sql server?Function can be used in an expression but we cann't use procedure in an expression [Difference between function and stored proc:========================================================Stored Procedure :supports deffered name resoultion Example while writing a stored procedure that uses table named tabl1 and tabl2 etc..but actually not exists in database is allowed only in during creation but runtime throws errorFunction wont support deffered name resolution. 2. Stored procedure returns always integer value by default zero. where as function return type could be scalar or table or table values(SQL Server).3. Stored Procedure is pre compiled exuction plan where as functions are not.4. Stored Procedure retuns more than one value at a time while funtion returns only one value at a time.5. We can call the functions in sql statements (select max (sal) from emp). where as sp is not so 6. Function do not return the images,text whereas sp returns all.7. Function and sp both can return the values. But function returns 1 value only.procedure can return multiple values(max. 1024) we can select the fields from function. in the case of procdure we cannot select the fields.8. Functions are used for computations where as procedures can be used for performing business logic 9. Functions MUST return a value, procedures need not be.10. You can have DML(insert, update, delete) statements in a function. But, you cannot call such a function in a SQL query..eg: suppose, if u have a function that is updating a table.. you can't call that function in any sql query.- select myFunction(field) from sometable; will throw error.11. Function parameters are always IN, no OUT is possible]difference between caching objects in session objects?session object creates for each user indivisually but 1 cach object for one application.

19

Page 20: ASP Interview Question

what is diference between the .net1.0 & .net2.0 ?In Asp2.0 have ultimate features like FormView,MasterPage,GridView,Web parts, Login Control,ClientCallback(use for avoid post pack),SiteMap. Asp2.0 will reduce 50% of code. How Web Services help Us? What r the difference between Remoting and webservices? In remoting objects communicates thru homogineous protocols i.e.,TCP.Where as Webservices provides funtionality thru hetrogenious protocals i.e., HTTP,SOAP.

In remoting data is passed as streams whereas webservices communicates in XML Format What namespaces are imported by default in ASMX files?The following namespaces are imported by default. Other namespaces must be imported manually.? System, System.Collections,System.ComponentModel,System.Data, System.Diagnostics,System.Web,System.Web.ServicesCan two different programming languages be mixed in a single ASMX file?No.What does AspCompat="true" mean and when should I use it?AspCompat is an aid in migrating ASP pages to ASPX pages. It defaults to false but should be set to true in any ASPX file that creates apartment-threaded COM objects--that is, COM objects registered ThreadingModel=Apartment.That includes all COM objects written with Visual Basic 6.0. AspCompat should also be set to true (regardless of threading model) if the page creates COM objects that access intrinsic ASP objects such as Request and Response. The following directive sets AspCompat to true: <%@ Page AspCompat="true" %> Setting AspCompat to true does two things. First, it makes intrinsic ASP objects available to the COM components by placing unmanaged wrappers around the equivalent ASP.NET objects.

Second, it improves the performance of calls that the page places to apartment- threaded COM objects by ensuring that the page (actually, the thread that processes the request for the page) and the COM objects it creates share an apartment.

AspCompat="true" forces ASP.NET request threads into single-threaded apartments (STAs). If those threads create COM objects marked ThreadingModel=Apartment, then the objects are created in the same STAs as the threads that created them. Without AspCompat="true," request threads run in a multithreaded apartment (MTA) and each call to an STA-based COM object incurs a performance hit when it's marshaled across apartment boundaries.Do not set AspCompat to true if your page uses no COM objects or if it uses COM objects that don't access ASP intrinsic objects and that are registered ThreadingModel=Free or ThreadingModel=Both.Is it possible to prevent a browser from caching an ASPX page?Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property, as demonstrated here: <%@ Page Language="C#" %> <% Response.Cache.SetNoStore (); Response.Write (DateTime.Now.ToLongTimeString ()); %>SetNoStore works by returning a Cache-Control: private, no-store header in the HTTP response. In this example, it prevents caching of a Web page that shows the current time.[Write this code in the Page load event of the code behind :-Response.Cache.SetCacheability(HttpCacheability.NoCache);]

20

Page 21: ASP Interview Question

About Windows/Forms AuthenticationwindowS AUTH: THGIS IS IMPLEMENTED VY USING WINDOWS(O/S) LOGIN PARAMETERSWE CAN CONFIGURE IT IN WEB.CONFIG FILE.<CONFIGURATION><APPSETTINGS><AUTHENDICATION MODE="WINDOWS"></AUTH><AUTHORIZATION><DENY USERS="8"></AUTHRIZATION>FORMSBASED AUTH:IT IS IMPLENTED BASED ON USER LOGIN VALUES MEANS USER CAN GIVE THE USERNAME & PASSWORD ,FIRST IT WILL CHECK,AFTER IT WILL GIVE THE PERMISSION TO NEXTY PAGE About session modesInproc(Session stored inside the asp.net worker processor) StateServer(aspnet_state.exe) SqlServer(InstallSqlState.sql or InstallPersistSqlState.sql)Trigger syntax in sql2000CREATE TRIGGER TriggerName ON TableName AFTER Insert, Update, DeleteAS Triger Code and CREATE TRIGGER TriggerName ON TableName INSTEAD OF InsertAS Triger CodeHow to merge 2 tables fields in DataTable in asp.netselect (databasename).(owner).(tablename1).(datafield),select (databasename).(owner).(tablename2).(datafield) from (databasename).(owner).(tablename1),(databasename).(owner).(tablename2)Example:select LSKGROUP.dbo.addsites.state,LSKGROUP.dbo.employee.empname from LSKGROUP.dbo.addsites,LSKGROUP.dbo.employee and then fill the values to new dataset table.Remember:if database also differ put databse's name accordingly [you can use the query to merge the fields.that query will be executed through the sqlcommand.]RequiredFieldValidator--write code in javascriptfunction validate(){ if(document.getElementById("NameId").value == null) alert("Please enter the name"); document.getElementById("NameId").focus(); return false;}or function validate(){ with(document.formname) { txtboxid.value == "" alert("Please enter value"); txtboxid.focus(); return false;}}or we can use document.form.txtboxid.value instead of document.getElementById("NameId").value[function validate(){ if(document.getElementById("NameId").value == null) alert("Please enter the name"); document.getElementById("NameId").focus(); return false;} in button OnClick() we hav to cal this function]

21

Page 22: ASP Interview Question

Write a code for "RequiredFieldValidator" in java scriptsuppose the id of the field required to be validated is NameIdThus:- function validate(){ if(document.getElementById("NameId").value == null) alert("Please enter the name");}[function validate(){ if(document.getElementById("NameId").value == null) alert("Please enter the name"); document.getElementById("NameId").focus(); return false;}or function validate(){ with(document.formname) { txtboxid.value == "" alert("Please enter value"); txtboxid.focus(); return false;}}or we can use document.form.txtboxid.value instead of document.getElementById("NameId").value ][function validate(){ if(document.getElementById("NameId").value =="") alert("Please enter the name"); document.getElementById("NameId").focus(); return false;}]How to set/get parent page values in child page in asp.netget=var uid=document.getElementById('txtUserId').value;set=document.getElementById('txtUserId').innerText=uid;what are the sitemap providers in Asp.net 2.0?SiteMapPath,TreeView and Menu controlswhy security trimming attribute?It is used to hide links in site mapwhat are the attributes of sitemapnode?Title,url,descriptionWhat is the use of Administration tool in Asp.net 2.0?The ASP.NET version 2.0 membership feature provides secure credential storage for application users. It also provides a membership API that simplifies the task of validating user credentials when used with forms authentication. Membership providers abstract the underlying store used to maintain user credentials. ASP.NET 2.0 includes the following providers: * ActiveDirectoryMembershipProvider. This uses either an Active Directory or Active Directory Application Mode (ADAM) user store.

• SqlMembershipProvider. This uses a SQL Server user store.what are the new server controls added in Asp.net 2.0?Navigation Controls: Site MapPath TreeView MenuDataBindingControls SqlDataSource oledbDatasource ObjectDataSource DataCotrols: GridView DetailsView FormsViewWhat are skins?

22

Page 23: ASP Interview Question

skin file is used to set the design settings of our html controls as well as web server controls .css file is used for html server controls .skin files are used for web server controlsHow to remove themes from certain controls?Override the property EnableTheming by setting it to "False" for those controlsWhat is the use of The Page.Master Property?For the <fo:simple-page-master> object this property identifies the name of the master.What are Master pages? How to define a Master page?ASP.NET master pages allow you to create a consistent layout for the pages in your application. A single master page defines the look and feel and standard behavior that you want for all of the pages (or a group of pages) in your application. You can then create individual content pages that contain the content you want to display. When users request the content pages, they merge with the master page to produce output that combines the layout of the master page with the content from the content page.What are the new page events added in Asp.net 2.0 ?init load unload dispose prerender[new events are init complete load complete prerender complete

prerender load comlete][pre-init() pre-load() pre-initcomplete() pre-loadcomplete()pre-rendercomplete()]What r new things introduced in ASP.NET 2.0 in comparision to ASP.NET 1.1There is lot of new feature include in ASP.Net 2.0 1. Role and membership Management . It is create tricky mathod for create an application with areas that are accesss by only select user . Example if(Membership.validateUser (userid,password)){}2.Personalization :- User can offer to setting there persnol setting .3.Site Navigation :- We can create Site Map for application in XML file that can easly inherite by specific co control 4. New Copilation System :- Page by Page Compilation with recomplilation whole appliction.5.Master Page: - This is proide easy way to same loke and fill whole site . 6.thems : - providing way to change Thims of application. 7.New Object For Accessing Data. Such as <SqlDataSource>8. New Server Control : -Such As GridView,FormView etc. What is Difference between Callbacks and Postback in ASP.NET?This is " Cliet Site Call back to server site "which won't require page refresh to execute a server call and its based on XMLHTTP protocol or soPostBack is for Server Site [The difference between a callback and postback is that, as with a postback, a callback does not refresh the currently viewed page (i.e. does not redraw the page). You can think of it as a quick trip back to get some data etc. For example if there were two drop down boxes, the second dependant on the value of the first, when a user selects a value of a the first, rather then posting the whole page, doing some server side calculations and returning a new whole page to the client, a callback can enable you to only go fetch the required data. Obviously from this, View State is not updated with a callback (it's the same instance of the page just updated!!!).]What r Callbacks in ASP.NET?Call Back Mathod Allow us to call Server Site Method though Client Site java script With out using Posting the Page. How many Directives r in ASP.NET?assembly directive register directive page directive implements directive import directive [@assembly : - Link assembly to current Page or user control directory .

23

Page 24: ASP Interview Question

@control :- Define control Spacific attributes to used by ASP.Net page parser and compiler included only in .ascx page. @ Impliment : - Indicates that a page or user control implements a specified .NET Framework interface declaratively @ import :- import a namespace in Page or user control explicit. @ Master :- Identifies a page as a master page and defines attributes used by the ASP.NET page parser and compiler and can be included only in .master files @ Master Type:- Defining class or vartual Path used to type master page property of page.@OutPut Cache.@Page.@Privious Page Type.@Reference .@Register]What data types do the RangeValidator control support?String,Integer,Double,Date,CurrencyWHAT IS BOXING? HOW WE CAN USE IT?There is two type datatype available Value and reference type . value are stored in stack and reference type used in heap . when we copy data from stack memmory to heap it call Boxing . Int32 x = 10; object o = x ; // Implicit boxing Int32 y = 10; object obj = (object) y; // Explicit BoxingWHAT ARE DEFFERENCE BETWEEN DATALIST AND DATAGRIDA Datagrid, Datalist are ASP.NET data Web controls.They have many things in common like DataSource Property , DataBind Method ItemDataBound and ItemCreated .When you assign the DataSource Property of a Datagrid to a DataSet then each DataRow present in the DataRow Collection of DataTable is assigned to a corresponding DataGridItem and this is same for the rest of the two controls also.But The HTML code generated for a Datagrid has an HTML TABLE <ROW> element created for the particular DataRow and its a Table form representation with Columns and Rows.For a Datalist its an Array of Rows and based on the Template Selected and the RepeatColumn Property value We can specify how many DataSource records should appear per HTML <table> row.In addition to these , Datagrid has a inbuild support for Sort,Filter and paging the Data ,which is not possible when using a DataList and for a Repeater Control we would require to write an explicit code to do paging.What r the page life cycle in asp.net page?Life Cycle of ASP.NetStart-properties such as Request,Response,IsPostBack are set.Page Intialization load Validation PostBack Event handlingRedering UnloadIn a page u have Web user controls . So what is the order in which the Page life Cycles takes place? order of events are initpage load control load page unloadWhat is boxing and unboxing ?boxing is conversion from value type to object(reference) type.Actually the copy of value type copied from stack to heap memory.unboxing is reverse of it.from heap memory back to stack memory.[Boxing allows value types to be implicitly treated like objects.Dim i As Integer = 5i.ToString() ' i --> object --->object.tostringORDim i As Integer = 5Dim obj As Object = i ' implicit boxing obj.ToString()OR you can do it explicitlyDim obj As Object = CType(i, Object) ' un-necessary explicit boxing

On the other hand, un-boxing is an explicit conversion from object type to value type.

24

Page 25: ASP Interview Question

Dim i As Integer = 5Dim obj As Object = i ' implicit boxing Dim j As Integer = CType(obj, Integer) ' explicit un-boxing? Boxing and Un-boxing is the transformation between value type and object type while casting just transforms the apparent (reference) type of objects. ? Value types are stored at the stack and objects are stored at the heap. Boxing takes a copy of value types from the stack to the heap while un-boxing takes value types back to the stack. On the other hand, casting does not physically move or operate on an object. Casting merely changes the way objects are treated in a program by altering their reference type.]How to write unmanaged code and how to identify whether the code is managed / unmanaged ?you can only write unmanaged code in c# not in vb.net you can only call unmanaged code in vb.net. calling and writing unmanaged code are different things.

To identify whether the code is managed or not open the file in ildasm in VS.Net Command prompt.Also you can use a .Net tool called dumpbin, which can be used to check the headers.or open the dll in notepad and check for "V e r s i o n". If you find that, it is managed assembly.Should sn.exe be used before gacutil.exe ?Yes. It is mandatory to assign the strong name to the assembly before placing it into the GAC. The stron name contains the public key to recognize by the GAC for whom the request comes.Note : GAC is a special area where more than one same named assemblies may be placed having different versions.[Yes. Before placing an assembly to GAC, we should sign the assembly with a strong name using sn.exe]Types of configuration files and their differences ?app.config-> contains application specific settingsweb.configWeb.config is a security in ASP.Net application and how to secure applications. Web.config does most of the work for the application the who, what, where, when and how to be authenticated.1.This is automatically created when you create an ASP.Net web application project.2.This is also called application level configuration file.3.This file inherits setting from the machine.config Machine.config contains settings that apply to an entire computer. This file is located in the %runtime install path% \Config directory. Machine.config contains configuration settings for machine-wide assembly binding, built-in remoting channels. 1.This is automatically installed when you install Visual Studio. Net.2.This is also called machine level configuration file.3.Only one machine.config file exists on a server.4.This file is at the highest level in the configuration hierarchy.Types of values mode can hold session state in web.config ?1) Inproc Mode : where the values are stored in ASPNET_WP.exe process2) StateServer : session values are stored in ASPNET_state.exe Process3) SQL Server : session values are stored in SQL server DatabasesAbout DataAdapters ?Data Adapters provide in teraction between DataBase and Dataset.It provite the functionalities like reading the data from database,update the data,filter the data and wite the data to Database[The data adapter we can use with data set.we can use data adapter when the data is in disconnected form & we have to apply some oprations on it.the data adapter is in the tabular form & we can create any no of virtual tables to fetch data.]Features of a dataset ?

25

Page 26: ASP Interview Question

i) Supports Disconnected Architecture ii) We can execute SQL Commands in Dataset iii) Dataset supports Cache Memory to store Frequently accesed Data.iv) It can be used with XML v) It can be used to bind the Data source with List controls like Datagrid,datalist....About Postback ?is Page Refresh to communicate the server side code executed.[if action attribute of the form tag is not declared then page goes to itself.]Types of object in asp ? ASP Response ASP Request ASP ApplicationASP Session ASP Server ASP ErrorDifference between Response.Expires and Expires.Absolute ?Response.Expires specifies the lenght of the time ie 20 secondsResponse.ExpiresAbsolute specifies the time ie 12:12:10What is view state and how this can be done and was this there in asp ?View state one of the state management process it is done by using hidden fieldsWhat are Http handler ?An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page via the page handler.To create a custom HTTP handler, you create a class that implements the IHttpHandler interface to create a synchronous handler or the IHttpAsyncHandler to create an asynchronous handler. Both handler interfaces require you to implement the IsReusable property and the ProcessRequest method. The IsReusable property specifies whether the IHttpHandlerFactory object (the object that actually calls the appropriate handler) can place your handlers in a pool and reuse them to increase performance, or whether it must create new instances every time the handler is needed. The ProcessRequest method is responsible for actually processing the individual HTTP requests.[Whenever we to work with user defined File Extensions we go for HTTP handlers.]State management in asp.net ?in asp.net following ways to mintain server site and client site state.client site: 1. View State 2.Query String 3.Hiddne Field 4. CookiesServer Site is:1.Session 2.Application [Ways to handle State Management 1. View State 2.Query String 3.Hiddne Field 4. CookiesServer Site is:1.Session 2.Application 3:Cache Object]What is stateless asp or asp.net ?asp.net is stateless [Both ASP and ASP.NET are stateless. Because both ASP and ASP.NET uses HTTP protocol which is stateless.]What is custom tag in web.config ?user defined settingdifference between Trace and Debug ?According to Microsoft Documentation there is not much difference between Trace and Debug Class.Debug only works in debug mode and trace works in debug and release both mode.Difference between Dataset and DataReader ?The DataSet consists of a collection of DataTable objects that you can relate to each other with DataRelation objects. A DataSet can read and write data and schema as XML documents..The DataReader object is the ADO.NET counterpart of the read-only, forward-only default ADO cursor[DataSet Data set can be said as a temporary data base which works on disconnected architecture which stores schema and data in application memory area..It fetches all data at a time..DML is entertained hereDataReader Datareader is like a forward only recordset. It fetches onerow at a time.DataReader is readonly so we cannot do any transaction on them.

26

Page 27: ASP Interview Question

DataReader will be the best choice where we need to show the data to the user which requires no transaction ie reports. Due to DataReader is forward only we cannot fetch the data randomly. .NET Dataproviders optimizes the datareaders to handle the huge amount of data.]Types of authentications in ASP.NET ?Type of authentications are - Windows, Forms, Passport

[Default is none. Windows(basic,digest,windows integrated)Forms, passport.]How to authenticate users using web.config ?if we are using form based authentication at that time in the web.config we can set the autentication mode to "form"then we can specify the user name and password which we are going to access.if any one can access that application then you can specify <allow users="*">inside the authentication tags[Forms authentication can be done at web.config

<authentication mode="Forms"> <forms name="appNameAuth" path="/" loginUrl="login.aspx" protection="All" timeout="30"> <credentials passwordFormat="Clear"> <user name="jeff" password="test" /> <user name="mike" password="test" /> </credentials> </forms> </authentication> <authorization> <deny users="?" /> </authorization>]What are asynchronous callbacks ?call multiple threads at a timeWhat is web.config. How many web.config files can be allowedto use in an application ?web.config is a file where we can configure the database connection ,authentication and authorization etc. for the entire application. we can have any number of web.config files in an application ,but only one file at each folder level.a web.config file at its least foleder level of a web page replaces the parent level web.config file[There is one web config by default but we can use any number of web config file but inheritance will apply from root to inward folder]How do you relate an aspx page with its code behind page ?using Page directive<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="LoginInformation.aspx.cs" Inherits="LoginInformation" Title="Untitled Page" %>Can we throw exception from catch block ? YesDifference between asp and asp.net ?asp.net has more controls, user friendly, here we use two different page one for design other for logical coding so we can work simultaniously both on designing and coding [Both are serverside technologies which are used to develop a dynamic and interactive pages. But the main differences between them are asp is an interpretted code where as asp.net is a compiled code and asp is a object based language ie it doesnt supports polymorphism and inheritance concept where as asp.net is a object oriented language .. (it supports) In asp.net. There is of two pages ..one

27

Page 28: ASP Interview Question

for designing and other for coding so designer can do his work and developer can do his work at same time on same application form.It results in better performance.. reducing time in devlopment of a file which is not possible for asp.]All kind of access specifiers for a class and for methods ?class - new,public,protected,internal,private,abstract,sealedMethod : new,public,protected,internal,private,static,virtual,sealed,override,abstract,externAbout friend and Protected friend ?Friend is same as internal in c#

if we used this keyword then that class is available to the particular assenbly where the application contains [Friend: Only members in current project access the variables.

Protected Friend: All members in current project and all members in derived class access the variables.]How do you retrieve information from web.config ?generaly we store our connection string in web.config file under tag <appsetting><add key=connection_string value="data source=......"/></appsetting> and for accessing the value in aspx page we writes string const= configurationsetting.appsetting.connection_stringHow many web.copnfig can exists in a web application & which will be used ?Generally one but it may be more than one in some casesLife cycle of ASP.NET page when a request is made ?These are the steps in the asp.net life cycle init() load() prerender()unload()About delegates ?Delegates are like function pointer in c++ with type-safe.They can be used in 2 situations 1. callback methods 2. eventHandlerWhat is web.config and machine.config ?web.Config: Web.Config file is maintained within a particular Web application and the Configuration setting specified within web.config file is applicable to that application only.

Machin.Config: Machin.Config file is maintained within .Net framework derectories and configuration setting within Machin.Config file affects all the managed application deployed on that machinDoes the following statement executes successfully: Response.Write(?value of i = ? + i);System.formatException Input string was not in a correct format.How does dataset acts in a disconnected fashion ?Once records poulated into DataSet, the DataSet is placed into server memory. Then connectiion is disconncted.Types of caching ?There are 3 types of caching1.Page caching2.Fragment Caching3.Output CachingWhat are various authentication mechanisms in ASP.NET ?there r thrr type of authentication mechanism in asp.net:Form AuthenticationWindow Authentication

28

Page 29: ASP Interview Question

Passport AuthenticationWhat is difference between ASP and ASP.NET ?ASP:1) this supports scripting languages,generally scripting languages are interpreter based,so execution will be slow,and no proper management2)no server side controls3)supports inpage technique4) supports inprocess session5)uses ADO for database connectivity6)manual coding to perform validations7)supports entire page caching towards client sideASP.NET:1) supports .net languages.these r compiler based,so execution will be fast2)supports server side controls3)supports inpage ,code behind techniques4)supports in process,out process session5) no manual coding to perform validation6)supports 3 types of caching a)out put caching b) fragment caching c) data cachingUses of CLR ?CLR common Language Runtime : It is a runtime excution engine for all the applications developed using .Net Framework.Some of the Uses Of it are :Automatic memory management,garbage collection,code execution,type safety, versioning , and some other system services...What is dataset and uses of dataset ?DATASET: The dataset is a in-memory representation of data.DataSet is made up of a collection of DataTable objects. It can be considered as a local copy of the relevant portions of the database. The data is persisted in memory and the data in it can be manipulated and updated independent of the database. When the use of this dataset is finished, changes can made back to the central database for updating. The data in dataset can be loaded from any valid datasources like Microsoft SQL Server database, an Oracle database or a Microsoft Access database.USES:1. You normally use datasets to hold results of database queries, but you can also create them on the fly and populate them programmatically. 2. The DataSet object has characteristics that make it suitable for persisting application settings: It can hold hierarchical data in the Tables collection, and you can use the WriteXml() method to save the entire dataset into an XML file with a simple call: ds.WriteXml(strFileName, XmlWriteMode.WriteSchema);3. We can seperate data layer from presentation layer by using class or dataset in .net 2.0.4. The DataSet in .Net rocks, it provides so much functionality for free, that it makes it the prefered data transport mechanism between the presentation layer and the buisiness layer, when dealing with a pure .Net technology stack then DataSet's are the way to go. 5. DataSet has some powerful XML-related capabilities. For example, you can serialize a DataSet into XML through its WriteXml() method; conversely, you can populate a DataSet from a properly formatted XML stream using the DataSet's ReadXml() method.What is CTS, CLS and CLR ?

29

Page 30: ASP Interview Question

Common Type System CTS :A fundamental part of the .NET Framework's Common Language Runtime (CLR), the CTS specifies no particular syntax or keywords, but instead defines a common set of types that can be used with many different language syntaxes.Common Language Specification (CLS):The Common Language Specification (CLS) describes a set of features that different languages have in common.The CLS includes a subset of the Common Type System (CTS).The CLR is a multi-language execution environmentWhat is JIT, what are types of JITS and their purpose ?JIT is Just in Time compiler which compiles the MSIL into NAtive code. There are three types of JIT copilers.Pre-JIT. Pre-JIT compiles complete source code into native code in a single compilation cycle. This is done at the time of deployment of the application.Econo-JIT. Econo-JIT compiles only those methods that are called at runtime.However, these compiled methods are removed when they are not required. Normal-JIT. Normal-JIT compiles only those methods that are called at runtime.These methods are compiled the first time they are called,and then they are stored in cache. When the same methods are called again, the compiled code from cache is used for execution.What is SOAP, UDDI and WSDL ?SOAP (Simple Object Access Protocol) is a simple protocol for exchange of information. It is based on XML and consists of three parts: a SOAP envelope (describing what's in the message and how to process it); a set of encoding rules, and a convention for representing RPCs (Remote Procedure Calls) and responses.UDDI (Universal Description, Discovery, and Integration) is a specification designed to allow businesses of all sizes to benefit in the new digital economy. There is a UDDI registry, which is open to everybody. Membership is free and members can enter details about themselves and the services they provide. Searches can be performed by company name, specific service, or types of service. This allows companies providing or needing web services to discover each other, define how they interact over the Internet and share such information in a truly global and standardized fashion.WSDL (Web Services Description Language) defines the XML grammar for describing services as collections of communication endpoints capable of exchanging messages. Companies can publish WSDLs for services they provide and others can access those services using the information in the WSDL. Links to WSDLs are usually offered in a company?s profile in the UDDI registry.What is caching and types of caching ?caching is generally used to catch frequently accessed data.when u used catching at that time u have to depend upon certain variables like parameter,time etc..But one demerit of using catching is if ur using dynamic page at that time u will unable to get the updated value.types of catching:1.data caching2.output caching3.fragment cachingHow do you set language in web.cofig ?? To set the UI culture and culture for all pages, add a globalization section to the Web.config file, and then set the uiculture and culture attributes, as shown in the following example:<globalization uiculture="es" culture="es-MX" />? To set the UI culture and culture for an individual page,set the Culture and UICulture attributes of the @ Page directive, as shown in the following example: <%@ Page UICulture="es" Culture="es-MX" %>How many web.config a application can have ?In an application you can create number of web.config file

30

Page 31: ASP Interview Question

,but they are not in same directory.but by default only one in an application Tell About Web.config ?web.config is an XML file. A folder can have only one web.config file. It helps to set configuration setting for an application.What is application variable and when it is initialized ?it is the process of clien side state management we can specify likeapplicatio["str"]="Value for ref"; like the above in global.asaxthis is for global purpose we can use this value in any where of our application Tell About Global.asax ?Global.asax is a file that resides in the root directory of your application. It is inaccessible over the web but is used by the ASP.NET application if it is there. It is a collection of event handlers that you can use to change and set settings in your site. The events can come from one of two places - The HTTPApplication object and any HTTPModule object that is specified in web.confg or machine.config [it allows to execute application level events and set application level variables.]Difference between server.Execute and response.redirect ?Server.execute combines the results of 2 pages into 1 page. It is normally used when the second page does not have controls which trigger postback events. Response.redirect is used to redirect to another page from the first pageWhat is early binding and Late binding. Difference which is better ?Early binding:: Properties and method can be identified by compile time.Example: dim rs as recordset Late binnding: Properties and method can be identified by Run time.Example: dim obj as classname set obj=new classnameDifference between dynamic query and static query ?Dynamic query will build at runtime where static query is already builded.Types of state management techniques ?There are two types of state management options available.1)client side statemanagement.2)server side statemanagement.In Client side statemanagement 1)View state 2)query string 3)custom cookiesIn server side statemanagement1)Session state 2)application state [ASP.NET Supports various client side and server side state management.client side view state,hidden fields, cookies, query strings server sideApplication state, session state, Database.]What is runtime host ?The runtime host loads the runtime into a process, creates the application domains within the process, and loads user code into the application domains.How do you pass session values from one page to another ?1.In first page set session variable. e.g.Session ["Name"] = "Pravesh";Here "Name" is name of session variable and "Pravesh" is the value of session variable "Name". 2. In next page get the sesion variable. e.g.:-string myName=Session["Name"].ToString();What is the difference between session state and session variables ?Session state is used to store session specific information for a website.session variable store infomation between http request for a particular user.What is machine.config and web.config ?machine.config that are used only applciations

31

Page 32: ASP Interview Question

where as web.config are used web projects[Machine.config file is for all ASP.NET's Application. it is only one.if u apply anything in machine.config file then it is applied on all ASP.NET application.Machine.config file is universal..while web.config file is only for particular ASP.NET application. each ASP.NET application has different file.]Is overloading possible in web services?yes, We can overload webmethods in a webservice. There is the MessageName property of a WebMethod attribute! The MessageName property enables the XML Web Service to uniquely identify overloaded methods using an alias. The default value of this property is the method name, but you can change it to distinguish this overloaded method implementation from others. When specifying the method name, the resulting SOAP messages will reflect this name instead of an actual method name.What are runtime hosts?the runtime host loads the runtime into a process, creates the application domains within the process, and loads user code into the application domains.What is an application domain ?A process is sub-divided in multiple Application Domain. Each domain can execute a thread. In other word, an application domin isloate between the applicationsTypes of objects in ASP ?Session,Application,Request,Response,serverWhat is viewstate?ViewState is the process of maintaining control properties after postback implemenation. This is done internal using Hidden fields.How do you do validations. Whether client-side or server-side validations are better ?using javascript. Client side validation better.How to implement caching?Data caching: DataView Source;//Declare variable for caching Source = (DataView)Cache["MyDataset"]; if (Source == null) { OleDbConnection objcon = new OleDbConnection(ConfigurationManager.ConnectionStrings["strcon"].ConnectionString); OleDbDataAdapter objcmd = new OleDbDataAdapter("select * from Customer", objcon); DataSet objds = new DataSet(); objcmd.Fill(objds, "Customer"); Source = new DataView(objds.Tables["Customer"]); Cache["MyDataset"] = Source; Label1.Text = "Dataset created explicitly"; } else { Label1.Text = "Dataset retrived from Cache"; } GridView1.DataSource = Source; GridView1.DataBind(); gridbind();What is the difference between and ActiveX dll and control ?Control is control exsample calander control

32

Page 33: ASP Interview Question

Dll is a library Control has an user iinterface but dll doesn't have Dll is plain code only Control have exe but dll doesn'tHow do you add a javascript function for a link button in a datagrid ?onClintClick() add the java funtion name and call it...[you can add a javascript function in the link button of the datagrid under the itemdatabound event as below e.item.findcontrol("linkbtnname") linkbtn.attribute.add("onclick",javascript:returnfuctionname()");]How do you make your site SSL enabled ?ssl-secure sockets layer If you want user certificate authentication enabled, figure out who should have access to your site, and how to distinguish this group from all other users. Some examples of groupings:Fermi people (i.e., FNAL.GOV Kerberos domain users eligible for KCA certificates) DOE-affiliated people (i.e., anyone who has DOEGrids certificate) Specific individuals with certificates from a known set of CAs Anyone with a certificate issued by a particular CA and connecting from a particular domain (e.g., fnal.gov) Some combination of the aboveIf cookies is disabled in client browser will session work ?No session will not work.if we set cookies session to true then it will work.[Sessions are normally tracked with cookies. However, clients are not required to accept cookies. Furthermore, you can turn off the use of cookies for session tracking altogether in the Web Application Server Control Panel. However when cookies are turned off or cookies are not enabled on a specific client computer, the server must work harder to track the session state, which has a performance impact. The recommendation is to leave cookies on and let the server automatically fall back to the cookieless operation only when required by a specific client connection.When a session is created by the server, some information is automatically stored in it - the session ID and a timestamp. as an application developer, you can also store other information in the session in order to make it available to subsequent requests without explicitly passing it to that request.]About Global .asax ?Global.asax is a file that resides in the root directory of your application. It is inaccessible over the web but is used by the ASP.NET application if it is there. It is a collection of event handlers that you can use to change and set settings in your site. The events can come from one of two places - The HTTPApplication object and any HTTPModule object that is specified in web.confg or machine.config. We will be covering both here.[it contains 7 events....1.Application start 2.Application End3.Session on start 4.Session on end 5.Session on Request 6.Application on Begining request 7.Application on Error]About writting a query and SP which is better ?sp is the better one... Its compile and inside that we can write any number of Query Statement , finally for the whole thing it will create only one object as a reference .But in Query Statement Each query be an Objects ...Difference between Active Exe and Dll ?1. EXE can run independaly ,while dll can not.2. An exe can contain manu dll, dll are supprting files containing all information.What is web application virtual directory ?Web applications and vitual directories to share the inforamation over an internet , an intranet or an extranet.web sites , web applications and virtual directories are work together in a hirarichacal relationship as the basic building blocks for hosting online content.web sites containes one or more web applications, web application containes on or more virtual directories.and virtual directory map to physical directory of web server.Difference between application and session ?Session & Appl r parts of State Management ... if v session one object in one form v can use it in all forms untill the project stop's..but,

33

Page 34: ASP Interview Question

In Appl state if v store value it may use throughout applacation even stop and restart it so it is very useful for permanent data...EX:In Some website they ll display the visitors no by incrementing Application State data by One each time a application Restarts..[session object is used to store information between http request for a particular user. Application are globally across users.]what are the types of ASP objects ?Request Response Application Session ServerHow to find the client browser type ?Request.UserAgent[we can identify the browser name using javascript var brw = new navigator();alert(brw.appname);alert(brw.appversion);]About the Usage of htmlencode and urlencode ?Use the Htmlencode method to encode input parameters when generating display.Use the urlencode method to encode the url's recieved as input parametersAbout SOAP ? Simple Object Access Protocol It is preferred way to encode information such as data values before sending it to or from a webservice...About dataset and data mining ?data set is an in memory cache of data retrived from datasource.it is major component of Ado.net. data set is a collection of data tables.that you can relate to each other with data relations. data set can read and write in a XML schema. Data minig some times called as data or knowledge discovery it is a process of analyzing data from different procepectives and summerizing into useful information. information that can be used to increase revenue, cuts costs, or both.Descrie about response.buffer and repsonse.flush ? Respence.Buffer method can be used to specify the current output should be buffered or not. when the buffering is set true, the page will not send output to the client until the scripts on the page has been processing or flush method is call.Response.flush method is used to send buffered output immediatly. when the response.buffer is set true.what are the main advantage in .net?It is a Language independent,It supports all most all 40 LAngauges includeing thrd party languagesHow many types of session in asp.net2.0three types of session states in asp.net InProc OutProc SqlServerwhat is the differance between native code & managed code?native code is cpu dependent and managed code target to clr [The code, which targets clr is called as managed code.managed code that does not have any providers .it is very fast than unmanaged code.If you want to prevent your program from being cracked by hackers, you can use native code. You can cipher/decipher this code, or it may be self-modifying code for more safety.][When the complier translates, it translates the .net source code into MSIL (Microsoft Intermediate Language) which is known as managed code. These managed code is the CPU - independent set of instructions which is later converted into native code (i.e CPU dependent) by the JIT ( Just In-time) compiler before execution.]what is the assembly?Assembly is a small unit for development. Assemblies are provides Reusability,Versioning,and Security..Assemblies will maintain collection of userdefined types and resources information.[Assemblies are small unit of deployment.There are somany types of assemblies they are:1.public 2.private 3.shared. 4.satellitethere will exceutable(.exe) assembly and Library code(.dll). Assembly contain version infornmation,metadata,actual code.]

34

Page 35: ASP Interview Question

Windows Authentication (via Active Directory) and SQL Server authentication (via Microsoft SQL Server username and passwords). Which one is trusted and which one is untrusted?we can log in to sql using both modes .but trusted one is sqlserver username and password is trusted because when ever we connect to the datebase we compulsory have to specify the username and password while establishing the connection ie sqlconnection con(user id ='sqlusername'password='password'intialcatalog='database') but we cant specify in windows authentication is untrusted.Define Query Interface,Adref,Release?every COM object supports atleast one interfaceie IUNKNOWN interface.each interface supports method acess data and perform operations transperantely to the programmer,example iunknown supports 3 methods addref(),release(),queryinterface().if p is apointer to any iunknow.p->addref()increments the reference count2)release().p->deleting the obkects when the reference count reaches zero.,3)queryinterface(idesired,pdesired).p->checks to see if the current interface supports another interface How do we make a poperty read only?Suppose we have a property BarColor the to make it read only useprivate string color;public string BarColor{ get{ return(color);}} // No need to set itWhy do we use Option Explicit?Need to declare all variables explicitly.What are the major differences between asp.net1.1 and asp.net 2.0?Benefits of ASP.NET 2.0 include:1) A wide array of new controls, such as GridView control, MultiView, Wizard and FileUpload.2) Superior separation of design and content, enabling developers and Web designers to work together.3) A new model for compiling and distributing applications. 4) Customization with Web Parts.Bug in ASP.NET 2.0:-If you have a control on a page that is marked Read-Only and EnableViewState is set to false on the Page, the ReadOnly value will no longer post back in ASP.NET 2.0 - the value gets lost. This even though the value is actually returned in the POST buffer.

This behavior is also different than 1.1 which (correctly I say) posted back the READONLY value.[Master Pages]Which template must you provide, in order to display data in a Repeater control? item templateIn what order do the events of an ASPX page execute, As a developer is it important to understand these events? page_init,(this event ocuurs when ever the page is satrted first tine)page_load(i occurs in subsequent requests)controlevents, page_unloadevents[Init Loading Pre Rendering Saving Rendering UnloadingDisposing]How is a property designated as read-only?By ommitting set part of property e.gclass A{ private int n=5;

35

Page 36: ASP Interview Question

public int Number{

get{return n;}}}

[if the property has only get accessor that property is called read only property.]How do you create a permanent cookie?by setting the expiry property greater than datetime.minvalue.....Explain the differences between Server-side and Client-side code?server side code is executed on server side only,client side code is executed on browers machine.What is the role of global.asax?The Global.asax file is in the root application directory. While Visual Studio .NET automatically inserts it in all new ASP.NET projects, it's actually an optional file. It's okay to delete it?if you aren't using it. The .asax file extension signals that it's an application file rather than an ASP.NET file that uses aspx.

The Global.asax file is configured so that any direct HTTP request (via URL) is rejected automatically, so users cannot download or view its contents. The ASP.NET page framework recognizes automatically any changes that are made to the Global.asax file. The framework reboots the application, which includes closing all browser sessions, flushes all state information, and restarts the application domain.[It is used to storing the global information about the application]What is the Difference between user and server controls?There are two main categories of creatable Web controls. User controls are more simple to create, but custom controls are more simple to use. The extra effort that goes into creating custom controls pays off for the developer using the control at design time.User controls are saved with an ASCX file extension. Although they can be easily reused on any of the pages within the project in which they were created, there is no good way to reuse them in a different project. Another downside to user controls is that they only appear on the page at run time; at design time they appear on the page as an ugly gray box, making it difficult to envision how they'll appear to your users.Custom controls can do everything that user controls can do - and much more. The biggest drawback is that they are more challenging and complex to create. Drag and drop is not supported for the creation of these controls. Therefore, all the HTML they output must be generated via code. Pretty much all the articles & controls on this web site are examples of custom controls. In addition to run-time functionality without limits, custom controls support rich design-time functionality. They can appear on a page at design time the same way they'll appear at run time, or differently if preferred. They can be adjusted to change how they'll appear in the toolbox, and how the properties will appear in the properties window. If the properties window doesn't support the desired functionality, it can be extended with custom popup dialog boxes and other UI tricks. Custom controls are easily distributed and can be enhanced with help documentation and licensing functionality, allowing them to be sold to other developers.[1.server controls are dll's and placed in toolbox,1.user controls are pages and it have an extexsion .ascx.It does not placed in toolbox.2.User controls are more simple to create2. but custom controls are more simple to use.]

36

Page 37: ASP Interview Question

What does the "EnableViewState" property do?if we set "enableviewSatate" property of a control to "True"The control will retain its state after post back to serverfor eg The textbox will retain its content after post back.What is the lifespan for items stored in ViewState?untill page expiresWhat are the different types of Session state management options available with ASP.NET?There are 3 types of session modes available in asp.net1)Inproc2)State Server3)SQL ServerHow many classes can a single .NET DLL contain?unlimitedWhich control would you use if you needed to make sure the values in two different controls matched?compare ValidatorWhich property on a Combo Box do you set with a column name, prior to setting the DataSource, to display data in the combo box?in visual studion 2005 DataTextField is used to add column in combo box/..Name two properties common in every validation control?Control To Validate Error MessageWhat base class do all Web Forms inherit from?All the Web forms inherits from Base class known as System.Web.UI.How can you provide an alternating color scheme in a Repeater control?AlternateItemTemplateWhich template must you provide, in order to display data in a Repeater control?ItemTemplateCan you edit data in the Repeater control?NO we can't edit data in Repeater whereas it is possible with datagrid.Which method do you invoke on the DataAdapter control to load your generated dataset with data?Fill MethodWhat is MSIL?converts the specified language in to the intermediate language which in turn is sent to jit compiler which convert the specified language in to the host languageExplain what a diffgram is, and a good use for one?diffgram is an XML format it maintanes the old and original version.Describe the difference between inline and code behind?inline:is written along side the html in a page.code behind:is a concept where the content of page in one file and the server side code is another file...What are the Application_Start and Session_Start subroutines used for?This is where you can set specific variables to the apllication and session objects.

37

Page 38: ASP Interview Question

What is the Global.asax used for?Global.asax file is resides in the root directory of the application. it is also known an asp.net application file.it is responding for the application and session levels events raised by Asp.net. At run time it is compiled dynamically.Can you explain the difference between an ADO.NET Dataset and an ADO Recordset?1. In ADO recordset(in memory representation of data) looks like single table where as in ADO.NET dataset(in-memory representation of data) is a collection of one or more tables(use JOIN Query).2. In ADO you communicate with the database by making the calls to an OLEDB Provider where as in ADO.NET you communicate with the database through a Data Adapter(an OledbDataAdapter,SQLDataAdapter,OdbcDataAdapter or OracleDataAdapter object) which make calls to an OLEDB Provider or the API's provided by the underlying datasource.3. In ADO recordset objects operate in a fully connected state where asin ADO.NET dataset operate in disconnected state. 4. ADO requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types. where asADO.NET does not require data-type conversions.5. In ADO it is sometime sproblematic firewalls( firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing) prevent many types of requets where asin ADO.NET datasets using XML, firewalls can allow datasets to pass.What is the difference between Server.Transfer and Response.Redirect?Server.Transfer transfers the currnet context of the page tothe next page and also avoids double roundtrips. WhereasResponse.Redirect could only pass querystring and alsorequires roundtrip.[Server.Transfer:In Server.Transfer Page their is no round trim between client and server.if u requested a page to server it will directly taken from the server itself

Response.Redirect:-Round Trim between client and server:- if u request a pageExample:client-->server-->client]Should user input data validation occur server-side or client-side? Why?User input data validation should occur on client side.Then for each transaction there is no need to contact with server thereby transactions decreases and efficiency

38

Page 39: ASP Interview Question

increases.What type of code (server or client) is found in a Code-Behind class?Serverside code c# is found in a code behind class.What data types do the RangeValidator control support?string , int, DateIf you want a certain ASP.NET function executed on MouseOver for a certain button. Where do you add an event handler?Code behind button.Attributes.add("onMouseOver", "return functionName();")'What is a bubbled event?When you have a complex control, likeDataGrid, writing an event processing routine for each object (cell, button,row, etc.) is quite tediousdifficult.The controls can bubble up their eventhandlers, allowing the main DataGrid event handler to take care of its constituents.Suppose you want a certain ASP.NET function executed on MouseOver over a certain button.What is the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?Src="MyCode.aspx.cs"? stands for code-behind class to compile Codebehind="MyCode.aspx.cs? stands for code-behind class to DesignWhere do you store the information about the user?s locale?System.Web.UI.Page.CultureWhat namespace does the Web page belong in the .NET Framework class hierarchy?System.Web.UI.PageWhen during the page processing cycle is ViewState available?after intializing and before loading...What methods are fired during the page load?BeginTranaction - only if the request is transactedInit - every time a page is processedLoadViewState - Only on postbackProcessPostData1 - Only on postbackLoad - every timeProcessData2 - Only on PostbackRaiseChangedEvent - Only on PostbackRaisePostBackEvent - Only on PostbackPreRender - everytimeBuildTraceTree - only if tracing is enabledSaveViewState - every timeRender - EverytimeEnd Transaction - only if the request is transactedTrace.EndRequest - only when tracing is enabledUnloadRecursive - Every request What?s the difference between Response.Write() andResponse.Output.Write()?Response.Output.Write() give formatted outputDescribe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process?inetinfo.exe is the microsoft server runing , handling

39

Page 40: ASP Interview Question

ASP.NET request and other things.when the asp.net request is recieved (usually the it gets .aspx extention) the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.how can u display multi language (i.e english,spanish...)web site?Create resource files for each language.. u want to dispaly on the website.(add+new item+resource file)now create instance for resourcemanager class and set its path.set the string(u want to convert) to the resource manager.now panel1.innerhtml=resourcemanager1.string;and so on...[For this you have to use the resource files in which the different language words are associated withthe key so u call the key and select the language then the key will automatically select its value.]main difference between asp.net2.0,asp.net1.1,asp.net1.0Feaures in 2.0:Special folders to make integration easier.navigation controls,login controls,new conrols,Master page,Website without IIS,Pesonalization,[1.Masterpage2.DataGridview3.Member ship control4.ASP.NET Administrator to manage web configfile]Explain what a diffgram is, and a good use for one?A DiffGram is an XML format that is used to identify currentand original versions of data elements . The DataSet usesthe DiffGram format to load and persist its contents, and toserialize its contents for transport across a networkconnection. Whena DataSet is written as a DiffGram, itpopulates the DiffGram with all the necessary information toaccurately recreate the contents, though not the schema, ofthe DataSet, including column values from both the Originaland Current row versions, row error information, and row order.Where would you use an iHTTPModule, and what are thelimitations of any approach you might take in implementing one?One of ASP.NET?s most useful features is the extensibilityof the HTTP pipeline, the path that data takes betweenclient and server. You can use them to extend your ASP.NETapplications by adding pre- and post-processing to each HTTPrequest coming into your application. For example, if youwanted custom authentication facilities for yourapplication, the best technique would be to intercept therequest when it comes in and process the requesting a customHTTP moduleWhat data type does the Range Validator control support?Integer,Date,String,Double,CurrencySuppose you want a certain ASP.NET function executed onMouseOver over a certain button. Where do you add an eventhandler?It?s the Attributesproperty,the Add function inside thatproperty. So

40

Page 41: ASP Interview Question

btnSubmit.Attributes.Add("onMouseOver","someClientCode();")Asimple"Javascript:ClientCode();? in the button control ofthe .aspxpage will attach the handler (javascriptfunction)to the onmouseover eventWhat?s a bubbled event?When you have a complex control, likeDataGrid, writing anevent processing routine for each object (cell, button, row,etc.)is quite tedious. The controls can bubble up theirevent handlers, allowing the main DataGrid event handler totake care of its constituents.What?s the difference between Codebehind="MyCode.aspx.cs"andSrc="MyCode.aspx.cs"?CodeBehind is relevant to Visual Studio.NET only[Code All build Assembly is placed inside the bin folderSrc the source cs file/vb fiel is placed in the source folder and the source file is complied and assembly is placed inside bin folder during runtime of the aspx page]Where do you store the information about the user?s locale?System.Web.UI.Page.CultureWhere does the Web page belong in the .NET Framework classhierarchy?System.Web.UI.PageWhat?s the difference between Response.Write()andResponse.Output.Write()?The latter one allows you to write formatted output.[Response.write - it writes the text stream Response.output.write - it writes the HTTP Output Stream.

They are used to display output text in formatted manner as belowResponse.Write() output fotmat :Response.Write"<h1>" & iTimer & "</h1>"Response.Output.Write() output format :Response.Output.Write("<h2>Process running as {0}</h2>", WindowsIdentity.GetCurrent().Name);]Describe the role of inetinfo.exe, aspnet_isapi.dllandaspnet_wp.exein the page loading process. inetinfo.exe is the MicrosoftIIS server running, handling ASP.NET requests among otherthings.When an ASP.NET request is received(usually a filewith .aspx extension),the ISAPI filter aspnet_isapi.dlltakes care of it by passing the request to the actual workerprocess aspnet_wp.exeDifference between DataView and DataTabledata view is used to filter and give sorting options that u have u added to form or component at design time.Alternatively u can use defaultview that is automatically available for every data table .when u use defaultview , u can specify filter and sorting options in codewhat is postback implementation?when pre-render event n init event is fired?post back event happens when the sender page sends Http request to the same page. checking for ispostback() and then writing the code within the if block would be the implementation for postback.

The following is the order of events that occur when a page

41

Page 42: ASP Interview Question

is loaded.init-> load -> prerender and finally unload.What is a DLL Hell Problem in .Net?WINDOWS REGISTRY CANNOT SUPPORT THE MULTIPLE VERSIONS OF SAME COM COMPONENT.THIS IS CALLED AS THE DLL HELL.[DLL HELL is the problem that occures when an installation of a newer application might break or hinder other application as newer DLLs are copied into the system and the older application do not support or not compatible with them. .net overcomes this problem by supporting multiple versions of an assembly at any given time.this is called side-by-side component versioning.]How to convert a string into an Integer in ASP.net?by two ways u can do that1.int a = Int.Parse("String");2.int a = Convert.Int32("String");How to manage pagination in a page?Using pagination option in DataGrid control. We have to setthe number of records for a page, then it takes care ofpagination by itself.[set allowpaging to true and you have to write some coding in pageindexchanging eventGridView1.PageIndex = e.NewPageIndex; binddata();]Can the validation be done in the server side? Or this canbe done only in the Client side?Validation can be done both Server & Client Side..among all the validatiors only Customer Validation is done at Server Side.. rest of them r done at Client side..How do you validate the controls in an ASP .NET page?by setting the control to validate property in validator to that controlerExplain the life cycle of an ASP .NET page1)Page_Init2)Page_load3)page_prerender4)page_unload[pre-initinitinit-completepre-loadloadload-complateprerenderunload]Why Web Services?To Exchange Data Between Hetrogenious Platforms andHetrogenious Applications.Ex:-Exchange Data between Windows and .NET Application and Linuxand J2EE application.What is a WebService and what is the underlying protocolused in it? Namespace?Web Services enable the exchange of data and the remoteinvocation of application logic using XML messaging to movedata through firewalls and between heterogeneous systems.

The key to understanding Web Services is knowledge of theunderlying protocols. Importantly, by default, all

42

Page 43: ASP Interview Question

communications between Web Services servers and clients isthrough XML messages transmitted over the HTTP protocol.

SOAP (Simple Object Access Protocol) is the protocol thatallows us to encapsulate object calls as XML.

Disco and UDDIYou need to know where and how to locate a Web Service inorder to be able to use it - a process known as discovery.The aim of these two protocols is to facilitate thediscovery process.

WSDLWSDL (WebServices Description Language) does what it says -allows description of the Web Service - it specifies theSOAP messages that it can send and receive.

System.Web.Services.WebService.What base class do all Web Forms inherit from?System.Web.UI.PageWhat tags do you need to add within the asp:datagrid tags tobind columns manuallySet AutoGenerateColumns Property to false on the datagrid tag[Column tag and an ASP:databound tag.]How would you get ASP.NET running in Apache web servers -why would you even do this?You need to create a CLRHost, which hosts the CLR (ASP.NET) on top of Apache.Since Apache is #1 webserver used by many companies, this would allow more number of web site ownersto take advantage of ASP.NET and its richness.What is smart navigation?When a page is requested by an Internet Explorer 5 browser, or later, smart navigation enhances the user's experience of the page by performing the following: * eliminating the flash caused by navigation. * persisting the scroll position when moving from page to page. * persisting element focus between navigations. * retaining only the last page state in the browser's history.

Smart navigation is best used with ASP.NET pages that require frequent postbacks but with visual content that does not change dramatically on return. Consider this carefully when deciding whether to set this property to true. Set the SmartNavigation attribute to true in the @ Page directive in the .aspx file. When the page is requested, the dynamically generated class sets this property.What are the different modes for the sessionstates in the web.config file?Off:Indicates that session state is not enabled.Inproc:Indicates that session state is stored locally.StateServer:Indicates that session state is stored on a remote server.SQLServer:Indicates that session state is stored on the SQL Server.What is the use of sessionstate tag in the web.config file?Configuring session state: Session state features can be configured via the <sessionState> section in a web.config file. To double the default timeout of 20 minutes, you can add the following to the web.config file of an application:<sessionStatetimeout="40"/>

43

Page 44: ASP Interview Question

You ve defined one page_load event in aspx page and samepage_load event in code behind how will prog run?The Page_load method in the aspx page will only run.It takesprecedence over the one in the code behind.What is the difference between control and component?One diffence is,control , such as a DataGrid or simple TextBox ,is a basic element of the user interface.component, which has no visible interface and adds specific functionality to project.What is the namespace for encryption?System.Security.CryptographyWhat are different transaction options?trasaction commit.trasaction rolback.Which is the namespace used to write error message in eventLog File?system.DaignosticsAny alternative to avoid name collisions other then Namespaces?A scenario that two namespaces named N1 and N2 are there both having the same class say A. now in another class i ve written using N1;using N2;and i am instantiating class A in this class. Then how will u avoid name collisions? Ans: using aliasEg: using MyAlias = MyCompany.Proj.Nested;What is the Global ASA(X) File?Global asax file is used to handle application, session level events and to initialise application and session level variables.How to do Caching in ASP?<%@ OutputCache Duration="60" VaryByParam="None" %>VaryByParam value Descriptionnone :One version of page cached (only raw GET)*: n versions of page cached based on query string and/or POST bodyv1: n versions of page cached based on value of v1 variable in query string or POST bodyv1;v2: n versions of page cached based on value of v1 and v2 variables in query string or POST body<%@ OutputCache Duration="60" VaryByParam="none" %><%@ OutputCache Duration="60" VaryByParam="*" %><%@ OutputCache Duration="60" VaryByParam="name;age" %>The OutputCache directive supports several other cache varying options * VaryByHeader - maintain separate cache entry for header string changes (UserAgent, UserLanguage, etc.) * VaryByControl - for user controls, maintain separate cache entry for properties of a user control * VaryByCustom - can specify separate cache entries for browser types and version or provide a custom GetVaryByCustomString method in HttpApplicationderived classAsp.net - How to find last error which occurred?Exception LastError;String ErrMessage;LastError = Server.GetLastError();if (LastError != null)ErrMessage = LastError.Message;

44

Page 45: ASP Interview Question

elseErrMessage = "No Errors";Response.Write("Last Error = " + ErrMessage);How can u handle Exceptions in Asp.Net?using system.exceptions namespaceTry Piece of code ..Catch objError as Exceptions display objError.messageFinally[try{ //set of code}catch(Exception1 e){ //error display}catch(Exception2 e){ //error display}finally{ //compulsory execution will be done here}]What is SQL injection?An SQL injection attack "injects" or manipulates SQL code by adding unexpected SQL to a query.Many web pages take parameters from web user, and make SQL query to the database. Take for instance when a user login, web page that user name and password and make SQL query to the database to check if a user has valid name and password.Username: ' or 1=1 ---Password: [Empty]This would execute the following query against the users table:select count(*) from users where userName='' or 1=1 --' and userPass=''How can you debug an ASP page, without touching the code?Microsoft script Debugger or Visual InterDevWhich two properties are there on every validation control?ControlToValidate and Text or ErrorMessage properties[Validator Control Basics

All of the validation controls inherit from the base class BaseValidator so they all have a series of properties and methods that are common to all validation controls. They are:? ControlToValidate - This value is which control the validator is applied to.

? ErrorMessage - This is the error message that will be displayed in the validation summary.

? IsValid - Boolean value for whether or not the control is valid.

45

Page 46: ASP Interview Question

? Validate - Method to validate the input control and update the IsValid property.

? Display - This controls how the error message is shown.]What are validator? Name the Validation controls in asp.net?How do u disable them?Validator means checking inputed data in any field like textBox or dropdownbox any other which we want to validate at client side using sever tag.

Following are type of validator control in asp.net.1. Ranage validator control2. RequireFieldvalidator control3. CompareValidator control4. RegularExpressionValidator control5. CustomValidator control6. ValidationSummary control

if we mention in our page but want to disable just use the property of validator control causevalidation=false.How do you specify whether your data should be passed asQuery string and Forms (Mainly about POST and GET)when form is submitted via POST method, FORms collection is created. values are stoed in forms collection.

When form submitted via GET method, values are stored in Querystring collectionWhat are the different authentication modes in the .NETenvironment?nonewindowsformspassportWhat is role-based security?Role Based Security lets you identify groups of users to allow or deny based on their role in the organization.In Windows NT and Windows XP, roles map to names used to identify user groups.

Windows defines several built-in groups, including Administrators, Users, and Guests.To allow or deny access to certain groups of users, add the <ROLES>element to the authorization list in your Web application's Web.config file.e.g.

<AUTHORIZATION>< authorization > < allow roles="Domain Name\Administrators" / > < !-- Allow Administrators in domain. -- > < deny users="*" / > < !-- Deny anyone else. -- >< /authorization >Explain authentication levels in .net ?BasicDigestWindows

46

Page 47: ASP Interview Question

FormsPassport[There are 3 authentication levels in .net 1.Windows2.Forms3.Passport

Basic and Digest Come under IIS Authentication Levels.]How to do Forms authentication in asp.net?in webconfig file

<authentication mode="Forms"><forms cookieless="UseCookies" loginUrl="~/LoginInformation.aspx" timeout="10"><credentials passwordFormat="Clear"><user name="Siva" password="siva"/><user name="joseph" password="jos"/></credentials></forms></authentication>

After In a aspx.cs page you have write a below coding

if (FormsAuthentication.Authenticate(TextBox1.Text, TextBox2.Text)) { Response.Write("Hi Joseph"); } else { Response.Write("Please Create account"); }How .Net has implemented security for web applications?1) Authentication/Authorization2) Encryption/Decryption3) Maintaining web servers outside the corporate firewall. etc.,Security types in ASP/ASP.NET? Different Authentication modes?There r 3 types of security in .Net1.Windows Authentication(i)Anoymous(ii)Basic(iii)Digest(iv)Windows integated2.Micsoft Authentication3.Form AuthenticationHow do you create a permanent cookie?Cookie is like a temporary file which contains a name and a value pair and resides in the client.

cookie prepared or modified by the server side script will be appended to the response and will be sent to the client.

dim cook as httpcookiecook=new httpcookie("items")cook.value=textbox1.textresponse.appendcookie(cook).

47

Page 48: ASP Interview Question

[You can set the permanent cookied by setting the expiry date to the MaxDate

<%Response.Cookies("username") = "you"Response.Cookies("username").Expires = Date.MaxValue %>]What is State Management in .Net and how many ways are thereto maintain a state in .Net?In .net state management means request send by the client can remember state of the previous request means maintaining the state of the request.

The ways to maintain the state in asp.net are server side state management like1)session management2)application client side state management like1)cookies2)Hidden fields[state management is the art of retaining information betweenrequests.

There are two types of statemanagement options in .net?1)client side state management.2)Server side state management.

In client side state management.1)view state2)query string 3)custom cookies

In server side state management.1)Session state.2)application state.]What method do you use to explicitly kill a users session?Session.Abandon()How you will handle session when deploying application inmore than a server? Describe session handling in a webfarm,how does it work and what are the limits?State Server aspnet_state.exeSql ServetHow many classes can a single .NET DLL contain?It can contain many classes.True or False: To test a Web service you must create awindows application or Web application to consume this service?False, the webservice comes with a test page and itprovides HTTP-GET method to test.Which control would you use if you needed to make sure thevalues in two different controls matched?CompareValidator ControlWhich property on a Combo Box do you set with a column name,prior to setting the DataSource, to display data in thecombo box?DataTextField propertyWhere on the Internet would you look for Web services?www.uddi.org

48

Page 49: ASP Interview Question

What does WSDL stand for?Web Services Description LanguageTrue or False: A Web service can only be written in .NET?FalseWhat is the transport protocol you use to call a Web service?SOAP is the preferred protocolSMTP,HTTP,SOAPWhat tag do you use to add a hyperlink column to the DataGrid?<asp:HyperLinkColumn>What tags do you need to add within the asp:datagrid tags tobind columns manually?<asp:DataGrid ID="gridename" runat="server"> <Columns> <asp:BoundColumn ataField="fieldname"></asp:BoundColumn> </Columns> </asp:DataGrid>What base class do all Web Forms inherit from?The Page class.What property must you set, and what method must you call inyour code, in order to bind the data from some data sourceto the Repeater control?You must set the DataSource property and call the DataBindMethodCan you edit data in the Repeater control?No, it just reads the information from its data sourceWhich method do you invoke on the DataAdapter control toload your generated dataset with data?The .Fill() methodIf I?m developing an application that must accommodatemultiple security levels though secure login and my ASP.NETweb application is spanned across three web-servers (usinground-robin load balancing) what would be the best approachto maintain login-in state for the users?Maintain the login state security through a database.Can you give an example of what might be best suited toplace in the Application_Start and Session_Start subroutines?This is where you can set the specific variables for theApplication and Session objects.Can you explain the difference between an ADO.NET Datasetand an ADO Recordset?? A DataSet can represent an entire relational database inmemory, complete with tables, relations, and views. ? A DataSet is designed to work without any continuingconnection to the original data source. ? Data in a DataSet is bulk-loaded, rather than being loadedon demand. ? There's no concept of cursor types in a DataSet. ? DataSets have no current record pointer You can use ForEach loops to move through the data. ? You can store many edits in a DataSet, and write them tothe original data source in a single operation. ? Though the DataSet is universal, other objects in ADO.NETcome in different versions for different data sources. Should validation (did the user enter a real date) occurserver-side or client-side? Why?Client-side. This reduces an additional request to theserver to validate the users input.

49

Page 50: ASP Interview Question

What type of code (server or client) is found in aCode-Behind class?Server-side code.What data type does the RangeValidator control support?Integer, String and Date.Suppose you want a certain ASP.NET function executed onMouseOver overa certain button. Where do you add an eventhandler?It?s the Attributesproperty, the Add function inside thatproperty. SobtnSubmit.Attributes.Add("onMouseOver","someClientCode();")Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading processinetinfo.exe is the Microsoft IIS server running, handlingASP.NET requests among other things. When an ASP.NET requestis received (usually a file with .aspx extension), the ISAPIfilter aspnet_isapi.dll takes care of it by passing therequest to the actual worker process aspnet_wp.exe.You create an assembly to access data in a relationaldatabase. This assembly will be used by several ASP.NETapplications on your Web server. You need to ensure that all your applications can access theassembly. Which two actions should you take (Each Answer: presentspart of the solution.)? (Choose two) A . Run the Assembly Registration tool (Regasm.exe). B . Run the String Name tool (Sn.exe). C . Run the Installer tool (Intallutil.exe). D . Run the Global Assembly Cache tool (Gacutil.exe).options C and DYou are planning the deployment of an ASP.NET application.The application uses a Visual Studio .NET component namedDataAccess that will be shared with other applications onyour Web server. You are using Visual Studio .NET to create a WindowsInstaller package. You need to deploy DataAccess and theASP.NET application so that they can be uninstalled later ofnecessary. What should you do? A . Create a setup project for DataAccess. Add the ASP.NETapplication in a custom action. B . Create a setup project for the ASP.NET application.Create another setup project for DataAccess. C . Create a Web setup project for the ASP.NET application.Add a project output for DataAccess. D . Create a Web setup project for the ASP.NET application.Add a merge module for DataAccess.dYou create an ASP.NET application for a hotel. Theapplication contains a page that displays current weatherconditions for the city in which the hotel is located. Theapplication calls an XML Web service every 10 minutes toupdate the current weather conditions. A new page is thendisplayed for subsequent requests. You want the same page to be cached and retrieved from thecache during the time between calls to the XML Web service.You decide to use a Page directive to accomplish this goal.

50

Page 51: ASP Interview Question

Which Page directive should you use? A . <%@ Cache Seconds="600 '' VaryByParam="Page" %> B . <%@ OutputCache Time="600" %> C . <%@ OutputCache Duration="600" VaryByParam="None" %> D . <%@ OutputCache Duration="600" %> C . <%@ OutputCache Duration="600" VaryByParam="None" %>Your ASP.NET application displays sales data on a page. Youwant to improve performance by holding the page in memory onthe server for one hour. You want to ensure that the page isflushed from memory after one hour, and that the page isre-created when the next request for the page is received. What should you do? A . Initialize a new instance of the Cache class in theApplication.Start event handler. B . Initialize a new instance of the Timer class in thePage.Load event handler. C . Set the Duration attribute of the OutputCache directivein the page. D . In the Web.config file, set the timeout attribute of thesessionState element. C[or D]You are creating a Web site for Your company. You receiveproduct lists in the form of XML documents. You are creatinga procedure to extract information from these XML documentsaccording to criteria that your users will select. When a user makes a request, you want the results of theserequests to be returned as quickly as possible. What should you do?

A . Create an XmlDataDocument object and load it with theXML dat Use the DataSet property of the object to create aDataSet object. Use a SQL SELECT statement to extract therequested dat B . Create an XmlDataDocument object and load it with theXML data. Use the SelectNodes method of the object toextract the requested data. C . Create an XPathDocument object and load it with the XMLdata. Call the CreateNavigator method to create anXPathNavigator object. Call the Select method of theXPathNavigator object to run an XPath query that extractsthe requested data. D . Create an XmlReader object. Use the Read method of theobject to stream through the XML data and to apply an XPathexpression to extract the requested data. CYour manager has asked you to describe what you would useapplication variables for. What statement best describes theuse of application variables?

a) Application Variables are used to keep state for eachconnected user.b) Application Variables are used to keep state for the web sitec) Application Variables are used to keep state for theapplication on the serverd) Application Variables are used to keep state for allapplications objects in the web site.C

51

Page 52: ASP Interview Question

You have been given the task of designing a web services toexpose the data that is stored in a database on the server.In order to successfully build the web services, you need toimport some namespaces. What is the minimum namespace youneed to import?

a) System.Webb) System.WebServicesc) System.Web.Servicesd) System.Web.ServiceModelC

What line in the following XML document will generate an error?<?xml version=?1.0?>

<employees><employee>

<name>Bob Andcarrol</name></employee><employee>

<name>Robert Burns</name></employee>

</employees>

a) 6b) 4c) 1d) There is no error

c

How many rules are there regarding a well formed XML document?a) Nineb) Threec) Sixd) Two

aYou are using the try? catch block seen in the followingcode segment, but no exceptions are ever caught by the catchblock. What is the problem?

SqlConnection cn =new sqlConnection(strSQL); SqlDataSet ds;

try{

cn.open(); //perform the data processing steps

??..} catch (OleDbException e) {?..}

a) The exception class is wrong; it should be sqlErrors.b) The exception class is wrong; it should be

52

Page 53: ASP Interview Question

sqlSyntaxExceptios.c) The exception class is wrong; it should be sqlExceptions.d) The exception class is wrong; it should be sqlExcptions.

CYou need to retrieve data from a Microsoft SQL Server 2000.Currently you are using an oleDbConnection object to connectto the database server. You need to be able to retrieve thedata from the database server in XML format. Which approachwould be the most efficient? Select all that apply. Eachanswer constitutes part of the whole answer.

a) Change to the SQL .NET provider.b) Use the ExecuteXmlReader() method of the xxxCommand objectc) Use the DOM to create the XML document.d) Use the XmlDocument.Load() method to create the XML Document.

COn what object is the transaction in ADO.NET focused on?a) The command objectb) The DataSet objectc) The Connection objectd) The DataAdapter object

d

When would you not use the oleDbConnection object?a) To connect to an SQL 7.0 database.b) To connect to a DB/2 database.c) To connect to an Access database.d) To connect to an SQL 6.5 database.

AWhat property is used on the datatable to indicate aconflict after an update?a) HasConflictb) HasErrorc) HasCollisiond) HasDataErrorbWhat object is used to encapsulate a rowset?a) DataSetb) DataAdapterc) DataRowSetd) DataTableaWhat is a transaction?a) A banking term.b) A concept used to describe a step in the business process.c) A combination of DML steps that must succeed or the datais retuned to its initial state.d) A combination of DDL steps that must succeed or the datais retuned to its initial state.CWhat does the following SQL statement return, assuming thatall tables and column names are correct?SELECT FirstName, StreetAddress

53

Page 54: ASP Interview Question

FROM EmployeesJOIN AddressBookON Employees.EmpID = AddressBook.EmpID

a) Nothing, the JOIN syntax is wrong.b) All the records form the Employees table, and only thematching ones form the StreetAddress table.c) All the records from the StreetAddress table and only thematching records form the Employees table.d) Only the matching records from the two tables.D[I think the state ment above should return the records from matching records from two talbes since the JOIN state ment specifies the middle element..i.e employee...let us see how it works..lets say we hav two elemt rows( here i am taking the only one column from each table since it would provide us with the required understanding....)

employees addressbook---------- ------------EMP_NAME EMP_NAME-------- -----------ram raju raj harishravi hanirohit jitenderraju finamanish kittu

now when these two statements are joined ,first of all the first state ment is scanned and its first element i.e 'ram' is matched againest the all the element of thhe other list i.e addressbook...if it finds the name 'ram' in addressbook it will select it as a part of the result otherwise it just looks move on to another one thats 'raj'...n one important thing ... in case 'ram' finds the match in the addressbook twice...it will not take bothe of them .....it will skip all the others and move on to the next row....]How do you enable tracing?a) Set the Trace property of the Web Form to Trueb) Set the Trace property of the server object to Truec) Set the Session variables Trace to Trued) Set the Applications Variable Trace to True.AWhat method must be overridden in a custom control?a) The Paint() methodb) The Control_Build() methodc) The Render() methodd) The default constructorcAfter building the custom control, you test it by adding anASP.Net web application to the solution. You add a correct<%@ Register %> directive and a proper declaration of thecontrol in the <asp:Form> tag to the Web Form, but when youexecute the application you get an error. What is the mostlikely reason for the problem?

54

Page 55: ASP Interview Question

a) The custom control must be compiled first.b) The web application must have a reference to the controlc) The custom control must be registered with windows first.d) The assembly from the custom control is not in theapplication?s bin directory.DWhat is the result when the Web Form containing thefollowing line is complied and executed?

<asp:Button id=?thebutton? onClick=?theEvent? />

a) The button control is created; theEvent is the clickevent handler.b) Compiler error; the control must be set to runat=?server?.c) Compiler error; onClick is not a valid attribute.

d) Runtime Exception; the control must be set to runat=?server?.D

After capturing the SelectIndexChanged event for a ListBoxControl, you find that the event handler doesn?t execute.What could be the problem be?

a) The AutoEventWireup attribute is set to Falseb) The AutomaticPostBack attribute is set to Falsec) The codebehind module is not properly compiledd) The ListBox must be defined WithEvents.Set AutomaticpostBack attribute is true..What is the Web.config file used for?a) To store the global information and variable definitionfor the application.b) Configures the time that the server-side codebehindmodule is calledc) To Configure the Web Server.d) To Configure the Web browser.AWhat layout mode is the default when a new Web Form is created?

a) GridBagLayoutb) GridLayoutc) FlowLayoutd) FormLayoutbGiven an ASP.NET Web Form called WebFrom1, what class doesthe WebForm1 class inherit from by default?

a) System.Web.Formb) System.Web.GUI.Pagec) System.Web.UI.Paged) System.Web.UI.FormcWhen an ASP.NET server control is added to a web form,Visual Studio .NET adds one item to the class for the form.What item is added?

a) The event registration.b) A protected class member for the control.c) A default event handler for the click event.d) A default class that inherits from the control?s base class.

55

Page 56: ASP Interview Question

BWhen working with ASP.Net server controls, it is importantto use the right event handlers to capture the event for theapplication to function properly. What event would you useto capture the selection of a new item in a DropDownListcontrol?a) The Click event.b) The SelectionChanged event.c) The SelectionIndexChanged event.d) The ChangedSelection event.CWhat is the purpose of the following segment?

If ( !IsPostBack){sqldataAdapter1.Fill (dsusers1);DataGrid1.DataBind ();}

a) To populate the DataAdapter the first time the web pageid displayed.b) To populate the DataSet every time the web page is displayed.c) To populate the DataAdapter every time the web page isdisplayed.d)To populate the DataSet the first time the web page isdisplayed.To populate the DataSet the first time the web page isdisplayed. i.e Instance is created first time with this.What ASP.NET object encapsulates the state of the client andthe browser?a) The Session objectb) The Application objectc) The Response objectd) The Request objecte) The Server objectdWhat is the name of the process the browser uses to find theaddress of a web server?a) DMZb) DNSc) Active Directoryd) Database lookupbWhat definition correctly defines a label server controlwith the name set to lblHoop?a) <asp:Label name=?lblHoop? runat=?server? />b) <Label id=?lblHoop? runat=?server? />c) <asp:Label id=?lblHoop? runat=?server? />d) <server label name=?lblHoop? runat=?asp? />cWhat are the main components of the ADO object model? Howare they used?Connection,Command,Recordset are the main components of ADO object. And others are Error, Field, Parameter, Property, Record, and Streams.Describe and In Process Vs Out of Process component. Whichis faster?An inprocess is one which runs in the same process area as that of the client giving tha advantage of speed but the

56

Page 57: ASP Interview Question

disadvantage of stability becoz if it crashes it takes the client application also with it.

Outprocess is one which works outside the clients memory thus giving stability to the client, but we have to compromise a bit on speed.

Inprocess is faster than outprocess.What is versioning in .NET?Versoning enables to solve the DLL hell problem in .net which is found in ASP and VB. DLL hell is nothing but a higher verson of DLL overwrites the older version.Briefly describe different techniques for ASP.NET StateManagement?There are different techniques for ASP.NET State Management1. View State2. Cookies3. Session4. Cache5. Application, Etc.,Explain how server control validation controls works?To perform server side validation we have an event called ?ServerValidate?. Syntax:ValidationControlName_ServerValidate(s, args){?..//Logic}For Web services where you can browse on the Internet?For consuming Web services first we have to go to the UDDIdirectory .In the UDDI directory we can find a link to discovery file.Then we can make a request for WSDL document.

This WSDL contains description of the services.Then we have to integrate the webserice into our application.To call a Web service SOAP which transport protocol you use?HTTP ProtocolWhich color scheme in a Repeater control can you provide alternatively?using Alternatingitemtemplate in repeater .web user and custom conrolsCustom controls:

A control authored by a user or a third-party software vendor that does not belong to the .NET Framework class library. This is a generic term that includes user controls. A custom server control is used in Web Forms (ASP.NET pages). A custom client control is used in Windows Forms applications.

User Controls:

In ASP.NET: A user-authored server control that enables an ASP.NET page to be re-used as a server control. An

57

Page 58: ASP Interview Question

ASP.NET user control is authored declaratively and persisted as a text file with an .ascx extension. The ASP.NET page framework compiles a user control on the fly to a class that derives from the System.Web.UI.UserControl class.is it possible to persiste customize object in view state? how it is?Yes it is possible to persiste customize object in view state, Supposed your are having one variable named x for which you want to persist the view state.

dim x as integerViewState(Value) = x

Which can then be accessed as follows:

x = ViewState(Value) User contro having 4 text boxes given validation controls. i want to execute validations after the button click event how it is?Write the code for validations in the button control.when the user control event occur in ASp page life cycle?When ever a page is called the control event is generated.What is the method used to load generated dataset with data on the DataAdapter control ?The method used to load generated dataset with data on the DataAdapter control is the Fill() method.When is the ViewState available during the page processing cycle ?ViewState is available After the Init() and before the Page_Load(), or OnLoad() for a control.Is it necessary to create a Windows application or Web application to test a Web service ? Is it must to consume this service?No, not necessary, to test a web service it provides HTTP-GET method to test.That too the web service comes with a test page. Explain how inline and code behind is used differently ?writting a code along side the html in a page is inline code. Writing a code in a separate file and referenced by the .aspx page is code Behind.Where can we set the specific variables for a application and Session objects ?Application variable value is static value and not expired the value.ex:

application("vari name")=10

session vari., value have been expired 2 their duration of session timing...

ex: session("vari-name")=12

58

Page 59: ASP Interview Question

In a Code-Behind class generally which type of code is found ?In a code-Behind class server-side code is found. Because code-behind is executed on the server. Eventhough it can render client-side code such as JavaScript to be processed in the clients browser. But just to be clear, code-behind executes on the server, thus making it server-side code.What is the main use of Response.Output.Write()?To write formatted output Response.Output.Write() function is used.What is the difference between a Stored procedure and function?Function allways returns value but stored procedure may or may not return value.Is data can be edited in the Repeater control?No data can not be edited in the repeater control. Repeater control just reads the information from its data source.What is the base class of .NET?System.objectWhat is an Interface and What is an Abstract Class?An abstract class is a parent class that allows inheritance but can never be instantiated

Abstract classes are the classes with no implementation of methods or concerete implementation of methods

An Interface can inherit several interfaces.

59