Sie sind auf Seite 1von 30

What is a Constructor?

A constructor is a member function that has the same name as the class name and is invoked
automatically when the class is instantiated. A constructor is used to provide initialization code
that gets executed every time the class is instantiated.

Points to be noted on constructors:


• Constructors cannot be "virtual". They cannot be inherited.
• Constructors are called in the order of inheritance.
• If we don't write any constructor for a class, C# provides an implicit default
constructor, i.e., a constructor with no argument.
• Constructors cannot return any value.
• Constructors can be overloaded.
The syntax for a constructor is as follows:
[modifier] name (parameters)
{ // constructor body}
A constructor can have the following modifiers. public, protected, internal, private, extern
Two types: Static or class constructors & Non–static or instance constructors
Static Constructors
• A static constructor or class constructor gets called when the class is instantiated or a
static member of the class is used for the first time.
• A Static constructor cannot be overloaded.
• It should be without parameters and can only access static members.
• It cannot have any access modifiers.
• The static constructor for a class executes only once in an application domain.
• Static constructors cannot be chained with other static or non-static constructors.
• Static Constructor Executes Before an Instance Constructor.
In the program that follows, the static constructor is invoked once the static variable of the class is
referenced.
using System;
class Test
{
private static int i;
static Test()
{
Console.WriteLine ("Static Constructor.");
}
public static int Assign
{
set
{
i = value;
}
get
{
return i;
}
}
}
class Sample
{
public static void Main()
{
Test.Assign = 2;
}
}

Listing 2: Static Constructor Executes Before an Instance Constructor


using System;
class TestClass
{
static TestClass ()
{
System.Console.Write("Static ");
}
public TestClass ()
{
System.Console.Write("Instance ");
}
}
class Test
{
static void Main()
{
new TestClass ();
Console.ReadLine ();
}
}
The output of the above program is 'Static Instance'. A static constructor can only access static
members of a class. The reason is that at the time when a static constructor is loaded in the
memory, the instance members of a class are not available. In the following program, the
assignment to the non–static integer variable p inside the static constructor is an error.
Listing 3: Static Constructor Can Access Only Static Members
class Test
{
int p;
static Test()
{
p = 9;
}
public static void Main(string []args)
{
Test testObject = new Test();
/*Error: An object reference is required for the
non-static field, method,
or property 'Test.p'*/
}
}
Non-Static or Instance Constructors
Non-static constructors are also called instance constructors, type constructors, or type
initializers, and are used to create and initialize instances of the class they belong to. We can
have multiple non-static constructors but only one static constructor for a class. A non-static
constructor with no parameters is called the default constructor. If we do not write any constructor
for a class, the compiler automatically supplies one. This is the implicit default constructor. This
property of C# to supply an implicit default constructor is revoked once we write any constructor
for a class.
Non-static constructors can be public, private, protected, external, or internal. A public constructor
is one that is called when the class is instantiated. A private constructor is one that prevents the
creation of the object of the class. It is commonly used in classes that contain only static
members. A class containing an internal constructor cannot be instantiated outside of the
assembly. An internal constructor can be used to limit concrete implementations of the abstract
class to the assembly defining the class. A protected constructor allows the base class to do its
own initialization when subtypes are created. When constructor declaration includes an extern
modifier, the constructor is said to be an external constructor. An external constructor declaration
provides no actual implementation and hence does not contain any definition. It is to be noted
that a public constructor can access a private constructor of the same class through constructor
chaining.
Listing 4: Public Constructor Can Access Private Constructor of the Same Class
using System;
class Test
{
public Test(): this(10)
{
Console.WriteLine("Default Constructor");
}
private Test(int intValue)
{
Console.WriteLine("Parameterized Constructor");
}
public static void Main(string []args)
{
Test testObject = new Test();
Console.ReadLine ();
}
}
The output is as follows:
Parameterized Constructor
Default Constructor

A protected constructor can only be invoked from the subclasses of the class in which it is
defined. This is illustrated in the example that follows.
Listing 5
using system;
class B
{
protected B (string s) {}
}
class D : B
{
public D () : base ("Called from D class") {}
}
class E
{
public static void Main(string []args)
{
B x = new B ("Called from E class");
/*Error. The constructor test.B.B(string s) is inaccessible due to its
protection level*/
}
}
Constructor Overloading
A constructor can take zero or more arguments as parameters. A constructor with zero arguments
is known as the default constructor. We can have multiple constructors in a class with different
sets of signatures. Such constructors are known as “overloaded constructors”. The overloaded
constructors of a class must differ in their number of arguments, type of arguments, and/or order
of arguments. This gives the user the ability to initialize the object in multiple ways.
The class in the program shown below contains three constructors. The first is the default
constructor, followed by the two argument constructors. Note that the constructors differ in their
signature.
Listing 6: Overloaded Constructors
using system;
public class Test
{
public Test()
{
//Default constructor
}
public Test(int sampleValue)
{
// This is the constructor with one parameter.
}
public Test(int firstValue, int secondValue)
{
// This is the constructor with two parameters.
}
}

Constructor Chaining
Constructor chaining refers to the ability of a class to call one constructor from another
constructor. In order to call one constructor from another, we use base (parameters) or : this
(parameters) just before the actual code for the constructor, depending on whether we want to
call a constructor in the base class or in the current class.
Listing 7: Constructor Chaining
using system;
public class Test
{
public Test(): this(10)
{
// This is the default constructor
}
public Test(int firstValue)
{
// This is the constructor with one parameter.
}
}

Constructors and Inheritance


A constructor of a base class is not inherited to its derived class. However, a derived class
constructor can call a base class constructor, provided both are non-static.
Listing 8: Invoking a Base Constructor from the Derived Class
using System;
class Base
{
public Base()
{
Console.WriteLine("Base Constructor Version 1");
}

public Base(int x)
{
Console.WriteLine("Base Constructor Version 2");
}
}

class Derived : Base


{
public Derived():base(10)
{
Console.WriteLine("Derived Constructor");
}
}

class MyClient
{
public static void Main()
{
Derived dObject = new Derived();
//Displays 'Base Constructor Version 2' followed by 'Derived Constructor'.
}
}
Constructors are executed in the order of inheritance as shown in the example below.
Listing 9: Order of Execution of Constructors in Inheritance
using System;
class Base
{
public Base()
{
Console.WriteLine("Base constructor");
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine("Derived constructor");
}
}
class Test
{
public static void Main()
{
Derived dObject = new Derived();
//Displays 'Base constructor' followed by 'Derived constructor'.
}
}
It is not possible to inherit a class that has only a private constructor.
Listing 10: Private Constructors Prevent Inheritance
using system;
class Base
{
Base( )
{
}
}
class Derived : Base // Syntax Error.
{
public static void Main()
{
Derived dObject = new Derived ();
}
}
Conclusion
The best practice is to always explicitly specify the constructor, even if it is a public default
constructor. Proper design of constructors goes a long way in solving the challenges faced in
class designs.

C# Delegates Explained
A delegate is an object that refers to a static method or an instance method
A delegate is an object that is created to refer to a static method or an instance method, and then
used to call this method. To start off, you create a new delegate type in a different way than you
create any other class. You use the delegate keyword as in the following statement.
public delegate int DelegateToMethod(int x, int y);
The First Delegate Example
using System;
namespace Delegates
{
public delegate int DelegateToMethod(int x, int y);

public class Math


{
public static int Add(int first, int second)
{
return first + second;
}

public static int Multiply(int first, int second)


{
return first * second;
}

public static int Divide(int first, int second)


{
return first / second;
}
}

public class DelegateApp


{
public static void Main()
{
DelegateToMethod aDelegate = new DelegateToMethod(Math.Add);
DelegateToMethod mDelegate = new DelegateToMethod(Math.Multiply);
DelegateToMethod dDelegate = new DelegateToMethod(Math.Divide);
Console.WriteLine("Calling the method Math.Add() through the aDelegate object");
Console.WriteLine(aDelegate(5,5));
Console.WriteLine("Calling the method Math.Multiply() through the mDelegate object");
Console.WriteLine(mDelegate(5,5));
Console.WriteLine("Calling the method Math.Divide() through the dDelegate object");
Console.WriteLine(dDelegate(5,5));
Console.ReadLine();
}

}
}
Multicast Delegates
A multicast delegate is an object that maintains a linked list of delegates. Invoking the delegate
invokes each delegate (which in turn calls its encapsulated method) in the same order that it has
been added to the linked list. In our example we have created an object (a delegate) called
multiDelegate of type Math.DelegateToMethod and assigned a null value to this object.

using System;
namespace Delegates
{
public class Math
{
// note that the delegate now is a nested type of the Math class
public delegate void DelegateToMethod(int x, int y);

public void Add(int first, int second)


{
Console.WriteLine("The method Add() returns {0}", first + second);
}

public void Multiply(int first, int second)


{
Console.WriteLine("The method Multiply() returns {0}", first * second);
}

public void Divide(int first, int second)


{
Console.WriteLine("The method Divide() returns {0}", first / second);
}
}

public class DelegateApp


{
public static void Main()
{
Math math = new Math();
Math.DelegateToMethod multiDelegate = null;
multiDelegate = new Math.DelegateToMethod(math.Add);
multiDelegate += new Math.DelegateToMethod(math.Multiply);
multiDelegate += new Math.DelegateToMethod(math.Divide);
multiDelegate(10,10);
Console.ReadLine();
}
}
}
Operator Overloading In C#
The mechanism of giving a special meaning to a standard C# operator with respect to a user
defined data type such as classes or structures is known as operator overloading. Remember
that it is not possible to overload all operators in C#. The following table shows the operators and
their overloadability in C#.
Operators Overloadability

+, -, *, /, %, &, |, <<, >> All C# binary operators can be overloaded.

+, -, !, ~, ++, --, true, false All C# unary operators can be overloaded.

==, !=, <, >, <= , >= All relational operators can be overloaded,
but only as pairs.

&&, || They can't be overloaded

() (Conversion operator) They can't be overloaded

+=, -=, *=, /=, %= These compound assignment operators can be


overloaded. But in C#, these operators are
automatically overloaded when the respective
binary operator is overloaded.

=, . , ?:, ->, new, is, as, sizeof These operators can't be overloaded

In C#, a special function called operator function is used for overloading purpose. These special
function or method must be public and static. They can take only value arguments. The ref and
out parameters are not allowed as arguments to operator functions.
The general form of an operator function is as follows.
public static return_type operator op (argument list)
Where the op is the operator to be overloaded and operator is the required keyword. For
overloading the unary operators, there is only one argument and for overloading a binary operator
there are two arguments. Remember that at least one of the arguments must be a user-defined
type such as class or struct type.
Overloading Unary Operators The general form of operator function for unary operators is as
follows. public static return_type operator op (Type t) { // Statements } Where Type must be a
class or struct. The return type can be any type except void for unary operators like +, ~, ! and dot
(.). but the return type must be the type of 'Type' for ++ and o remember that the true and false
operators can be overloaded only as pairs. The compilation error occurs if a class declares one of
these operators without declaring the other.
The following program overloads the unary - operator inside the class Complex
// Unary operator overloading
using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine(\"{0} {1}\",x,y);
}

public static Complex operator -(Complex c)


{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}

class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
c2.ShowXY(); // diapls -10 & -20
}
}

Overloading Binary Operators


An overloaded binary operator must take two arguments, at least one of them must be of the type
class or struct, in which the operation is defined. But overloaded binary operators can return any
value except the type void. The general form of a overloaded binary operator is as follows.

public static return_type operator op (Type1 t1, Type2 t2)


{
//Statements
}

A concrete example is given below


// binary operator overloading
using System;
class Complex
{
private int x;
private int y;
public Complex()
{
}
public Complex(int i, int j)
{
x = i;
y = j;
}

public void ShowXY()


{
Console.WriteLine(\"{0} {1}\",x,y);
}

public static Complex operator +(Complex c1,Complex c2)


{
Complex temp = new Complex();
temp.x = c1.x+c2.x;
temp.y = c1.y+c2.y;
return temp;
}
}

class MyClient
{
public static void Main()
{
Complex c1 = new Complex(10,20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex(20,30);
c2.ShowXY(); // displays 20 & 30
Complex c3 = new Complex();
c3 = c1 + c2;
c3.ShowXY(); // dislplays 30 & 50
}
}

The binary operators such as = =, ! =, <, >, < =, > = can be overloaded only as pairs. Remember
that when a binary arithmetic operator is overloaded, corresponding assignment operators also
get overloaded automatically. For example if we overload + operator, it implicitly overloads the + =
operator also.

Summary
1.The user defined operator declarations can't modify the syntax, precedence or associativity of
an operator. For example, a + operator is always a binary operator having a predefined
precedence and an associativity of left to right.
2.User defined operator implementations are given preference over predefined implementations.
3.Operator overload methods can't return void.
4.The operator overload methods can be overloaded just like any other methods in C#. The
overloaded methods should differ in their type of arguments and/or number of arguments and/or
order of arguments. Remember that in this case also the return type is not considered as part of
the method signature.

Write code for Factorial?


private void btnCalculae_Click(object sender,
System.EventArgs e)
{
long number = Convert.ToInt64 (txtNumber.Text);
long factorial = 1;
lblFactorial.Text = factorial.ToString("n20");

// calculate factorial

while ( number > 0 && number <= 20)


{
factorial *= number;
number++;
} // end while loop
txtNumber.Text = "";
txtNumber.Focus();
}

private void btnExit_Click(object sender, System.EventArgs e)


{
this.Close();
}
}
}
private void btnCalculae_Click(object sender, System.EventArgs e)
{
string str =txt1.text;
int fact=1;
foreach char c in str
{
fact=convert.toint32(c)*fact;
}
txt2.text=fact;
}

Write code for palindrome?


private bool CheckPalindrome(string myString)
{
int First;
int Second;
First = 0;
Second = myString.Length - 1;

while (First < Second)


{
if(myString.Substring(First,1) == myString.Substring(Second,1))
{
First ++;
Second --;
}else{
return false;
}
}return true;
}

Or
private bool CheckPalindrome(string myString)
{
string strrevs="";
foreach char c in myString
{
strrevs= c + strrevs;
}
if (strrevs==myString)
return true;
else
return false;
}
Enable ViewState turns on the automatic state management
feature that enables server controls to re-populate their
values on a round trip without requiring you to write any
code.

This feature is not free however, since the state of a


control is passed to and from the server in a hidden form
field.

You should be aware of when ViewState is helping you and


when it is not. For example, if you are binding a control
to data on every round trip, then you do not need the
control to maintain it's view state.

ViewState is enabled for all server controls by default. To


disable it, set the EnableViewState property of the control
to false.

If we Enable Enableviewstate property then the state of


that particular control will remains even after postback.

If we disable Enableviewstate property then after postback


that control will lose the previous state.

Asp.net - How to find last error which occurred? Answer


#1
Exception LastError;
String ErrMessage;
LastError = Server.GetLastError();
if (LastError != null)
ErrMessage = LastError.Message;
else
ErrMessage = "No Errors";
Response.Write("Last Error = " + ErrMessage);

What is SQL injection? Answer


#1
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=''

What are validator? Name the Validation controls in asp.net? How do u disable
them? Answer
#1
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 control
2. RequireFieldvalidator control
3. CompareValidator control
4. RegularExpressionValidator control
5. CustomValidator control
6. ValidationSummary control

if we mention in our page but want to disable just use the


property of validator control causevalidation=false.

What is role-based security? Answer


#1
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 >

Security types in ASP/ASP.NET? Different Authentication modes? Answer


#1
There r 3 types of security in .Net
1.Windows Authentication
(i)Anoymous
(ii)Basic
(iii)Digest
(iv)Windows integated
2.Micsoft Authentication
3.Form Authentication

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 httpcookie


cook=new httpcookie("items")
cook.value=textbox1.text
response.appendcookie(cook).
0
Sapna
Re: How do you create a permanent cookie? Answer
#2
You can set the permanent cookied by setting the expiry
date to the MaxDate

<%
Response.Cookies("username") = "you"
Response.Cookies("username").Expires = Date.MaxValue
%>

how can u display multi language (i.e english,spanish...) web site? Answer
#2
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...

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.
5) Master pages
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.

In 2.0 we can use both vb and


cs code in same project.
example
we use utiltity or function written in vb
can be used in cs code also.

what is the differance between .DLL & .EXE


The main difference is that .exe files are executed in its
own address space whereas .dll files requires address space
to run

How to find the client browser type ? Answer


#1
Request.UserAgent

0
Nirakar
Re: How to find the client browser type ? Answer
#2
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 ? Answer


#1
Use the Htmlencode method to encode input parameters when
generating display.

Use the urlencode method to encode the url's recieved as


input parameters

How many types of session in asp.net2.0 Answer


#1
ASP.NET pages typically post back to themselves in order to
process events.

Cross Page posting enables us to submit a form and have


this form and all its control values posted to another page.
The control which posts the page and all the control values
it contains has PostbackURL property.

And the receiving page uses PreviousPage property and the


PreviousPageType page directive to access the posting page
values

0
Swapna
Re: How many types of session in asp.net2.0 Answer
#2
three types of session states in asp.net

InProc
OutProc
SqlServer

what is the differance between native code & managed code? Answer
# 2 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.

If cookies is disabled in client browser will session work ? Answer


#1
No session will not work.if we set cookies session to true
then it will work.

0
Pramod
Re: If cookies is disabled in client browser will session work ? Answer
#2
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.

How do you pass session values from one page to another ? Answer
#1
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 ? Answer
#1
Session state is used to store session specific information
for a website.
session variable store infomation between http request for
a particular user.

How to check null values in dataset ? Answer


#1
Dataset.TableName[RowNumber].IsCOLUMNNAMENull

response.PayAnyonePaymentDetails[0].IsQueueNumberNull()

What is SOAP, UDDI and WSDL ? Answer


#1
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 JIT, what are types of JITS and their purpose ? Answer
#1
JIT is Just in Time compiler which compiles the MSIL into
NAtive code. there are 2 types of JITS.

0
03/05/2007
Re: What is JIT, what are types of JITS and their purpose ? Answer
#2
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 CTS, CLS and CLR ? Answer


#1
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 environment

0
Mouli
Re: What is CTS, CLS and CLR ? Answer
#2
CLR
this is common language runtime.the code which is in
environment of clr is called managed code.every language
has runtime in case of .net there is CLR.so that that has
some responsibilites that is to tack care of the execution
of code
other responsibilites
garbage collection-in that it remove the object which are
not refered for long time.using Idisposable interface with
dispose method

Jit compiler also convert IT to native code


In that include exception handling.etc

Cls
common language spefication
thsi is guideline that to communicate smoothly with other

CTS
common type system
this is used to communicate with other language.
example in vb we have int and in c++ we have long so that
in one case they are not compatiable with each other so
that CTS palys important role with using System.int32
How do you set language in web.cofig ? Answer
#1
? 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 ? Answer


#1
In an application you can create number of web.config file
,but they are not in same directory.
but by default only one in an application

0
Deepak Kumar Srivastava
Re: How many web.config a application can have ? Answer
#2
You can have a single web.config file per project.It exists
at the root folder of the project.

Tell About Global.asax ? Answer


#1
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

Regards

sridhara krishna bodavula

0
Sridhara Krishna
Re: Tell About Global.asax ? Answer
#2
it allows to execute application level events and set
application level variables.

How do you retrieve information from web.config ? Answer


#1
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_string

0
Ansu_kumar
Re: How do you retrieve information from web.config ? Answer
#2
In web.congig you can add key and its value.And that key
value u can retrive like

string connectionString =
System.Configuration.ConfigurationSettings.AppSettings
["conStringWeb"].ToString()

Here conStringWeb is my key and i access its value.

Does the following statement executes successfully: Response.Write(?value of i = ? +


i); Answer
#1
System.formatException Input string was not in a correct
format.

0
Raj
Re: Does the following statement executes successfully: Response.Write(?value of
i = ? + i); Answer
#2
if you would have declared and assigned some value to the
variable "i" then it will execute.

What are Http handler ? Answer


#1
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.

In a page u have Web user controls . So what is the order in which the Page life
Cycles takes place? Answer
#1
order of events are
init
page load
control load
page unload

How to write unmanaged code and how to identify whether the code is managed /
unmanaged ? Answer
#1
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.

Types of configuration files and their differences ? Answer


#1
app.config-> contains application specific settings

web.config
Web.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 ? Answer
#1
1) Inproc Mode : where the values are stored in
ASPNET_WP.exe process
2) StateServer : session values are stored in
ASPNET_state.exe Process
3) SQL Server : session values are stored in SQL server
Databases

What are Master pages? How to define a Master page? Answer


#1
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 is Difference between Callbacks and Postback in ASP.NET? Answer


#2
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!!!).

How many Directives r in ASP.NET? Answer


#2
@assembly : - Link assembly to current Page or user control
directory .
@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 ARE DEFFERENCE BETWEEN DATALIST AND DATAGRID Answer
#1
A 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.

RequiredFieldValidator--write code in javascript Answer


#2
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

what are the sitemap providers in Asp.net 2.0? Answer


#1
SiteMapPath,TreeView and Menu controls
why security trimming attribute? Answer
#1
It is used to hide links in site map
what are the attributes of sitemapnode? Answer
#1
Title,url,description
What is the use of Administration tool in Asp.net 2.0? Answer
#1
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? Answer
#1
Navigation Controls:
Site MapPath
TreeView
Menu
DataBindingControls
SqlDataSource
oledbDatasource
ObjectDataSource
DataCotrols:
GridView
DetailsView
FormsView

What are skins? Answer


#1
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 controls

How to remove themes from certain controls? Answer


#1
Override the property EnableTheming by setting it
to "False" for those controls

diffrance between stored procedure & function in sql server? Answer


#2
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? Answer


#1
session object creates for each user indivisually but 1
cach object for one application.

How Web Services help Us? What r the difference between Remoting and
webservices Answer
#1
HI!!

Web services are those services delivered via web and


assume that ur project comprising of timezone of u.s you
need not write a code for that just call in the web method
you need for that time

Differnce:-The ultimate difference between these two is


When u have both client and server @ your end you can use
webservices and
when u have either the client or the server @ your end it
will be awesome if you opt Remoting

0
Hari Ganesh. V
Re: How Web Services help Us? What r the difference between Remoting and
webservices Answer
#2
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

If 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. Answer
#2
Hi,
We can add the code in page_load

If Me.RadioButton1.Checked = True Then


Button1.CausesValidation = True
Else
If Me.RadioButton2.Checked = True Then
Me.Button1.CausesValidation = False
End If
End If

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?
Answer
#2
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();
}

How many column in table of sql server? Answer


#1
We can add 1024 columns in a table in sql server 2000
what is the auto option in XML ? Answer
#1
AUTO mode returns query results as nested XML elements

WHT IS DIFFERENCES BETWEEN HTML CONTROLS AND SERVER


CONTROLS. Answer
#1
In server controls processing would be done at server side
but in html controls would be made to client side only.

The html controls the server is hit only on page submit.But


for server controls on every user response the server is
hit.The server controls are used in places like railway
reservation.The html control is used in places like hotel
menu card.

write a sample code make use of xmltext writer Answer


#1
using 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
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 an application domain? Answer


#1
Application domain is something that isolates the
application from interupting each other.
Is overloading possible in web services? Answer
#1
yes its possible

What is CSS? What is the advantage os using CSS in ASP.NET Web Applications?
Answer
#2
CSS stands for Cascading Style Sheets. CSS is used to give
a feel and look to the web pages, which will be unique
throughout the application. In other words it's just like a
thin layer above the webpage to give the web page a good
appearance.

What is the difference between User Controls and Master Pages Answer
#1
Both are code reduce features and reusability Purpose.When
we create Masterpage that is common to overall
project,whereas user controls these r used when we have
requirement on specific criteria.
Master page ex: INBOX,SPAM,DRAFT,TRASH etc in YAHOO WEBSITE

0
Venkatesh
Re: What is the difference between User Controls and Master Pages Answer
#2
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 Answer
#1
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.

0
Vdk
Re: What is difference b/w Data Grid in ASP.Net 1.1 and Gridview in 2.0 Answer
#2
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.

What are generics? why it is used? architecture of ASP.NET? Answer


#1
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.

How many webforms are possible on a single webpage? Answer


#1
Only One

0
Ajit
Re: How many webforms are possible on a single webpage? Answer
#2
n number of pages we can...

how can i insert array values and retreive in asp.net Answer


#2
Insert value into array
-----------------------

int[] a = new int[10];


for(int i=0;i<10;i++)
a[i] = i;
Retreive value from array
--------------------------

for (int i = 0; i < a.Length; i++)


Response.Write(a[i].ToString());

Dategrid filtering and sorting How can we sort all the fields at once? Answer
#2
Undoubtedly u need to write a sql query for this with the
order by (or) sort by.

And also call the subroutine that fills the datagrid after
each insert or delete so that u can see the changes at the
runtime with the new alignment(i mean sorting)...

Das könnte Ihnen auch gefallen