Sie sind auf Seite 1von 159

MBT Pune

1. N E T CONTENTS:1.Object Oriented Concepts:1-1717pages 2.NET Framework.:18-2911pages 3.Page:30-32 -->3pages 4.ASP.NET:32-71-->40pages 5 Data Access Technologies. 6. Caching 7.SessionManagement 8.Security 9.General 10.Exceptions 11.Transactions & COM+ 12.XML 12.Serialization&Deserialization 13.Remoting 14.Tracing 15.Webservices 16.Configuration Settings 17.Queued Components 18.SQLSERVER 19.SQLSERVER DBA 20.SQLSERVER LAB EXCERCISES. I N T E R V I E W Q U E S T I O N S

1.OBJECT ORIENTED CONCEPTS: What are the Basic Concepts of Object Oriented Programming? Basic Concepts of OOPs are 1.DataAbstraction and Encapsulation. 2.Inheritence 3.Polymorphism. 1) Encapsulation: It is the mechanism that binds together code and data in manipulates, and keeps both safe from outside interference and misuse. In short it isolates a particular code and data from all other codes and data. A well-defined interface controls the access to that particular code and data. 2) Inheritance: It is the process by which one object acquires the properties of another object. This supports the hierarchical classification. Without the use of hierarchies, each object would need to define all its characteristics explicitly. However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent. A new sub-class inherits all of the attributes of all of its ancestors. 3) Polymorphism: It is a feature that allows one interface to be used for general class of actions. The specificaction is determined by the exact nature of the situation. In general polymorphism means "one interface,

Page of 159

MBT Pune
multiple methods", This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler's job to select the specific action (that is, method) as it applies to each situation. Its an Example for LateBinding. What is DataEncapsulation? The wrapping up of data and methods into a single unit is called Encapsulation. So data is not accessible to outside world and only those methods can access it. This insulation of data from direct access by programs is called DataHiding. What is Inheritance? Inheritance is the process by which Objects of one class acquire properties of Another class. Inheritance Provides the idea of Reusability. What are different types of Inheritance? 1.Single Inheritance:- Only One Base class and One derived Class 2.Multiple Inheritance:- Several Base Classes and a single Derived class But this possible only with Interfaces and not with Base classes as a class can atmost extend a base class but can Implements more than one interfaces. 3.Hierarchical Inheritance:-One Base Class and many derived classes. 4.Multilevel Inheritance:-Derived from derived class. pWhat is Shared and Repeatable Inheritance?

What is Polymorphism? Polymorphism means the ability to take more than one form. Polymorphism means having Different implementation for the same method. Polymorphism Plays an Important role in allowing Objects having different internal Structures to share the same external interface. The benefit of Polymorphism is when the appropriate implementation is invoked automatically at runtime depending on the type of Object. pWhat are different types of Polymorphisms that are available ? Operation Polymorphism or Compile Polymorphism(EarlyBinding/StaticBinding/StaticLinking)-Using OverLoaded Methods-The Compiler is able to select and bind the appropriate method to the object for a Particular call at Compiletime Itself. Eg. Class Dog{} Class Cat{} Class Operation{ static void Call(Dog d){} static void Call(Cat c){} } Public static void Main(){Dog d=new Dog();Cat c=new Cat();Call(d);Call(c);} And Inclusion Polymorphism or Runtime Polymorphism(LateBinding)-Using Virtual Methods The decision of which method to call is delayed until Runtime. Class Maruthi{public virtual void Display(){}} Class Esteem:Maruthi{public override void Display(){}} Class Zen:Maruthi{public override void Display(){}} Class Inclusion{ Public static void Main(){ Maruthi m=new Maruthi(); m=new Esteem(); m.Display(); m=new Zen(); m.Display(); }

Page of 159

MBT Pune
What is Class? Class is a template of an Object which contains Fields,Properties and Methods What is Object? Object is an instance of a class. What is Interface? Like class Interface contains, properties, methods, but interfaces doesnt contain implementation of those methods. Interface defines only Abstract Methods and Final fields. An Interface represents a contract and a class that implements an Interface must implement every aspect of that interface exactly as it is defined. An Interface is implemented and not extended. 1.A class can implement multiple interfaces. 2.An Interface cant contain data declarations but you can declare properties. 3.All method declarations in an Interface are Public. 4.There can be no implementation in an Interface. 5.A class implementing the interface must provide implementation code. 6.An Interface can be derived from another Interface. 7.An Interface may not Contain DataMembers,Constructors and Destructors. 8.They cant contain any static Members also. 9.They does not have any Acess Modifiers. What is an Abstract Class? An Abstract class is a class that contains methods that have no implementation(i.e abstract methods). An abstract method is simply a shell or place-marker for a method that will be defined later in a derived class. The intention of abstract methods is to force every derivation of the class to implement those methods. If a derived class does not implement an abstract method , then that class must also be declared as abstract. An Abstract class is the class that cant be instantiated(i.e no direct instances), but must be inherited from. (but whose descendents may have direct instances) An Abstract class is usually partially implemented or not implemented at all, there by encapsulating common functionality for inherited classes. NB:-Derived class is also called Concrete class. And Implementation of Abstract class is optional, unlike interface. MustInherit-Class/MustOverridable-Method-vb.net Abstract(Class&Method) C# Differences between an Abstract Class and Interface? Abstract Class 1.May or maynot have abstract methods. use virtual attribute in class to implement Partial Implementation. 2.Methods can have access modifiers.(except Private Members.) 3.can have fields, Properties and Methods. Interface 1.Can only have abstract methods, but abstract Key word is not allowed.

2.no access modifiers are allowed, implicitly Public.

3.can have only final constants, Properties and Methods. 4.Can Extend a single class and implement one 4.Cant Extend a Class and can extend a single or or more Interfaces. multiple interfaces. *5.Abstract classes form part of the 5.Interfaces do not .we can use same interface in Inheritance schema. two projects that are not related interms of Inheritance. 6.Can Have Constructor. 6.Cant Have Constructor. *7.Its Speed and Fast at Execution. 7.Slow at Execution. *8.If you are Designing Large Functional units you are designing small,Consise bits of 8.If use an Abstract Class. Functionality use Interfaces.

Page of 159

MBT Pune

*9.If you want provide Common, Implemented the Functionality you are creating will be usefu 9.If functionality among all implementations of across a wide range of Disperate objects your Component, use an Abstract Class. ,use an Interface.

What are Delegates? Delegate is a Type defining a method signature, so that delegate instances can hold and Invoke method or list of methods that match its signature. Delegates Provides Callback behavior in an ObjectOrientedType Safe Manner. A delegate is a type safe reference to a function or method. It is useful when you want to register a callback function that gets called when the user selects a menu or when an un handled exception is thrown or you may want a function to be called when an asynchronous operation completes its execution. Using of Delegate Invoke 4 steps as follows. a)Delegate Declaration:-modifier delegate return_type delegate_name(parameters) Modifier -new/static/override/abstract/sealed eg. delegate void Mathop(double a, double b) b)Delagate Method Defination:public static double Multiply(double a,double b) { return (a*b);} public double Divide(double a,double b) {return (a/b);} c)Delegate Instantiation:new delegate_type(expression) Mathop m=new Mathop(multiply); d)Delegate Invocation:delegate_object(paramers list) double d=Mathop(12.23,34.44); What is Event - Delegate? An event is a Delegate type class member that is used by the Object or class to provide a notification to other objects that an event has occurred. Modifier event type event_name Modifier -new/static/override/abstract/sealed Public event Eventhandler click;---here type eventhandler is the delegate type. When button is clicked the following code will be added in Initailized Component. This.Button1.Click+=new System.EventHandler(this.Button1_Click) The event keyword lets you specify a delegate that will be called upon the occurrence of some "event" in your code. The delegate can have one or more associated methods that will be called when your code indicates that the event has occurred. An event in one program can be made available to other programs that target the .NET Framework Common Language Runtime.

Page of 159

MBT Pune
What is new Modifier? New modifier is used to hide the base class method from derived class method. It allows to reDefine some methods contained in Derived class. What is Enum? Enums specify a group of named numeric Constants. An Enum can be of Type byte, short, int or long. Public enum Direction: byte{Northe=1,Easr=2,West=4,South=8} What is Structure? Structures can be think as Light weight, memory efficient Classes. Structure is a User defined Structure, similar to Class. Its a Class of Value Type. It can have one or more Attributes, of any of other Datatypes.It can also have methods. A Struct object is created using new Keyword, just like a Class. What is the difference between a Struct and a Class?

The struct type is suitable for representing lightweight objects


such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive.

When you create a struct object using the new operator, it gets
created and the appropriate constructor is called. Unlike classes, structs can be instantiated without using the new operator. If you do not use new, the fields will remain unassigned and the object cannot be used until all of the fields are initialized.

It is an error to declare a default (parameterless) constructor


for a struct. A default constructor is always provided to initialize the struct members to their default values. It is an error to initialize an instance field in a struct.

There is no inheritance for structs as there is for classes. A struct


cannot inherit from another struct or class, and it cannot be the base of a class. Structs, however, inherit from the base class Object. A struct can implement interfaces, and it does that exactly as classes do. A struct is a value type, while a class is a reference type. What is Shadowing? Shadowed members are used to create the Local version of members that have broader scope. Shadowing is used when two programmers come up with same method in the same class , one of the methods get shadowed by scope or inheritance. What is Virtual method? The Concept of Virtual method is such that the bottom-most implementation of the method is always used in favor of the Parent implementation-regardless of the data type of variable being used in the client code. Virtual method has an implementation and Provide the derived class with the option of overriding it. The class which contains Virtual methods is known as Virtual Class. Override modifier is used while overriding an Virtual method. What are Constructors? Constructors are methods that control Initialization of new instances of a class.

Page of 159

MBT Pune
What are Destructors? Destructors are methods that are used to free System Resources when a class leaves a scope or is set to nothing. What are References? References allow you to use objects defined in Other Assemblies. What are Shared Members (VB)/Static Members(C#)? Shared Members are Properties, Methods and Fields that are shared by all instances of the class. Sharing single instance of a data member or function among all instances of a class is useful in applications that use Inheritance. What is Namespace? Namespaces prevent naming conflicts by organizing classes, Interfaces and Methods into hierarchies. An assembly can contain one ore more namespaces. The namespace keyword is used to declare a scope. This namespace scope lets you organize code and gives you a way to create globally-unique types. Even if you do not explicitly declare one, a default namespace is created. This unnamed namespace, sometimes called the global namespace, is present in every file. Any identifier in the global namespace is available for use in a named namespace. Namespaces implicitly have public access and this is not modifiable. Any 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 alias Eg: using MyAlias = MyCompany.Proj.Nested; What are attributes? Attributes enable you to provide additional Information about Program elements. Eg. Access Modifiers .these can be used on class and members in the class like variable,property,methods. Method signature: Attributes(opt) method_modifier(opt) return_type member_name(parameter_list opt) 1.Public:-Entries that are declared as Public, have public access. There is no Restriction on the accessibility of Public Entries. 2.Protected:- Entries that are declared as Protected, have protected access. They are accessible only from their own classes or from a Derived class. 3.Friend(Internal):- Entries that are declared as Friend, have friend access. They can be accessible from within the program that contains the Declaration and within the Assembly. 4.Private:- Entries that are declared as private, have private access. They can be accessible only within the Class. 5.Protected Friend/Protected Internal:- Entries that are declared as Protected Friend, have Protected Friend. They can be accessible from within the program that contains the Declaration and within the Assembly and in the Derived Classes also. What is Dynamic Binding? Dynamic Binding means that the code associated with a given Procedure call is not known until the time of the call at runtime. What are Me/MyBase/MyClass keywords? Me keyword is used any time we want to refer to methods within the Current Object.

Page of 159

MBT Pune
(this in C#) Mybase keyword is used to call Parent Class method within the Subclass. MyClass is used in a scenario , where the code in ourclass might endup invoking code from other classes created from our class. What is Over Loading? Over Loading is the ability to define Properties, Methods that have the same name but use different type of data types and different type of Parameters. Overloading Procedures allow you to provide as many implementations as necessary to handle different kinds of data while giving the appearance of a single Versatile procedure. Functions of Same name but with different Parameters. Simply by Changing return type we cant Overload a method. Overloads---Keyword-VB NoKeyword-C# What is Overriding? Overriding is Defining a method in Derived class that has the same name ,same arguments and same return type as a method in Base Class. Overridable/Overrides/NotOverridable(sealed)/MustOverride(abstract)---vb Virtual/Override---C# What is Distributed Computing? It is a Programming Model in which processing occurs in Many Different Places around the network eg. On a server, Personal Computer ,Hand held device. This is contrast to the two node system prevalent today(The client and Centralized server). Which namespace is the base class for .net Class library? system.object

using directive vs using statement?


You create an instance in a using statement to ensure that Dispose

is called on the object when the using statement is exited. A using


statement can be exited either when the end of the using statement is reached or if, for example, an exception is thrown and control leaves the statement block before the end of the statement. The using directive has two uses:

Create an alias for a namespace (a using alias). Permit the use of types in a namespace, such that, you do not have
to qualify the use of a type in that namespace (a using directive). What is the difference between CONST and READONLY? Both are meant for constant values. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. readonly int b; public X() { b=1; } public X(string s) { b=5; } public X(string s, int i)

Page of 159

MBT Pune
{ b=i; } Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants, as in the following example: public static readonly uint l1 = (uint) DateTime.Now.Ticks; (this can't be possible with const) What is the difference between ref & out parameters? An argument passed to a ref parameter must first be initialized. Compare this to an out parameter, whose argument does not have to be explicitly initialized before being passed to an out parameter. What is the difference between Array and Arraylist? As elements are added to an ArrayList, the capacity is automatically increased as required through reallocation. The capacity can be decreased by calling TrimToSize or by setting the Capacity property explicitly. What is Jagged Arrays? A jagged array is an array whose elements are arrays. The elements of a jagged array can be of different dimensions and sizes. A jagged array is sometimes called an "array-of-arrays." What are indexers? Indexers are Location indicators and are used to access class objects, just like elements in an array. They are useful in cases where a class is a container for other objects. An Indexer looks like a Property with two following differences. 1.Indexer takes an Index argument and looks like an Array. 2.Indexer is declared using the name this. Indexers are similar to properties, except that the get and set accessors of indexers take parameters, while property accessors do not. Public double this [int idx]{get{}set{}} Eg.class List{ArrayList array=new ArrayList(); Public object this[int index] {get{return(array[index])}} set{array[index]=value;}}} class IndexerTest{public static void main() {List list=new List();list[0]=123;list[1]=abc; for(int I=0;I<list.count;I++) Console.writeline(list[I])}} What are Different DataTypes available in .NET? 1.In Value Type, the variable stores the Data directly in the Stack Memory.(Permanent Memory). i.e Structures,Enumerations.

Page of 159

MBT Pune
2.In Reference Type,the Variable stores the Address of the Data and the Data is Stored in the Heap Memory.(Temporary Memory).and Garbage collector take care of freeing of memory resources. i.e Class,Arrays,Interfaces,Delegate. What are Data Types available in .NET?

Data Type is an attribute that specifies the type of data that object can hold. System.Boolean 1 byte System.Byte 1 byte System.Char 2 bytes System.Int16 2 bytes System.Int32 4 bytes System.Int64 8bytes System.Object 4bytes System.Single 4bytes System.Double 8bytes System.Decimal 12bytes System.DateTime 8bytes System.String 10bytes +(2*string length) System.ValueType Sum of Member sizes(User Defined Type) Value type & reference types difference? Example from .NET. Integer & struct are value types or reference types in .NET? Most programming languages provide built-in data types, such as integers and floating-point numbers, that are copied when they are passed as arguments (that is, they are passed by value). In the .NET Framework, these are called value types. The runtime supports two kinds of value types:

Built-in value types


The .NET Framework defines built-in value types, such as System.Int32 and System.Boolean, which correspond and are identical to primitive data types used by programming languages.

User-defined value types


Your language will provide ways to define your own value types, which derive from System.ValueType. If you want to define a type representing a value that is small, such as a complex number (using two floating-point numbers), you might choose to define it as a value type because you can pass the value type efficiently by value. If the type you are defining would be more efficiently passed by reference, you should define it as a class instead. Variables of reference types, referred to as objects, store references to the actual data. This following are the reference types: class interface delegate This following are the built-in reference types: object

Page of 159

MBT Pune
string What is Boxing and Unboxing? Boxing is a mechanism of converting a value type to reference type. Un Boxing is a mechanism of Converting reference type to value type. What are Different Object types offered by CLR? There are two types of Object types that are offered by CLR. They are Value Types Reference Types Reference Types are always allocated from the managed heap and the new operator returns the memory address of object and Garbage collector take care of freeing of memory resources. Eg: Strings,objects etc Value Types are allocated on a threads stack and variable representing the object does not contain a pointer to an object. Value types are lightweight than reference types because they are not allocated in managed heap, not garbage collected and not referenced to by pointers. Value type is referred as structure. value type is primitive type and type does not inherit from another type. Eg: int32,Boolean,decimal etc. NB:-Heap is Temporary Memory i.e RAM and Stack is Permanent Memory i.e HardDisk. What are Custom Attributes? Custom Attributes are used to adorn type,methods,fields etc. When compiled the compiler emits these method attributes into the managed modules metadata. At runtime, this metadata can be examined and based on the presence of these attributes the behaviour of the application changes.

What is Custom attribute? How to create? If I'm having custom attribute in an assembly, how to say that name in the code? A: The primary steps to properly design custom attribute classes are as follows: a. Applying the AttributeUsageAttribute ([AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]) b. Declaring the attribute. (class public class MyAttribute : System.Attribute { // . . . }) c. Declaring constructors (public MyAttribute(bool myvalue) { this.myvalue = myvalue; }) d. Declaring properties public bool MyProperty { get {return this.myvalue;}

Page of 159

10

MBT Pune
set {this.myvalue = value;} } The following example demonstrates the basic way of using reflection to get access to custom attributes. class MainClass { public static void Main() { System.Reflection.MemberInfo info = typeof(MyClass); object[] attributes = info.GetCustomAttributes(); for (int i = 0; i < attributes.Length; i ++) { System.Console.WriteLine(attributes[i]); } } }

What are Attributes?What are different types of Attributes? Attributes are used to adorn type,methods,fields etc. There are at least two types of .NET Attributes. They are Metadata Attributes:-It allows some data to attached to a class or method. This data becomes part of metadata for the class and can be accessed via reflection. Eg [serializable] NB:-System.Attribute class Context Attributes:-This also uses same syntax as Metadata Attributes but they are fundamentally different. Context Attributes provide an interception mechanism whereby instance activation and method calls can be pre and /or post processed.

What is early binding and late binding? time Early binding means that the compiler has knowledge about an object at compile Late binding means that compiler do not have any knowledge about an object Late Binding uses Create Object to create and instance of the application object, which you can then control. Eg: Dim oXL as Object Set oXL=CreateObject(Excel.Application) NB: -Regardless of whether you are using early or late binding use GetObject to manipulate an existing object.

To use Early binding you need to set a reference in your project to the application you want to manipulate.

Page of 159

11

MBT Pune
Eg. Dim oXL as Object Set oXL=New Excel.Application

What are the advantages of early binding and late binding? Advantages of Early Binding: 1.Code will run considerably faster, because it can all be compiled up front, but in late binding the code is compiled as it runs. 2.As code is compiled up front, debugging is far easier and compiler will able to spot syntax errors which would have been missed had you used late binding. 3.We can have full access to Intellisense in the project. 4.We can access the applications built-in constants. Eg. .windowState=wdWindowStateMaximize In LateBinding, we use it like the following .windowState=1

Advantages of Late Binding:1.The main Advantage to use late binding is that the code is more certain to be version Independent. 2.In Early binding, the more references your project contains , the larger the file size and the longer it takes to compile. 3.Some Programming environments dont allow you to create references to another application. In which cases you use override and new base? Use the new modifier to explicitly hide a member inherited from a base class. To hide an inherited member, declare it in the derived class using the same name, and modify it with the new modifier. What are Sealed Classes in C#? The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a sealed class is specified as the base class of another class. (A sealed class cannot also be an abstract class) In which Scenario you will go for Interface or Abstract Class? Interfaces vs. Abstract Classes Feature Interface Multiple inheritance A class may implement several interfaces.

Abstract class A class may extend only one abstract class.

Default An interface cannot An abstract class can implementation provide any code at provide complete code, all, much less default default code, and/or just

Page of 159

12

MBT Pune

code.

stubs that have to be overridden.

Constants

Static final constants only, can use them without qualification in classes that implement the interface. On the Both instance and static other paw, these constants are possible. Both unqualified names static and instance intialiser pollute the code are also possible to namespace. You can compute the constants. use them and it is not obvious where they are coming from since the qualification is optional. An interface implementation may A third party class must be be added to any rewritten to extend only existing third party from the abstract class. class.

Third party convenience

Interfaces are often An abstract class defines the used to describe the core identity of its peripheral abilities of descendants. If you defined a class, not its central a Dog abstract class then identity, e.g. an Damamation descendants is-a vs -able or Automobile class are Dogs, they are not can-do might implement the merely dogable. Recyclable interface, Implemented interfaces which could apply to enumerate the general many otherwise things a class can do, not totally unrelated the things a class is. objects. Plug-in You can write a new You must use the abstract replacement module class as-is for the code for an interface that base, with all its attendant contains not one stick baggage, good or bad. The of code in common abstract class author has with the existing imposed structure on you. implementations. Depending on the When you implement cleverness of the author of the interface, you the abstract class, this may start from scratch be good or bad. Another without any default issue that's important is implementation. You what I call "heterogeneous have to obtain your vs. homogeneous." If tools from other implementors/subclasses classes; nothing are homogeneous, tend comes with the towards an abstract base interface other than a class. If they are

Page of 159

13

MBT Pune

heterogeneous, use an interface. (Now all I have to do is come up with a good definition of hetero/homogeneous in this few constants. This context.) If the various gives you freedom to objects are all of-a-kind, implement a radically and share a common state different internal and behavior, then tend design. towards a common base class. If all they share is a set of method signatures, then tend towards an interface. If all the various implementations share is the method signatures, then an interface works best. If your client code talks only in terms of an interface, you can easily change the concrete implementation behind it, using a factory method. If the various implementations are all of a kind and share a common status and behavior, usually an abstract class works best. Just like an interface, if your client code talks only in terms of an abstract class, you can easily change the concrete implementation behind it, using a factory method.

Homogeneity

Maintenance

Speed

Slow, requires extra indirection to find the corresponding method in the actual Fast class. Modern JVMs are discovering ways to reduce this speed penalty. The constant declarations in an interface are all presumed public static final, so you may leave that part out. You can't call any methods to compute the initial values of your constants. You need not declare individual methods of an interface abstract. They are all You can put shared code into an abstract class, where you cannot into an interface. If interfaces want to share code, you will have to write other bubblegum to arrange that. You may use methods to compute the initial values of your constants and variables, both instance and static. You must declare all the individual methods of an abstract class abstract.

Terseness

Page of 159

14

MBT Pune

presumed so. If you add a new method to an interface, you must track down all implementations of that interface in the universe and provide them with a concrete implementation of that method.

Adding functionality

If you add a new method to an abstract class, you have the option of providing a default implementation of it. Then all existing code will continue to work without change.

Write one code example for compile time binding and one for run time binding? What is early/late binding? An object is early bound when it is assigned to a variable declared to be of a specific object type. Early bound objects allow the compiler to allocate memory and perform other optimizations before an application executes. ' Create a variable to hold a new object. Dim FS As FileStream ' Assign a new object to the variable. FS = New FileStream("C:\tmp.txt", FileMode.Open) By contrast, an object is late bound when it is assigned to a variable declared to be of type Object. Objects of this type can hold references to any object, but lack many of the advantages of early-bound objects. Dim xlApp As Object xlApp = CreateObject("Excel.Application") pHow can you write a class to restrict that only one object of this class can be created (Singleton class)? Difference between type constructor and instance constructor? What is static constructor, when it will be fired? And what is its use? (Class constructor method is also known as type constructor or type initializer) Instance constructor is executed when a new instance of type is created and the class constructor is executed after the type is loaded and before any one of the type members is accessed. (It will get executed only 1st time, when we call any static methods/fields in the same class.) Class constructors are used for static field initialization. Only one class constructor per type is permitted, and it cannot use the vararg (variable argument) calling convention. A static constructor is used to initialize a class. It is called automatically to initialize the class before the first instance is created or any static members are referenced. What is Private Constructor? and its use? Can you create instance of a class which has Private Constructor? A: When a class declares only private instance constructors, it is not possible for classes outside the program to derive from the class or to directly create instances of it. (Except Nested classes) Make a constructor private if: - You want it to be available only to the class itself. For example, you might have a special constructor used only in the implementation of your class' Clone method. - You do not want instances of your component to be created. For example, you may have a class containing nothing but Shared utility functions, and no instance data. Creating instances of the class would waste memory.

Page of 159

15

MBT Pune
I have 3 overloaded constructors in my class. In order to avoid making instance of the class do I need to make all constructors to private? (yes) Overloaded constructor will call default constructor internally? (no) p What is check/uncheck? p What is Asynchronous call and how it can be implemented using delegates? p How to create events for a control? What is custom events? How to create it? p without modifying source code if we compile again, will it be generated MSIL again?

2 .NET FRAMEWORK:NB:- Microsoft .NET is is an umbrella term that describes a no. of recently released technologies from Microsoft. What is .NET?(.NET Framework) .NET is a new Environment for Developing and Running software Applications, featuring ease of Development of Web based Services, rich standard runtime services available to Components written in a variety of Programming Languages and Inter language interoperability. What is .NET Framework? .NET Framework is a set of Technologies that are designed to transform Internet into a full-scale distributed Computing Platform. What are the new features of Framework 1.1 ? 1.Native Support for Developing Mobile Web Applications 2.Enable Execution of Windows Forms Assemblies Originating from the Internet Assemblies originating from the Internet zonefor example, Microsoft Windows Forms controls embedded in an Internet-based Web page or Windows Forms assemblies hosted on an Internet Web server and loaded either through the Web browser or programmatically using the System.Reflection.Assembly.LoadFrom() methodnow receive sufficient permission to execute in a semi-trusted manner. Default security policy has been changed so that assemblies assigned by the common language runtime (CLR) to the Internet zone code group now receive the constrained permissions associated with the Internet permission set. In the .NET Framework 1.0 Service Pack 1 and Service Pack 2, such applications received the permissions associated with the Nothing permission set and could not execute. 3.Enable Code Access Security for ASP.NET Applications Systems administrators can now use code access security to further lock down the permissions granted to ASP.NET Web applications and Web services. Although the operating system account under which an application runs imposes security restrictions on the application, the code access security system of the CLR can enforce additional restrictions on selected application resources based on policies specified by systems administrators. You can use this feature in a shared server environment (such as an Internet service provider (ISP) hosting

Page of 159

16

MBT Pune
multiple Web applications on one server) to isolate separate applications from one another, as well as with stand-alone servers where you want applications to run with the minimum necessary privileges. 4.Native Support for Communicating with ODBC and Oracle Databases 5.Unified Programming Model for Smart Client Application Development The Microsoft .NET Compact Framework brings the CLR, Windows Forms controls, and other .NET Framework features to small devices. The .NET Compact Framework supports a large subset of the .NET Framework class library optimized for small devices. 6.Support for IPv6 The .NET Framework 1.1 supports the emerging update to the Internet Protocol, commonly referred to as IP version 6, or simply IPv6. This protocol is designed to significantly increase the address space used to identify communication endpoints in the Internet to accommodate its ongoing growth. What are the new Technologies in .NET Framework? Or What .NET Framework consists? .Net Framework Consists of Two main Parts. a).Common Language Runtime(CLR) b) .NET Framework Class Library What is CLR? CLR is a set of Standard Resources responsible for execution of Code developed using .NET Languages. CLR is a Replacement to win32 API. CLR is responsible for executing and managing all code written in any language that targets .NET Platform. What CLR do? CLR take care of 1.Memory Management 2.Thread Execution 3.CodeExecution 4.Code Safety Verification 5.Compilation 6.Automatic Garbage Collection 7.Very High Level Of Security while Executing It Provides Cross-Language Inheritance and abilty to compile once and run on any CPU and OS that supports runtime through Compilers.

Page of 159

17

MBT Pune
Memory management. The CLR maintains a managed heap that is used for all memory allocations. The CLR also cleans up objects that are no longer used. Because of the information found in IL and Metadata, the CLR is able to enforce that references always refer to compatible types, null references are never accessed, instances are never referenced after they are freed, etc. This is one very important aspect of code management performed by the Common Language Runtime. Security. The CLR makes sure that code can not undermine a system if it is not trusted. An example of un-trusted code would be a binary that was downloaded and executed from a website. The great thing about managed code is that the un-trusted software still runs at full native speed. However, at the point of JIT-compiling, the CLR was able to insert enough code to assure that security cannot be breached. If the executable crosses the line, the CLR knows about it, and will raise a security exception. This will cause the unacceptable operation to fail. Thread management. Although you can create your own thread objects with managed code, the CLR maintains a thread pool which can be used by your software. The thread pool efficiently uses threads for asynchronous behavior, and then returns an unused thread to a queue until it is needed again. Type safety. It is impossible for managed code to coerce a type into an incompatible type. At runtime the CLR checks all typecasting operations to be sure that the cast is valid. Because managed code uses references to objects in a managed heap (rather than pointers), it is also impossible to coerce one type to another through pointer manipulation. This drastically reduces bugs, and removes the fear that third-party code might undermine the integrity of your system. Code verification. The CLR asserts certain truisms about managed code. For example, the CLR (by default) will not JIT compile code that references a variable before it has been assigned to. The CLR can also be made to JIT compile code so that numerical operations that overflow raise exceptions so that they can be caught (although this is not the default). The CLR also asserts that all methods must have a return instruction. It is impossible for one instruction to run-over into the next. Code verification is another feature that makes code robust, and makes it safe to run un-trusted or semi-trusted components. What Compiler does? The compiler compiles the source code into Intermediate Language (Microsoft Intermediate Language),Which is language Independent. Then it is compiled to native machine code. What is Microsoft Intermediate Language(MSIL)? MSIL or IL is the CPU Independent Instruction set that is generated by Microsoft .NET Framework Compilers and Consumed by .NET Frameworks Common Language Runtime. Before MSIL can be executed, it must be converted to native CPU-Specific Code by Common Language Runtime. IL = Intermediate Language. Also known as MSIL (Microsoft Intermediate Language) or CIL (Common Intermediate Language). Can I do things in IL that I can't do in C#? Yes. A couple of simple examples are that you can throw exceptions that are not derived from System.Exception, and you can have non-zero-based arrays. What is JIT (just in time)? how it works? Before Microsoft intermediate language (MSIL) can be executed, it must be converted by a .NET Framework just-in-time (JIT) compiler to native code, which is CPU-specific code that runs on the same computer architecture as the JIT compiler. Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code, it converts the MSIL as it is needed during

Page of 159

18

MBT Pune
execution and stores the resulting native code so that it is accessible for subsequent calls. The runtime supplies another mode of compilation called install-time code generation. The install-time code generation mode converts MSIL to native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the resulting native code for use when the assembly is subsequently loaded and executed. As part of compiling MSIL to native code, code must pass a verification process unless an administrator has established a security policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether the code can be determined to be type safe, which means that it is known to access only the memory locations it is authorized to access. What is the CTS? CTS = Common Type System. This is the range of types that the .NET runtime understands, and therefore that .NET applications can use. However note that not all .NET languages will support all the types in the CTS. The CTS is a superset of the CLS.CTS facilitates cross-language integration, type safety, and high performance code execution. What is the CLS? CLS = Common Language Specification. This is a subset of the CTS, which all .NET languages are expected to support. The idea is that any program, which uses CLScompliant types, can interoperate with any .NET program written in any language. In theory this allows very tight interlope between different .NET languages - for example allowing a C# class to inherit from a VB class. Performing Cross-Language Inheritance the Language Compilers must follow CLS. CLS(Common Language Specification) describes a subset of Data types supported by Runtime, that are common to all of the languages used in .NET. What is UnManaged Code? UnManaged Code is code that is executed directly by O.S, outside the Microsoft .NET Frameworks Common Language Runtime. Unmanaged code must provide its own memory management, typechecking and security support, unlike Managed code which receives these services from Common Language Runtime. Unmanaged code must be executed outside the .NET Framework What is Managed Environment? A Managed Environment is one which the Environment Provides Services such as Garbage Collection, Security and Other Similar Features. What is Managed Code? .NET Framework Provides Several Core Runtime Services to the Programs that run within it. For eg: Memory Management, Cross-Language Integration, Automatic Lifetime Control of Objects etc. For these services to work the code must provide a minimum Level of Information to the Runtime. Such a Code is called Managed Code. All C# and VB.NET code is Managed by Default. The Code That is Developed using CLR is Called Managed Code. What are Managed Classes? These are Classes that the memory for Garbage Collector and the Class manage Instances of the class becomes a Fully Paid up member of .NET community with the benefits that brings. Eg: Benefit is proper interop with classes written in Other Languages.

Page of 159

19

MBT Pune
Restriction is that a managed class can inherit from one base class only. Describe the Managed Execution Process? The managed execution process includes the following steps: 1.Choosing a compiler. To obtain the benefits provided by the common language runtime, you must use one or more language compilers that target the runtime. 2.Compiling your code to Microsoft intermediate language (MSIL). Compiling translates your source code into MSIL and generates the required metadata. 3.Compiling MSIL to native code. At execution time, a just-in-time (JIT) compiler translates the MSIL into native code. During this compilation, code must pass a verification process that examines the MSIL and metadata to find out whether the code can be determined to be type safe. 4.Executing your code. The common language runtime provides the infrastructure that enables execution to take place as well as a variety of services that can be used during execution.

What is an Assembly? An Assembly Consists of one or more files (Dlls, exes, Html files etc), which represents a group of resources ,Type Definitions and Implementation of those Types. An Assembly may also contain references to other assemblies. What are the New Features in an Assembly? 1.Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality. An assembly provides the common language runtime with the information it needs to be aware of type implementations. To the runtime, a type does not exist outside the context of an assembly. Assemblies are a fundamental part of programming with the .NET Framework. An assembly performs the following functions:

It contains code that the common language runtime executes.


Microsoft intermediate language (MSIL) code in a portable executable (PE) file will not be executed if it does not have an associated assembly manifest. Note that each assembly can have only one entry point (that is, DllMain, WinMain, or Main).

It forms a security boundary. An assembly is the unit at which


permissions are requested and granted.

It forms a type boundary. Every type's identity includes the name


of the assembly in which it resides. A type called MyType loaded in the scope of one assembly is not the same as a type called MyType loaded in the scope of another assembly.

It forms a reference scope boundary. The assembly's manifest


contains assembly metadata that is used for resolving types and

Page of 159

20

MBT Pune
satisfying resource requests. It specifies the types and resources that are exposed outside the assembly. The manifest also enumerates other assemblies on which it depends.

It forms a version boundary. The assembly is the smallest


versionable unit in the common language runtime; all types and resources in the same assembly are versioned as a unit. The assembly's manifest describes the version dependencies you specify for any dependent assemblies. It forms a deployment unit. When an application starts, only the assemblies that the application initially calls must be present. Other assemblies, such as localization resources or assemblies containing utility classes, can be retrieved on demand. This allows applications to be kept simple and thin when first downloaded. It is the unit at which side-by-side execution is supported. 2. Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Static assemblies are stored on disk in PE files. You can also use the .NET Framework to create dynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed. There are several ways to create assemblies. You can use development tools, such as Visual Studio .NET, that you have used in the past to create .dll or .exe files. You can use tools provided in the .NET Framework SDK to create assemblies with modules created in other development environments. You can also use common language runtime APIs, such as Reflection. Emit, to create dynamic assemblies. What are the contents of assembly? In general, a static assembly can consist of four elements:

The assembly manifest, which contains assembly metadata. Type metadata. Microsoft intermediate language (MSIL) code that implements the
types.

A set of resources.
What is Versioning in .NET? Each assembly has a four-part version number as a part of its identity. This version number is essential to distinguish different versions of an assembly for the purposes of side-by-side. The 4 part number will be in the following format. MajorVersion.MinorVersion.BuildNumber.Revision Assemblies of either of first two parts different are viewed as Incompatible. If First two parts are same , but third is different , the assemblies are referred as may be compatible. If only fourth part is different , assemblies are declared as Compatible NB:-This version policy can be specified via The Application Configuration File What is Manifest?

Page of 159

21

MBT Pune
Manifest is the set of Metadata that describes the contents of the assembly and the Metadata also describes the dependencies and Version Information associated with an assembly. Every assembly, whether static or dynamic, contains a collection of data that describes how the elements in the assembly relate to each other. The assembly manifest contains this assembly metadata. An assembly manifest contains all the metadata needed to specify the assembly's version requirements and security identity, and all metadata needed to define the scope of the assembly and resolve references to resources and classes. The assembly manifest can be stored in either a PE file (an .exe or .dll) with Microsoft intermediate language (MSIL) code or in a standalone PE file that contains only assembly manifest information. It contains Assembly name, Version number, Culture, Strong name information, List of all files in the assembly, Type reference information, Information on referenced assemblies. Difference between assembly manifest & metadata? Assembly manifest - An integral part of every assembly that renders the assembly self-describing. The assembly manifest contains the assembly's metadata. The manifest establishes the assembly identity, specifies the files that make up the assembly implementation, specifies the types and resources that make up the assembly, itemizes the compile-time dependencies on other assemblies, and specifies the set of permissions required for the assembly to run properly. This information is used at run time to resolve references, enforce version-binding policy, and validate the integrity of loaded assemblies. The selfdescribing nature of assemblies also helps makes zero-impact install and XCOPY deployment feasible. Metadata - Information that describes every element managed by the common language runtime: an assembly, loadable file, type, method, and so on. This can include information required for debugging and garbage collection, as well as security attributes, marshaling data, extended class and member definitions, version binding, and other information required by the runtime.

What are different types of Assemblies? There are Two Types of Assemblies. They are Private Assembly and Shared Assembly. Private Assembly is used by a single application and is stored in Application Directory or a subdirectory beneath. Shared Assembly is used by Multiple Applications and is Stored in Global Assembly Cache (GAC). Runtime enforces Versioning Constraints on Shared Assemblies only and not on Private Assemblies. What are the different types of assemblies? Private, Public/Shared, Satellite What is the difference between a private assembly and a shared assembly? 1.Location and visibility: A private assembly is normally used by a single application, and is stored in the application's directory, or a subdirectory beneath. A shared assembly is normally stored in the global assembly cache, which is a repository of assemblies maintained by the .NET runtime. Shared assemblies are usually libraries of code which many applications will find useful, e.g. the .NET framework classes.

Page of 159

22

MBT Pune
2.Versioning: The runtime enforces versioning constraints only on shared assemblies, not on private assemblies. What are Satellite Assemblies? How you will create this? How will you get the different language strings? Satellite assemblies are often used to deploy language-specific resources for an application. These language-specific assemblies work in side-by-side execution because the application has a separate product ID for each language and installs satellite assemblies in a language-specific subdirectory for each language. When uninstalling, the application removes only the satellite assemblies associated with a given language and .NET Framework version. No core .NET Framework files are removed unless the last language for that .NET Framework version is being removed. (For example, English and Japanese editions of the .NET Framework version 1.1 share the same core files. The Japanese .NET Framework version 1.1 adds satellite assemblies with localized resources in a \ja subdirectory. An application that supports the .NET Framework version 1.1, regardless of its language, always uses the same core runtime files.) p How will u load dynamic assembly? How will create assemblies at run time? What is strong name? A name that consists of an assembly's identityits simple text name, version number, and culture information (if provided)strengthened by a public key and a digital signature generated over the assembly. What is portable executable (PE)? The file format defining the structure that all executable files (EXE) and Dynamic Link Libraries (DLL) must use to allow them to be loaded and executed by Windows. PE is derived from the Microsoft Common Object File Format (COFF). The EXE and DLL files created using the .NET Framework obey the PE/COFF formats and also add additional header and data sections to the files that are only used by the CLR.

What is GAC and what is the purpose of it? (How to make an assembly to public? Steps) How more than one version of an assembly can keep in same place? Global Assembly Cache is a repository of assemblies maintained by .NET runtime. Each computer where the common language runtime is installed has a machine-wide code cache called the global assembly cache. The global assembly cache stores assemblies specifically designated to be shared by several applications on the computer. You should share assemblies by installing them into the global assembly cache only when you need to. Steps - Create a strong name using sn.exe tool eg: sn -k keyPair.snk - with in AssemblyInfo.cs add the generated file name eg: [assembly: AssemblyKeyFile("abc.snk")] - recompile project, then install it to GAC by either drag & drop it to assembly folder (C:\WINDOWS\assembly OR C:\WINNT\assembly) (shfusion.dll tool) or gacutil -i abc.dll

Page of 159

23

MBT Pune

If I have more than one version of one assemblies, then how'll I use old version (how/where to specify version number?)in my application? ** How to find methods of a assembly file (not using ILDASM) Reflection

How Assembly Dll or exe is checked? Using ILDASM.EXE Utility.(IntermediateLanguageDissassembler). What is reflection? All .NET compilers produce metadata about the types defined in the modules they produce. This metadata is packaged along with the module (modules in turn are packaged together in assemblies), and can be accessed by a mechanism called reflection. The System. Reflection namespace contains classes that can be used to interrogate the types for a module/assembly. Using reflection to access .NET metadata is very similar to using ITypeLib/ITypeInfo to access type library data in COM, and it is used for similar purposes - e.g. determining data type sizes for marshalling data across context/process/machine boundaries. Reflection can also be used to dynamically invoke methods (see System.Type.InvokeMember), or even create types dynamically at run-time (see System.Reflection.Emit.TypeBuilder). What is .NET Class Library?

.NET Class Library is a collection of reusable types that are tightly integrate with the Common Language Runtime, from which your own Managed Code can derive functionality. What is Application Domain? Application Domain is a Construct in the CLR that is the unit of isolation for an application. The Isolation Guarantees the following: a) An Application Can be Independently stopped. b) An Application cannot directly access code or resources in another application. c) A fault in an application cannot affect other applications. What is Application Domain? The primary purpose of the AppDomain is to isolate an application from other applications. Win32 processes provide isolation by having distinct memory address spaces. This is effective, but it is expensive and doesn't scale well. The .NET runtime enforces AppDomain isolation by keeping control over the use of memory - all memory in the AppDomain is managed by the .NET runtime, so the runtime can ensure that AppDomains do not access each other's memory. Objects in different application domains communicate either by transporting copies of objects across application domain boundaries, or by using a proxy to exchange messages. MarshalByRefObject is the base class for objects that communicate across application domain boundaries by exchanging messages using a proxy. Objects that do not inherit from MarshalByRefObject are implicitly marshal by value. When a remote application references a marshal by value object, a copy of the object is passed across application domain boundaries. How does an AppDomain get created?

Page of 159

24

MBT Pune
AppDomains are usually created by hosts. Examples of hosts are the Windows Shell, ASP.NET and IE. When you run a .NET application from the command-line, the host is the Shell. The Shell creates a new AppDomain for every application. AppDomains can also be explicitly created by .NET applications. What is Active Directory? What is the namespace used to access the Microsoft Active Directories? What are ADSI Directories? Active Directory Service Interfaces (ADSI) is a programmatic interface for Microsoft Windows Active Directory. It enables your applications to interact with diverse directories on a network, using a single interface. Visual Studio .NET and the .NET Framework make it easy to add ADSI functionality with the DirectoryEntry and DirectorySearcher components. Using ADSI, you can create applications that perform common administrative tasks, such as backing up databases, accessing printers, and administering user accounts. ADSI makes it possible for you to:

Log on once to work with diverse directories. The DirectoryEntry


component class provides username and password properties that can be entered at runtime and communicated to the Active Directory object you are binding to.

Use a single application programming interface (API) to perform


tasks on multiple directory systems by offering the user a variety of protocols to use. The DirectoryServices namespace provides the classes to perform most administrative functions. Perform "rich querying" on directory systems. ADSI technology allows for searching for an object by specifying two query dialects: SQL and LDAP. Access and use a single, hierarchical structure for administering and maintaining diverse and complicated network configurations by accessing an Active Directory tree.

Integrate directory information with databases such as SQL Server.


The DirectoryEntry path may be used as an ADO.NET connection string provided that it is using the LDAP provider. using System.DirectoryServices; What platforms do the .NET Framework run on? The runtime supports Windows XP, Windows 2000, NT4 SP6a and Windows ME/98. Windows 95 is not supported. Some parts of the framework do not work on all platforms for example, ASP.NET is only supported on Windows XP and Windows 2000. Windows 98/ME cannot be used for development. What is garbage Collection? Garbage Collection is a system by which Common Language Runtime takes responsibility for managing the lifetime of Objects and heap memory that they occupy. Garbage collection is an algorithm. It works by periodically running through a list of all the objects that are currently being referenced by an application. All objects that it doesnt find during this search are ready to be destroyed and the memory reclaimed. The Implication of this algorithm is that the runtime doesnt get notified immediately when the final reference on an object goes away-it only finds out during the next sweep of the heap.

Page of 159

25

MBT Pune
For this Microsoft Recommends Dispose() method and Finalize() methods, to get freed object resources. NB: - System.GC class provides Collect method that uses to collect all un referenced objects immediately. How Garbage Collector (GC) Works? The methods in this class influence when an object is garbage collected and when resources allocated by an object are released. Properties in this class provide information about the total amount of memory available in the system and the age category, or generation, of memory allocated to an object. Periodically, the garbage collector performs garbage collection to reclaim memory allocated to objects for which there are no valid references. Garbage collection happens automatically when a request for memory cannot be satisfied using available free memory. Alternatively, an application can force garbage collection using the Collect method. Garbage collection consists of the following steps: 1.The garbage collector searches for managed objects that are referenced in managed code. 2.The garbage collector attempts to finalize objects that are not referenced. 3.The garbage collector frees objects that are not referenced and reclaims their memory. Why do we need to call CG.SupressFinalize? Requests that the system not call the finalizer method for the specified object. public static void SuppressFinalize( object obj); The method removes obj from the set of objects that require finalization. The obj parameter is required to be the caller of this method. Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.

What is the difference between Finalize and Dispose (Garbage collection) Class instances often encapsulate control over resources that are not managed by the runtime, such as window handles (HWND), database connections, and so on. Therefore, you should provide both an explicit and an implicit way to free those resources. Provide implicit control by implementing the protected Finalize Method on an object (destructor syntax in C# and the Managed Extensions for C++). The garbage collector calls this method at some point after there are no longer any valid references to the object. In some cases, you might want to provide programmers using an object with the ability to explicitly release these external resources before the garbage collector frees the object. If an external resource is scarce or expensive, better performance can be achieved if the programmer explicitly releases resources when they are no longer being used. To provide explicit control, implement the Dispose method provided by the IDisposable Interface. The consumer of the object should call this method when it is done using the object. Dispose can be called even if other references to the object are alive. Note that even when you provide explicit control by way of Dispose, you should provide implicit cleanup using the Finalize method. Finalize provides a backup to prevent resources from permanently leaking if the programmer fails to call Dispose.

Page of 159

26

MBT Pune
pWhat is close method? How its different from Finalize & Dispose? What is nmake tool? The Nmake tool (Nmake.exe) is a 32-bit tool that you use to build projects based on commands contained in a .mak file. usage : nmake -a all p What are virtual destructors? Destructor and finalize Generally in C++ the destructor is called when objects gets destroyed. And one can explicitly call the destructors in C++. And also the objects are destroyed in reverse order that they are created in. So in C++ you have control over the destructors. In C# you can never call them, the reason is one cannot destroy an object. So who has the control over the destructor (in C#)? it's the .Net frameworks Garbage Collector (GC). GC destroys the objects only when necessary. Some situations of necessity are memory is exhausted or user explicitly calls System.GC.Collect() method. Points to remember: 1. Destructors are invoked automatically, and cannot be invoked explicitly. 2. Destructors cannot be overloaded. Thus, a class can have, at most, one destructor. 3. Destructors are not inherited. Thus, a class has no destructors other than the one, which may be declared in it. 4. Destructors cannot be used with structs. They are only used with classes. 5. An instance becomes eligible for destruction when it is no longer possible for any code to use the instance. 6. Execution of the destructor for the instance may occur at any time after the instance becomes eligible for destruction. 7. When an instance is destructed, the destructors in its inheritance chain are called, in order, from most derived to least derived. Is goto statement supported in C#? How about Java? Gotos are supported in C#to the fullest. In Java goto is a reserved keyword that provides absolutely no functionality. Add your assemblies to .NET Reference Tab in VS.NET ? The .NET tab of the Add Reference dialog box displays system assemblies and Primary Interop Assemblies that are supplied with the .NET Framework and optionally other assemblies. These are usually (but not necessarily) those installed in the GAC. You can enable your own assemblies to appear in this list, but this requires a registry modification to designate the folder or folders that contain your assemblies. For example, you could apply registry updates to point to the folders that contain assemblies built by your build script (either locally or on the build server). This allows developers to reference these assemblies from the .NET tab and avoids the use of the Browse button. To add your own assemblies to the .NET tab

1. Create a new registry key (for example, one called

InnerSystemAssemblies) beneath either of the following registry keys: HKEY_LOCAL_MACHINE\Software\Microsoft\.NETFramework\AssemblyFold

Page of 159

27

MBT Pune
ers HKEY_CURRENT_USER\Software\Microsoft\.NETFramework\AssemblyFolde rs

2. Set the new key's default value to point to the folder that contains your
assemblies.

3. If you have Visual Studio .NET open, you must close it and then launch it
again for the changes to take effect.

2.PAGE:What is Roundtrip? For Each user action on the form, the form must be posted to the server, processed, and returned to the browser. This sequence of events is referred to as a round trip. Why pages are said to be stateless? And Advantages of ASPNET? The values of a page's variables and controls are not preserved on the server. In a traditional Web application, the only information that the server has about a form is the information that the user has added to the controls on the form, because that information is sent to the server when the form is posted. Other information, such as variable values and property settings, is discarded. ASP.NET works around these limitations in the following ways: It saves page and control properties between round trips. This is referred to as saving the view state of the control. It provides state management facilities so you can save your own variable and application-specific or session-specific information between round trips. It can detect when a form is requested for the first time versus when the form is posted, which allows you to program accordingly. You may want a different behaviour during a page post back versus an initial request.

Benefits of an Event-Driven Model versus a Linear Processing Model If you have experience using Active Server Pages (ASP), you recognize that ASP is a linear processing model. An ASP page is processed in a top-to-bottom sequence. Each line of ASP code and static HTML is processed in sequence as it appears in the file. User actions cause the page to be posted to the server in a round trip. Since this action causes a round trip, the server must recreate the page. After the page is recreated, it is processed in the same top-to-bottom sequence as before, and therefore the page is not exhibiting truly event-driven behaviour. To create an event-driven experience, you need to explicitly design it. In addition, you have to explicitly maintain page and control state at the most basic level. This model limits the richness of the user interfaces that can be assembled, and it increases the complexity of the code needed to support it. In comparison, an event-driven model, as in a traditional Visual Basic application, contains programmable elements that are initialised and displayed on the form. Users interact with the elements, which cause events to be raised that in turn call event handlers. This model supports true event-driven behaviour, which, by design, greatly extends the

Page of 159

28

MBT Pune
richness of the user interfaces that can be assembled, and it reduces the complexity of the code needed to support it. ASP.NET replaces the linear processing model of ASP by emulating the behaviour of an event-driven model. The ASP.NET page framework is provided to implicitly make the associations of an event to an event handler for you. Using the page framework allows you to easily create a user interface that reacts to user actions. For details on creating and using events and event handlers,. For example, ASP.NET allows you to set up event handlers in server code for events that are passed from the browser. Assume the user is interacting with a Web Forms page that contains one button server control. The user clicks the button control and an event is raised that is transmitted via an HTTP post to the server where the ASP.NET page framework interprets the posted information and associates the raised event with an appropriate event handler. This event handler can be a default handler supplied by ASP.NET or it can be your custom implementation. The framework automatically calls the appropriate event handler for the button as part of the framework's normal processing. As a result, you no longer need to explicitly design event-like behavior into a linear processing model. For more information on Web Forms event handling, see ASP.NET Server Control Event Model Asp.net and asp differences? Code Render Block Code Declaration Block Compiled Request/Response Event Driven Object Oriented Constructors/Destructors, Inheritance, overloading.. Exception Handling - Try, Catch, Finally Down-level Support Cultures User Controls In-built client side validation It can span across servers, It can Session weren't transferable survive server crashes, can work across servers with browsers that don't support cookies its an integral part of OS under the .net framework. It shares built on top of the window & IIS, many of the same objects that it was always a separate entity traditional applications would & its functionality was limited. use, and all .net objects are available for asp.net's consumption. Garbage Collection Declare variable with datatype In built graphics support Cultures

What are the different Stages in Page Processing?

Page of 159

29

MBT Pune
The first time that an ASP.NET Web form page is executed, the code contained within the page(and any code-behind class associated with the page) is compiled into a class that inherits from the Page base class. Once compiled, the class is executed, the resulting HTML is rendered to the browser and the class is removed from memory. During this the Web Forms Page goes through different stages. They are 1.Init:-Page and Control settings are Initialized as necessary for the request. 2.LoadViewState:-Server control state that was saved to ViewState in an earlier request is restored. 3.LoadPostData:-Any data returned in Server Control form fields is processed and the relevant Control Properties are updated. 4.Load:-Controls are Created and Loaded, and Control state matches the data entered by the client. 5.RaisePostDataChanged Event:-Events are raised in response to changes in control data from previous request to current request. 6.RaisePostBackEvent:-The event that caused the Post Back is handled and the appropriate Server-side events are raised. 7.PreRender:-Any Changes that need to be made prior to Rendering the page are processed. Any Processing after this point will not be rendered to the page. 8.SaveViewState:-Server Control State is Saved back to the Pages View State prior to tearing down the controls. 9.Render:-Control and Page Output is rendered to the client. (Dispose Stage:- in which References to Expensive resources such as database connections must be released in this phase. Here Dispose Method is used) 10.Unload:-The Page and its Constituent Controls are removed from memory on the server. Of These Stages in which stages we can handle Events? Of These Stages you can add Page Level Event Handler for Init, Load, Pre Render and Render Stages. For other Stages such as, LoadViewState, SaveViewState, LoadPostData, RaisePostDataChangedEvent, RaisePostBackEvent Stages you can override the appropriate method to customize the processing of these stages. What is Post Back? Post Back is the process by which a Web Form Page submits an Http Post Request to itself in response to some User action. How do u handle Post Back? LoadPostData and RaisePostDataChangedEvent are methods of the IPostBackDataHandler interface, and RaisePostBackEvent belongs to the IPostBackEventHandler interface. If your control participates in post-back data processing you must implement IPostBackDataHandler. If your control receives post back events you must implement IPostBackEventHandler.

Page of 159

30

MBT Pune
NB:-The CreateChildControls method is not listed in the table because it is called whenever the ASP.NET page framework needs to create the controls tree and this method call is not limited to a specific phase in a control's lifecycle. For example, CreateChildControls can be invoked when loading a page, during data binding, or during rendering.

3.ASP.NET:**What is the process-flow for ASP.Net? 1. User requests an ASPx page in their browser 2. An HTTP requests is sent to IIS 3. The xspisapi.dll isapi filter intercepts the request and passes the request on to the XSP worker process (xspwp.exe) 4. Xspwp takes care of handing the request to the appropriate HTTPModules and finally an HTTPHandler as defined in the configuration files. 5. The ASPX page is read from the Hard Disk or cache and server code is loaded into memory and executed. 6. The server side code outputs normal HTML, which is handed back through the chain of modules and eventually to IIS, which sends the response back to the client's browser. 7. If the user clicks or otherwise acts on an HTML element (say, a textbox) that has a server side event handler, the form is posted back to the server with hidden form fields containing information as to what control and event occurred. Some controls do not automatically post by default, but wait for a button click event to post. This is configurable by the developer. 8. The ASPx page is again loaded into memory using the same sequence of events as before, but this time ASP.NET reads in the hidden form field data and automatically triggers the appropriate _OnChange, OnClick and other appropriate event handlers. 9. Resulting HTML is sent to the browser 10. The process continues in a continual "Post Back" cycle. What are HTTP Modules? Definition of HTTP Modules: (ISAPI: Internet Service Application Programming) HTTP modules are a logical replacement for ISAPI filters. Modules are a class that can participate in every web request. This is appropriate for code that should run on every request, such as caching, authentication or state management What are HTTP Handlers? HTTP Handlers provide the end point in the processing of a web request and are equivalent to ISAPI Extensions today. For example, many handlers can be involved in the request for an ASPX page, but only 1 handler is invoked. The handler runs after the

Page of 159

31

MBT Pune
HTTP modules have run. Which handler is invoked is determined by configuration settings in the config.web file. Handlers are assigned to handle requests based on the extension of the page requested. What are HttpHandlers and Httpmodules? ASP.NET allows you to extend its functionality in two main ways : HttpHandlers HttpModules

Http handlers are special applications that typically handle files with certain extension. For example when you request a file with extension .asp IIS routes it to ASP processor. But what if I want to handle files with my own extensions say .bipin? Http handlers allow us to do just that. Now, you might be thinking what is the use of a new file extension? Consider a case where you want to generate graphics on the fly. In such cases you will write an Http handler that will do your task. Note that Http handlers are typically called for the specific file extensions they are designed for. If you have worked with ISAPI extensions in past you will find this concept very familiar. Http modules are similar to Http handlers in that they allow you to tweak with the request and response. However, they are typically executed for every request irrespective of the file type. If you have worked with ISAPI filters before you will find this concept very familiar.

What an ASP.NET Web Application Consists? A simple ASP.NET Web Application Consists of Four Things. 1.A virtual Directory in IIS , configured as an Application Root, to hold the files that make up the application and to control access to the files. 2. One or more .aspx files. 3. A Global. asax file that is used to provide Application and Session Startup and Cleanup code. 4. A Web.Config file used to store configuration Settings. What Global. asax Contains? The Global. asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level events, session-level events and CustomHttpModules events raised by ASP.NET.Global.asax file resides in the root directory of an ASP.NET based application. Global. asax is a file used to provide Application and Session Startup and Cleanup code. The following Tasks can be performed in Global.asax 1.Respond to selected Application and Session Events. a)Application_OnStart :Event is fired when first Request for any .aspx page is received. This even is used to a). Initialize Application Variables. b).To execute Startup Code. b)Session_Onstart: Event is fired, When a request comes from a user who does not have a current session in Application Current Session is identified by SessionID cookie.. This even is used to a). Initialize Session -level Variables. b).To execute per user Startup Code. c)Application_BeginRequest d)Application_EndRequest e)Session_OnEnd f)Application_OnEnd 2.Respond to Events of Custom HttpModules you have created for applications.

Page of 159

32

MBT Pune
NB:- HttpModules are Classes that inherit the IHttpModule interface and Participate in Processing ASP.NET Requests. 3.Import Namespaces into the application using @Import Directive. So without need of Import Namespace in each page and without having to fully qualify the member Names. NB:- If two or more Namespaces contain same members then must use Fully qualified member names to avoid conflicts. 4.Register Assemblies for use in your application using @Assembly Directive. 5.Create Instances of application level objects using <Object runt at=server> tag syntax. <Object run at=server id=MyclassInstance class=Myclassname Scope=Application/Session/AppInstance > In webformspage it can be used like this MyVar=MyclassInstance.MyValue Limitations:1.Limit no. of Components Instantiated at Application/Session Level, since these Objects will be Consuming Resources(Such as memory) for entire life time of Application/Session, which causes Scalability Problems. 2. Any Components Instantiated in <object> Tag should be multithreaded. 3.Objects created with <object > tag are not Instantiated immediately, but at the time when first they are called. Does ASP.NET support server-side object tags? Yes. The following tag creates an instance of a custom type named ShoppingCart and assigns it session scope (that is, it creates a unique ShoppingCart instance for each and every session created on the server):

<object id="MyShoppingCart" class="ShoppingCart" scope="session" runat="server" />

Managed types created this way are identified by class name. Unmanaged types (COM classes) are identified by CLSID or ProgID.

Storing Connection String Information in Web.Config ? You can store the connecting string information in your web.config file in two ways: Using <appSettings> Section Using <CustomSection> Section.

Using <appSettings> Section The predefined <appSettings> section can be placed in any web.config file or the machine.config file. This section is useful for storing name-value pairs of data. An example of the use of the <appSettings> section is as follows, <appSettings> <add key="ConnectionString" Value="myconnectionstring" /> </appSettings>

Page of 159

33

MBT Pune
To access the appSettings Value, you need to use ConfiugrationSttings.AppSetting ["ConnectionString"]. This uses the NameValueFileSectionHandler, which returns a System.Collection.Specialized.NameValueCollection object. The collection implements the IEnumerable interface so you can enumerate the collection, or read values directly for any valid key. For more details accessing appSetting value refer this link, Accessing the appSettings Section Using <CustomSection> Section You can create your own custom sections in a configuration file. The easiest way to do this is to configure one of the pre-existing configuration section handlers, assuming your section uses one of the generic structures such as name-value data, or single tag data. In this particular case you might use the Name-Value data. To do this, you need to use the pre-defined section handlers. For example, you can define a section called , <myNameValueSection> <myNameValueSection> <add key="ConnectionString" Value="my connection string" <myNameValueSection> To read the data, you will need the following code snippet , NameValuecollection config = ConfigurationSettings.GetConfig("myNameValueSection") For each key in config.keys label1.Text = "Key:" + key.toString() label2.Text = "Value:" + config[key] End Loop What Web.config Contains? Web.Config is an XML-Based human and machine-readable file that contains the configuration options for the Application. Its Optional, since Machine.Config exists. When you add web.config to your application root, the configuration settings contained in that file will apply throughout your application. You can also override these settings in specific areas of your application by setting child folders in your applications. Some of Configuration Options are a) HttpModules and HttpHandlers: - Process specific types of requests and are similar to ISAPI filters. b) Session Settings: -Determines whether session settings are Improves, Out Of Process (Shared Across Multiple Machine) or Stored by SqlServer. c) Browser Capabilities: - Customize properties returned by HttpBrowserCapabilities Class when it encounters a given browser. d) Security: - Determines settings for Authentication, Authorization and Identity. e) Compilation: -Determine settings used for Compiling the code in ASP.NET application, Including which external assemblies are included in the compilation of the application What is Different ways of working with ASP.NET? There are 3 ways to work with ASP.NET. 1.Inline Code that is compiled on the web server, as it is needed as Application Logic exists within the .aspx file. 2.Code-behind Files that are compiled into .dll file and then removed from production. 3.Code-behind file that are compiled on the web server, as they are needed as as Application Logic exists outside the .aspx file.

Page of 159

34

MBT Pune
*What is Code Behind? Code behind is a new feature in ASP.NET that allows developers to truly separate Presentation layer (HTML UI code) from Application Logic(code in VB.NET.) *What are the advantages of Code Behind? a) Clean separation Of HTML and Code. b) Easier Reuse. c) Simpler Maintenance. d) Deployment Without Source Code What happened to date () and time ()? In ASP.Net you should use: System.DateTime.Now.ToShortDateString () and System.DateTime.Now.ToShortTimeString () What are major differences between ASP.NET and ASP? 1.Current Versions of ASP supports only scripting Languages. This means that developers move section of code to COM objects to get compiled and early bound support. ASP.NET strongly supports Compiled languages. Compiled code means that all the variables must have to be declared. so all objects are early bound. 2.In the Current version of ASP deploying COM objects is difficult. IIS keeps DLL loaded in the memory forcing to shutdown all MTS packages. ASP.NET provides support to manage and restart components that are in use when there is a overload. This prevents memory leak from soaking up the resources.

*** What are the advantages of ASP.NET over Classic ASP? 1.Clean Separation between the application logic(Server-side code) and the Presentation layer(HTML mark up)-no mixed code. 2.application server-side is compiled for better performance. 3. Application logic can be written in any Microsoft .net Language (VB,C#). 4.A Rich set of Server Controls that automatically render HTML suitable for any clients and additionally manage their states. 5.Enhanced Session-State Management. 6.An Event-Based programming model on the server side, which is simple and more intuitive. 7.Visualstudio.NET as a RAD tool, which simplifies the development process of web Forms.

What is Server control ? Server controls are tags that are understood by the server. There are three kinds of server controls: HTML Server Controls - Traditional HTML tags

Page of 159

35

MBT Pune
Web Server Controls - New ASP .NET tags Validation Server Controls - For input validation

Difference Between ASP.NET Server Controls,HTML Server Controls and HTML Intrinsic Controls ?

ASP.NET Server Controls Advantages: 1. ASP .NET Server Controls can however detect the target browser's capabilities and render themselves accordingly. No issues for compatibility issues of Browsers i.e page that might be used by both HTML 3.2 and HTML 4.0 browsers code to be written by you. 2. Newer set of controls that can be used in the same manner as any HTMl control like Calender controls. (No need of Activex Control for doing this which would then bring up issues of Browser compatibility). 3. Processing would be done at the server side. In built functionality to check for few values(with Validation controls) so no need to choose between scripting language which would be incompatible with few browsers. 4. ASP .NET Server Controls have an object model different from the traditional HTML and even provide a set of properties and methods that can change the outlook and behavior of the controls. 5. ASP .NET Server Controls have higher level of abstraction. An output of an ASP .NET server control can be the result of many HTML tags that combine together to produce that control and its events. Disadvantages: 1. The control of the code is inbuilt with the web server controls so you have no much of direct control on these controls 2. Migration of ASP to any ASP.NET application is difficult. Its equivalent to rewriting your new application

HTML Server Controls Advantages: 1. The HTML Server Controls follow the HTML-centric object model. Model similar to HTML 2. Here the controls can be made to interact with Client side scripting. Processing would be done at client as well as server depending on your code. 3. Migration of the ASP project thought not very easy can be done by giving each intrinsic HTML control a runat = server to make it HTML Server side control. 4. The HTML Server Controls have no mechanism of identifying the capabilities of the client browser accessing the current page. 5. A HTML Server Control has similar abstraction with its corresponding HTML tag and offers no abstraction. Disadvantages: 1. You would need to code for the browser compatibility.

HTML Intrinsic Controls Advantages: 1. Model similar to HTML 2. Here the controls can be made to interact with Client side scripting

Page of 159

36

MBT Pune
Disadvantages: 1. You would need to code for the browser compatibility

What are Different Types of ASP.NET controls ? HTML controls : They represent standard HTML controls but run at server end.

Web Controls : ASP.NET offers a set of controls which map closely to standard HTML controls but provide consistant properties, methods and events. Some WebControls like data grid provide advance features which are not available with standard HTML controls

The common HTML controls <table> <tr> <td> <form> <input> <select> <textarea> <button> <a> <img>

The common Web Controls <asp:Button> <asp:TextBox> <asp:CheckBox> <asp:RadioButton> <asp:DropDownList> <asp:ListBox> <asp:Label> <asp:Panel> <asp:Table> <asp:TableRow>

Page of 159

37

MBT Pune
<asp:TableCell> <asp:Image> <asp:HyperLink> <asp:Repeater> <asp:Calendar>

There are also some advance controls like Input validation controls and data bound grid. What are Validation Controls? ASP.NET Provides a set of Web Server Controls called validation controls that provide sophisticated validation on both the client side and the server side depending on the validation settings and the browsers capabilities. ASP.NET ensures that all validations are performed on the server side even if they were already performed on the client-side. This ensures that validations are not by passed if a malicious user circumvents client-side validation. If the client-side validation fails, the server side validation is never performed. The Different types of Validation Controls are: 1.RequiredFieldValidator 2.CompareValidator 3.RangeValidator 4.RegularExpressionValidator 5.CutomValidator 6.ValidationSummaryValidator NB:-page.isvalid Control HtmlInputText HtmlTextArea HtmlSelect HtmlInputFile TextBox ListBox DropDownList RadioButtonList Validation Property value value value value Text SelectedItem.Value SelectedItem.Value SelectedItem.Value

Which two properties are there on every validation control? ControlToValidate, ErrorMessage How do you use css in asp.net? Within the <HEAD> section of an HTML document that will use these styles, add a link to this external CSS style sheet that follows this form: <LINK REL="STYLESHEET" TYPE="text/css" HREF="MyStyles.css"> MyStyles.css is the name of your external CSS style sheet.

What are the Advantages of Server side Controls? Your code structure becomes clean and more readable

Page of 159

38

MBT Pune
Seperatation of processing code and display code is possible

To access the values of the controls you no longer need to use Request collection, you can refer to the control by its id directly The problem of state maintenance is automatically taken care by ASP.NET

Web server controls provide a higher level of abstraction than HTML controls because the Object model matches closely with .NET Framework. Web server controls provide richer functionality, such as the Calendar control, Ad Rotator Control and so, on which are not available in HTML controls. Web server controls have advanced features such as automatic browser detection, automatic post back and event bubbling.

How do you Make control run at server? To process HTML or Web control you need to add runat="server" attribute the control defination. e.g.<input type="text" id="text1" runat="server"> <asp:TextBox id="text1" runat="server />

How ASP.NET maintains state? ASP.NET uses hidden fields to maintain state of your controls. Hidden fields are used to store values entered by the user into the form controls. There are some points which you should note about state maintenance : Your FORM must run at server i.e. you must set runat attribute of FORM element to "server" You must use POST method. This is because if you use GET the data will be passed as query string.

When a control is declared to run on the server, a ViewState is created which remembers the ID of that control, and the method to call when an action is performed. Submit event calls the JavaScript function __doPostBack. You do not write this function, instead its generated by the ASP.NET engine and automatically included in our page. It submits the form to the same page, and accepts 2 arguments. EventTarget: The control doing the submission. EventArgumet: any additional information for the event.

If the control is set visible=false, then the java script function will not be included and will not be able to perform any actions.

Page of 159

39

MBT Pune
Disabling Back button in ASP.NET ? In your application you might come across the situation where you need to disable back button. For example if you consider this scenario, user gets data which can change frequently from database to display it in the screen. From that screen user can go another page where he presses back button of browser to come back to this page again. During that time browser might show the page which is in cache because of which user might not see the approriate data. To avoid this you can open the browser without toolbar. So that user wont see the back button. But in lots of cases we cant do this. Other way for doing this is, dont cache the page. So everytime any page is requested it will go to the server. Hence user will get the current data. For avoiding page to be cached, you need to set the following properties for response object. Response.Buffer = True Response.ExpiresAbsolute = Now().Subtract(New TimeSpan(1, 0, 0, 0)) Response.Expires = 0 Response.CacheControl = "no-cache" ExpiresAbsolute : Gets or sets the absolute date and time at which to remove cached information from the cache. Expires : Gets or sets the number of minutes before a page cached on a browser expires. If the user returns to the same page before it expires, the cached version is displayed. CacheControl : Possible values: Sets the Cache-Control HTTP header to Public or Private.

Public - may be cached in public shared caches Private - may only be cached in private cache no-cache - may not be cached no-store - may be cached but not archived How to set the automatic state maintenance for controls? By means of ViewState property for that Control. Set this property to true if you want automatic state maintennece. As I told you, The viewstate is enabled by default for all the server controls. ** Does HTML controls support the automatic state maintenance? No Is view state is encrypted in between requests? Yes, Normally, the view state is a hashed string encoded as Base64 and stored in a hidden field called __VIEWSTATE

How Server-side Event Processing Takes place? Server side controls have events that are processed at server end. Here again you set the runat attribute of SCRIPT element to "server". The server side events have different naming convention to separate them from client side events. Each event is of the form On Server<event> e.g. OnSeverClick e.g <SCRIPT language="VB" runat="server"> Sub MyProc(sender as object,evt as EventArgs) text1.value = "Hello From ASP.NET"

Page of 159

40

MBT Pune
End Sub </SCRIPT> <INPUT type="text" value="" runat="server" id="text1> <INPUT type="submit" value="Submit" runat="server" onserverclick="MyProc"> NB:ASP.NET also provides some advanced controls like datagrid, datalist , repeater and calender which provide rich functionality and saves programmer from lot of code. ASP.NET uses compiled languages rather that scripting languages. For example VB C#, JScript and Perl. You can use only one language per page If you want mix two languages you have to use pagelets. Pagelets are miniature ASP.NET pages that can be embedded in other pages. Functions must be inside a <SCRIPT> block rather than <% and %> block What are User Controls? A User Control is an extension of the functionality of an existing server controls. Server controls that are shipped with .NET Framework, is a compiled DLL file and cannot be edited. But it can be manipulated through its public properties at design-time or runtime. It is possible to build a Custom Server Control. What is difference between Web User Control and Web Custom Control? The Main Difference between the two controls lies in ease of creation Vs ease of use at design time. Web User Controls are easy to make, its developed exactly same as developing web form pages. As they are compiled dynamically at runtime they cannot be added to toolbox and They are represented by simple placeholder glyph when added to the page. Web custom controls are compiled code , which makes them easier to use but more difficult to create. Custom controls must be authored in code. Once you have created the control, you can add it to the toolbox and display it in a visual designer with full properties window support and all other design-time features of ASP.NET Server controls. In addition, you can install a single copy of web custom control in the Global Assembly Cache and share it between applications, which make maintenance easier.

Web user controls Easier to create Limited support for consumers who use a visual design tool A separate copy of the control is required in each application Cannot be added to the Toolbox in Visual Studio Good for static layout

Web custom controls Harder to create Full visual design tool support for consumers Only a single copy of the control is required, in the global assembly cache Can be added to the Toolbox in Visual Studio Good for dynamic layout

Can I create ASP.NET server controls of my own? Yes. You can modify existing server controls by deriving from the corresponding control classes or create server controls from scratch by deriving from System.Web.UI.Control. Although a full treatment of custom controls is beyond

Page of 159

41

MBT Pune
the scope of this FAQ, here's a simple custom control that writes "Hello, world" to a Web page: using System; using System.Web; using System.Web.UI; namespace Wintellect { public class HelloControl : Control { protected override void Render (HtmlTextWriter writer) { writer.Write ("Hello, World!"); } } A custom control emits HTML by overriding the virtual Render method it inherits from Control and using the provided HtmlTextWriter to write its output. What does the System.Web.UI.Page.RegisterClientScriptBlock method do, and do I need it when I write custom ASP.NET server controls? RegisterClientScriptBlock enables a custom control to register a block of clientside script that the control returns to a browser. Why does it exist? So the same script block doesn't get returned multiple times if the page contains multiple instances of a control that emits client-side script. Here's the source code for a custom control called AlertButton that renders itself an as <input type="submit"> tag with an onclick attribute that displays a message using a JavaScript alert: using using using using System; System.Web; System.Web.UI; System.Text;

namespace Wintellect { public class AlertButton : Control { protected string _Text; protected string _Message; public string Text { get { return _Text; } set { _Text = value; } } public string Message { get { return _Message; } set { _Message = value; } } protected override void OnPreRender (EventArgs e) {

Page of 159

42

MBT Pune
Page.RegisterClientScriptBlock ( "__doAlert", "<script language=\"javascript\">\n" + "<!--\n"+ "function __doAlert (message)\n" + "{\n" + " alert (message);\n" + "}\n" + "-->\n"+ "</script>" );

protected override void Render (HtmlTextWriter writer) { StringBuilder builder = new StringBuilder (); builder.Append builder.Append builder.Append builder.Append builder.Append } ("<input type=\"submit\" value=\""); (_Text); ("\" onclick=\"javascript:__doAlert (\'"); (Message); ("\');\" />");

writer.Write (builder.ToString ()); } } If the control's register tag prefix is win, then the following statement declares an AlertButton control that, when clicked, displays "Hello, world" in a message box: <win:AlertButton Text="Click Me" Message="Hello, world" RunAt="server" /> The control uses RegisterClientScriptBlock to register the client-side script block that it returns. That script block contains the __doAlert function referenced by the <input> tag's onclick attribute. It's returned only once no matter AlertButtons a page contains. RegisterClientScriptBlock should always be called from the control's OnPreRender method so ASP.NET can control the script's position in the output. What's the difference between Page.RegisterClientScriptBlock and Page.RegisterStartupScript? RegisterClientScriptBlock is for returning blocks of client-side script containing functions. RegisterStartupScript is for returning blocks of client-script not packaged in functions-in other words, code that's to execute when the page is loaded. The latter positions script blocks near the end of the document so elements on the page that the script interacts are loaded before the script runs. Can a calendar control be customized so that it limits users to selecting certain days of the week, and only dates that fall on or after today's date? Yes. The secret is to customize the control by processing DayRender events, which are fired as the calendar renders each and every cell. Here's an example that limits selections to future Fridays and Saturdays: <asp:Calendar OnDayRender="OnDayRender" RunAt="server" /> . .

Page of 159

43

MBT Pune
. void OnDayRender (Object sender, DayRenderEventArgs e) { e.Day.IsSelectable = (e.Day.Date.DayOfWeek == DayOfWeek.Friday || e.Day.Date.DayOfWeek == DayOfWeek.Saturday) && e.Day.Date >= DateTime.Now; } The DayRenderEventArgs passed to a DayRender event handler has a property named Day that identifies the day being rendered. This example sets Day's IsSelectable property to true or false depending on whether the day currently being rendered represents a legitimate selection. Setting IsSelectable to false prevents the control from placing a hyperlink in the corresponding cell, effectively making that cell unselectable. Is it necessary to lock application state before accessing it? Only if you're performing a multistep update and want the update to be treated as an atomic operation. Here's an example: Application.Lock (); Application["ItemsSold"] = (int) Application["ItemsSold"] + 1; Application["ItemsLeft"] = (int) Application["ItemsLeft"] - 1; Application.UnLock (); By locking application state before updating it and unlocking it afterwards, you ensure that another request being processed on another thread doesn't read application state at exactly the wrong time and see an inconsistent view of it. The ASP.NET application cache doesn't have Lock and UnLock methods as application state does. Does this mean I never need to lock it? No. It means you have to come up with your own mechanism for locking. System.Threading.ReaderWriterLock is the perfect tool for the job. Assuming rwlock is an instance of ReaderWriterLock, here's how you'd lock the application cache during an update: rwlock.AcquireWriterLock (Timeout.Infinite); Cache["ItemsSold"] = (int) Cache ["ItemsSold"] + 1; Cache["ItemsLeft"] = (int) Cache ["ItemsLeft"] - 1; rwlock.ReleaseWriterLock (); And here's how you'd read "ItemsSold" and "ItemsLeft" values from the cache: rwlock.AcquireReaderLock (Timeout.Infinite); int sold = (int) Cache["ItemsSold"]; int left = (int) Cache ["ItemsLeft"]; rwlock.ReleaseReaderLock (); As with application state, locking the application cache is only necessary when performing multistep updates that are to be treated as atomic operations. If I update session state, should I lock it, too? Are concurrent accesses by multiple requests executing on multiple threads a concern with session state? Concurrent accesses aren't an issue with session state, for two reasons. One, it's unlikely that two requests from the same user will overlap. Two, if they do overlap, ASP.NET locks down session state during request processing so that two threads can't touch it at once. Session state is locked down when the

Page of 159

44

MBT Pune
HttpApplication instance that's processing the request fires an AcquireRequestState event and unlocked when it fires a ReleaseRequestState event. ASP.NET's application cache supports expiration policies and cache removal callbacks. Expiration policies are based on time dependencies and file dependencies. Are database dependencies supported, too? In other words, can I have an item automatically removed from the cache in response to a database update? Do ASP.NET forms authentication cookies provide any protection against replay attacks? Do they, for example, include the client's IP address or anything else that would distinguish the real client from an attacker? No. If an authentication cookie is stolen, it can be used by an attacker. It's up to you to prevent this from happening by using an encrypted communications channel (HTTPS). Authentication cookies issued as session cookies, do, however, include a time-out valid that limits their lifetime. So a stolen session cookie can only be used in replay attacks as long as the ticket inside the cookie is valid. The default time-out interval is 30 minutes. You can change that by modifying the timeout attribute accompanying the <forms> element in Machine.config or a local Web.config file. Persistent authentication cookies do not time-out and therefore are a more serious security threat if stolen. By default, a persistent forms authentication cookie issued by ASP.NET is valid for 50 years. Is it possible to shorten that? Yes. Unfortunately, there is no configuration setting you can tweak to customize the lifetime of a persistent authentication cookie, but you can customize it programmatically. Here's a snippet of code that returns a persistent authentication cookie from a forms login page and limits the cookie's lifetime to 7 days: string url = FormsAuthentication.GetRedirectUrl ("Elmo", true); FormsAuthentication.SetAuthCookie ("Elmo", true); HttpCookie cookie = Response.Cookies[FormsAuthentication.FormsCookieName]; cookie.Expires = DateTime.Now + new TimeSpan (7, 0, 0, 0); Response.Redirect (url); To set the cookie's lifetime to something other than 7 days, simply modify the TimeSpan value. I wrote an HTTP handler and registered it in the <httpHandlers> section of a local Web.config file, but the handler never gets called. What could be wrong? In addition to being mapped to a file type (or specific file name) in a CONFIG file, an HTTP handler has to be registered in the IIS metabase. For example, if you register an HTTP handler with the Web.config file shown below, you also have to map *.igen to Aspnet_isapi.dll in the IIS metabase. Otherwise, ASP.NET doesn't see the request and can't forward it to the handler. <configuration> <system.web> <httpHandlers> <add verb="*" path="*.igen" type="ImageGen, ImageGenLib" /> </httpHandlers> </system.web> </configuration> How do I send e-mail from an ASP.NET application? MailMessage message = new MailMessage (); message.From = "webmaster@wintellect.com";

Page of 159

45

MBT Pune
message.To = "Everyone@wintellect.com"; message.Subject = "Scheduled Power Outage"; message.Body = "Our servers will be down tonight."; SmtpMail.SmtpServer = "localhost"; SmtpMail.Send (message); MailMessage and SmtpMail are classes defined in the .NET Framework Class Library's System.Web.Mail namespace. Due to a security change made to ASP.NET just before it shipped, you need to set SmtpMail's SmtpServer property to "localhost" even though "localhost" is the default. In addition, you must use the IIS configuration applet to enable localhost (127.0.0.1) to relay messages through the local SMTP service. How do I read an image from a database using ADO.NET and display it in a Web page? The following ASPX file reads and displays an image from the Pubs database that comes with Microsoft SQL Server. <%@ <%@ <%@ <%@ Import Import Import Import Namespace="System.Data.SqlClient" %> Namespace="System.Drawing" %> Namespace="System.Drawing.Imaging" %> Namespace="System.IO" %>

<html> <body> </body> <html> <script language="C#" runat="server"> void Page_Load(object sender, System.EventArgs e) { MemoryStream stream = new MemoryStream (); SqlConnection connection = new SqlConnection ("server=localhost;database=pubs;uid=sa;pwd="); try { connection.Open (); SqlCommand command = new SqlCommand ("select logo from pub_info where pub_id='0736'", connection); byte[] image = (byte[]) command.ExecuteScalar (); stream.Write (image, 0, image.Length); Bitmap bitmap = new Bitmap (stream); Response.ContentType = "image/gif"; bitmap.Save (Response.OutputStream, ImageFormat.Gif); } finally { connection.Close (); stream.Close (); } } </script>

Some Web service classes derive from System.Web.WebServices; others do not. What's the deal?

Page of 159

46

MBT Pune
WebService contributes properties named Application, Session, Context, Server, and User to derived classes enabling Web services to access the ASP.NET objects of the same name. If you don't use these objects in your Web service-for example, if you don't use application state or session state-then you don't have to derive from WebService, either. Incidentally, if you want to use ASP.NET session state in a Web method, use the following WebMethod attribute to enable session state for that method: [WebMethod (EnableSession="true")] What are VSDISCO files? VSDISCO files are DISCO files that support dynamic discovery of Web services. If you place the following VSDISCO file in a directory on your Web server, for example, it returns references to all ASMX and DISCO files in the host directory and any subdirectories not noted in <exclude> elements: <?xml version="1.0" ?> <dynamicDiscovery xmlns="urn:schemas-dynamicdiscovery:disco.2000-03-17"> <exclude path="_vti_cnf" /> <exclude path="_vti_pvt" /> <exclude path="_vti_log" /> <exclude path="_vti_script" /> <exclude path="_vti_txt" /> </dynamicDiscovery> How does dynamic discovery work? ASP.NET maps the file name extension VSDISCO to an HTTP handler that scans the host directory and subdirectories for ASMX and DISCO files and returns a dynamically generated DISCO document. A client who requests a VSDISCO file gets back what appears to be a static DISCO document. Note that VSDISCO files are disabled in the release version of ASP.NET. You can reenable them by uncommenting the line in the <httpHandlers> section of Machine.config that maps *.vsdisco to System.Web.Services.Discovery.DiscoveryRequestHandler and granting the ASPNET user account permission to read the IIS metabase. However, Microsoft is actively discouraging the use of VSDISCO files because they could represent a threat to Web server security. How does a Web service client call Web methods asynchronously? Web service proxy classes generated by Wsdl.exe contain asynchronous as well as synchronous versions of the Web service's methods. Suppose a Web service implements the following Add method: [WebMethod] public int Add (int a, int b) { return a + b; } A proxy generated by Wsdl.exe has BeginAdd and EndAdd methods for calling Add asynchronously. Assuming calc is an instance of the proxy class, here's how a client calls Add asynchronously:

// Initiate an async call IAsyncResult res = calc.BeginAdd (2, 2, null, null); . .

Page of 159

47

MBT Pune
. // Get the results int sum = calc.EndAdd (res); If the call hasn't completed when EndAdd is called, EndAdd blocks until it does. If desired, a client can ask to be notified when an asynchronous call returns by providing a reference to an AsyncCallback delegate wrapping a callback method. In the next example, EndAdd won't block because it isn't called until the client is certain the method call has returned: AsyncCallback cb = new AsyncCallback (AddCompleted); IAsyncResult res = calc.BeginAdd (2, 2, cb, null); . . . public void AddCompleted (IAsyncResult res) { int sum = calc.EndAdd (res); } Another option is to use the IsCompleted property of the IAsyncResult interface returned by BeginAdd to determine whether the call has completed and avoid calling EndAdd until it does: IAsyncResult res = calc.BeginAdd (2, 2, null, null); . . . if (res.IsCompleted) { int sum = calc.EndAdd (res); } else { // Try again later } How do I upload files to Web pages in ASP.NET? Use the HtmlInputFile class, which you can declare an instance of with an <input type="file" runat="server"/> tag. The following example is a complete ASPX file that lets a user upload an image file and a comment descibing the image. The OnUpload method writes the image and the comment to a table named Pictures in a SQL Server database named MyPictures. <%@ Import Namespace="System.Data.SqlClient" %> <form enctype="multipart/form-data" runat="server"> <table> <tr> <td>File name</td> <td><input type="file" id="Upload" runat="server" /></td> </tr> <tr> <td>Comment</td> <td><asp:TextBox ID="Comment" RunAt="server" /></td> </tr> <tr> <td></td> <td><asp:Button Text="Upload" OnClick="OnUpload" RunAt="server" /></td>

Page of 159

48

MBT Pune
</tr> </table> </form> <script language="C#" runat="server"> void OnUpload (Object sender, EventArgs e) { // Create a byte[] from the input file int len = Upload.PostedFile.ContentLength; byte[] pic = new byte[len]; Upload.PostedFile.InputStream.Read (pic, 0, len); // Insert the image and comment into the database SqlConnection connection = new SqlConnection ("server=localhost;database=mypictures;uid=sa;pwd="); try { connection.Open (); SqlCommand cmd = new SqlCommand ("insert into Pictures " + "(Picture, Comment) values (@pic, @text)", connection); cmd.Parameters.Add ("@pic", pic); cmd.Parameters.Add ("@text", Comment.Text); cmd.ExecuteNonQuery (); } finally { connection.Close (); }

} </script> How do I create an ASPX page that periodically refreshes itself? Most browsers recognize the following META tag as a signal to automatically refresh the page every nn seconds: <meta http-equiv="Refresh" content="nn"> Here's an ASPX file that displays the current time of day. Once displayed, it automatically refreshes every 5 seconds: <%@ Page Language="C#" %> <meta http-equiv="Refresh" content="5"> <html> <body> <% Response.Write (DateTime.Now.ToLongTimeString ()); %> </body> </html> How can an ASP.NET application determine whether cookies are enabled in a browser? Determining whether cookies are enabled requires a round trip to the browser and back. If you can live with an extra round trip, the basic strategy is to return a cookie in an HTTP response and redirect to a page that checks for the cookie. Here's a page that does just that:

Page of 159

49

MBT Pune
<html> <body> <form runat="server"> <asp:Button Text="Test Cookie Support" OnClick="OnTest" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void OnTest (Object sender, EventArgs e) { HttpCookie cookie = new HttpCookie ("Foo", "Bar"); Response.Cookies.Add (cookie); Response.Redirect ("OtherPage.aspx"); } </script> And here's the page that it redirects to (OtherPage.aspx). This page uses the presence or absence of the cookie to determine whether cookies are enabled and displays the result: <%@ Page Language="C#" %> <html> <body> <% HttpCookie cookie = Request.Cookies["Foo"]; if (cookie != null && cookie.Value == "Bar") Response.Write ("Cookies are enabled"); else Response.Write ("Cookies are not enabled"); %> </body> </html> Is it possible to prevent a browser from caching an ASPX page? You bet. Just call SetNoStore on the HttpCachePolicy object exposed through the Response object's Cache property, as demonstrated here: <%@ Page Language="C#" %> <html> <body> <% Response.Cache.SetNoStore (); Response.Write (DateTime.Now.ToLongTimeString ()); %> </body> </html> 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. How do I create a DataGrid with Delete buttons and pop up a message box asking the user for confirmation before deleting a record?

Page of 159

50

MBT Pune
The ASPX file below demonstrates the proper technique. It populates a DataGrid with content from the Titles table of the Pubs database that comes with Microsoft SQL Server. The DataGrid's leftmost column contains a row of Delete buttons. The OnDeleteRecord method simulates a record deletion by writing the Title field of the record to be deleted to a Label control. The OnAttachScript method, which is called once for each row in the DataGrid in response to ItemCreated events, attaches to each button an OnClick attribute that activates a bit of client-side JavaScript. That script displays a confirmation dialog and prevents the page from posting back to the server (thus preventing OnDeleteRecord from being called) if the user clicks Cancel rather than OK. <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <asp:DataGrid ID="MyDataGrid" AutoGenerateColumns="false" CellPadding="2" BorderWidth="1" BorderColor="lightgray" Font-Name="Verdana" Font-Size="8pt" GridLines="vertical" Width="90%" OnItemCreated="OnAttachScript" OnItemCommand="OnDeleteRecord" RunAt="server"> <Columns> <asp:ButtonColumn Text="Delete" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="center" ButtonType="PushButton" CommandName="Delete" /> <asp:BoundColumn HeaderText="Item ID" DataField="title_id" /> <asp:BoundColumn HeaderText="Title" DataField="title" /> <asp:BoundColumn HeaderText="Price" DataField="price" DataFormatString="{0:c}" HeaderStyle-HorizontalAlign="center" ItemStyle-HorizontalAlign="right" /> </Columns> <HeaderStyle BackColor="teal" ForeColor="white" Font-Bold="true" /> <ItemStyle BackColor="white" ForeColor="darkblue" /> <AlternatingItemStyle BackColor="beige" ForeColor="darkblue" /> </asp:DataGrid> <asp:Label ID="Output" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlDataAdapter adapter = new SqlDataAdapter ("select * from titles where price != 0", "server=localhost;database=pubs;uid=sa;pwd=");

Page of 159

51

MBT Pune
DataSet ds = new DataSet (); adapter.Fill (ds); MyDataGrid.DataSource = ds; MyDataGrid.DataBind (); } }

void OnAttachScript (Object sender, DataGridItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { WebControl button = (WebControl) e.Item.Cells[0].Controls[0]; button.Attributes.Add ("onclick", "return confirm (\"Are you sure?\");"); } } void OnDeleteRecord (Object sender, DataGridCommandEventArgs e) { if (e.CommandName == "Delete") { Output.Text = "Deleted \"" + e.Item.Cells[2].Text + "\""; } } </script> How do I localize an ASP.NET application so that it formats dates and times based on the requestor's locale? Deploy the following Global.asax file in the application's virtual root: <%@ Import Namespace="System.Threading" %> <%@ Import Namespace="System.Globalization" %> <script language="C#" runat="server"> void Application_BeginRequest (Object sender, EventArgs e) { try { if (Request.UserLanguages.Length > 0) { Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture (Request.UserLanguages[0]); } } catch (ArgumentException) { // Do nothing if CreateSpecificCulture fails } } </script> Application_BeginRequest executes at the beginning of each and every request. This example reads the requestor's preferred language from the Request object's UserLanguage property (which is populated with information found in the request's Accept-Language header), creates a CultureInfo object from it, and assigns the CultureInfo object to the CurrentCulture property of the thread that's processing the request. FCL methods that are culture-aware (such as DateTime.ToShortDateString) will format dates, times, currency values, and numbers accordingly. 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

Page of 159

52

MBT Pune
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 STAbased 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. I've developed a custom Windows Forms control that I'd like to use in a Web Form. I've heard that ASP.NET can use Windows Forms controls. Is that true? If so, how do I create a Windows Forms control in a Web Form? You can embed Windows Forms controls in Web pages using <object> tags similar to those that declare ActiveX controls. To demonstrate, here's the source code for a very simple slider control-one that derives from the FCL's TrackBar class: namespace Wintellect { public class WebSlider : System.Windows.Forms.TrackBar {} } Compile this source code into a DLL with the following command (assuming the source code file is named Controls.cs): csc /t:library controls.cs Copy the resulting DLL (Controls.dll) to the virtual directory of your choice on your Web server. Now create a text file named Slider.aspx in the same directory and add the following HTML: <html> <body> <form> <object id="Slider" classid="http:Controls.dll#Wintellect.WebSlider" width="64" height="256"> <param name="Minimum" value="0">

Page of 159

53

MBT Pune
<param name="Maximum" value="10"> <param name="Value" value="3"> <param name="Orientation" value="Vertical"> <param name="BackColor" value="gainsboro"> </object> </form> </body> </html> The <object> tag declares an instance of the control and names it Slider. It also uses <param> tags to initialize some of the control's properties. Open the ASPX file in your browser and the slider control should be displayed. IE downloads the control implementation from the Web server, so you don't have to install Controls.dll on the client. The client must, however, have the .NET Framework installed. Internet Explorer 5.01 or higher is required on the client, too. If I use the slider control in the previous example in a Web page, what must I do to allow a server-side event handler to determine the position of the slider's thumb? The trick is to intercept the form submit event fired before the form posts back to the server and add the thumb position to the form's postback data. Here's a modified version of the ASPX file in the previous example that does just that. The onsubmit attribute in the <form> tag calls the JavaScript function SubmitForm before the form posts back to the server. SubmitForm writes the slider's thumb position to a hidden <input> control named __THUMBPOS. The browser submits the __THUMBPOS control's value to the server, and the server-side event handler extracts the value from the request. In this example, the event handler writes the thumb position to the Web page. <html> <body> <form id="MyForm" onsubmit="javascript:return SubmitForm ();" runat="server"> <input type="hidden" name="__THUMBPOS" value="" > <object id="Slider" classid="http:Controls.dll#Wintellect.WebSlider" width="64" height="256"> <param name="Minimum" value="0"> <param name="Maximum" value="10"> <param name="Value" value="3"> <param name="Orientation" value="Vertical"> <param name="BackColor" value="gainsboro"> </object> <br><br> <input type="submit" value="Test" onserverclick="ShowThumbPos" runat="server"> <br><br> <span id="Output" runat="server" /> </form> </body> </html> <script language="JavaScript"> function SubmitForm () { MyForm.__THUMBPOS.value = MyForm.Slider.value; return true; }

Page of 159

54

MBT Pune
</script> <script language="C#" runat="server"> void ShowThumbPos (Object sender, EventArgs e) { Output.InnerText = "You chose " + Request["__THUMBPOS"]; } </script> If I use the slider control in the previous example in a Web page, the slider's thumb snaps back to its default position each time the page posts back to the server. Is there a way to make the thumb stay put? The ASPX file below shows one way to do it. The <param> tag that controls the slider's thumb position is no longer embedded in the page's HTML; instead, it's output programmatically with Response.Write. That enables the page to emit a <param> tag containing a default value if the page is fetched outside of a postback, or a <param> tag containing the __THUMBPOS value submitted in the request if the page is being returned following a postback. It's not pretty, but it works. <%@ Page Language="C#" %> <html> <body> <form id="MyForm" onsubmit="javascript:return SubmitForm ();" runat="server"> <input type="hidden" name="__THUMBPOS" value=""> <object id="Slider" classid="http:Controls.dll#Wintellect.WebSlider" width="64" height="256"> <param name="Minimum" value="0"> <param name="Maximum" value="10"> <% if (Request["__THUMBPOS"] == null) Response.Write ("<param name=\"Value\" value=\"3\">\r\n"); else Response.Write ("<param name=\"Value\" value=\"" + Request["__THUMBPOS"] + "\">\r\n"); %> <param name="Orientation" value="Vertical"> <param name="BackColor" value="gainsboro"> </object> <br><br> <input type="submit" value="Test" onserverclick="ShowThumbPos" runat="server"> <br><br> <span id="Output" runat="server" /> </form> </body> </html> <script language="JavaScript"> function SubmitForm () { MyForm.__THUMBPOS.value = MyForm.Slider.value; return true; } </script>

Page of 159

55

MBT Pune
<script language="C#" runat="server"> void ShowThumbPos (Object sender, EventArgs e) { Output.InnerText = "You chose " + Request["__THUMBPOS"]; } </script> How can I create a DataGrid that displays a column of images obtained from a database? The following ASPX file demonstrates how: <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <asp:DataGrid ID="MyDataGrid" RunAt="server" AutoGenerateColumns="false" CellPadding="2" BorderWidth="1" BorderColor="lightgray" Font-Name="Verdana" Font-Size="8pt" GridLines="vertical" Width="100%"> <Columns> <asp:TemplateColumn HeaderText="Photo" HeaderStyle-HorizontalAlign="center"> <ItemTemplate> <center> <img src='<%# "NorthwindImageGrabber.ashx?id=" + DataBinder.Eval (Container.DataItem, "EmployeeID") %>'> </center> </ItemTemplate> </asp:TemplateColumn> <asp:BoundColumn HeaderText="Last Name" HeaderStyle-HorizontalAlign="center" DataField="LastName" /> <asp:BoundColumn HeaderText="First Name" HeaderStyle-HorizontalAlign="center" DataField="FirstName" /> <asp:BoundColumn HeaderText="Title" HeaderStyle-HorizontalAlign="center" DataField="Title" /> </Columns> <HeaderStyle BackColor="teal" ForeColor="white" Font-Bold="true" /> <ItemStyle BackColor="white" ForeColor="darkblue" /> <AlternatingItemStyle BackColor="beige" ForeColor="darkblue" /> </asp:DataGrid> </form> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlConnection connection = new SqlConnection

Page of 159

56

MBT Pune
("server=localhost;database=northwind;uid=sa;pwd="); try { connection.Open (); SqlCommand command = new SqlCommand ("select employeeid, lastname, firstname, title from employees", connection); SqlDataReader reader = command.ExecuteReader (); MyDataGrid.DataSource = reader; MyDataGrid.DataBind (); } finally { connection.Close (); } } } </script> This ASPX file contains a DataGrid that displays data from the Employees table of SQL Server's Northwind database. Each row rendered by the DataGrid represents one employee, and each row's leftmost column contains the employee's picture. The picture comes from the table's Photo field. The image is rendered by the <ItemTemplate> tag, which emits an <img> tag accompanied by a src attribute that points to a file named NorthwindImageGrabber.ashx. Inside the ASHX file is an HTTP handler that retrieves an image from the database. A query string appended to the URL tells the handler which image to retrieve. Here's NorthwindImageGrabber.ashx's source code: <%@ WebHandler Language="C#" Class="ImageGrabber" %> using using using using using using System; System.Web; System.Drawing; System.Drawing.Imaging; System.Data.SqlClient; System.IO;

public class ImageGrabber : IHttpHandler { public void ProcessRequest (HttpContext context) { string id = (string) context.Request["id"]; if (id != null) { MemoryStream stream = new MemoryStream (); SqlConnection connection = new SqlConnection ("server=localhost;database=northwind;uid=sa;pwd="); Bitmap bitmap = null; Image image = null; try { connection.Open (); SqlCommand cmd = new SqlCommand ("select photo from employees where employeeid='" + id + "'", connection); byte[] blob = (byte[]) cmd.ExecuteScalar ();

Page of 159

57

MBT Pune
stream.Write (blob, 78, blob.Length - 78); bitmap = new Bitmap (stream); // Shrink the image, but maintain its aspect ratio int width = 48; int height = (int) (width * ((double) bitmap.Height / (double) bitmap.Width)); image = bitmap.GetThumbnailImage (width, height, null, IntPtr.Zero); context.Response.ContentType = "image/jpeg"; image.Save (context.Response.OutputStream, ImageFormat.Jpeg); } finally { if (image != null) image.Dispose (); if (bitmap != null) bitmap.Dispose (); stream.Close (); connection.Close (); }

} }

public bool IsReusable { get { return true; } } } The ProcessRequest method, which is called every time the ASHX file is requested, retrieves the image from the database and returns it to the client as a JPEG. For good measure, it also shrinks the image down to thumbnail size using Image.GetThumbnailImage. NorthwindImageGrabber.ashx discards the first 78 bytes of each image because the Northwind database's Photo field doesn't store raw images; it stores BMP bitmaps prefixed by 78 bytes of unrelated header information. Is it possible to write an ASP.NET handler that works like an ISAPI filter-that is, that sees requests and responses and perhaps modifies them, too? You can do it by writing an HTTP module-a class that implements IHttpModuleand registering it in Web.config. Here's a simple HTTP module written in C# that appends "Hello, world" to every response: using System; using System.Web; public class MyModule : IHttpModule { public void Init (HttpApplication application) { application.EndRequest += new EventHandler (Application_EndRequest); } void Application_EndRequest (Object source, EventArgs e) { HttpApplication application = (HttpApplication) source; HttpContext context = application.Context;

Page of 159

58

MBT Pune
context.Response.Write ("Hello, world");

public void Dispose () { } } Here's how you register it if MyModule is in an assembly named CustomModules: <configuration> <system.web> <httpModules> <add name="MyModule" type="MyModule, CustomModules" /> </httpModules> </system.web> </configuration> An HTTP module can handle the per-request events fired by HttpApplication instances, and it can fire events of its own that can be processed in Global.asax. To deploy the module, simply drop the DLL containing MyModule into the application root's bin subdirectory. How can ASP.NET apps transmit data from one page to another? One way to transfer data from page to page is to have the sending page encode the data in a query string and the receiving page read the data from the request. Here's the source code for a page named PageOne.aspx that encodes a string typed by the user in a query string and passes it to PageTwo.aspx: <!-- PageOne.aspx --> <html> <body> <form runat="server"> <asp:TextBox ID="Input" RunAt="server" /> <asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void OnNextPage (Object sender, EventArgs e) { Response.Redirect ("PageTwo.aspx?Input=" + Input.Text); } </script> And here's the page it redirects to, which echoes what the user typed: <!-- PageTwo.aspx --> <%@ Page Language="C#" %> <html> <body> <% Response.Write ("You typed \"" + Request["Input"] + "\""); %>

Page of 159

59

MBT Pune
</body> </html> Another way to pass data from one page to another--a technique that has the added benefit of keeping the data on the server and not exposing it to the user--is to pass the data in session state, as demonstrated here: <!-- PageOne.aspx --> <html> <body> <form runat="server"> <asp:TextBox ID="Input" RunAt="server" /> <asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void OnNextPage (Object sender, EventArgs e) { Session["Input"] = Input.Text; Response.Redirect ("PageTwo.aspx"); } </script>

<!-- PageTwo.aspx --> <%@ Page Language="C#" %> <html> <body> <% Response.Write ("You typed \"" + Session["Input"] + "\""); %> </body> </html> If you use Server.Transfer rather than Response.Redirect to transfer control to another page, you can use public fields in the sending page's code-behind class to transmit data. The following example demonstrates how:

<!-- PageOne.aspx --> <%@ Page Inherits="PageOneClass" %> <html> <body> <form runat="server"> <asp:TextBox ID="Input" RunAt="server" /> <asp:Button Text="NextPage" OnClick="OnNextPage" RunAt="server" /> </form> </body> </html>

Page of 159

60

MBT Pune
// PageOneClass.cs using System; using System.Web.UI; using System.Web.UI.WebControls; public class PageOneClass : Page { public string _Input; protected TextBox Input; public void OnNextPage (Object sender, EventArgs e) { _Input = Input.Text; Server.Transfer ("PageTwo.aspx"); } } <!-- PageTwo.aspx --> <%@ Page Language="C#" %> <html> <body> <% PageOneClass prevpage = (PageOneClass) Context.Handler; Response.Write ("You typed \"" + prevpage._Input + "\""); %> </body> </html> How do I display an ASPX or HTML page in a new browser window in ASP.NET? The following tag creates a hyperlink that, when clicked, opens an ASPX file in a new window:

<asp:HyperLink Text="Wintellect home page" NavigateUrl="http://www.wintellect.com/default.aspx" Target="_new" RunAt="server" /> How do I initialize a TextBox whose TextMode is "password" with a password? Initializing the TextBox's Text property doesn't seem to work. This won't work: <asp:TextBox Text="imbatman" TextMode="Password" ID="Password" RunAt="server" /> But this will: <asp:TextBox TextMode="Password" ID="Password" RunAt="server" /> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { Password.Attributes.Add ("value", "imbatman"); } </script>

Page of 159

61

MBT Pune
The latter code fragment manually adds a value="imbatman" attribute to the <input> tag output by the TextBox control, causing the specified text to appear in the TextBox. You can also initialize a password TextBox by including a Value attribute in the control tag, as demonstrated below: <asp:TextBox Value="imbatman" TextMode="Password" ID="Password" RunAt="server" /> I know I can write custom server controls by deriving from Control or WebControl. But can I modify the behavior of existing controls by deriving from them and modifying their output? You bet. Here's a custom control named NumTextBox that derives from TextBox and adds an onkeydown attribute to the <input> tag that TextBox outputs. That attribute references a local JavaScript function that filters out non-numeric keys, producing a TextBox that accepts only numbers. For good measure, NumTextBox senses the browser type and renders differently to Internet Explorer and Netscape Navigator, enabling it to work in either browser. It also overrides TextBox's Text property and implements a set accessor that throws an exception if a non-numeric string is written to it. using System; using System.Web.UI; using System.Web.UI.WebControls; namespace Wintellect { public class NumTextBox : TextBox { string IEClientScriptBlock = "<script language=\"javascript\">\n" + "<!--\n" + "var keys = new Array (8, 9, 13, 33, 34, 35, " + "36, 37, 39, 45, 46);\n" + "function isKeyValid (keyCode)\n" + "{\n" + " return ((keyCode >= 48 && keyCode <= 57) || " + "isAuxKey (keyCode));\n" + "}\n" + "function isAuxKey (keyCode)\n" + "{\n" + " for (i=0; i<keys.length; i++)\n" + " if (keyCode == keys[i])\n" + " return true;\n" + " return false;\n" + "}\n" + "-->\n" + "</script>"; string NetscapeClientScriptBlock = "<script language=\"javascript\">\n" + "<!--\n" + "function isKeyValid (keyCode)\n" + "{\n" + " return ((keyCode >= 48 && keyCode <= 57) || " + "keyCode == 8 || keyCode == 13);\n" +

Page of 159

62

MBT Pune
"}\n" + "-->\n" + "</script>"; public override string Text { get { return base.Text; } set { // Make sure value is numeric before storing it Convert.ToInt64 (value); base.Text = value; } } protected override void OnPreRender (EventArgs e) { string browser = Context.Request.Browser.Type.ToUpper (); int version = Context.Request.Browser.MajorVersion; if (browser.IndexOf ("IE") > -1 && version >= 4) Page.RegisterClientScriptBlock ("NumTextBoxScript", IEClientScriptBlock); else if (browser.IndexOf ("NETSCAPE") > -1 && version >= 4) Page.RegisterClientScriptBlock ("NumTextBoxScript", NetscapeClientScriptBlock); } protected override void Render (HtmlTextWriter writer) { string browser = Context.Request.Browser.Type.ToUpper (); int version = Context.Request.Browser.MajorVersion; if (browser.IndexOf ("IE") > -1 && version >= 4) writer.AddAttribute ("onkeydown", "javascript:return isKeyValid (window.event.keyCode)"); else if (browser.IndexOf ("NETSCAPE") > -1 && version >= 4) writer.AddAttribute ("onkeydown", "javascript:return isKeyValid (event.which)"); } } } base.Render (writer);

Here's an ASPX file you can use to test the control. It assumes that the control is compiled into an assembly named NumTextBoxControl. <%@ Register TagPrefix="win" Namespace="Wintellect" Assembly="NumTextBoxControl" %> <html> <body> <form runat="server"> <win:NumTextBox runat="server" /> </form>

Page of 159

63

MBT Pune
</body> </html Is it possible to associate hidden values--say, values from an identity field in a database table--with items in a DataGrid? You bet. Just declare a BoundColumn in the DataGrid and set its Visible property to false, like so:

<asp:BoundColumn DataField="ItemID" Visible="false" /> The column won't show up in the DataGrid, but you'll be able to read data from it following a postback just as if it were visible. How do I configure a DataGrid to show a column of row numbers: 1, 2, 3, 4, and so on? The easiest way to do it is to use a TemplateColumn. The following ASPX file demonstrates how. The TemplateColumn displays the value of a rownum field that is incremented each time a row is output. <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <asp:DataGrid ID="MyDataGrid" AutoGenerateColumns="false" RunAt="server"> <Columns> <asp:TemplateColumn HeaderText="Number" ItemStyleHorizontalAlign="center"> <ItemTemplate> <%# rownum++ %> </ItemTemplate> </asp:TemplateColumn> <asp:BoundColumn HeaderText="Title" DataField="title" /> </Columns> <HeaderStyle HorizontalAlign="center" /> </asp:DataGrid> </form> </body> </html> <script language="C#" runat="server"> int rownum = 1; void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlDataAdapter adapter = new SqlDataAdapter ( "select title from titles where price != 0", "server=localhost;database=pubs;uid=sa" ); DataSet ds = new DataSet (); adapter.Fill (ds); MyDataGrid.DataSource = ds;

Page of 159

64

MBT Pune
MyDataGrid.DataBind ();

} </script> Is it possible to call Fill on a DataAdapter and fill two DataTables in a DataSet with a single call? You bet. Here's a sample that demonstrates how by performing a double query and binding each of the resulting DataTables to a different DataGrid. <%@ Import Namespace="System.Data" %> <%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <asp:DataGrid ID="DataGrid1" RunAt="server" /> <asp:DataGrid ID="DataGrid2" RunAt="server" /> </form> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlDataAdapter adapter = new SqlDataAdapter ( "select * from titles; select * from authors", "server=localhost;database=pubs;uid=sa" ); DataSet ds = new DataSet (); adapter.Fill (ds); DataGrid1.DataSource = ds.Tables[0]; DataGrid1.DataBind (); DataGrid2.DataSource = ds.Tables[1]; DataGrid2.DataBind (); } } </script I'm trying to use Server.CreateObject to instantiate a legacy COM component in an ASPX page. If I use VB.NET, I can create and call the COM object just fine. But the same code written in C# doesn't compile. The compiler complains that the method I'm calling isn't a member of Object. What gives? You've discovered an interesting feature of VB.NET--namely, that it trades type safety for simplicity when late binding to COM objects. Check out the following VB.NET code sample, which instantiates a COM object (ProgID="Wintellect.Math") and calls its Add method to add 2 and 2:

Dim Sum As Integer Dim WinMath As Object WinMath = Server.CreateObject ("Wintellect.Math") Sum = WinMath.Add (2, 2)

Page of 159

65

MBT Pune
This code works just fine, despite that fact that Add is not a member of System.Object. The VB.NET compiler relaxes its type-checking rules to simplify your code. The C# compiler, however, does not. The following code won't compile: Object math = Server.CreateObject ("Wintellect.Math") int sum = WinMath.Add (2, 2) The solution for C# programmers is to late-bind to the COM object using System.Type.InvokeMember. Here's the C# equivalent of the VB.NET code above:

Type t = Type.GetTypeFromProgID ("Wintellect.Math"); Object math = Server.CreateObject (t); Object[] args = { 2, 2 }; int sum = (int) t.InvokeMember ("Add", BindingFlags.InvokeMethod, null, math, args);

It's not pretty, but it works, and it perfectly illustrates the extra effort required to accomplish late binding in C#. I'm trying to use ASP.NET's HtmlInputFile control to upload files to a Web server, but the control's PostedFile property is always nulleven after I select a file and post back to the server. What am I doing wrong? Most likely you forgot to include an enctype="multipart/form-data" attribute in your <form> tag. The following HTML form doesn't support file uploads: <form runat="server"> <input type="file" id="MyFile" runat="server" /> </form>

But the next one does. Decorate the <form> tag as shown here and file uploads will work just fine:

<form enctype="multipart/form-data" runat="server"> <input type="file" id="MyFile" runat="server" /> </form> ASP.NET's @ OutputCache directive lets me cache different versions of a page based on varying input parameters, HTTP headers, and browser types. I'd also like to be able to cache based on varying session IDs. Is that possible? You bet. Here's a sample page that uses a VaryByCustom attribute to cache different versions of a page based on session IDs:

<%@ Page Language="C#" %> <%@ OutputCache Duration="10" VaryByParam="None" VaryByCustom="SessionID" %>

Page of 159

66

MBT Pune

<html> <body> <% Session["MyData"] = "Foo"; // Make the session persistent Response.Write ("Your session ID is " + Session.SessionID); Response.Write ("<br>"); Response.Write ("The current time is " + DateTime.Now.ToLongTimeString ()); %> </body> </html>

In order for VaryByCustom="SessionID" to work, you must include in the application root a Global.asax file containing the following GetVaryByCustomString method:

<script language="C#" runat="server"> public override string GetVaryByCustomString (HttpContext context, string arg) { if (arg.ToLower () == "sessionid") { HttpCookie cookie = context.Request.Cookies["ASP.NET_SessionId"]; if (cookie != null) return cookie.Value; } return base.GetVaryByCustomString (context, arg); } </script>

GetVaryByCustomString is a mechanism for extending ASP.NET's page output cache. This implementation of GetVaryByCustomString, which overrides the one inherited from HttpApplication, responds to a VaryByCustom="SessionID" attribute in an @ OutputCache directive by returning the current session ID, if present. ASP.NET responds by caching different versions of the page if the session IDs differ. Note that GetVaryByCustomString extracts the session ID from the session cookie, not from the session's SessionID property. That's because the request has yet to be associated with a session when GetVaryByCustomString is called. An unpleasant side effect is that this technique doesn't work with cookieless session state. Also note that the page won't be cached until a user requests the page for the second time, because the first request lacks a valid session cookie.

I've noticed that DataGrids round-trip tons of information in view state, decreasing the effective bandwidth of the connection. Is there anything I can do to reduce the DataGrid's view state usage? You bet. Set the DataGrid's EnableViewState property to false, as shown here:

Page of 159

67

MBT Pune
<asp:DataGrid RunAt="server" EnableViewState="false" ... />

Once you make this change, you'll also have to reinitialize the DataGrid in every request (even during postbacks), because the DataGrid will no longer retain its state across postbacks. In other words, instead of doing this:

void Page_Load (Object sender, EventArgs e) if (!IsPostBack) { // TODO: Initialize the DataGrid }

Do this:

void Page_Load (Object sender, EventArgs e) { // TODO: Initialize the DataGrid }

The performance you lose may be more than compensated for by the effective bandwidth you gain--especially if instead of querying a database on every request, you query once, cache the data, and initialize the DataGrid from the cache. Is it possible to create a DataGrid that uses scrolling rather than paging to provide access to a long list of items? With a little help from a <div> tag, yes. The following ASPX file displays the "Products" table of SQL Server's Northwind database in a scrolling table:

<%@ Import Namespace="System.Data.SqlClient" %> <html> <body> <form runat="server"> <div style="height: 256px; overflow: auto"> <asp:DataGrid ID="MyDataGrid" Width="100%" RunAt="server" /> </div> </form> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { if (!IsPostBack) { SqlConnection connection = new SqlConnection ("server=localhost;database=northwind;uid=sa");

Page of 159

68

MBT Pune
try { connection.Open (); SqlCommand command = new SqlCommand ("select * from products", connection); SqlDataReader reader = command.ExecuteReader (); MyDataGrid.DataSource = reader; MyDataGrid.DataBind (); } finally { connection.Close (); } } } </script> I want to make DataGrid paging more efficient by using custom paging. Oracle makes custom paging easy by supporting query-by-rownumber. SQL Server is just the opposite. There's no obvious way to ask SQL Server for, say, rows 101-150 in a 500-row result set. What's the best way to do custom paging when you have SQL Server on the back end? You can use a query of the following form to retrieve records by row number from Microsoft SQL Server. This example retrieves rows 41-50 from the "Products" table of the Northwind database:

SELECT * FROM (SELECT TOP 50 * FROM Products ORDER BY ProductID) AS t1 WHERE NOT EXISTS (SELECT * FROM (SELECT TOP 40 * FROM Products ORDER BY ProductID) AS t2 WHERE t1.ProductID = t2.ProductID)

You can modify this query to target an arbitrary range of rows by replacing "50" with the number of the last row and "40" with the number of the first row minus 1. You can combine this query technique with custom paging to make DataGrid paging more efficient. With default paging, you must initialize the data source with all records displayed on all pages. With custom paging, you can initialize the data source with just those records that pertain to the current page. Is it possible to prevent a Web form from scrolling to the top of the page when it posts back to the server? With a little help from some server-side script that generates client-side script, yes. The first step is to replace the page's <body> tag with the following statements:

<% if (Request["__SCROLLPOS"] != null && Request["__SCROLLPOS"] != String.Empty) { int pos = Convert.ToInt32 (Request["__SCROLLPOS"]); Response.Write ("<body id=\"theBody\" " + "onscroll=\"javascript:document.forms[0].__SCROLLPOS.value = " + "theBody.scrollTop;\" " +

Page of 159

69

MBT Pune
"onload=\"javascript:theBody.scrollTop=" + pos + ";\">"); } else { Response.Write ("<body id=\"theBody\" " + "onscroll=\"javascript:document.forms[0].__SCROLLPOS.value =" + "theBody.scrollTop;\">"); } %>

Step two is to add the following line somewhere between the <form runat="server"> and </form> tags:

<input type="hidden" name="__SCROLLPOS" value="" />

How does it work? The server-side script block outputs a <body> tag containing an onscroll attribute that keeps tabs on the scroll position and an onload attribute that restores the last scroll position following a postback. The scroll position is transmitted to the server in a hidden <input> control named __SCROLLPOS. Note that this technique is compatible with Internet Explorer but not with Netscape Navigator.

If I use the same user control in two different pages and include an @ OutputCache directive in the ASCX file, will the user control be cached once or twice? In ASP.NET version 1.0, the control will be cached twice. In version 1.1, you can include a Shared="true" attribute in the @ OutputCache directive to cache the control just once. How do I set the focus to a specific control when a Web form loads? With a dash of client-side script. Upon loading, the following page sets the focus to the first of its three TextBox controls:

<html> <body> <form runat="server"> <asp:TextBox ID="TextBox1" RunAt="server" /><br> <asp:TextBox ID="TextBox2" RunAt="server" /><br> <asp:TextBox ID="TextBox3" RunAt="server" /> </form> </body> </html> <script language="javascript"> document.forms[0].TextBox1.focus (); </script> Is it possible to post a page containing a runat="server" form to a page other than itself? Adding an action attribute to the <form> tag is

Page of 159

70

MBT Pune
futile because ASP.NET overrides it with an action attribute that points back to the same page. ASP.NET forbids a runat="server" form from posting back to another page, but you may be able to accomplish what you're after by taking a slightly different approach. It turns out that if you remove runat="server" from the <form> tag, ASP.NET won't alter the tag's action attribute. The bad news is that a form lacking a runat="server" attribute can't host Web controls. The good news is that it can host HTML controls, which means that if you can do without DataGrids and other rich controls, you can post back to other pages just fine. The following page contains a login form that hosts three HTML controls. Note the runat="server" attributes adorning the controls but the absence of runat="server" in the <form> tag:

<html> <body> <form action="Welcome.aspx"> <table cellpadding="8"> <tr> <td>User Name:</td> <td><input type="text" ID="UserName" runat="server" /></td> </tr> <tr> <td>Password:</td> <td><input type="password" ID="Password" runat="server" /></td> </tr> <tr> <td></td> <td><input type="submit" value="Log In" runat="server" /></td> </tr> </table> </form> </body> </html>

Clicking the Log In button submits the form to Welcome.aspx, which reads the user name that the user typed from the HTTP request and outputs it to the page. Here's Welcome.aspx:

<html> <body> <h1><asp:Label ID="Output" RunAt="server" /></h1> </body> </html> <script language="C#" runat="server"> void Page_Load (Object sender, EventArgs e) { Output.Text = "Hello, " + Request["UserName"]; } </script> Do the runat="server" attributes on the <input> tags do anything useful? You bet. They make the controls visible to server-side scripts.

Page of 159

71

MBT Pune
I'm using an <error> element in Web.config to redirect to a custom error page when a 404 error occurs. Inside the error page, I want to retrieve the URL that caused the 404 error so I can write it to a log file. How do I get that URL? When ASP.NET redirects to a custom error page, it passes the original URL (the one that caused the error) in a query string. Here's an example in which PageNotFound.aspx is the custom error page and foo.aspx is the page that produced the error: http://localhost/PageNotFound.aspx?aspxerrorpath=/foo.aspx PageNotFound.aspx can therefore obtain the URL of the page that generated the error (in your case, the nonexistent page that resulted in a 404 error) like this:

string badurl = Request["aspxerrorpath"];

If you'd like to retrieve the IP address from which the request originated for logging purposes as well, read it from Request.ServerVariables["REMOTE_ADDR"] or Request.UserHostAddress. How to find last error which occurred? Server.GetLastError() [C#] Exception LastError; String ErrMessage; LastError = Server.GetLastError(); if (LastError != null) ErrMessage = LastError.Message; else ErrMessage = "No Errors"; Response.Write("Last Error = " + ErrMessage); p How can u handle Un Managed Code Exceptions in ASP.Net? p Which is the namespace used to write error message in event Log File? Difference Between DataGrid and DataList? Datagrid is used to define a template on Column Output. DataList is used to define a template for the entire row output and each row can again be table. Each of the data Web controls has its own strengths and weaknesses. The DataGrid, for example, is great for quickly and easily displaying database data in an HTML <table>, and allows for advanced features such as paging, sorting, and in-place editing to be added with little to no programming. However, the DataGrid is quite limited in the general format with which the data is presented. The DataList allows for more freedom. For example, in an earlier live demo we saw that using the DataList's RepeatColumns property, multiple DataSource records could be displayed in a single HTML <table> row. Additionally, the

Page of 159

72

MBT Pune
DataList's content is specified via templates, which allows for a high degree of customization. The Repeater allows for the utmost flexibility in its output, since the only HTML rendered from a Repeater is the HTML generated in its templates. That is, no additional HTML output is generated, as is the case with both the DataGrid and DataList. The Repeater, however, does not have any built-in support for sorting, paging, or editing of its data.

Similarities Among the DataGrid, DataList, and Repeater? The data Web controls each also have the following three events: 1. ItemCreated, 2. ItemDataBound, and 3. ItemCommand The ItemCreated event fires once for every DataWebControlNameItem added to the data Web control. It fires before the DataWebControlNameItem's DataItem property is assigned. The ItemDataBound event also fires once for every DataWebControlNameItem added to the data Web control, but this event fires after the DataWebControlNameItem's DataItem property is assigned. Finally, the ItemCommand event fires whenever the Command event for a Button or LinkButton within the data Web control fires. Passing Multiple Parameters in NavigateURL Property of Hyperlink ? convert that column to itemtemplate hyperlink column and then pass multiple parameters using navigateURL property. <asp:datagrid id="Datagrid3" runat="server" AutoGenerateColumns="False" BorderColor="black" HeaderStyle-CssClass="tableHeader" ItemStyle-CssClass= "tableItem"> <Columns> <asp:TemplateColumn HeaderText="Order"> <ItemTemplate> <asp:Hyperlink runat="server" Text='< %#DataBinder.Eval(Container.DataItem,"Name")%' NavigateUrl='<%# "page.aspx?Name=" + DataBinder.Eval (Container.DataItem,"Name") + "&ProductID="+ DataBinder.Eval(Container.DataItem,"ProductID")%>' ID="ProductName"/> </ItemTemplate> </asp:TemplateColumn> </Columns> </asp:datagrid> How do I change the width of the Textboxes created in edit-mode of my Datagrid? Updated! Answer: Here's an example of how to set the width of an edit Textbox in the EditItemTemplate of your TemplateColumn: <asp:DataGrid id="YourID" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateColumn HeaderText="Sample Column">

Page of 159

73

MBT Pune
<ItemTemplate> <%#Container.DataItem("AColumnName")%> </ItemTemplate> <EditItemTemplate> <asp:Textbox runat="server" width="600" maxlength="600"/> </EditItemTemplate> </asp:TemplateColumn> And for a BoundColumn, you can modify the width just before the Datagrid is rendered: Private Sub DataGrid1_PreRender(s As Object, e As EventArgs) If DataGrid1.EditItemIndex > -1 Then Dim tbx As TextBox tbx = CType(DataGrid1.Items(DataGrid1.EditItemIndex).Cells(0).Controls(0), TextBox) tbx.Width = Unit.Parse("1cm") End If End Sub How do I hide a column in my Datagrid if AutoGenerateColumns is set to True? Answer: AutoGenerated columns do not appear in the Datagrid's Columns() collection, and so the usual method of hiding a Datagrid column will fail: 'Will NOT work for AutoGenerated columns: Datagrid1.Columns(1).Visible = False So the place to handle this is in the ItemDataBound event of the Datagrid: <asp:DataGrid id="Datagrid1" runat="server" AutoGenerateColumns="True" OnItemDataBound="Datagrid1_OnItemDataBound"/> Private Sub DataGrid1_ItemDataBound(s As Object, e As DatagridItemEventArgs) e.Item.Cells(1).Visible = False End Sub

How do I conditionally set the backcolor of a cell in my Datagrid based on a value from the database? (conditional formatting) Answer: Handle this in the ItemDataBound event, where you can access the DataItem as it is bound to the Datagrid, and the Cells() collection of the current Datagrid item. Sub Datagrid1_ItemDataBound(source As Object, e As DataGridItemEventArgs) If (e.Item.ItemType = ListItemType.Item Or _ e.Item.ItemType = ListItemType.AlternatingItem) Then If Convert.ToDateTime(e.Item.Cells(1).Text) < DateTime.Today Then _ e.Item.Cells(1).BackColor = System.Drawing.Color.FromName("#ffccff") If e.Item.DataItem("UserID") = 590 Then _ e.Item.Cells(2).BackColor = System.Drawing.Color.DeepPink

Page of 159

74

MBT Pune
End If End Sub How do I specify more than one parameter for my hyperlinkColumn? Answer: The HyperlinkColumn's DataNavigateUrlFormatString only supports one parameter. If you need more than one, switch to a TemplateColumn with an <asp:Hyperlink>. Note: You should always encode values passed into querystring to protect against spaces and special characters. <asp:DataGrid id="YourID" runat="server" AutoGenerateColumns="False"> <Columns> <asp:TemplateColumn HeaderText="Sample Column"> <ItemTemplate> <asp:Hyperlink runat="server" Text='<%#Container.DataItem("TextVal") %>' NavigateUrl='<%# "page.aspx?Param1=" & Server.UrlEncode(Container.DataItem("Val1")) & "&Param2=" & Server.UrlEncode(Container.DataItem("Val2"))%>'/> </ItemTemplate> </asp:TemplateColumn> </Columns>

How do I set the selected item in a drop-down list? Try using DropDownList.SelectedIndex = DropDownList.Items.IndexOf(New ListItem("ABC")) or DropDownList.SelectedItem.Text = "ABC" Can I show an image and text in a data grid column header at the same time? Answer: You can encode the html for the <img> tag within the HeaderText string, and combine it with text. For example: <asp:BoundColumn HeaderText="<img src=some.gif><br>Here is some text" DataField="SomeField"/>

5.DATABASE TECHNOLOGY:What is ADO.NET? ADO.NET is next generation of Data Access Technology from Microsoft Target at .NET Platform. ADO.NET is built with Distributed and Internet applications in mind.ADO.NET Provides strong support for XML and disconnected Data Processing. What is .NET Data Provider? or What is .NET Managed Provider?

Page of 159

75

MBT Pune
A .NET Data Provider is a set of classes that allow managed code to interact with a specific data source to retrieve, Update and Manipulate data. A data provider in the .NET Framework serves as a bridge between an application and a data source. What are different types of .NET Data Providers? ADO.NET currently provides two .NET Data Providers. a) SQLSERVER .NET Data Provider:-Which provides Optimized access to SqlServer Databases. For Microsoft SQL Server version 7.0 or later. SQLClient .NET classes are highly optimized for the .net / sqlserver combination and achieve optimal results. It's faster because it accesses the native library (which automatically gives you better performance) b) OLEDB .NET Data Provider:-Which lets you connect to any data source for which you have an OLEDB Provider is installed. For data sources exposed using OLE DB. DataAcess API s for both the providers are found in separate namespaces. What are Data Access Namespaces? System.Data System.Data.Oledb classes that make up the .NET Framework Data Provider for OLE DBcompatible data sources System.Data.SqlClient classes that make up the .NET Framework Data Provider for SQL Server. System.Data.SqlTypes System.Data.XML System.Data.Odbc - classes that make up the .NET Framework Data Provider for ODBC. System.Data.OracleClient - classes that make up the .NET Framework Data Provider for Oracle. What are The main Objects in ADO.NET? 1.Connection Object-SqlConnection/Oledb Connection 2.Command Object-SqlCommand/OledbCommand 3.DataReader Object-SqlDataReader/OledbDatareader 4.DataAdapter Object-SqlDataAdapter/OledbDataAdapter These Are Core Elements of .NET Data Provider Model. 5.Parameter Object-SqlParameter/Oledb Parameter 6.Dataset Object 7.Data Table Object 8.DataView Object 9.Data Row Object 10.Data Column Object What are connection,Command, DataReader, and DataAdapter Objects? The Connection, Command, DataReader, and DataAdapter objects represent the core elements of the .NET data provider model. The following table describes these objects. Object Connection Command DataReader Description Establishes a connection to a specific data source. Its used for setting or retrieving Properties of a connection or handling connection Related events. Its used to Executes sql statements and stored procedures against a data source. Exposes Parameters and can execute within the scope of a Transaction from a Connection. It Provide Light Weight, High Performance access to forward-only, read-only stream of data from a data source. It is the best choice for accessing data to be displayed in ASP.NET. It only contains one row of data in memory at a time. As in ADO, Once connection to data source is closed ,the data is not available. DisAdv: we cant modify,search,sort the data and we do not have random acess to our ResultSet. Its used to Populates a Data Set from a given Sql Statement or Stored Procedure represented by a Sql Command Instance and update,manipulate and Insert rows

DataAdapter

Page of 159

76

MBT Pune
in the data source. Along with the core classes listed in the preceding table, a .NET data provider also contains the classes listed in the following table. Object Description Transaction Enables you to enlist commands in transactions at the data source. Command Builderr helper object that will automatically generate command properties A DataAdapter or will derive parameter information from a stored procedure and populate the Parameters collection of a Command object. Parameter Defines input, output, and return value parameters for commands and stored procedures. Exception Returned when an error is encountered at the data source. For an error encountered at the client, .NET data providers throw a .NET Framework exception. Error Exposes the information from a warning or error returned by a data source. Client PermissionProvided for .NET data provider code access security attributes. Parameters Properties such as Parameter Name, Type (SqlType or OledbType) and Value need to set and then add the Parameter Object to Parameters collection of the Command Object. What are the values in the SqlConnection.ConnectionString? The following table lists the valid names for values within the ConnectionString. Name Application Name AttachDBFilename -orextended properties -orInitial File Name Connect Timeout -orConnection Timeout Connection Lifetime 0 15 Default

Description The name of the application, or '.Net SqlClient Data Provider' if no application name is provided. The name of the primary file, including the full path name an attachable database. The database name must be specified with the keyword 'database'.

The length of time (in seconds) to wait for a connection to the server before terminating the attempt and generating error.

Connection Reset

'true'

Current Language Data Source -or-

When a connection is returned to the pool, its creation tim is compared with the current time, and the connection is destroyed if that time span (in seconds) exceeds the valu specified by connection lifetime. Useful in clustered configurations to force load balancing between a running server and a server just brought on-line. Determines whether the database connection is reset whe being removed from the pool. Setting to 'false' avoids ma an additional server round-trip when obtaining a connecti but the programmer must be aware that the connection s is not being reset. The SQL Server Language record name. The name or network address of the instance of SQL Serv to which to connect.

Page of 159

77

MBT Pune
Server -orAddress -orAddr -orNetwork Address Enlist Initial Catalog -orDatabase Integrated Security -orTrusted_Connection Max Pool Size Min Pool Size Network Library -orNet 100 0 'dbmssocn' 'false' Recognized values are 'true', 'false', and 'sspi', which is equivalent to 'true'. 'true'

When true, the pooler automatically enlists the connectio the creation thread's current transaction context. The name of the database.

Whether the connection is to be a secure connection or no

The maximum number of connections allowed in the pool The minimum number of connections allowed in the pool. The network library used to establish a connection to an instance of SQL Server. Supported values include dbnmpn (Named Pipes), dbmsrpcn (Multiprotocol), dbmsadsn (App Talk), dbmsgnet (VIA), dbmsipcn (Shared Memory) and dbmsspxn (IPX/SPX), and dbmssocn (TCP/IP).

The corresponding network DLL must be installed on the system to which you connect. If you do not specify a netw and you use a local server (for example, "." or "(local)"), shared memory is used. Packet Size Password -orPwd Persist Security Info 'false' 8192

Size in bytes of the network packets used to communicat with an instance of SQL Server. The password for the SQL Server account logging on.

Pooling User ID Workstation ID

When set to 'false', security-sensitive information, such a the password, is not returned as part of the connection if connection is open or has ever been in an open State. Resetting the connection string resets all connection strin values including the password. 'true' When true, the SQL Connection object is drawn from the appropriate pool, or if necessary, is created and added to appropriate pool. The SQL Server login account. the local computer name of the workstation connecting to SQL Server. The name

When setting Boolean properties, you can use 'yes' instead of 'true', and 'no' instead of 'false'.

Page of 159

78

MBT Pune

What is Dataset? Dataset is an In-memory representation of one or more tables of data. Its not specific to datasource.This data may be read from an XML file or stream or may be result of a query. Rows, Columns and Constraints objects are properties of DataTableClass. You can put relations and Constraints within varies data tables of a dataset. What is Data View? Data view Class provides a means for sorting, Searching, Editing, Filtering and Navigating Databases. Data views can also be Data Bound. What is Data Binding? Data binding is the process of (Declaratively or Programmatically) tying the elements of UI of a page (Such as Controls) to data in an underlying Data store. What are Different types of Data Bound Controls? Data bound Controls are of three types. 1.Data Grid: This control Presents Data in a tabular Format. 2.DataList: This control display Items in Multiple Columns and can display rows horizontally and vertically. 3.Repeater: This control allows you to work with templates. What are major differences between ADO.NET and ADO? In ADO, The in-memory representation of data is the record set. In ADO.NET ,it is dataset. There are important differences between them. 1.A Record set looks like a single table. Record set by nature is not able to represent multiple tables without the use of DataShapeProvider.In contrast, a dataset is collection of one or more tables. The tables in dataset are called Data Tables. If the dataset contains data from multiple database tables, it will typically contain multiple DataTable Objects. That is each DataTable Object typically corresponds to a single database table or view. In this way dataset can mimic the structure of the underlying database. 2.A dataset usually contains relationships, where as Record set cant contain any relationships.A relation ship within a dataset is analogous to a foreign-key relationship in a database. Hence dataset can hold much richer structures than a recordset. 3.Minimizing Open Connections:-In ADO.NET connections are opened only long enough to perform a database operation, such as a select or update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO the record set can provide disconnected access, but ADO is designed primarily for connected access. 4.In ADO, you communicate with database by making calls to an OLEDB Provider, While in ADO.NET you communicate with the database through a data adapter. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database-by optimising for performance, performing data validation checks, or adding any other extra processing. 4.Sharing Data Between Applications:-Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected record set. To transmit an ADO disconnected record set from one component to another, you use COM Marshalling. To transmit data in ADO.NET , you use dataset, which can transmit an XML Stream. Transmitting of XML files offers the following advantages over COM marshalling. a) Richer Data types:- COM marshalling provides a limited set of data types ,but there is no restriction of data types in XML. b) Conversion of Data type is needed in Com Marshalling, where In XML Stream its not needed, which accounts to good performance. c) Penetrating Firewalls:-Record sets cant penetrate firewalls as XML streams do, since Firewalls are designed to allow HTML text to pass, but to prevent system-level requests from passing.

Page of 159

79

MBT Pune
NB:-Record set was not XML-based and could not be serialized to XML easily or flexibly. How should I destroy my objects in ASP.Net? ASP.Net actually has very solid internal garbage collection so this should not be an issue as it was in previous versions of Active Server Pages. ***p What is the difference between Server.Transfer and Response.Redirect? Server.Transfer is the method you use to redirect the user to another page without performing a round trip to the client. client is shown as it is on the requesting page only, but the all the content is of the requested page. Data can be persist accros the pages using Context.Item collection, which is one of the best way to transfer data from one page to another keeping the page state alive. Response.Redirect() :client know the physical loation (page name and query string as well). Context.Items loses the persisitance when nevigate to destination page. In earlier versions of IIS, if we wanted to send a user to a new Web page, the only option we had was Response.Redirect. While this method does accomplish our goal, it has several important drawbacks. The biggest problem is that this method causes each page to be treated as a separate transaction. Besides making it difficult to maintain your transactional integrity, Response.Redirect introduces some additional headaches. First, it prevents good encapsulation of code. Second, you lose access to all of the properties in the Request object. Sure, there are workarounds, but theyre difficult. Finally, Response.Redirect necessitates a round trip to the client, which, on high-volume sites, causes scalability problems. As you might suspect, Server.Transfer fixes all of these problems. It does this by performing the transfer on the server without requiring a roundtrip to the client.

What are relation objects in dataset and how & where to use them? In a DataSet that contains multiple DataTable objects, you can use DataRelation objects to relate one table to another, to navigate through the tables, and to return child or parent rows from a related table. Adding a DataRelation to a DataSet adds, by default, a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table. The following code example creates a DataRelation using two DataTable objects in a DataSet. Each DataTable contains a column named CustID, which serves as a link between the two DataTable objects. The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the example specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn. custDS.Relations.Add ("CustOrders", custDS.Tables["Customers"].Columns["CustID"], custDS.Tables["Orders"].Columns["CustID"]); OR private void CreateRelation() { // Get the DataColumn objects from two DataTable objects in a DataSet. DataColumn parentCol;

Page of 159

80

MBT Pune
DataColumn childCol; // Code to get the DataSet not shown here. parentCol = DataSet1.Tables["Customers"].Columns["CustID"]; childCol = DataSet1.Tables["Orders"].Columns["CustID"]; // Create DataRelation. DataRelation relCustOrder; relCustOrder = new DataRelation("CustomersOrders", parentCol, childCol); // Add the relation to the DataSet. DataSet1.Relations.Add (relCustOrder); } After establishing a DataRelation between a table of customers and a table of orders, you can retrieve all the order rows for a particular customer row using DataRow.GetChildRows. [C#] DataRelation custOrderRel = custDS.Relations.Add("CustOrders", custDS.Tables["Customers"].Columns["CustomerID"], custDS.Tables["Orders"].Columns["CustomerID"]); foreach (DataRow custRow in custDS.Tables["Customers"].Rows) { Console.WriteLine(custRow["CustomerID"]); foreach (DataRow orderRow in custRow.GetChildRows(custOrderRel)) Console.WriteLine(orderRow["OrderID"]); } [VB] Dim drl As New DataRelation("customerorders", ds.Tables(0).Columns("customerid"), ds.Tables(1).Columns("customerid")) ds.Relations.Add(drl) Dim r As DataRow Dim childrows() As DataRow Dim cr As DataRow For Each r In ds.Tables(0).Rows Response.Write(r.Item(1)) childrows = r.GetChildRows("customerorders") For Each cr In childrows Response.Write(cr("orderid")) Response.Write("<br/>") Next Next How to Bind Relations to the Dataset? Datagrid.Datasource= objDataSet.Relations; Datagrid.DataBind(); NB:-To get Collection of Tables. Datagrid.Datasource= objDataSet.Tables; Datagrid.DataBind(); Write the code to define the PK and FK relation ship using Data Set and its Objects. Dim connstr As String connstr = "Provider=Microsoft.Jet.OLEDB.4.0;User ID=Admin;Data Source=c:db.mdb;Mode= ReadWrite" Dim cnn As OleDbConnection Dim da As OleDbDataAdapter Dim ds As New DataSet() cnn = New OleDbConnection(connstr) da = New OleDbDataAdapter("select * from customers", cnn)

Page of 159

81

MBT Pune
da.Fill (ds, "customers") Here I populated the dataset with Customers table. Primary Key Constraints ======================= Now, we will add CustomerID as a primary key constraint to the customers table from our dataset. Dim pk(1) As DataColumn pk(0) = ds.Tables(0).Columns("custid") ds.Tables("customers").PrimaryKey = pk Foreign Key Constraints ======================= Lets assume that we have another table called orders and I populate the orders data as follows: Da.SelecteCommand.CommandText="select * from orders" da.Fill(ds, "orders") CustID is foreign key in Orders table. Add following code that establishes foreign key constraints between them. Dim fk As ForeignKeyConstraint fk = New ForeignKeyConstraint("fk", ds.Tables(0).Columns("custid"), ds.Tables(1).Columns("custid")) fk.DeleteRule = Rule.Cascade fk.UpdateRule = Rule.Cascade ds.Tables(1).Constraints.Add(fk) ds.EnforceConstraints = True Here we have created an object of ForeignKeyConstraint with name "fk" that sets foreign key of orders table. Next, we have also set rules for cascade update and deletes. Finally we have added this constraint to the constraints collection of the datatable.

Explain different methods and Properties of Data Reader which you have used in your project? Read GetString GetInt32 while (myReader. Read ()) Console.WriteLine ("\t {0}\t {1}", myReader.GetInt32(0), myReader.GetString(1)); myReader.Close(); In how many ways we can retrieve table records count? How to find the count of records in a dataset? foreach (DataTable thisTable in myDataSet. Tables){ // For each row, print the values of each column. foreach (DataRow myRow in thisTable. Rows){ ***p What happens when u try to update data in a dataset in .NET while the record is already deleted in SQL SERVER as backend? OR What is concurrency? How will you avoid concurrency when dealing with dataset? (One user deleted one row after that another user through his dataset

Page of 159

82

MBT Pune
was trying to update same row. What will happen? How will you avoid the problem?) p How do you merge 2 datasets into the third dataset in a simple manner? OR If you are executing these statements in command Object. "Select * from Table1; Select * from Table2 how you will deal result set? p How do you sort a dataset? p If a dataset contains 100 rows, how to fetch rows between 5 and 15 only? Differences between dataset. Clone and dataset. Copy? Clone - Copies the structure of the DataSet, including all DataTable schemas, relations, and constraints. Does not copy any data. Copy - Copies both the structure and data for this DataSet. ***p How to generate XML from a dataset and vice versa? ReadXml() and ReadXmlSchema():-Takes an Xml Document or an Xml schema and reads it into the Dataset. GetXml() and GetXmlSchema():-Returns a string containing an Xml Document or an Xml schema that represents the data in the Dataset. WriteXml() and WritexmlSchema():-Writes the Xml Document or Xml schema that represents the data in the DataSet to a disk file or to a reader/writer instance or to a stream. What is method to get XML and schema from Dataset? getXML () and get Schema () p How do u implement locking concept for dataset? Can we keep Data Set in view state? Yes. The example stores a dataset in view state on a Web Forms page. It first creates an XML representation of the dataset and then stores the XML as a string. Dim sw As New System.IO.StringWriter DsNorthwind1.WriteXml(sw) ViewState("dsNorthwind") = sw.ToString() This example retrieves the DataSet from a view state. if (Page.IsPostBack) { System.IO.StringReader sr = new System.IO.StringReader((string)(ViewState["dSet"])); dSet.ReadXml(sr); } Note: As a rule, in the Web Applications, storing datasets in view state only if the dataset is very small. Large datasets can significantly increase the size of the ASPX page, resulting in slower download to the client and slower posting. 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 ---

Page of 159

83

MBT Pune
Password: [Empty] This would execute the following query against the users table: select count(*) from users where userName='' or 1=1 --' and userPass='' When do database connections need to be closed? Answer: You do not need to explicitly close any database connections when using a DataSet to obtain data. Instead, the connection will be automatically closed after populating the DataSet (which makes sense since the DataSet grabs all data in a snapshot operation -- and as such doesn't need to hold the connection open). If you use SQLDataReader or the SQLCommand object directly, however, then you do need to manually close it once you are done. The general rule to remember: if you explicitly open a connection (by calling an Open() method), then you probably need to explicitly close it. If you didn't have to explicitly open a connection (like in the DataSet case), then you probably don't need to explicitly close it.

6.CACHING&SESSION MANAGEMENT:What is State? The data or a variable that need to be maintained across a series of requests or shared between multiple users is referred as State. What is Scalability? It is the ability of an application to service requests from increasing no. Of users without any significant decrease in performance or response time. What factors effect Scalability? 1.Failure to disable session state when not used. 2.Misuse of Application.Lock() 3.Storing references to a single threaded Objects. 4.Overuse of Session or Application storage. What are the ways that ASP.NET supports various Client-side and server-side options for state management? Client-Side potions:1. ViewState Property 2. Hidden fields 3. cookies 4.QueryString Server-Side Options:1. Application State 2. Session State 3.Data Base How State is maintained in Rich Client Applications? Simply by allocating space in memory on the client machine, hence it is simple to maintain Individual state. Why maintaining State is difficult in Web Applications? Since HTTP Protocol, which is used to send or receive requests through a web browser, is inherently Stateless. So HTTP doesnt inherently provide a way for web server to identify a series of requests as coming from the same user, hence maintaining state with as individual user is difficult. What is Application State?

Page of 159

84

MBT Pune
It Refers to any data that need to share among multiple users of an Application. e.g. Connection Strings, Shared Variables, Cached Datasets etc. NB:- In general Connection Strings are stored in Web.Config and getConfig method of Context Object is used to retrive them and Cached datasets are saved using ASP.NET caching Engine and Shared variables that are shared and updated frequently are stored In Database. How Application State can be stored? Basically Application State is maintained using Collection of Key-Value pairs There are three ways to store Application State. They are a) By using Application Object Application (Key)=value b) By Using Application. Contents Collection Application. Contents (Key)=Value NB:-Application State Storage in ASP.NET is supplied by the .NET HttpApplication State Class. An Instance of which is exposed as the Application Property of the Page Class. c) By using Application. Add or Remove Methods Application. Application. Application. Application. Add (Key, Value) Remove (Key) Clear () RemoveAll ()

What are the Properties and Methods of an Application Object? Properties:AllKeys Property : Returns Collection of All keys by which Application Collection Values can be accessed. Count Property :Returns the number of Objects Stored in the Application Collection. Methods:Get Method:-Returns an Item from the application Collection by Key or by Index. Set Method:-Updates an Item in the Application Collection by Key or by Index. GetKey Method:-Returns the key for an item based on supplied index. ToString Method:-Returns a string that represents an item in the Application collection .Useful when a string value is required rather than an Object Reference. How Access to Application State is Synchronized? Or What are the cautions to be taken while maintaining Application State? Ensure that no two users can attempt to update the state information simultaneously, which lead to corruption of data being processed. For this ASP.NET Application Object provides Lock and Unlock methods. Eg. Application. Lock(), Appliaction.Unlock(0 But this can cause scalability problems. For this ensure to keep application Locked for short time possible. NB:- References to Object Instances with Wrong threading model (COM) have severe Scalability Problems. What are Limitations of Application State? 1.Durability: -When WebApplication /Webserver shutdowns or crashes state information will be destroyed. 2.Application State is not shared across in Webfarms and Web Gardens. 3.Memory:-Overuse of Application State may result in Information being swapped to virtual memory, that can reduce performance significantly. What is WebFarm? Groups of Identically configured servers that share the load of Serving user requests for a given web application. What is WebGarden? Through WebGarden, an Application can be set to run on specific Processor or Multi Processor server. What is Session State?

Page of 159

85

MBT Pune
Session State is Per User State Storage. How Session State can be stored? Basically Session State is maintained using Collection of Key-Value pairs There are two ways to store Session State. They are a) By using Session Object Session (Key)=value Eg. Session (MyVar)=My Value Mylocalvar=session(Myvar) b) By Using Session. Contents Collection Session.Contents (Key)=Value Eg. Session.Contents (MyVar)= MyValue Mylocalvar=session.contents(Myvar) NB: -Session State Storage in ASP.NET is supplied by the .NET HttpSession State Class. An Instance of which is exposed as the Session Property of the Page Class. What are the Properties and Methods of a Session Object? Properties:Keys Property: Returns Collection of All keys by which session Collection Values can be accessed. Count Property: Returns the number of Objects Stored in the Session Collection. SessionId Property: Returns a string contain session Id for the current session. Timeout Property:-Returns a Int32 value reprenting the current sessionTimeOut . Methods:Abandon Method: -Destroys current User session. Clear Method: -Removes all items from a session Collection. RemoveAt Method: -Specified items will be removed. ToString Method:-Returns a string that represents an item in the Session collection .Useful when a string value is required rather than an Object Reference. <@Page Enablesessionstate=False%> NB: -While designing an application the developer need to consider following things. 1.Maintainability 2.Reusability 3.Portability 4.Security 5.Integrity 6. User Friendliness of Software Products. What setting are stored in SessionState? 1.User Specific settings:-Most frequently queried data is preserved in Session state. Otherwise its preserved in a database. 2.Datasets containing frequently queried data is not stored in session state, but is stored in Asp.net Cache engine. What are the different types/Ways of storing SessionState? ASP.NET provides several new possibilities to store session state .They are 1.In process (InProc):This is Default setting. Simple to deal ,but lacks Scalability and Durability, as state cant sustain Web application or Webserver shutdowns or Crashes. 2.Out-of-Process(State Server) :This is the First Solution to the problems of Scalability and Durability for session state by storing session state out of process in a Dedicated ASP.NET State Process Provided by an NT Service. Advantages:1.Can service requests from multiple servers, making possible to scale session state across a web form. 2.As ASP.NET State service runs in a separate process so state information can survive restarts or crashes of a specific web application process. But cant survive if a restart or crash occurs on the machine, in which the ASP.NET state service is running. To do this change the session state configuration setting

Page of 159

86

MBT Pune

<SessionState mode =StateServer StateConnectionString=tcpip=127.0.0.1:42424/> Port that monitor ASP.NET StateService. Now start in services, ASP.NET Stateservice in MicrosoftManagementConsole(MMC)Snapin. Disadvantages:Retrieving state information from a different machine (i.e Different Process) is significantly more costly than retrieving it from within the same process. 3.Sqlserver (SQLServer): The second Solution to the problems of Scalability and durability for session state is To be store it out of process in a SqlServer Database. Advantages:1.Specified Sql Server can survive requests from multiple servers making it possible to scale session state across webform. 2.As session state Information is stored in a Sqlserver Database, so state Information can be survive restarts or crashes of any web application process, even Sqlserver itself. To enable Sqlserver to store session state 1.run installsqlstate.sql batch. 2. modify session state configuration section in Web.Config. <Session State mode=Sqlserver Sqlconnectionstring=data source=127.0.0.1;user id=sa; password=sa> 4.Cookiless Sessions:In configuration section set <Session state cookiless=true/> In this situation ASP.NET automatically embed the session Id value in the URL for all requests .If a request doesnt contain an embedded session Id ,asp.net will create New session Id and Embed it in the URL for that request. To prevent this problem, you can manually format URLs by calling ApplyAppPathModifier method of response intrinsic object and passing it a virtual path.It returns an Absolute URL, that includes protocol domain,Path and file name necessary to request a given resource. Dim myAbsUrl as string MyAbsUrl=Response.ApplyAppPathModifier(foo.aspx) Difference between ASP Session and ASP.NET Session? asp.net session supports cookie less session & it can span across multiple servers. What is cookie less session? How it works? By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. If cookies are not available, a session can be tracked by adding a session identifier to the URL. This can be enabled by setting the following: <sessionState cookieless="true" /> How you will handle session when deploying application in more than a server? Describe session handling in a webfarm, how does it work and what are the limits? By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. Additionally, ASP.NET can store session

Page of 159

87

MBT Pune
data in an external process, which can even reside on another machine. To enable this feature: Start the ASP.NET state service, either using the Services snap-in or by executing "net start aspnet_state" on the command line. The state service will by default listen on port 42424. To change the port, modify the registry key for the service: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\aspnet_state\Param eters\Port Set the mode attribute of the <sessionState> section to "StateServer". Configure the stateConnectionString attribute with the values of the machine on which you started aspnet_state. The following sample assumes that the state service is running on the same machine as the Web server ("localhost") and uses the default port (42424): <sessionState mode="StateServer" stateConnectionString="tcpip=localhost:42424" /> Note that if you try the sample above with this setting, you can reset the Web server (enter iisreset on the command line) and the session state value will persist. What method do you use to explicitly kill a users session? Abandon() What are the different ways you would consider sending data across pages in ASP (i.e between 1.asp to 2.asp)? Session public properties When maintaining session through Sql server, what is the impact of Read and Write operation on Session objects? will performance degrade? Maintaining state using database technology is a common practice when storing userspecific information where the information store is large. Database storage is particularly useful for maintaining long-term state or state that must be preserved even if the server must be restarted. p How do you create a permanent cookie?

What are Persistent and Non-Persistent Cookies? Persistent cookies will persist across multiple browser sessions. Non-Persistent Cookies persist to a single browser session. NB:1.Never store sensitive data like credit card details in Cookies. 2.Keep expiration of cookies to reasonable time. Mycookie.Expires=Now.address(2) How Cookies are declared? Dim mycookie as new HttpCookie(Mycookiename) Mycookie.value=Myvalue Response.Cookie.add(mycookie) --Response.appendcookie(cookie) What is Viewstate? Its a Mechanism through which All ASP.NET Server controls are capable of maintaining their own state between Requests.It is maintained on a page by page basis as a hidden

Page of 159

88

MBT Pune
that contains all the state information for all the form elements on that page.HTML controls wont provide any view state. Is it possible to protect view state from tampering when it's passed over an unencrypted channel? Yes. Simply include an @ Page directive with an EnableViewStateMac="true" attribute in each ASPX file you wish to protect, or include the following statement in Web.config:

<pages enableViewStateMac="true" /> This configuration directive appends a hash (officially called the message authentication code, or MAC) to view state values round-tripped to the client and enables ASP.NET to detect altered view state. If ASP.NET determines that view state has been altered when a page posts back to the server, it throws an exception. The hash is generated by appending a secret key (the validationKey value attached to the <machineKey> element in Machine.config) to the view state and hashing the result. An attacker can't modify view state and fix up the hash without knowing the secret key, too. Is it possible to encrypt view state when it's passed over an unencrypted channel? Yes. Set EnableViewStateMac to true and either modify the <machineKey> element in Machine.config to look like this: <machineKey validation="3DES" ... /> Or add the following statement to Web.config: <machineKey validation="3DES" /> What is Caching? Caching is the process of temporarily storing expensive resources in memory.These Resource may be expensive because the amount of processor time necessary to render them as they may reside on disk or in a backend database on another machine. What are the different types of Caching available? ASP.NET has three kinds caching that can be used by WebApplications. a)Output caching:-Which caches dynamic response generated by request. b)Fragment Caching:-Which caches portions of a response generated by a request. c)DataCaching:-Which caches arbitrary Objects programatically.To support this ASP.NET provides a full featured CacheEngine that allows programs to easily retain data across requests. What are attributes of Output Caching ? Duration: - Number of seconds to Cache the content. Location: -Sets the location to be used to the cache content. It can be Client, server, downstream, None or Any. In client the content is cached by the requesting Clients Browser. In server contents are Cached on the webserver.In Downstream content can be cached by any cache aware application downstream of the webserver fulfilling the request.(ProxyServer).In any content can be cached one of the above.And in none content is not at all cached. What are attributes of Fragment Caching? VaryByParam: -Allows varying of Cached content based on the values of one or more querystring values sent with a GET request, or form fields sent with a POST request. Multiple key or field names are separated by Semicolon.

Page of 159

89

MBT Pune
And * is set to vary by all parameters and none is used to use the same page regardless of GET/POST parameters. <%@ OutPutCache Duration=120 VaryByParam =Categoryid;selectedid%> VaryByControl: - Sets the names of properties of a user control by which to vary the caching of the user control output. This attribute is used with usercontrols only NB:-Whereas VaryByParam attribute varies cached results based on names/Value pairs sent using POST or GET , the VaryByControl attribute varies the cached fragment by controls within the user control. <%@OutPutCache Duration=120 VaryByParam=none VaryByControl=Category%> NB:- Similar to Output cache pages, explicit use of VaryByParam is required even if it is not used. VaryByCustom: -Allows varying of Cached content by browser user agent, browsercapabilities or custom logic. When set to any value other than Browser, requires that the HttpApplication.GetVaryByCustomString be overridden in Global.asax in order to Implement the custom logic. VaryByHeader: -Allows varying of cached content Based on value of one or more HTTP request headers. Multiple Properties are separated by semicolons. This attribute is used only with WebformPages. When Output Caching is used? Output caching is useful when the contents of an entire page can be cached. On a heavily accessed site, caching frequently accessed pages for even a minute at a time can result in substantial throughput gains. While a page is cached by the output cache, subsequent requests for that page are served from the output page without executing the code that created it. When Output Cache is enabled , an output cache entry is created on the first GET request to page. Subsequent GET/HEAD requests are served from this entry until cached time expires. NB:-ASP.NET is a Compiled Language rather than interpreted language, which increases performance. Hence these applications are always faster than classic ASP. When Fragment Caching is used? Sometimes it is not practical to cache an entire page - perhaps portions of the page must be created or customized for each request. In this case, it is often worthwhile to identify objects or data that are expensive to construct and are eligible for caching. Once these items are identified, they can be created once and then cached for some period of time. Additionally, fragment caching can be used to cache regions of a page's output. When Data Caching is used? ASP.NET provides a full-featured cache engine that can be used by pages to store and retrieve arbitrary objects across HTTP requests. The ASP.NET cache is private to each application and stores objects in memory. The lifetime of the cache is equivalent

Page of 159

90

MBT Pune
to the lifetime of the application; that is, when the application is restarted, the cache is recreated. Key-Value Pairs NB:- Cache("mykey") = myValue myValue = Cache("mykey") For applications that need more sophisticated functionality, the ASP.NET cache supports scavenging, expiration, and file and key dependencies. What is Scavenging, expiration, and file and key dependencies ? Scavenging means that the cache attempts to remove infrequently used or unimportant items if memory becomes scarce. Programmers who want to control how scavenging occurs can provide hints to the scavenger when items are inserted into the cache that indicate the relative cost of creating the item and the relative rate at which the item must be accessed to remain useful. Expiration allows programmers to give cache items lifetimes, which can be explicit (for example, expire at 6:00) or can be relative to an item's last use (for example, expire 20 minutes after the item was last accessed). After an item has expired, it is removed from the cache and future attempts to retrieve it return the null value unless the item is reinserted into the cache. File and key dependencies allow the validity of a cache item to be based on an external file or on another cache item. If a dependency changes, the cache item is invalidated and removed from the cache. For an example of how you might use this functionality, consider the following scenario: an application reads financial information from an XML file that is periodically updated. The application processes the data in the file and creates a graph of objects that represent that data in a consumable format. The application caches that data and inserts a dependency on the file from which the data was read. When the file is updated, the data is removed from the cache and the application can reread it and reinsert the updated copy of the data.

Note that a file dependency is added by using Cache.Insert and supplying a CacheDependency object referencing the XML file. Cache.Insert("MyData", Source, _ New CacheDependency(Server.MapPath("authors.xml"))) A cache item can depend on a single or multiple files or keys. As mentioned previously, an application can also set expiration policy on a cache item. The following code sets an absolute cache expiration time. Cache.Insert("MyData", Source, null, _ DateTime.Now.AddHours(1), TimeSpan.Zero) The relevant parameter is the call to DateTime.Now.AddHours(1), which indicates that the item expires 1 hour from the time it is inserted. The final argument, TimeSpan.Zero indicates that there is no relative expiration policy on this item. The following code shows how to set a relative expiration policy. It inserts an item that expires 20 minutes after it is last accessed. Note the use of DateTime.MaxValue, which indicates that there is no absolute expiration policy on this item. Cache.Insert("MyData", Source, null, DateTime.MaxValue, _ TimeSpan.FromMinutes(20))

Page of 159

91

MBT Pune
How Caching is removed? There are two ways to remove cache from memory. 1.Remove an item from cache Programmatically by calling the Remove method of the Cache Class and passing the key of the item to be removed. This is simple one and ASP.NET actually do it for you. Cache.Remove(Key) 2.The second and complex method is that if you want to control how ASP.NET decides which items to remove from the cache, and when it does so, you need to provide ASP.NET with that information when you add an item to cache. You can do so by using Add or Insert methods of the Cache class. ASP.NET determines the order in which items are scavenged from the cache based on their Priority. Overtime if an item is not accessed ASP.NET will reduce its priority periodically. when its priority reaches a predetermined point , it may be scavenzed. You can set the priority of an item by passing one of the values of the CacheItemPriority Enumeration when calling Add or Insert method. You can also set the rate at which an item decays by passing one a value of the CacheItemPriorityDecay Enumeration to Add or Insert method. Cache.insert(key,item,CacheDependency,AbsoluteExpiration,SlidingExpiration, CacheItemPrority.High,CacheItemPriorityDecay.Slow,Nothing) CacheDependency--Nothing AbsoluteExpiration-DateTime.Now.AddMinutes(20)- 2min:Expiration for two minutes from the time when the item is added to the cache. SlidingExpiration-Timespan.Zero Nothingsets the call back function for the item to nothing. What is Cache dependency? It is a class that allows you to create a dependency for a cached item on more files or Directories(file dependency) or on one or more Cache items(Kaydependencies). The constructor for the CacheDependency Class has the following three forms. Monitor a file or Directory for changes Dim mydependency as CacheDependency Mydependency=New CacheDependency(myFile or Dirname) Monitor an array of file names and/or paths for changes Dim mydependency as CacheDependency Mydependency=New CacheDependency(myFile or Dirarray) Monitor an array of file names and/or paths, and an array of keys for changes Dim mydependency as CacheDependency Mydependency=New CacheDependency(myFile or Dirarray,myKeyArray) Inorder to setup a key dependency without any file dependencies , you must create an array of keys(even if there is only one key) and pass Nothing as the first argument to the contructor,passing the array of key as the second. Dim Keys(0) as String Keys(0)=mykeyname Mydependency=New CacheDependency (Nothing, Keys)

Page of 159

92

MBT Pune
Once the instance of cache dependency has been created, it can be passed as a Parameter to Add or Insert method of the Cache Class. Cache.Insert(MyDS,myDs,myDependency) NB:- Unlike Application and Session Collections which can be accessed by either key or numeric index, cache item can only be accessed by their key. What is the difference between Add and Insert Methods of Cache class? Both provides essentially the same functionality, with two differences. The first difference is that all parameters of Add method are required. So even If you are not using a Particular parameter ,you must still pass a placeholder parameter. The Insert method is Overloaded, which makes this method easier to use when you want to pass only some of possible parameters. The second difference is That the Add method returns an object that represents the item just added to the Cache, while the insert method doesnt return a value. Can I use the cache object from a DLL? You need to reference the Cache object either directly from the page -- or alternatively off of the current HttpContext instance. If you were using a business component, then this would look like: Imports System.Web Dim Context as HttpContext Context = HttpContext.Current Dim FolderCache as String FolderCache = Cache("Folder")

7.SECURITY:How security takes place in ASP.NET Applications? IIS(Internet Information Server) authenticate all web requests. If ALLOWANONYMOUS is turned on , no authentication occurs.IIS authorizes clients requests and returns appropriate resource.In addition to built in ASP.NET Security features an ASP.NET application can also use the Low-level security features of .NET Framework.(i.e CodeAccessSecurity and RoleBasedSecurity), hence if you request a URL containing ASP.NET application,the request and authentication information are handed off to the application. What is CodeAccessSecurity? What is RoleBasedSecurity? What is Authentication? Authentication is Determining the identity of the User Making a Request. What are Different Types of Authentications Available?

Page of 159

93

MBT Pune
NB:- Authentication and Authorization work in hand in hand to Operate on 2 Distinct Levels.They are i. OS/IIS Level ii. ASP.NET Level There are 3 Basic types of Authentication Available for ASP.NET Applications. a) Windows Based Authentication b) Passport Authentication c) Form Based Authentication 1.Windows Based Authentication:In Windows Based Authentication ASP.NET Relies on IIS to authenticate Incoming request using one of its available Authenticate Methods.

a)

Basic Authentication:-Basic Authentication is Compatible with most browsers. But Password is sent in Clear Text. These are Protected with SSL Encryption. b) Digest Authentication:- Digest Authentication is introduced with HTTP 1.1,So it may not support all browsers. It sends hashed value instead of Clear-Text Password, its more secure than Basic Authentication. But it requires a Windows 2000 Domain Controller. c) Integrated windows (NTLM) Authentication:-Integrated Windows Authentication is Available only with Internet Explorer. Its most secure method because it never sends a username /Password over the network., but it will not work over HTTP Proxy Connection. In Web.config it is set as <authentication mode=windows/> <identity impersonate=true/> 2.Password Authentication:Password Authentication used the Centralized Password service provided by Microsoft. Passport authentication gives users a single login to use with any passport-enabled site. In order to use Passport Authentication with ASP.NET , you must download and install SDK, which is available with www.passport.com/business <authentication mode=passport/> <passport redirectUrl=<url>/> 3.Form Based Authentication:-(Cookie Athentication) Form-Based Authentication allows developers to easily implement roll-your-own security in their Applications. All you need to do is create the login page, tell ASP.NET where to find (via web.config) and set the desired Authorisation restrictions. In your login page, you can verify username and password credentials entered by user against a database, windows 2000 autrhenticate directory. Once Credentials are verified you can use methods exposed by Forms Authentication class to set or remove an authentication cookie redirect the user to original page they requested or renew the authentication Cookie. AUTHENTICATION TAG in WEB.CONFIG <authentication mode=windows|Forms|Passport|None> <forms loginurl=url name=name path=/ protection=All|None|Encryption|Validation timeout=number(min)>

Page of 159

94

MBT Pune
<credentials PasswordFormat=Clear|MD5|SHA1> <username=username password=password/> </credentials> </forms> <passport redirectUrl=url/> </authentication> What is SSL? When Its used? Secure Socket Layer Protocol request a server certificate and Register it. Encryption is an important tool for keeping information secure. The most commonly used form of encryption in web application is Secure Socket Layer Protocol. SSL is used by sites requiring secure communications between the webserver and browser to create and exchange a key used to encrypt communications between the client and the server. Its useful to protect credit card information, session id cookies and Login Information , when using Basic Authentication or Asp.net Forms Based Authentication. SSL Coomunication occurs at 443 port instead of 80 and http:// are used as https://. What is Authorization? Authorization is determining whether the user has permission to take the action required. What are Different Types of Authorizations Available? Authorization in ASP.NET takes two major forms. I . Authorization Against NTFS Access Control Lists(ACLs) II. URL Based Authorization I. NTFS ACLS For Authorization:ACLs based authorization is useful when you are using Windows Based Authentication in ASP.NET. With ACL-Based Authorization, you use tools such as properties dialog for a file or folder in Windows explorer to set the list of users or groups that are allowed to access a given resource and what rights(read,write,execute) each one has. Advantages:1. It doesnt requiring writing any security specific code in ASP.NET applications. 2. All are taken by Administrator only. II. URL Based Authorization:URL Based Authorization lets you grant or deny access to resources in your application based on their URL using <authorization> tag in web.config. NB: -Unlike <authentication> tag, this can be applied to subdirectories, even individual fields also. Wild cards: - * Allow/deny all users ? Allow/deny anonymous users <authorization> <allow users=userlist *,?,names

Page of 159

95

MBT Pune
roles=rolelist administrators,users verbs=verblists/ >GET/POST/HEAD/DEBUG <deny users=userlist roles=roleslist verbs=verbslist/> </authorization> <Location allowOverride=false> <authorization> </authorization> </location> Path Attributes that allow you to specify the path to which the settings contains between <Location> tags apply. What is Impersonation? Impersonation is the process by which ASP.NET takes on the security context of the user making request. This allows ASP.NET to gain access to resources that the user is authorized to use. This can be conformed using <identity> tag without impersonation, ASP.NET runs as the buit-in SYSTEM account. <identity impersonate=true/false username=username password=password> What is CAS? Code Access Security is the part of the .NET security model that determines whether or not a piece of code is allowed to run , and what resources it can use when it is running. Hence it is CAS that will prevent a .NET web applet from formatting your hardisk. How CAS works?

The CAS Security policy revolves around two key concepts. a) code groups b) Permissions Each .NET Assembly is a member of a particular code group and each code group is granted the permissions specified in a named permission set. Using caspol we can define our own permission sets. What is Role-Based security? A role is a named set of principals that have the same privileges with respect to security (such as a teller or a manager). A principal can be a member of one or more roles. Therefore, applications can use role membership to determine whether a principal is authorized to perform a requested action. How do you specify whether your data should be passed as Query string and Forms (Mainly about POST and GET) Through attribute tag of form tag. pWhat is the other method, other than GET and POST, in ASP.NET?

Page of 159

96

MBT Pune

14.General:How do I add an existing solution to Source Safe? Answer: The best way to work with web projects and teams is to use 'File Share' Web access - set this in Tools Options, and in Project Properties. Then, you'll need to have the VSSafe client installed on your client machine. Since File Share access doesn't rely on FrontPage, you don't have to get source control installed on your web server. Then, all you need to do is choose File->Source Control->Add Solution to source control. You then check in and out through the IDE, and use 'Get latest version' to get new changes others have checked in. Each new member who joins the team simply does File->Open from source control, choosing the same solution file. They will be prompted to choose a location for their private copy of the web projects (The Set Project Location dialog). They will be able to check in, out and get just as each other team member can. Note that, in beta1, there are issues with Web References to other projects. If you plan to use these, you should be sure to use http://localhost in the Set Project Location dialog. Why won't ASP.Net cookie authentication redirect to a logon page specified by a relative path? This is a known issue with Beta 1. To work around this you should use a fully qualified path to the logon page. ('/logon.aspx' instead of 'logon.aspx') Why do I get a JavaScript error when I try to use paging on a DataGrid control? The DataGrid control needs to be rendered inside of a server-side form so it knows to generate the required JavaScript. Is there a memory leak in the Beta 1 version of ASP.Net? Yes. Whenever an ASP.Net application restarts (caused by changes to config.web, global.asax, or an assembly in the \bin\ folder), memory leaks. This should be self-handled internally by the .Net Framework though because it detects when the worker process consumes more than 40% of available memory and it restarts itself (clearing the memory consumed). I have a .Net DLL loaded into \myweb\bin\ but the namespace isn't getting registered. What could be the problem? Make sure that \myweb\ is defined as a separate IIS 'application'. By default the .Net framework looks for DLLs in the web root, so defining this sub-folder as it's own web (application) should correct the error. Do you have to strongly type all variables in ASP.Net? Although you can provide type information in .NET, it isn't necessarily required (although Microsoft does recommend it for performance reasons). For example, you can declare a variable in VB.NET as: Dim Name as String You can also declare it as: Dim Name When the "type" declaration is not added, the VB.NET compiler will automatically

Page of 159

97

MBT Pune
declare it as type "Object". This is roughly analogous to a Variant in VBScript -meaning any type can be assigned to it. Note that all of the generic .NET Dictionaries, arrays, collections, etc. accept data types of type Object -- meaning you can put anything into them. How many maximum controls can be place in a form in Vb. 245 Is it possible for me to change my aspx file extension to some other name? Yes. Open IIS->Default Website -> Properties Select HomeDirectory tab Click on configuration button Click on add. Enter aspnet_isapi details (C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\aspnet_isapi.dll | GET,HEAD,POST,DEBUG) Open machine.config(C:\WINDOWS\Microsoft.NET\Framework\v1.0.3705\CONFIG) & add new extension under <httpHandlers> tag <add verb="*" path="*.santhosh" type="System.Web.UI.PageHandlerFactory"/> What base class do all Web Forms inherit from? System.Web.UI.Page 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. Differentiate between FullyQualified Vs Relative URLs? There are 2 types of URLs used for creating hyperlinks in webpages. 1.FullyQualified URLs(Absolute URLs) and 2.Relative URLs. Absolute URLs contain all information necessary for the browser to locate the resource named in the URL. This includes the protocol moniker(http://,ftp:// etc),servers domain name or IP address and the path to the resource. Relative URLs provide only the information necessary to locate a resource relative to the current document(known as document relative) or current server or domain(known as root relative).

Page of 159

98

MBT Pune
Because some controls or applications may not know how to use relative URLs, there may be times when you need to use a fully qualified URL. What is IIS? Microsoft Internet Information Server is a webserver that enables to publish information (on A corporate Intranet or) on the Internet. To whom will you report regularly? Team Leader. Architecture of an Organization:Project Manager-Project Leader - Team Leader or Module Leader Onsite coordinator generally keep sending Requests to Project Manager for Problems rectification .Project Manager will assign the work to Project Leader and the Project Leader in turn assigns the work based on the Module, who worked previously on it. What are the Recent Modifications you did in the Project? Where did you have programs to modify? From Visual Source Safe. How will you modify the programs when others are working on it simultaneously? What are different types of Test types that are available? What type of testing will you perform while designing and Developing Application? Unit Testing is Generally Performed , after Developing the application. What is Unit Testing ? How will you Perform it? Unit Testing can be defined as Verification of Smallest unit in the Program. This is performed by preparing Test Cases, Test Plans and Test Reports. In Test Cases Expected Results are written, In Test Plans some Input values are feeded and Out Puts will be noticed and In Test Reports all the Results are wrote and are verified. p How can u debug your .net application? p How do u deploy your asp.net application? pWhere do we store our connection string in asp.net application? p Various steps taken to optimize a web based application (caching, stored procedure etc.) pHow can you debug an ASP page, without touching the code? Can you override method="post" in a <form runat="server"> tag by writing <form method="get" runat="server">? Yes. Can an ASPX file contain more than one form marked runat="server"? No. Is it possible to see the code that ASP.NET generates from an ASPX file? Yes. Enable debugging by including a <%@ Page Debug="true" %> directive in the ASPX file or a <compilation debug="true"> statement in Web.config. Then look for the generated CS or VB file in a subdirectory underneath \%SystemRoot %\Microsoft.NET\Framework\v1.0.nnnn\Temporary ASP.NET Files.

Page of 159

99

MBT Pune
How do I comment out statements in ASPX files?

<%-<asp:Button Text="Click Me" OnClick="OnClick" runat="server" /> --%> Can I use custom .NET data types in a Web form? Yes. Place the DLL containing the type in the application root's bin directory and ASP.NET will automatically load the DLL when the type is referenced. How do I debug an ASP.NET application that wasn't written with Visual Studio.NET and that doesn't use code-behind? Start the DbgClr debugger that comes with the .NET Framework SDK, open the file containing the code you want to debug, and set your breakpoints. Start the ASP.NET application. Go back to DbgClr, choose Debug Processes from the Tools menu, and select aspnet_wp.exe from the list of processes. (If aspnet_wp.exe doesn't appear in the list, check the "Show system processes" box.) Click the Attach button to attach to aspnet_wp.exe and begin debugging. Be sure to enable debugging in the ASPX file before debugging it with DbgClr. You can enable tell ASP.NET to build debug executables by placing a

<%@ Page Debug="true" %> statement at the top of an ASPX file or a <compilation debug="true" /> statement in a Web.config file. Can a user browsing my Web site read my Web.config or Global.asax files? No. The <httpHandlers> section of Machine.config, which holds the master configuration settings for ASP.NET, contains entries that map ASAX files, CONFIG files, and selected other file types to an HTTP handler named HttpForbiddenHandler, which fails attempts to retrieve the associated file. Here are the relevant statements in Machine.config: <add verb="*" path="*.asax" type="System.Web.HttpForbiddenHandler, ... /> <add verb="*" path="*.config" type="System.Web.HttpForbiddenHandler, ... /> Do Web controls support Cascading Style Sheets? Yes. All Web controls inherit a property named CssClass from the base class System.Web.UI.WebControls.WebControl. The following example defines a CSS class named Input and uses it to modify a TextBox control to display text in red 10-point Verdana type: <html> <head> <style> .Input { font: 10pt verdana; color: red; } </style> </head> <body>

Page of 159

100

MBT Pune
<form runat="server"> <asp:TextBox CssClass="Input" RunAt="server" /> </form> </body> </html>

Are ASP.NET server controls compatible with Netscape Navigator? Most are. Some controls, such as Label, emit simple HTML tags that are compatible with virtually all browsers. Others, such as Calendar, emit a mix of HTML and client-side JavaScript. Fortunately, that JavaScript is simple enough to work with any browser that supports client-side scripting. The exception is the validation controls, which emit complex JavaScript that integrates intimately with the browser's DHTML Document Object Model (DOM). Because the DOMs used by Navigator and IE are so different, the ASP.NET validation controls don't work with Navigator. They can still validate input on the server, but they don't even attempt to validate on the client in Navigator. What assemblies can I reference in an ASPX file without using @ Assembly directives? ASP.NET links to the following assemblies by default: Mscorlib.dll System.dll System.Data.dll System.Drawing.dll System.Web.dll System.Web.Services.dll System.Xml.dll

This list of "default" assemblies is defined in the <assemblies> section of Machine.config. You can modify it by editing Machine.config or including an section in a local Web.config file. What namespaces are imported by default in ASPX files? The following namespaces are imported by default. Other namespaces must be imported manually using @ Import directives. System System.Collections System.Collections.Specialized System.Configuration System.Text System.Text.RegularExpressions System.Web System.Web.Caching

Page of 159

101

MBT Pune
System.Web.Security System.Web.SessionState System.Web.UI System.Web.UI.HtmlControls System.Web.UI.WebControls

How does setting a Web control's AutoPostBack property to true cause a page to post back to the server? With a sprinkle of JavaScript and a dash of Dynamic HTML (DHTML). Enter this into a Web form: <asp:TextBox ID="UserName" AutoPostBack="true" RunAt="server" /> And the control returns this: <input name="UserName" type="text" id="UserName" onchange="__doPostBack('UserName','')" language="javascript" /> . . . <script language="javascript"> <!-function __doPostBack(eventTarget, eventArgument) { var theform = document.ctrl0; . . . theform.submit(); } // --> </script> The <input> tag includes an onchange attribute that activates a JavaScript function named __doPostBack on the client when the control loses the input focus following a text change. __doPostBack programmatically posts the page back to the server by calling the Submit method of the DHTML object that represents the form (theform).

I sometimes see ASP.NET apps that include ASHX files. What are ASHX files? ASHX files contain HTTP handlers-software modules that handle raw HTTP requests received by ASP.NET. The following code institutes a simple HTTP handler:

<%@ WebHandler Language="C#" Class="Hello"%> using System.Web; public class Hello : IHttpHandler { public void ProcessRequest (HttpContext context) {

Page of 159

102

MBT Pune
string name = context.Request["Name"]; context.Response.Write ("Hello, " + name); } public bool IsReusable { get { return true; } } } If this code is placed in an ASHX file named Hello.ashx and requested using the URL http://.../hello.ashx?Name=Jeff, it returns "Hello, Jeff" in the HTTP response. ASHX files provide developers with a convenient way to deploy HTTP handlers without customizing CONFIG files or modifying the IIS metabase.

10.EXCEPTIONS:Exception 1: Jayasuscripr

How error handling is done in ASP.NET ? In Addition to Exception Handling ASP.NET Provides 3 types of ErrorHandling. 1.Page_level error event for errors on an Individual Page. 2.application_level error event for errors in an Application. 3.Through application configuration file to perform declarative error handling for an Application. 1.Page_Error Event:-In Page By calling GetLastError method of server object. Sub Page_error(sender as object, E as Eventargs) Dim err as string=error in : & Request.url.Tostring() & Server.GetLastError().Tostring() Response.write(err) Server.ClearError() End sub 2.Application_Error Event:-In Global.asax file By calling GetLastError method of server object. Sub Page_error(sender as object, E as Eventargs)

Page of 159

103

MBT Pune
Dim err as string=error in : & Request.url.Tostring() & Server.GetLastError().Tostring() Response.write(err) Server.ClearError() End sub 3.Application Error Configuration:This method is for handling HTTP errors not handled elsewhere in application.i.e for Completely unexpected errors. By Providing a simple way to return Custom pages. Its configured using CustomErrors element of System.web section in Web.config file. <system.web> <customErrors defaultRedirect=url mode=on |off |RemoteOnly> <error statusCode=code redirect=url/> </customErrors </system.web> on-->To specify that Custom errors be enabled. off-->To specify that Custom errors be disabled. RemoteOnly-->To specify that Custom errors are only enabled for RemoteClients. Error -->this sub-element allows individual pages to be shown for individual errors. Notifying Administrators of errors:1.Writing to the EventLog:a.First Edit the Identity element in System.web section as follows and give that user Permissions to modify/write the Registry. <configuration> <system.web> <identity impersonate=true user name=RegWriter password=iRule/> </system.web> </configuration> b.Write to Eventlog Imports Systsem.Diagnostics Try Catch ex as exception WriteToEventLog(Nanda,ex.Tostring()) End try Sub WriteToEventLog(LogName as string ,Message as String) Create event log if it doesnt exists. If(Not EventLog.SourceExists(LogName)) then EventLog.CreateEventSource(LogName,LogName) End if Fire Off to event Log dim Log as New EventLog(LogName) Log.Source=LogName Log.WriteEntry(Message,EventLogEntryType.Error) End sub

Page of 159

104

MBT Pune

2.Sending Email ErrorNotifications:By using MailMessage class of the System.web.Mail namespace. Try Catch ex as Exception SendMail(ex.Tostring()) End Try Public Sub SendMail(message as String) Dim MyMessage as new MailMessage MyMessage.To=webmaster@yourcompany.com MyMessage.From=webmaster@yourcompany.com MyMessage.Subject=UnHandled ASP.NET Error. MyMessage.BodyFormat=MailFormat.Text MyMessage.Body=message SmtpMail.SmtpServer=Your SMTP Server SmtpMail.Send(MyMessage)

End Sub

Debugging Problems in ASP.NET ? When you try to debug an ASP.NET application in Visual Studio.NET. you may receive the following debugging error. Error while trying to run project: Unable to start debugging on the web server. The project is not configured to be debugged. Following are reasons and solutions for this problems. Possibility 1: You are not a part of debugger group. Solution Local Users and Groups ->Users- > add yourself as a Debugger User (Also check if you are a VSDeveloper Possibility 2: You dont have execute permissions on your virtual folder. Solution Step 1: Control Panel -> Administrative Tools- >Internet Service Manager

Page of 159

105

MBT Pune
Step 2: Default Web Site -> Right Click on your Project-> Properties->Execute Permissions -> Scripts and Executables Possibility 3: You have kept ASP.NET debugging unchecked. Solution In VS.NET IDE, Right Click Project - >Properties->Configuration Properties ->Debugging-> Debuggers Enable Check the checkbox for ASP.NET Debugging How do I resolve the VS.Net error "has not been setup for the current user"? Run regedit and try to find the following Registry Key [HKEY_CLASSES_ROOT\Licenses\C4B8C1BC-A36C-4723-AF48-F362BFAB9DF5] If it exists, then delete it. Then, try launching VS.NET Beta 2 again.

11.TRANSACTIONS AND COM+:

Interop Services? The common language runtime provides two mechanisms for interoperating with unmanaged code:

Platform invoke, which enables managed code to call functions


exported from an unmanaged library.

COM interop, which enables managed code to interact with COM


objects through interfaces. Both platform invoke and COM interop use interop marshaling to accurately move method arguments between caller and callee and back, if required. *** How does u handle this COM components developed in other programming languages in .NET? ** What is RCW (Runtime Callable Wrappers)? The common language runtime exposes COM objects through a proxy called the runtime callable wrapper (RCW). Although the RCW appears to be an ordinary object to .NET clients, its primary function is to marshal calls between a .NET client and a COM object. ** What is CCW (COM Callable Wrapper) A proxy object generated by the common language runtime so that existing COM applications can use managed classes, including .NET Framework classes, transparently.

Page of 159

106

MBT Pune
How CCW and RCW is working? *** How will you register com+ services? a)The .NET Framework SDK provides the .NET Framework Services Installation Tool (Regsvcs.exe - a command-line tool) to manually register an assembly containing serviced components. b) You can also access these registration features programmatically with the System.EnterpriseServicesRegistrationHelper class by creating an instance of class RegistrationHelper and using the method InstallAssembly . What is use of ContextUtil class? ContextUtil is the preferred class to use for obtaining COM+ context information. What is Pinvoke? Platform invoke is a service that enables managed code to call unmanaged functions implemented in dynamic-link libraries (DLLs), such as those in the Win32 API. It locates and invokes an exported function and marshals its arguments (integers, strings, arrays, structures, and so on) across the interoperation boundary as needed. Is it true that COM objects no longer need to be registered on the server? Answer: Yes and No. Legacy COM objects still need to be registered on the server before they can be used. COM developed using the new .NET Framework will not need to be registered. Developers will be able to auto-register these objects just by placing them in the 'bin' folder of the application. Can .NET Framework components use the features of Component Services.? Answer: Yes, you can use the features and functions of Component Services from a .NET Framework component.

What are different types of COM components in VB? ActiveX DLL ActiveX EXE ActiveX Controls ActiveX Documents

What are in-process components ? In process components are ActiveX DLLs which run in the same address space as that of client. The communication between client and in-process server is fast but if the server crashes it can also cause the client to crash.

What are out-of-process components? Out-of-process components are ActiveX EXEs which run in their own address space. The communication between client and out-of-process server is slow

Page of 159

107

MBT Pune
because of marshalling. If the server crashes the client can still continue to function as the two processes are different.

What is marshalling? When a client calls a method from out-of-process server component the required parameters need to be sent across process boundries. Packaging and transporting of all parameters and return values between client and server is known as Marshalling.

What is instancing of a component? When you open an ActiveX DLL or EXE project each class has a designtime property called Instancing. This property determines how your objects will be created. There are three main catagories : Single use : in which case each requesting client is provided with new copy of the component Multi use : in which case multiple clients share the same instance of the component PublicNotCreatable : this means instance of your component can not be created directly by 'New' or 'CreateObject' but some other component returns one to you(generally as return value from a function).

What is most efficient way to create objects? In VB you can create objects using following methods : dim x as new myclass dim x as myclass set x=CreateObject("progID") dim x as myclass set x=new myclass Out of these methods the first method is least efficient and you should actually never use it(unless you are doing testing etc.) The second method uses standard COM services and is the only way to use in scripting languages like VBScript. If you are coding in VB and creating multiple instances of same class then try using last method instead The last method also uses standard COM services but is optimised for creating multiple objects of same class. Thus it is the most efficient.

Page of 159

108

MBT Pune
How do I provide events to my class? There are four basic steps in designing and using an event : Declare an event in your class public Event myevent(param1 as integer) Raise event in some of the method of the class RaiseEvent myevent(100) Now, at client side declare object of your class dim WithEvents x as new myclass Write code to handle myevent event public sub myevent(param1 as integer) msgbox param1 end sub ***Why host .NET Components in COM+? a.COM+ Provide many middleware services like 1.Increased Scalability 2.Transactions 3.Object-Pooling 4.Just-in-Time Activation to your Components. b..NET Components are different from Traditional COM Components in terms of 1.Reference Counting. 2.Memory Management 3.Registration. c.NET Provides a way to host your .net components inside COM+ Environment. d. and COM+ Provides easy Programmatic Configuration Options. What is COM+? What are its features? All the best ideas of COM and MTS have been integrated into a new runtime named COM+. Like COM, COM+ is based on binary components and Interface-based programming.(1)Method calls are remoted across process and computer boundaries through the use of a transparent RPC Layer(2). And like COM ,COM+ components can be upgraded and extended in production without adversely affecting the client applications that use them(3) Like MTS,COM+ supports distributed Transactions(1) and Role-based security(2).It provides built in Thread pooling scheme as transparent as MTS(3).The COM+ programming model also uses Interception to expose platform services to developers through declarative attributes(4).Hower,COM+ takes attribute programming much faster than MTS. In addition to transactional services and integrated security,COM+ exposes services such as CustomObjectContruction(5),Synchronization(6) and ObjectPooling(7).Other new features such as QueadComponents (8)and COM+ Events(9) are Also Exposed Through Configurable attributes. ****What is Configured Component? A component that has been installed in a COM+ Application is known as a Configured Component, primarily because it has associated COM+ attribute settings. If you want your components take advantage of COM+ services, you must install them in a COM+ application. When a component is installed in a COM+ application, its given a profile in a system catalog called COM+

Page of 159

109

MBT Pune
registrationDatabase(RegDB).The catelog holds configured attribute settings for components as well as for COM+ applications. What is Non-Configured Component? The components that doesnt have associated COM+ attributes are known as Non-Configured Component. Theses components are not installed in COM+ applications. Instead they registered in a manner consistent with earlier vertions of COM.These components cant take advantages of COM+Services. Eg ADO(Activex Data Objects) What are COM+ Services? 1.Automatic Transaction Processing 2.Just-in-time activation 3.Loosly-coupled events. 4. Object contruction 5. Object pooling 6. Queued components 7.Private Components 8.Role Based Security 9. SOAP services 10.Synchronization What is Automatic Transaction Processing? Automatic Transaction Processing is a service provided by COM+ that enables you to configure a class at design time to participate in a transaction at runtime.To use this service the class must derive directly or indirectly from the System.EnterpriseServices.Serviced Component class. What is Transaction TimeOut? COM+ allows you to specify a different Transaction timeout for each class that requires a transaction. You can use this to resolve conflicting time-out scenarios, Such as forcing short transactions versus allowing long-running batch stored procedures. <Transaction(TransactionOption.Required,_Isolation:= TransactionIsolationLevel.serializable,Timeout:=10> What is Transaction? A transaction is a set of related tasks that either succeed or fails as a unit. In transaction Processing Terminology, the transaction either commits or fails as a unit. For a transaction to commit, all participants must guarantee that any change to data will be permanent. What are ACID Properties? The term ACID Conveys the role transactions play in applications. ACID stands for Automicity, Consistency, Isolation and Durability. A transaction must be: 1. Atomic - it is one unit of work and does not dependent on previous and following transactions. 2.Consistent - data is either committed or roll back, no in-between case where something has been updated and something hasnt.

Page of 159

110

MBT Pune
a transaction should transform a system from one consistent state to another consistent state 3. Isolated - no transaction sees the intermediate results of the current transaction. 4. Durable - the values persist if the data had been committed even if the system crashes right after.

What are Transaction Boundaries? A Transaction boundary defines the scope of a transaction.Objects inside a transaction boundary share a common Transaction Identifier. As transaction executes, various transaction-aware resources may participate in the transaction. For example , if within the scope of transaction , your application connects to a database, the transaction flows to that resource and extends the transaction boundary to include the database server. You control over Transaction boundary varies depending on the transaction model you select for your application. Manual or Automatic. In Manual Transaction you control transaction boundaries with explicit instructors to begin and end the transaction. From one transaction boundary , you can begin a second transaction, called a nested transaction. The parent transaction doesnot commit until all its subordinate transactions commit. An Automatic Transaction manages transaction boundaries for you, based on a declarative attribute set for each component.A transaction automatically flows to objects instructed to participate in a transaction and by passes objects instructed to execute outside a transaction. You cannot nest transactions when using the automatic transaction model. What are Distributed Transactions? Distributed Transaction Processing (TP) systems are designed to facilitate transactions that span heterogeneous, transaction-aware resources in a distributed environment. Supported by a distributed TP system, your application can combine into a Transactional unit such diverse activities as retrieving a message from a MicrosoftMessageQueing(MSMQ) queue, storing the message in a Microsoft SQL Server database, and removing all existing references to the message from an Oracle Server database.Because they span multiple data sources, its important that distributed transactions enforce ACID Properties to maintain data consistency across all resoucrces. A Distributed TP system consists of several cooperating entities as mentioned below. These entities are logical and can reside on the same computer or on different computer. a)Transaction Processing(TP) Monitors:A TP monitor is software that sits between a transaction-aware application and a collection of resources. It maximizes operating system activities, streamlines network communications and connects multiple clients to multiple applications that potentially access multiple data sources. Instead of writing an application that manages a multi-user, distributed environment, you write an application that consists of a single transaction requests.The monitor scales your application as required. The Distributed Transaction Coordinator(DTC) is the TP Monitor for Microsoft Windows2000.

Page of 159

111

MBT Pune

b)Transaction Managers:In a distributed transaction, each participating resource has a local transaction manager(TM) to track incoming and Outgoing transactions on that computer. The TP monitor assigns one TM the additional task of coordinating all activities among local TMs. The TM that coordinates transaction activities is called the roof or coordinating TM. A TM coordinates and manages all transaction processing functions, but it is not equipped to manage data directly. Resource managers handle data related activities. c)Resource Managers:A Resource Manager is a system service that manages persistent or durable data in databases, durable message queues, or transactional file systems. The resource manager stores data and performs disaster recovery. SQLServer,Orcale,sybase,Informix,IBM(for IBM DB2),Ingres and MSMQ provide resource managers that participate in distributes transactions. d)Resource Dispensers:A Resource dispenser manages nondurable state that can be shared.For Example the ODBC resource dispenser manages pools of database connections, reclaiming each connection when it is no longer needed. NB: -For a .NET Framework object to participate in an automatic transaction, the .NET framework class must be registered with windows 2000 component services. What are Different Transaction Models? a)Automatic Transaction Model b)Manual Transaction Model NB:- MTS,COM+1.0 and the Common Language runtime support the same automatic distributed transaction model. Once ASP.NET page, XML WebServiceMethod or .NET Framework class is marked to participate in a transaction, it will automatically execute within the scope of a transaction. How Automatic Transactions Work? The Declarative transaction attribute specifies how an object participates in a transaction, and is configured programmatically. Although this declarative level represents the logic of a transaction, it is one step removed from the physical transaction. A physical Transaction occurs when a transactional Object accesses a data source, such as a database or message queue. The Transaction associated with the Object automatically flows to the appropriate resource manager. An associated driver, such as OLEDB , ODBC or ADO looks up the transaction in the Objects context and enlists in the transaction through the Distributed Transaction Coordinator(DTC).The entire physical Transaction occurs automatically. What are the Transaction Directives available in ASP.NET? Directive Disabled Description Indicates that the transaction context will be ignored

Page of 159

112

MBT Pune
by ASP.NET. This is the default transaction state. Indicates that the page does not run within the scope of transactions. When a request is processed, its object context is created without a transaction, regardless of whether there is a transaction active. Indicates that the page runs in the context of an existing transaction. If no transaction exists, the page runs without a transaction. The page runs in the context of an existing transaction. If no transaction exists, the page starts one. Indicates that the page requires a transaction and a new transaction is started for each request.

NotSupported

Supported

Required

RequiresNew

You can indicate the level of transaction support on a page by placing the directive in your code. For example, you can ensure that the page activities always execute in the scope of a transaction by inserting the following directive. <%@ Page Transaction="Required" %> If you omit the transaction directive, transactions are disabled for the page. What are the Transaction Directives available in ASP.NET? ASP.NET provides built-in support for creating and exposing XML Web services using a programming abstraction that is consistent and familiar to Web Forms. XML Web services provide to you the option of running your code within the scope of an automatic transaction. A transaction ensures that all interactions with resource managers such as SQL Servers, MSMQ Servers, Oracle Servers, and SNA Servers maintain the ACID Properties required to run robust distributed applications. You can declare an automatic transaction by using the TransactionOption property of the WebMethod attribute. Setting the TransactionOption property to TransactionOption.RequiresNew begins a new transaction each time a XML Web service client calls the XML Web service method. What are the Transaction Attributes available in .NET? Attribute value Disabled Description Eliminates the control of automatic transactions on the object. An object with this attribute value applied can engage the Distributed Transaction Coordinator (DTC) directly for transactional support. [Transaction(TransactionOption.Disabled)] Indicates that the object does not run within the scope of transactions. When a request is processed, its object context is created without a transaction, regardless of whether there is a transaction active. [Transaction(TransactionOption.NotSupported)] Indicates that the object runs in the context of an existing transaction, if one exists. If no transaction exists, the object runs without a transaction. [Transaction(TransactionOption.Supported)] Indicates that the object requires a transaction. It runs in the scope of an existing transaction, if one exists. If no transaction exists, the object starts one.

NotSupported

Supported

Required (default)

Page of 159

113

MBT Pune
[Transaction(TransactionOption.Required)] Indicates that the object requires a transaction and a new transaction is started for each request. [Transaction(TransactionOption.RequiresNew)]

RequiresNew

What is Object Pooling? Object pooling is nothing but recycling a certain number of objects among clients requesting them. The client requests for an object. If no instance of the object is available MTS will create a new instanced and give it to the calling client. The client will use the object and inform MTS when done with the help of special methods. MTS will not immediately destroy the object but keep it in 'object pool'. The same instance of the object is supplied to other clients requesting for the same component. Presently (ver 2.0) MTS do not provide object pooling but Microsoft has promised it at some later date. Microsoft has also provided some interfaces which you can use for this forward compatibility. Currently, MTS simply creates and destroys objects rather than recycling them. ****What is object pooling? Object pooling is an automatic service provided by COM+ that enables you to configure a component to have instances of itself kept active in a pool, ready to be used by any client that requests the component. You can administratively configure and monitor the pool maintained for a given component, specifying characteristics such as pool size and creation request time-out values. When the application is running, COM+ manages the pool for you, handling the details of object activation and reuse according to the criteria you have specified. You can achieve very significant performance and scaling benefits by reusing objects in this manner, particularly when they are written to take full advantage of reuse. With object pooling, you gain the following benefits: You can speed object use time for each client, factoring out timeconsuming initialization and resource acquisition from the actual work that the object performs for clients. You can share the cost of acquiring expensive resources across all clients. You can preallocate objects when the application starts, before any client requests come in. You can govern resource use with administrative pool management for example, by setting an appropriate maximum pool level, you can keep Sopen only as many database connections as you have a license for. You can administratively configure pooling to take best advantage of available hardware resourcesyou can easily adjust the pool configuration as available hardware resources change. You can speed reactivation time for objects that use Just-in-Time (JIT) activation, while deliberately controlling how resources are dedicated to clients.

Page of 159

114

MBT Pune
<Transaction (TransactionOption.Required), ObjectPooling(MinPoolSize:=2,MaxPoolSize:5,CreationTimeo ut:=20000)>

**** What are object pooling and connection pooling and difference? Where do we set the Min and Max Pool size for connection pooling? Object pooling is a COM+ service that enables you to reduce the overhead of creating each object from scratch. When an object is activated, it is pulled from the pool. When the object is deactivated, it is placed back into the pool to await the next request. You can configure object pooling by applying the ObjectPoolingAttribute attribute to a class that derives from the System.EnterpriseServices.ServicedComponent class. Object pooling lets you control the number of connections you use, as opposed to connection pooling, where you control the maximum number reached. Following are important differences between object pooling and connection pooling: Creation. When using connection pooling, creation is on the same thread, so if there is nothing in the pool, a connection is created on your behalf. With object pooling, the pool might decide to create a new object. However, if you have already reached your maximum, it instead gives you the next available object. This is crucial behavior when it takes a long time to create an object, but you do not use it for very long. Enforcement of minimums and maximums. This is not done in connection pooling. The maximum value in object pooling is very important when trying to scale your application. You might need to multiplex thousands of requests to just a few objects. (TPC/C benchmarks rely on this.) COM+ object pooling is identical to what is used in .NET Framework managed SQL Client connection pooling. For example, creation is on a different thread and minimums and maximums are enforced.

What is JIT(JustInTime) Activation? Just-in-Time (JIT) activation is an automatic service provided by COM+ that can help you use server resources more efficiently, particularly when scaling up your application to do high-volume transactions. When a component is configured as JIT activated, COM+ can deactivate an instance of it while a client still holds an active reference to the object. The next time the client calls a method on the object, which the client believes to be still active, COM+ will reactivate the object transparently to the client, just in time. The advantage of JIT activation is that you enable clients to hold references to objects for as long as they need them, without necessarily tying up server resourcessuch as memoryto do so. Other benefits include the following: From the client perspective, JIT activation greatly simplifies the programming modelthe client doesn't have to think about how it uses expensive server objects and server resources. Without JIT activation, when clients are aggressive about releasing server objects, they can incur a significant penalty in frequently calling and releasing objects.

Page of 159

115

MBT Pune
Note You can refine this performance benefit further by using object pooling. By pooling JIT-activated objects, you can greatly speed object reactivation for clients while reusing whatever resources they might be holding. And doing this gives you more precise control over how much memory is used by a given object on the server. For more detail, see Object Pooling and JIT Activation. By holding long-lived object references, clients keep open the channel to the object for as long as they need it. The farther the client is from the server, the greater the benefits of JIT activation becomebecause without JIT activation, the cost of activating and marshaling the server object, opening the channel, setting up the proxy and stub, and so on is much greater. With distributed applications, an expensive network round-trip is required with every object creation. As the volume of client calls increases, you want to minimize the frequency of object creation because it can significantly affect the performance of your application. When you JIT activate those objects to which clients hold long-lived references, but which they aren't necessarily using all the time, server memory is not always tied up keeping those objects alive. With lazy activation, memory is used only when the objects are actually needed. This can significantly increase the scalability of your application. The only performance hit that clients see is the time it takes COM+ to reactivate the objectusually just marginally more than the time it takes to allocate memory for the object, and substantially less than the network roundtrip for remote object creation.

*What is Connection Pooling? Connection pooling is similar to object pooling but it applies to database connections instead of object instances. MTS does provide connection pooling. Or Connection pooling is recycling of available database connections. Connection pooling is always per user basis i.e. connections set by user A can not be used by user B. Generally, a separate NT account is create for use by MTS components.

What is general rule while using database connections? Connect to database as late as possible and release the connection as early as possible

12.XML:What are the Objects you use to Read,Write and Transform XML? XmlTextReader, XmlTextWriter,XmlNodeReader,XslTransform (to create files into different format to original Xml Document). What are the Objects you use to store XML?

Page of 159

116

MBT Pune
XmlDocument,XmlDataDocument and XpathDocument objects. How do you Query XML? XpahNavigator object. What are Differences among XmlDocument,XmlDataDocument and XpathDocument objects? XmlDataDocument exposes the same Properties and Methods of XmlDocument and once loaded wih Xml Document it can expose it as DataSet object alsoThese allows to work on Data with RelationalDataBase Techniques. Xpathdocument object is fast and Compact implementation of XML storage object that is designed for access via an XpathNavigator object, using Xpathqueries or navigation element by-element using pull technique.

12.SERIALIZATION AND DESERIALIZATION:What is Serialization? Serialization is the Process of Converting an Object into a stream of Bytes, that can be persisted or transported. What is De Serialization? DeSerialization is the process of Creating an Object from a stream of Bytes. Serialization and Deserialization are mostly used to transport Objects(Eg. During Remoting) or to Persist Objects(Eg. To a file or Database). Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly containing the class, are converted to a stream of bytes, which is then written to a data stream. When the object is subsequently deserialised, an exact clone of the original object is created. What are Different Types of Serialization Technologies? The .NET Frame work features two serializing technologies. 1.Binary Serialization 2.XML Serialization/Soap Serialization 1.Binary Serialization: Binary Serialization Preserves Type Fiedelity, which is useful for preserving the state of an object between different invocations of an application. During this process , the public and private fields of the object and the name of the class, including the assembly containing the class is converted to a stream of bytes, which is then written to a data stream. Remoting uses binary serialization to pass objects by value from one computer, or application domain to another. 2.XML Serialization: XML serializes public properties and fields of an Object , or the parameters and return values of methods, into an XML stream that conforms to a specific XML schema Definition Language(XSD) document and does not preserves type fidelity. This is useful when you want to provide or consume data without restricting the application that uses the data. Because XML is an Open standard, it is an attractive choice for sharing data across the web. It serializes the class that implement ICollection or IEnumerable , XMLelement objects,xmlNodeObjects and Dataset Objects.

Page of 159

117

MBT Pune
SOAP is an open standard, which makes it an attractive choice. XML serialization can also be used to serialize objects into XML Streams that conform to the SOAP specification. SOAP is a protocol based on XML, designed specifically to transport procedure calls using XML. Webservices uses XML serialization. XMLSerializer class is used for this. XMLSerialization is slow as there is a once-per-process-per-type overhead with XMLSerializer. There are two separate mechanisms provided by the .NET class library XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code Why do I get errors when I try to serialize a Hashtable? XmlSerializer will refuse to serialize instances of any class that implements IDictionary, e.g. Hashtable. SoapFormatter and BinaryFormatter do not have this restriction.

13.REMOTING:What is Remoting? Under .NET framework Remoting provides an infrastructure for developing and using distributed components. Using remoting multiple AppDomains can talk with each other. What are PROXYOBJECTS? While developing a distributed application the underlying framework should provide transparent programming model to the application developer. Proxies play major role in this area. The proxy object acts as a 'dummy' of the remote object and forward all the method calls to the remote object instance. These proxy objects are created at client end (here client simply means a component which is calling the remote object). The client is unaware of the actual location of the remote object and it simply calls the methods on the proxy object which are then forwarded to the actual object. ***How Activation of RemoteObjects Takes Place? The remote objects can be activated in two ways Server Activation Client Activation In the server activation managing the life time of the remote object is not in the hands of client where as client activation involves life time management of the remote object. The server activated objects are of two types: Single call objects : These objects are state less objects i.e. they do not maintain state across method calls Singleton objects: These objects share the same instance of object among various clients and also maintain state across method calls. Here various clients share the same state information. Client Activated Objects are created for individual clients and can store state information between method calls for that specific client.

What is Leased based life time?

Page of 159

118

MBT Pune
We just mentioned that the client activated objects can control the life time of the remote objects. The mechanism by which it happens is called as Leasing. The remote objects have a default lease period. When the lease expires the object is garbage collected. The client can control the lease period by following ways: The server object can set its lease time to infinity The client can renew the lease of the object The client can make use of a sponsor which in turn requests a lease renewal

**What are Formatters? The communication between the client and remote object involves method parameters and return values. This data must be serialized before it is sent across the network. The serialization process creates a persistent copy of the data as a sequence of bytes. The process of converting these bytes back into the original data structure is called de-serialization. .NET remoting framework provide special objects for performing this serialization and de-serialization. They are called as Formatters. Formatters are available in following namespaces: System.Runtime.Serialization.Formatters.Binary System.Runtime.Serialization.Formatters.SOAP As the names suggest Binary formatter deals with data in binary format while SOAP formatter deals with data in XML format. ***What are Channels? To communicate with remote object we need a path through which the data transfer can take place. This path is called as Channel. There are two types of channels: TCP channels : As the name suggestes these channels use TCP for communication. TCP channels typically carry data in binary form i.e. they use Binary formatters HTTP Channels: These channels use HTTP for communication. They typically carry SOAP messages i.e. they use SOAP formatters. TCP channels with Binary formatters are suitable where speed and performance is important where as HTTP Channels with SOAP formatters are suitable for platform independent or over the web communication. The channels are available in following namespaces: System.Runtime.Remoting.Channels.TCP System.Runtime.Remoting.Channels.HTTP You can create your own channels for gaining more control over the transmission process.

How it works? When the client application communicates with the remote object following steps are involved. At Server Side A Channel is established at a specific port which will listen all the client requests.

Page of 159

119

MBT Pune
Remote object registers itself with remoting framework and declares its presence over the network. At Client Site Client establishes a channel at a specific port to talk with remote object. Client creates an instance of remote object by calling Getobject or CreateInstance or new method. Client gets the proxy for the remote object Client calls remote object methods on the proxy

14.TRACING:-

15.WEBSERVICES:What platforms do .NET XML Web Services run on? Currently, they're supported on Windows 2000 and Windows XP. ASP.NET integrates with Internet Information Server (IIS) and thus requires that IIS be installed. It runs on server and non-server editions of Windows 2000 and XP as long as IIS is installed. Can two different programming languages be mixed in a single ASMX file? No What is code-behind in Webservices? Code-behind allows you to associate Web Service source code written in a CLR compliant language (such as C# or VB.NET) as compiled in a separate file (typically *.asmx.vb). You would otherwise typically find the executable code directly inserted into the .asmx file. What event handlers can I include in Global.asax? Application_Start Application_End Application_AcquireRequestState Application_AuthenticateRequest Application_AuthorizeRequest Application_BeginRequest Application_Disposed Application_EndRequest Application_Error Application_PostRequestHandlerExecute

Page of 159

120

MBT Pune
Application_PreRequestHandlerExecute Application_PreSendRequestContent Application_PreSendRequestHeaders Application_ReleaseRequestState Application_ResolveRequestCache Application_UpdateRequestCache Session_Start Session_End

You can also include event handlers in Global.asax for events fired by custom HTTP modules. Note that not all of the event handlers make sense for Web Services. For example, the Application_AuthenticateRequest and Application_AuthorizeRequest events are designed to be used with ASP.NET Forms authentication. 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.Services

What are ASHX files? ASHX files contain HTTP handlers-software modules that handle raw HTTP requests received by ASP.NET. They are requested using URL http://.../hello.ashx? Name=Cindy, it returns "Hello, Cindy" in the HTTP response. ASHX files provide developers with a convenient way to deploy HTTP handlers without customizing Machine.config or Web.config. ASHX files can also employ code-behind just like ASPX and ASMX files. If I want to charge for a Web service, how do I know who's calling it? While there are probably many possible use models, the three most likely are service agreement, subscription, and per-use. With a service agreement, you and your clients sign agreements indicating the terms of the service. These terms vary widely, as you might imagine.

Page of 159

121

MBT Pune
Subscriptions allow your clients to access the Web Service for a given period of time or for a set number of invocations. Assuming their account remains in good standing, you continue to allow them to access your Web Service. Per-use, of course, is billed each time the client uses the Web Service. What is WSDL? WSDL is the Web Service Description Language, and it is implemented as a specific XML vocabulary. While it's very much more complex than what can be described here, there are two important aspects to WSDL with which you should be aware. First, WSDL provides instructions to consumers of Web Services to describe the layout and contents of the SOAP packets the Web Service intends to issue. It's an interface description document, of sorts. And second, it isn't intended that you read and interpret the WSDL. Rather, WSDL should be processed by machine, typically to generate proxy source code (.NET) or create dynamic proxies on the fly (the SOAP Toolkit or Web Service Behavior). The Web Services Description Language (WSDL) currently represents the service description layer within the Web service protocol stack. In a nutshell, WSDL is an XML grammar for specifying a public interface for a Web service. This public interface can include the following: Information on all publicly available functions. Data type information for all XML messages. Binding information about the specific transport protocol to be used. Address information for locating the specified service.

WSDL is not necessarily tied to a specific XML messaging system, but it does include built-in extensions for describing SOAP services. What is UDDI? UDDI stands for Universal Description, Discovery, and Integration. While UDDI is implemented as a series of Web Services that execute against known UDDI repositories, you can imagine UDDI as being a sort of "Yellow Pages" for Web Services. The repositories, maintained by Microsoft, IBM, and Ariba, are designed to provide you with detailed information regarding registered Web Services for all vendors. You query the repositories for specific information and/or Web Services as necessary to discover and ultimately use Web Services provided by any number of vendors. UDDI (Universal Description, Discovery, and Integration) currently represents the discovery layer within the Web services protocol stack. UDDI was originally created by Microsoft, IBM, and Ariba, and represents a technical specification for publishing and finding businesses and Web services. At its core, UDDI consists of two parts. First, UDDI is a technical specification for building a distributed directory of businesses and Web services. Data is stored within a specific

Page of 159

122

MBT Pune
XML format, and the UDDI specification includes API details for searching existing data and publishing new data. Second, the UDDI Business Registry is a fully operational implementation of the UDDI specification. Launched in May 2001 by Microsoft and IBM, the UDDI registry now enables anyone to search existing UDDI data. It also enables any company to register themselves and their services.

The data captured within UDDI is divided into three main categories: White Pages: This includes general information about a specific company. For example, business name, business description, and address. Yellow Pages: This includes general classification data for either the company or the service offered. For example, this data may include industry, product, or geographic codes based on standard taxonomies. Green Pages: This includes technical information about a Web service. Generally, this includes a pointer to an external specification, and an address for invoking the Web service.

What is a Web service? Many people and companies have debated the exact definition of Web services. At a minimum, however, a Web service is any piece of software that makes itself available over the Internet and uses a standardized XML messaging system. XML is used to encode all communications to a Web service. For example, a client invokes a Web service by sending an XML message, then waits for a corresponding XML response. Because all communication is in XML, Web services are not tied to any one operating system or programming language--Java can talk with Perl; Windows applications can talk with Unix applications. Beyond this basic definition, a Web service may also have two additional (and desirable) properties:

First, a Web service can have a public interface, defined in a common XML grammar. The interface describes all the methods available to clients and specifies the signature for each method. Currently, interface definition is accomplished via the Web Service Description Language (WSDL). Second, if you create a Web service, there should be some relatively simple mechanism for you to publish this fact. Likewise, there should be some simple mechanism for interested parties to locate the service and locate its public interface. The most prominent directory of Web services is currently available via UDDI, or Universal Description, Discovery, and Integration. Web services currently run a wide gamut from news syndication and stock-market data to weather reports and package-tracking systems.

Page of 159

123

MBT Pune
What is new about Web services? People have been using Remote Procedure Calls (RPC) for some time now, and they long ago discovered how to send such calls over HTTP. So, what is really new about Web services? The answer is XML. XML lies at the core of Web services, and provides a common language for describing Remote Procedure Calls, Web services, and Web service directories. Prior to XML, one could share data among different applications, but XML makes this so much easier to do. In the same vein, one can share services and code without Web services, but XML makes it easier to do these as well. By standardizing on XML, different applications can more easily talk to one another, and this makes software a whole lot more interesting. What is the Web service protocol stack? The Web service protocol stack is an evolving set of protocols used to define, discover, and implement Web services. The core protocol stack consists of four layers: Service Transport: This layer is responsible for transporting messages between applications. Currently, this includes HTTP, SMTP, FTP, and newer protocols, such as Blocks Extensible Exchange Protocol (BEEP). XML Messaging: This layer is responsible for encoding messages in a common XML format so that messages can be understood at either end. Currently, this includes XML-RPC and SOAP. Service Description: This layer is responsible for describing the public interface to a specific Web service. Currently, service description is handled via the WSDL. Service Discovery: This layer is responsible for centralizing services into a common registry, and providing easy publish/find functionality. Currently, service discovery is handled via the UDDI.

Beyond the essentials of XML-RPC, SOAP, WSDL, and UDDI, the Web service protocol stack includes a whole zoo of newer, evolving protocols. These include WSFL (Web Services Flow Language), SOAP-DSIG (SOAP Security Extensions: Digital Signature), and USML (UDDI Search Markup Language). For an overview of these protocols, check out Pavel Kulchenko's article, Web Services Acronyms, Demystified, on XML.com. Fortunately, you do not need to understand the full protocol stack to get started with Web services. Assuming you already know the basics of HTTP, it is best to start at the XML Messaging layer and work your way up.

What is XML-RPC? XML-RPC is a protocol that uses XML messages to perform Remote Procedure Calls. Requests are encoded in XML and sent via HTTP POST; XML responses are embedded in the body of the HTTP response. More succinctly, XML-RPC = HTTP + XML + Remote Procedure Calls.

Page of 159

124

MBT Pune
Because XML-RPC is platform independent, diverse applications can communicate with one another. For example, a Java client can speak XML-RPC to a Perl server. What is SOAP? SOAP is an XML-based protocol for exchanging information between computers. Although SOAP can be used in a variety of messaging systems and can be delivered via a variety of transport protocols, the main focus of SOAP is Remote Procedure Calls (RPC) transported via HTTP. Like XML-RPC, SOAP is platform independent, and therefore enables diverse applications to communicate with one another. Difference between web services & remoting? ASP.NET Web Services Protocol Can be accessed only over HTTP .NET Remoting Can be accessed over any protocol (including TCP, HTTP, SMTP and so on) Provide support for both stateful and stateless environments through Singleton and SingleCall objects Using binary communication, .NET Remoting can provide support for rich type system

State Management

Web services work in a stateless environment Web services support only the datatypes defined in the XSD type system, limiting the number of objects that can be serialized.

Type System

Web services support .NET remoting requires the interoperability across client be built using .NET, Interoperability platforms, and are ideal for enforcing homogenous heterogeneous environment. environments. Highly reliable due to the fact that Web services are always hosted in IIS Provides extensibility by allowing us to intercept the SOAP messages during the serialization and deserialization stages. Can also take advantage of IIS for fault isolation. If IIS is not used, application needs to provide plumbing for ensuring the reliability of the application. Very extensible by allowing us to customize the different components of the .NET remoting framework.

Reliability

Extensibility

Ease-ofProgramming

Easy-to-create and deploy. Complex to program.

Page of 159

125

MBT Pune
16.CONFIGURATION SETTINGS:a)TRACE:Trace element allows you to enable or disable application-wide tracing as well as set the parameters for the tracing functionality. When tracing is enabled, you can review information about requests received by the Web Server with the special URL http://<servername>/<appname>/trace.axd.

<trace enabled=true|false-1 localOnly=true|false-2 pageOutput=true|false-3 requestLimit=integer-4 traceMode=SortByTime|SortByCategory-5 />

1.False-Default 2.Determines whether trace information is viewable by computers other than local webserver. True-Only from Local WebserverDefault False-From Any machine. 3.Determines whether trace output is appended to each ASP.NET page in the application or is available only through trace.axd.(false)Default 4.Determines the number of requests that are stored for review through the trace.axd URL.once this limit has been reached then the current trace must be cleared by browsing trace.axd in order to collect information on additional requests. The Default is 10, but higher this number ,the more overhead is involved in tracing.Set this number as small as feasible. 5.Determines the sort order of the requests stored. SortByTime-Sorts trace information by the order in which events are processed- Default SortByCategory-Sorts trace information by Alphabetically by category. This is very useful while using Trace.Write method, for grouping statements using the same category argument.

b)globalization:-

Page of 159

126

MBT Pune
<globalization> element controls globalization settings for ASP.NET applications.This includes the encoding used for requests,responses and files as well as settings for specifying the culture to be associated with web requests and Local Searches. <globalization culture=any valid culture string-1 fileEncoding=any valid encoding string-2 requestEncoding= any valid encoding string-3 responseEncoding= any valid encoding string-4 uiCulture= any valid culture string-5/> 1.Determines the culture such as language defaults used to process incoming Web Requests. System.Globalization.CultureInfo class provides a list of valid culture strings. 2.Determines type of character encoding used for parsing ASP.NET application files(.aspx,.asmx and .asax).This must be a valid encoding string either in Machine.Config or in Web.config.If both are not available then the coding will be base on Machines regional Options setting in control panel. 3. Determines type of character encoding used to process incoming WebRequests. This must be a valid encoding string either in Machine.Config or in Web.config.If both are not available then the coding will be base on Machines regional Options setting in control panel. The Default is utf-8. 4. Determines type of character encoding used to encode outgoing responses. This must be a valid encoding string either in Machine.Config or in Web.config.If both are not available then the coding will be base on Machines regional Options setting in control panel. The Default is utf-8. 5. Determines the culture such as language defaults used to process searches that are culture or local specific. System.Globalization. CultureInfo class provides a list of valid culture strings. c)httpRuntime:The <httpRuntime> element controls several aspects of the ASP.NET HTTP Runtime engine. <httpRuntime appRequestQueueLimit=number of requests-1 executionTimeOut=seconds-2 maxRequestLength=Kbytes-3 minLocalRequestFreeThreads=number of threads-4 minFreeThreads=number of threads-5 useFullyQualifiedRedirectUrl=true|false -6/> 1.Specifies number of requests that ASP.NET will queue when no threads are available to process them, before returning a 503-server too busy error message. The Default is 100.Increasing this value may result in unacceptable long wait times for users, so use caution and test carefully when making adjustments to this value. 2.Determines amount of time (sec), that an ASP.NET request may continue executing before being shutdown. This can be used to prevent hung or longrunning requests from consuming more resources than necessary.The default is 90 seconds.

Page of 159

127

MBT Pune

3.Determines maximum size of incoming file uploads ,in KB.This attribute is designed to help prevent denial of service attacks mounted by uploading large files to a server.set it to small size feasible for files you expect your users to upload. The default is 4,096KB. 4.Configures the minimum number of threads ASP.NET will keep free for processing new requests. The Default is 8. 5. Configures the minimum number of threads ASP.NET will keep free for processing requests coming from local machine. Maintaining these free threads can help prevent deadlocks in multithreaded processing. The Default is 4. 6.Determines whether relative or fully qualified URLs (True-Default)are used for client-side redirects. This attribute allows developers to support certain mobile controls that require fully qualified URLs for client-side redirects.False-Relative URLs. D)httpModules:HttpModules are classes that implements IHttpModule interface and are used to provide functionality to ASP.NET assplications.For example , by default , the Machine.Config file adds HttpModules for OutputCaching, Session-state Management, authentication and authorization.The <httpModules> element allows you to add HttpModules to ASP.NET applications. The<httpModules> element supports three child elements,<add>,<remove> and <clear> and has the following syntax. <httpModules> <add-1 name=name-2 type=type\assembly name />-3 <remove-4 name=name/ > -5 <clear/>-6 </httpModules> <httpModules>-Determines the httpModules available for the ASP.NET applications within the scope of configuration file. 1.Each <add> child element adds a specified httpModule. 2.Specifies a name that can be used by ASP.NET applications to refer to the module identified by the type attribute. 3.Specifies the .NET class that implements the desired httpModule. This is string containing a comma separated list with the class name and other information, such as Version and public key, that enables ASP.NET to locate the class in either the applications bin directory or the global assembly cache. 4.Removes an httpModule based on the name and type attributes specified. 5.Removes all httpModules either those configured by the currentfile or those inherited from the parent configuration files.

E)httpHandlers:-

Page of 159

128

MBT Pune
The <httpHandlers> element allows you to assign requests of certain types or for certain resources to specific handler classes. For example, in Machine.Config, the handling of the ASP.NET pages is assigned to the System.Web.UI.PageHandlerFactory class. The <httpHandlers> element can also be used to prevent HTTP access to certain types of files by assigning them to System.Web.HttpForbiddenHandler class. The<httpHandlers> element supports three child elements,<add>,<remove> and <clear> and has the following syntax. < httpHandlers > <add-1 path= path-2 type=type\assembly name -3 validate=true|false-4 verb=verblist/>-5 <remove-6 path= path-7 verb=verblist/>-8 <clear/>-9 < /httpHandlers > < httpHandlers >-Determines the assignment of requests to httpHandlers for ASP.NET applications. 1.Each <add>child element maps a specific type of request to a given httpHandler. 2.Specifies the URL path this httpHandler will handle. This can be a single URL as in case of the default mapping of the trace.axd URL to System.Web.Handlers.TraceHandler, or may use a wildcard to specify that the httpHandler should handle all requests of a given type(such as .aspx or .asmx) 3.Specifies the .NET class that should handle the requests specified by the Path and verb attributes. This is string containing a comma separated list with the class name and other information, such as Version and public key, that enables ASP.NET to locate the class in either the applications bin directory or the global assembly cache. 5.Specifies the HTTP Verbs for which the httpHandler will handle requests. Comma-separated list of verbs(GET,POST) or wild card(such as * which specifies that all verbs should be handled). 6.Removes an httpHandler based on the path and verb attributes specified. 5.Removes all httpHandlers either those configured by the currentfile or those inherited from the parent configuration files.

F)processModel:The <processModel> element configures settings related to how ASP.NET applications run, and it provides access to a number of features geared towards improving the availability of applications. Theses includes automatic restart(which can be configured based on elapsed time or number of requests),allowed memory size and webgarden. Note that when ASP.NET is running under IIS6.O In native mode,the settings in the <processModel> element are ignored in favour of the settings configured by the IIS administrative UI.

Page of 159

129

MBT Pune

<processModel clientConnectedCheck=time-00:00:05 comAuthenticationLevel=Default|None|Connect|Call|Pkt| PktIntegrity|PktPrivacy comImpersonationLevell=Default|Anonymous|Identity|Impersonate| Delegate cpuMask=number-0xffffffff enable=true|false idleTimeOut=time-Infinite logLevel=logLevel-Errors maxIoThreads=number-25 maxWorkerThreads=number-25 memoryLimit=number pingFrequency=hh:mm:ss-30 sec pingTimeout=hh:mm:ss-5 sec requestLimit=number requestQueueLimit=number-5000 responseDeadlockInterval=infinite|hh:mm:ss-3 min responseRestartDeadlockInterval= infinite|hh:mm:ss-9 min restartQueueLimit=number-10 serverErrorMessageFile=filename shudownTimeout=time-5 sec timeout=time webGarden=true|false username=user name-MACHINE password=password/>-autogenerate G)browserCaps:The <browserCaps> element contains settings used by ASP.NET to provide the functionality of the browser capability component(accessible via the Request.Browser Property).It provides filtering processes that allow the browser capabilities component to populate its properties with information on the capabilities of a users browser, based on the information contained in the user agent string passed by the browser.The element supports 3 child elements, <result>,<use>,<filter>.The<filter> element supports one child element <case>. <browserCaps> <result type=System.Web.HttpBrowserCapabilities/> <use var=HTTP_USER_AGENT/> <filter> <case match=string1|string2|string3> property=value </case> </filter> </browserCaps> 18. S Q L S E R V E R F A Q S pWhat are the new features introduced in SQL Server 2000 (or the latest release of SQL Server at the time of your interview)? What changed between the previous version of SQL Server and the current version?

Page of 159

130

MBT Pune
This question is generally asked to see how current is your knowledge. Generally there is a section in the beginning of the books online titled "Whats New", which has all such information. Of course, reading just that is not enough, you should have tried those things to better answer the questions. Also check out the section titled "Backward Compatibility" in books online which talks about the changes that have taken place in the new version.

function Validate( element ){ if( document.getElementById( element ).value =='' ) { alert('Please Enter SRNo to Search'); document.getElementById( element ).focus(); return false; } return true; } function ValidatePaging(evt) { var key = (evt.which) ? evt.which : event.keyCode; if((key>47) && (key
*** What is Normalization? Normalization is a process of efficiently organizing your data in your database. The goals in doing so: Eliminate all the redundant data and ensure data dependencies. Both of these goals are worth achieving. Normalizing tables would reduce the amount of space a database may consume. And as said earlier each of these are a set of rules. Each of these rules are called as "Normal Form" or NF in short. All the rules are cumulative in nature. Meaning if we have three of the rules adhered then we are in the 3NF. In this document we will First Normal Form ( 1NF ) Eliminate repeating groups from the same table Aggregate similiar data in separate tables and identify each row with an unique identifier In simple language if we were to say each attribute of the relation would be atomic in nature for 1NF. Look at the example below to understand better.

Second Normal Form ( 2NF ) Moving forward lets take a look at the rules that goven 2NF. We get a step even more closer to remove duplicate records.

Page of 159

131

MBT Pune
Remove data that apply to multiple rows and place them in a separate table Relate the above table with foreign keys i.eeach nonkey attribute in the relation must be functionally dependent upon the primary key Consider the below example to understand the same.

Third Normal Form ( 3NF ) This is the most preferred normalization technique followed for most of the database. Eliminate all fields that donot depend on the Primary key Values in a record that are not part of that record's key do not belong in the table. In general, any time the contents of a group of fields may apply to more than a single record in the table, consider placing those fields in a separate table.

Page of 159

132

MBT Pune

Note: All these normalization are cummulative in nature. I re-iterate this point. There are 4NF otherwise called as Boyce-Codd normal form (BCNF). I wouldnot deal much into this form as it becomes far beyond practicle limits to have such a requirement. The rule is, we are in BCNF if and only if every determinant is a candidate key

FOURTH NORMAL FORM: A table may not contain independent 1:n relationships between primary key columns and non-key columns. You would not put person_id, favorite_juice, and favorite_itch_powder in the same table because a person may enjoy fruit drinks but not be itchy or a person may be very itchy and detest fruit drinks. This situation would result in holes in your table's data. It would be better to create two tables (one for favorite_juice and one for favorite_itch_powder) with person_id foreign keys to handle this situation. FIFTH NORMAL FORM: Fifth normal form breaks tables into the smallest possible pieces to eliminate redundancies. There is a point of diminishing returns when you start to have more work managing the redundancy of primary and foreign keys than of data so balance between redundant data and redundant keys is needed What is de-normalization and when do you do it? As the name indicates, denormalization is the reverse process of normalization. Its the controlled introduction of redundancy in to the database design. It helps improve the query performance as the number of joins could be reduced. What is a transaction and what are ACID properties? A transaction is a logical unit of work in which, all the steps must be performed or none. ACID stands for Atomicity, Consistency, Isolation, Durability. These are the properties of a transaction. How do you implement one-to-one, one-to-many and many-to-many relationships while designing tables?

Page of 159

133

MBT Pune
One-to-One relationship can be implemented as a single table and rarely as two tables with primary and foreign key relationships. One-to-Many relationships are implemented by splitting the data into two tables with primary key and foreign key relationships. Many-to-Many relationships are implemented using a junction table with the keys from both the tables forming the composite primary key of the junction table. *Explain different isolation levels? An isolation level determines the degree of isolation of data between concurrent transactions. The default SQL Server isolation level is Read Committed. Here are the other isolation levels (in the ascending order of isolation): Read Uncommitted, Read Committed, Repeatable Read, Serializable. See SQL Server books online for an explanation of the isolation levels. Be sure to read about SET TRANSACTION ISOLATION LEVEL, which lets you customize the isolation level at the connection level. 1. Read Committed - A transaction operating at the Read Committed level cannot see changes made by other transactions until those transactions are committed. At this level of isolation, dirty reads are not possible but nonrepeatable reads and phantoms are possible. 2.Read Uncommitted - A transaction operating at the Read Uncommitted level can see uncommitted changes made by other transactions. At this level of isolation, dirty reads, nonrepeatable reads, and phantoms are all possible. 3.Repeatable Read - A transaction operating at the Repeatable Read level is guaranteed not to see any changes made by other transactions in values it has already read. At this level of isolation, dirty reads and nonrepeatable reads are not possible but phantoms are possible. 4.Serializable - A transaction operating at the Serializable level guarantees that all concurrent transactions interact only in ways that produce the same effect as if each transaction were entirely executed one after the other. At this isolation level, dirty reads, nonrepeatable reads, and phantoms are not possible. What is lock escalation? Lock escalation is the process of converting a lot of low level locks (like row locks, page locks) into higher level locks (like table locks). Every lock is a memory structure too many locks would mean, more memory being occupied by locks. To prevent this from happening, SQL Server escalates the many fine-grain locks to fewer coarse-grain locks. Lock escalation threshold was definable in SQL Server 6.5, but from SQL Server 7.0 onwards its dynamically managed by SQL Server. What are user defined datatypes and when you should go for them? User defined datatypes let you extend the base SQL Server datatypes by providing a descriptive name, and format to the database. Take for example, in your database, there is a column called Flight_Num which appears in many tables. In all these tables it should be varchar(8). In this case you could create a user defined datatype called Flight_num_type of varchar(8) and use it across all your tables. See sp_addtype, sp_droptype in books online. What is bit datatype and whats the information that can be stored inside a bit column?

Page of 159

134

MBT Pune
Bit datatype is used to store boolean information like 1 or 0 (true or false). Untill SQL Server 6.5 bit datatype could hold either a 1 or 0 and there was no support for NULL. But from SQL Server 7.0 onwards, bit datatype can represent a third state, which is NULL.

Write a SQL Query to find first day of month? SELECET DATEADD(m,DATEDIFF(m,0,GETDATE()),0) --> 2005-04-01 00:00:00.000 DateFunctions:1.GetDate():Returns the currentDate and Time. 2.DatePart(datepart,date_expr):Returns specified part of the date expression as an Integer.eg. datepart(yy,getdate())-->2005 3.Datename(datepart,date_expr):Returns specified part of Date expression as a String. Eg.datename(dw,getdate())--->Sunday 4.Datediff(datepart,date_expr1,date_expr2):Returns date_expr2date_expr1 in units(day,month,years etc) eg.datediff(mm,getdate(),8/1/1998) 5.Dateadd(datepart, number,date_expr):Returns the date obtained by adding the number in units(day,month,years etc) eg:Dateadd(mm,5,getdate()) Write a SQL Query to find LastDay of month? SELECT DAY(DATEADD(DAY,-1,DATEADD(MONTH,1,DATEADD(DAY,1DAY(GETDATE()),GETDATE())))) ConvertFunctions:These are used to Convert Data from one DataType to another. 1.Convert(datatype[(length)],expression) 2.Convert(datatype[(length)],expression,format) Without Century 1 2 3 4 11 8 With Century 101 102 103 104 111 108 Format of the Converted Date mm/dd/yy yy.mm.dd dd/mm/yy dd.mm.yy yy/mm/dd hh:mi:ss

Define candidate key, alternate key, composite key. A candidate key is one that can identify each row of a table uniquely. Generally a candidate key becomes the primary key of the table. If the table has more than one candidate key, one of them will become the primary key, and the rest are called alternate keys. A key formed by combining at least two or more columns is called composite key. Data Integrity Enforcing data integrity ensures the quality of the data in the database. For example, if an employee is entered with an employee_id value of 123, the database should not allow another employee to have an ID with the same value. If you have an employee_rating column intended to have values ranging from 1 to 5, the database should not accept a value of 6. If the table has a dept_id

Page of 159

135

MBT Pune
column that stores the department number for the employee, the database should allow only values that are valid for the department numbers in the company. Two important steps in planning tables are to identify valid values for a column and to decide how to enforce the integrity of the data in the column. Data integrity falls into four categories: Entity integrity Domain integrity Referential integrity User-defined integrity

There are several ways of enforcing each type of integrity. Integrity type Entity Recommended options PRIMARY KEY constraint UNIQUE constraint IDENTITY property DEFAULT definition FOREIGN KEY constraint CHECK constraint NOT NULL FOREIGN KEY constraint CHECK constraint All column- and table-level constraints in CREATE TABLE Stored Procedures Triggers

Domain

Referential User-defined

Entity Integrity Entity integrity defines a row as a unique entity for a particular table. Entity integrity enforces the integrity of the identifier column(s) or the primary key of a table (through indexes, UNIQUE constraints, PRIMARY KEY constraints, or IDENTITY properties). Domain Integrity Domain integrity is the validity of entries for a given column. You can enforce domain integrity by restricting the type (through data types), the format (through CHECK constraints and rules), or the range of possible values (through FOREIGN KEY constraints, CHECK constraints, DEFAULT definitions, NOT NULL definitions, and rules). Referential Integrity Referential integrity preserves the defined relationships between tables when records are entered or deleted. In Microsoft SQL Server, referential integrity is based on relationships between foreign keys and primary keys or between foreign keys and unique keys. Referential integrity ensures that key values are consistent across tables. Such consistency requires that there be no references to nonexistent values and that if a key value changes, all references to it change consistently throughout the database. When you enforce referential integrity, SQL Server prevents users from:

Page of 159

136

MBT Pune
Adding records to a related table if there is no associated record in the primary table. Changing values in a primary table that result in orphaned records in a related table. Deleting records from a primary table if there are matching related records.

For example, with the sales and titles tables in the pubs database, referential integrity is based on the relationship between the foreign key (title_id) in the sales table and the primary key (title_id) in the titles table. User-defined Integrity User-defined integrity allows you to define specific business rules that do not fall into one of the other integrity categories. All of the integrity categories support user-defined integrity. Constraints

CHECK Constraints CHECK constraints enforce domain integrity by limiting the values that are accepted by a column. They are similar to FOREIGN KEY constraints in that they control the values that are placed in a column. The difference is in how they determine which values are valid: FOREIGN KEY constraints get the list of valid values from another table, and CHECK constraints determine the valid values from a logical expression that is not based on data in another column. For example, it is possible to limit the range of values for a salary column by creating a CHECK constraint that allows only data that ranges from $15,000 to $100,000. This prevents salaries from being entered beyond the normal salary range.

UNIQUE Constraints You can use UNIQUE constraints to ensure that no duplicate values are entered in specific columns that do not participate in a primary key. While both a UNIQUE constraint and a primary key enforce uniqueness, use a UNIQUE constraint instead of a PRIMARY KEY constraint when you want to enforce the uniqueness of: A column, or combination of columns, that is not the primary key. Multiple UNIQUE constraints can be defined on a table, whereas only one PRIMARY KEY constraint can be defined on a table. A column that allows null values. UNIQUE constraints can be defined on columns that allow null values, whereas PRIMARY KEY constraints can be defined only on columns that do not allow null values.

Page of 159

137

MBT Pune
Jayasudha Primary Key Constraints A table usually has a column or combination of columns whose values uniquely identify each row in the table. This column (or columns) is called the primary key of the table and enforces the entity integrity of the table. You can create a primary key by defining a PRIMARY KEY constraint when you create or alter a table. A table can have only one PRIMARY KEY constraint, and no column that participates in the PRIMARY KEY constraint can accept null values. Because PRIMARY KEY constraints ensure unique data, they are often defined for identity column. When you specify a PRIMARY KEY constraint for a table, Microsoft SQL Server enforces data uniqueness by creating unique index for the primary key columns. This index also permits fast access to data when the primary key is used in queries. If a PRIMARY KEY constraint is defined on more than one column, values may be duplicated within one column, but each combination of values from all the columns in the PRIMARY KEY constraint definition must be unique.

Foreign Key Constraints A foreign key (FK) is a column or combination of columns used to establish and enforce a link between the data in two tables. A link is created between two tables by adding the column or columns that hold one tables primary key values to the other table. This column becomes a foreign key in the second table. You can create a foreign key by defining a FOREIGN KEY constraint when you create or alter a table. Triggers Compared to Other Data Integrity Methods Microsoft SQL Server provides two primary mechanisms for enforcing business rules and data integrity: constraints and triggers. Each has benefits that make them useful in special situations. The primary benefit of triggers is that they can contain complex processing logic that uses Transact-SQL code. Therefore, triggers can support all of the functionality of constraints; however, triggers are not always the best method for a given feature. Entity integrity should always be enforced at the lowest level by indexes that are part of PRIMARY KEY and UNIQUE constraints or are created independently of constraints. Domain integrity should be enforced through CHECK constraints, and referential integrity should be enforced through FOREIGN KEY constraints, assuming their features meet the functional needs of the application. Triggers are most useful when the features supported by constraints cannot meet the functional needs of the application. For example: FOREIGN KEY constraints do not support cascading activities, and they can validate a column value only with an exact match to a value in another column. If your application requires that a delete from one table will also result in a delete of related data in another table, or if the referential

Page of 159

138

MBT Pune
integrity requires something other than an exact match, you must use a trigger. A CHECK constraint can validate a column value only against a logical expression or another column in the same table. If your application requires that a column value be validated against a column in another table, you must use a trigger.

Constraints can communicate about errors only through standardized system error messages. If your application requires (or can benefit from) customized messages and more complex error handling, you must use a trigger. What are constraints? Explain different types of constraints? Constraints enable the RDBMS enforce the integrity of the database automatically, without needing you to create triggers, rule or defaults. Types of constraints: NOT NULL, CHECK, UNIQUE, PRIMARY KEY, FOREIGN KEY. For an explanation of these constraints see books online for the pages titled: "Constraints" and "CREATE TABLE", "ALTER TABLE"

What are defaults? Is there a column to which a default cant be bound? A default is a value that will be used by a column, if no value is supplied to that column while inserting data. IDENTITY columns and timestamp columns cant have defaults bound to them. See CREATE DEFAULT in books online. Whats the difference between a primary key and a unique key? Both primary key and unique enforce uniqueness of the column on which they are defined. But by default primary key creates a clustered index on the column, where are unique creates a nonclustered index by default. Another major difference is that, primary key doesnt allow NULLs, but unique key allows one NULL only. What is a Stored Procedure? Its nothing but a set of T-SQL statements combined to perform a single task of several tasks. Its basically like a Macro so when you invoke the Stored procedure, you actually run a set of statements. Can you give an example of Stored Procedure? sp_helpdb , sp_who2, sp_renamedb are a set of system defined stored procedures. We can also have user defined stored procedures which can be called in similar way. What is an extended stored procedure? Can you instantiate a COM object by using T-SQL? An extended stored procedure is a function within a DLL (written in a programming language like C, C++ using Open Data Services (ODS) API) that can be called from T-SQL, just the way we call normal stored procedures using the EXEC statement. See books online to learn how to create extended stored procedures and how to add them to SQL Server. Yes, you can instantiate a COM (written in languages like VB, VC++) object from T-SQL by using sp_OACreate stored procedure. Also see books online for sp_OAMethod, sp_OAGetProperty,

Page of 159

139

MBT Pune
sp_OASetProperty, sp_OADestroy. For an example of creating a COM object in VB and calling it from T-SQL, see My code library section of this site. what are User-Defined Functions? User-Defined Functions (UDFs) - one or more Transact-SQL statements that can be used to encapsulate code for reuse. User-defined functions cannot make a permanent changes to the data or modify database tables. UDF can change only local objects for this UDF, such as local cursors or variables.

What is the system function to get the current users user id? USER_ID(). Also check out other system functions like USER_NAME(), SYSTEM_USER, SESSION_USER, CURRENT_USER, USER, SUSER_SID(), HOST_NAME(). What is a trigger? - Triggers are basically used to implement business rules. Triggers is also similar to stored procedures. The difference is that it can be activated when data is added or edited or deleted from a table in a database. How many triggers you can have on a table? How to invoke a trigger on demand? Triggers are special kind of stored procedures that get executed automatically when an INSERT, UPDATE or DELETE operation takes place on a table. In SQL Server 6.5 you could define only 3 triggers per table, one for INSERT, one for UPDATE and one for DELETE. From SQL Server 7.0 onwards, this restriction is gone, and you could create multiple triggers per each action. But in 7.0 theres no way to control the order in which the triggers fire. In SQL Server 2000 you could specify which trigger fires first or fires last using sp_settriggerorder. Triggers cant be invoked on demand. They get triggered only when an associated action (INSERT, UPDATE, DELETE) happens on the table on which they are defined. Triggers are generally used to implement business rules, auditing. Triggers can also be used to extend the referential integrity checks, but wherever possible, use constraints for this purpose, instead of triggers, as constraints are much faster. Till SQL Server 7.0, triggers fire only after the data modification operation happens. So in a way, they are called post triggers. But in SQL Server 2000 you could create pre triggers also. Search SQL Server 2000 books online for INSTEAD OF triggers. Also check out books online for inserted table, deleted table and COLUMNS_UPDATED(). There is a trigger defined for INSERT operations on a table, in an OLTP system. The trigger is written to instantiate a COM object and pass the newly insterted rows to it for some custom processing. What do you think of this implementation? Can this be implemented better? Instantiating COM objects is a time consuming process and since you are doing it from within a trigger, it slows down the data insertion process. Same is the case with sending emails from triggers. This scenario can be better implemented by logging all the necessary data into a separate table, and have a job which periodically checks this table and does the needful.

What is a view? - If we have several tables in a db and we want to view only specific columns from specific tables we can go for views. It would also suffice the needs of security some times allowing specfic users to see only specific columns

Page of 159

140

MBT Pune
based on the permission that we can configure on the view. Views also reduce the effort that is required for writing queries to access specific columns every time. What are Distributed partitioned views? Distributed partitioned views allows you to partition tables horizontally across multiple servers. So, you can scale out one database server to a group of database servers that cooperate to provide the same performance levels as a cluster of database servers.

What is an Index? - When queries are run against a db, an index on that db basically helps in the way the data is sorted to process the query for faster and data retrievals are much faster when we have an index. What are the types of indexes available with SQL Server? - There are basically two types of indexes that we use with the SQL Server. Clustered and the Non-Clustered. What is the basic difference between clustered and a non-clustered index? - The difference is that, Clustered index is unique for any given table and we can have only one clustered index on a table. The leaf level of a clustered index is the actual data and the data is resorted in case of clustered index. Whereas in case of non-clustered index the leaf level is actually a pointer to the data in rows so we can have as many non-clustered indexes as we can on the db. Indexes in SQL Server are similar to the indexes in books. They help SQL Server retrieve the data quicker. Indexes are of two types. Clustered indexes and nonclustered indexes. When you create a clustered index on a table, all the rows in the table are stored in the order of the clustered index key. So, there can be only one clustered index per table. Non-clustered indexes have their own storage separate from the table data storage. Non-clustered indexes are stored as B-tree structures (so do clustered indexes), with the leaf level nodes having the index key and its row locater. The row located could be the RID or the Clustered index key, depending up on the absence or presence of clustered index on the table. If you create an index on each column of a table, it improves the query performance, as the query optimizer can choose from all the existing indexes to come up with an efficient execution plan. At the same t ime, data modification operations (such as INSERT, UPDATE, DELETE) will become slow, as every time data changes in the table, all the indexes need to be updated. Another disadvantage is that, indexes need disk space, the more indexes you have, more disk space is used. CREATE INDEX myIndex ON myTable(myColumn)What type of Index will get created after executing the above statement? Non-clustered index. Important thing to note: By default a clustered index gets created on the primary key, unless specified otherwise. What are cursors? - Well cursors help us to do an operation on a set of data that we retreive by commands such as Select columns from table. For example : If we have duplicate records in a table we can remove it by declaring a cursor which would check the records during retreival one by one and remove rows which have duplicate values. When do we use the UPDATE_STATISTICS command? - This command is basically used when we do a large processing of data. If we do a large amount of deletions any modification or Bulk Copy into the tables, we need to basically

Page of 159

141

MBT Pune
update the indexes to take these changes into account. UPDATE_STATISTICS updates the indexes on these tables accordingly. Which TCP/IP port does SQL Server run on? - SQL Server runs on port 1433 but we can also change it for better security. From where can you change the default port? - From the Network Utility TCP/IP properties > Port number.both on client and the server. Can you tell me the difference between DELETE & TRUNCATE commands? - Delete command removes the rows from a table based on the condition that we provide with a WHERE clause. Truncate will actually remove all the rows from a table and there will be no data in the table after we run the truncate command. DELETE TABLE is a logged operation, so the deletion of each row gets logged in the transaction log, which makes it slow. TRUNCATE TABLE also deletes all the rows in a table, but it wont log the deletion of each row, instead it logs the deallocation of the data pages of the table, which makes it faster. Of course, TRUNCATE TABLE can be rolled back. TRUNCATE TABLE is functionally identical to DELETE statement with no WHERE clause: both remove all rows in the table. But TRUNCATE TABLE is faster and uses fewer system and transaction log resources than DELETE. The DELETE statement removes rows one at a time and records an entry in the transaction log for each deleted row. TRUNCATE TABLE removes the data by deallocating the data pages used to store the tables data, and only the page deallocations are recorded in the transaction log. TRUNCATE TABLE removes all rows from a table, but the table structure and its columns, constraints, indexes and so on remain. The counter used by an identity for new rows is reset to the seed for the column. If you want to retain the identity counter, use DELETE instead. If you want to remove table definition and its data, use the DROP TABLE statement. You cannot use TRUNCATE TABLE on a table referenced by a FOREIGN KEY constraint; instead, use DELETE statement without a WHERE clause. Because TRUNCATE TABLE is not logged, it cannot activate a trigger. TRUNCATE TABLE may not be used on tables participating in an indexed view Can you have a nested transaction? Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and @@TRANCOUNT

Can we use Truncate command on a table which is referenced by FOREIGN KEY? - No. We cannot use Truncate command on a table with Foreign Key because of referential integrity. What is the use of DBCC commands? - DBCC stands for database consistency checker. We use these commands to check the consistency of the databases, i.e., maintenance, validation task and status checks. Can you give me some DBCC command options?(Database consistency check) - DBCC CHECKDB - Ensures that tables in the db and the indexes are correctly linked.and DBCC CHECKALLOC - To check that all pages in a db are correctly allocated. DBCC SQLPERF - It gives report on current usage of transaction log in percentage. DBCC CHECKFILEGROUP - Checks all tables file group for any damage.

Page of 159

142

MBT Pune
What command do we use to rename a db? - sp_renamedb oldname , newname Well sometimes sp_reanmedb may not work you know because if some one is using the db it will not accept this command so what do you think you can do in such cases? - In such cases we can first bring to db to single user using sp_dboptions and then we can rename that db and then we can rerun the sp_dboptions command to remove the single user mode. What is the difference between a HAVING CLAUSE and a WHERE CLAUSE? - Having Clause is basically used only with the GROUP BY function in a query. WHERE Clause is applied to each row before they are part of the GROUP BY function in a query. What do you mean by COLLATION? - Collation is basically the sort order. There are three types of sort order Dictionary case sensitive, Dictonary case insensitive and Binary. What is a Join in SQL Server? Can you explain the types of Joins that we can have with Sql Server? Join actually puts data from two or more tables into a single result set. There are three types of joins: Inner Join, Outer Join, Cross Join . Joins are used in queries to explain how different tables are related. Joins also let you select data from a table depending upon data from another table. Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs are further classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULL OUTER JOINS. For more information see pages from books online titled: "Join Fundamentals" and "Using Joins". What is a self join? Explain it with an example. Self join is just like any other join, except that two instances of the same table will be joined in the query. Here is an example: Employees table which contains rows for normal employees as well as managers. So, to find out the managers of all the employees, you need a self join. CREATE TABLE emp ( empid int, mgrid int, empname char(10) ) INSERT emp SELECT 1,2,Vyas INSERT emp SELECT 2,3,Mohan INSERT emp SELECT 3,NULL,Shobha INSERT emp SELECT 4,2,Shridhar INSERT emp SELECT 5,2,Sourabh SELECT t1.empname [Employee], t2.empname [Manager] FROM emp t1, emp t2 WHERE t1.mgrid = t2.empid Heres an advanced query using a LEFT OUTER JOIN that even returns the employees without managers (super bosses) SELECT t1.empname [Employee], COALESCE(t2.empname, No manager) [Manager] FROM emp t1 LEFT OUTER JOIN emp t2 ON t1.mgrid = t2.empid

When do you use SQL Profiler? - SQL Profiler utility allows us to basically track connections to the SQL Server and also determine activities such as which SQL Scripts are running, failed jobs etc..

Page of 159

143

MBT Pune
What is a Linked Server? - Linked Servers is a concept in SQL Server by which we can add other SQL Server to a Group and query both the SQL Server dbs using T-SQL Statements. Can you link only other SQL Servers or any database servers such as Oracle? - We can link any server provided we have the OLE-DB provider from Microsoft to allow a link. For Oracle we have a OLE-DB provider for oracle that microsoft provides to add it as a linked server to the sql server group. Which stored procedure will you be running to add a linked server? sp_addlinkedserver, sp_addlinkedsrvlogin What are the OS services that the SQL Server installation adds? - MS SQL SERVER SERVICE, SQL AGENT SERVICE, DTC (Distribution transac coordinator) SQL SERVER - is for running the databases SQL AGENT - is for automation such as Jobs, DB Maintanance, Backups DTC - Is for linking and connecting to other SQL Servers How do you troubleshoot SQL Server if its running very slow? - First check the processor and memory usage to see that processor is not above 80% utilization and memory not above 40-45% utilization then check the disk utilization using Performance Monitor, Secondly, use SQL Profiler to check for the users and current SQL activities and jobs running which might be a problem. Third would be to run UPDATE_STATISTICS command to update the indexes

Lets say due to N/W or Security issues client is not able to connect to server or vice versa. How do you troubleshoot? - First I will look to ensure that port settings are proper on server and client Network utility for connections. ODBC is properly configured at client end for connection Makepipe & readpipe are utilities to check for connection. Makepipe is run on Server and readpipe on client to check for any connection issues. What are the authentication modes in SQL Server? - Windows mode and mixed mode (SQL & Windows). Where do you think the users names and passwords will be stored in sql server? - They get stored in master db in the sysxlogins table. What is log shipping? Can we do logshipping with SQL Server 7.0 Logshipping is a new feature of SQL Server 2000. We should have two SQL Server - Enterprise Editions. From Enterprise Manager we can configure the logshipping. In logshipping the transactional log file from one server is automatically updated into the backup database on the other server. If one server fails, the other server will have the same db and we can use this as the DR (disaster recovery) plan. Let us say the SQL Server crashed and you are rebuilding the databases including the master database what procedure to you follow? For restoring the master db we have to stop the SQL Server first and then from command line we can type SQLSERVER m which will basically bring it into the maintenance mode after which we can restore the master db.

Page of 159

144

MBT Pune
p Let us say master db itself has no backup. Now you have to rebuild the db so what kind of action do you take? - (I am not sure- but I think we have a command to do it). What is BCP? When do we use it? - BulkCopy is a tool used to copy huge amount of data from tables and views. But it wont copy the structures of the same. What should we do to copy the tables, schema and views from one SQL Server to another? - We have to write some DTS packages for it. p What is a sub-query? When would you use one? p What is a NOLOCK? pWhat are three SQL keywords used to change or set someones permissions? pWhich command using Query Analyzer will give you the version of SQL server and operating system? pWhat is one of the first things you would do to increase performance of a query? For example, a boss tells you that a query that ran yesterday took 30 seconds, but today it takes 6 minutes What are the steps you will take to improve performance of a poor performing query? This is a very open ended question and there could be a lot of reasons behind the poor performance of a query. But some general issues that you could talk about would be: No indexes, table scans, missing or out of date statistics, blocking, excess recompilations of stored procedures, procedures and triggers without SET NOCOUNT ON, poorly written query with unnecessarily complicated joins, too much normalization, excess usage of cursors and temporary tables. Some of the tools/ways that help you troubleshooting performance problems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SET STATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performance monitor, Graphical execution plan in Query Analyzer. Download the white paper on performance tuning SQL Server from Microsoft web site. Dont forget to check out sql-serverperformance.com

pWhat is an execution plan? When would you use it? How would you view the execution plan? p What is the STUFF function and how does it differ from the REPLACE function? p What does it mean to have quoted_identifier on? What are the implications of having it off? pWhat are the different types of replication? How are they used? pWhat is the difference between a local and a global variable? pWhat is the difference between a Local temporary table and a Global temporary table? How is each one used?

Page of 159

145

MBT Pune
What are cursors? Name four types of cursors and when each one would be applied? Cursors allow row-by-row processing of the resultsets. Types of cursors: Static, Dynamic, Forward-only, Keyset-driven. See books online for more information. Disadvantages of cursors: Each time you fetch a row from the cursor, it results in a network roundtrip, where as a normal SELECT query makes only one roundtrip, however large the resultset is. Cursors are also costly because they require more resources and temporary storage (results in more IO operations). Further, there are restrictions on the SELECT statements that can be used with some types of cursors. Most of the times, set based operations can be used instead of cursors. Here is an example: If you have to give a flat hike to your employees using the following criteria: Salary between 30000 and 40000 5000 hike Salary between 40000 and 55000 7000 hike Salary between 55000 and 65000 9000 hike. In this situation many developers tend to use a cursor, determine each employees salary and update his salary according to the above formula. But the same can be achieved by multiple update statements or can be combined in a single UPDATE statement as shown below: UPDATE tbl_emp SET salary = CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000 WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000 WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000 END Another situation in which developers tend to use cursors: You need to call a stored procedure when a column in a particular row meets certain condition. You dont have to use cursors for this. This can be achieved using WHILE loop, as long as there is a unique key to identify each row. For examples of using WHILE loop for row by row processing, check out the My code library section of my site or search for WHILE. Write down the general syntax for a SELECT statements covering all the options. Heres the basic syntax: (Also checkout SELECT in books online for advanced syntax). SELECT select_list [INTO new_table_] FROM table_source [WHERE search_condition] [GROUP BY group_by_expression] [HAVING search_condition] [ORDER BY order_expression [ASC | DESC] ]

SQL Server 2000 advantages? User-Defined Functions. User-Defined Functions (UDFs) - one or more Transact-SQL statements that can be used to encapsulate code for reuse. User-defined functions cannot make a permanent changes to the data or modify database tables. UDF can change only local objects for this UDF, such as local cursors or variables. Distributed partitioned views. Distributed partitioned views allows you to partition tables horizontally across multiple servers. So, you can scale out one database server to a group of database servers that cooperate to provide the same performance levels as a cluster of database servers. Due to distributed partitioned views, SQL Server 2000 now on the first place in the tpc-c tests. See this link for more details: TPC-C tests New data types. There are new data types:

Page of 159

146

MBT Pune
bigint data type sql_variant data type table data type

bigint data type is an 8-byte integer type. sql_variant data type is a type that allows the storage of data values of different data types. table data type is a type that allows applications to store results temporarily for later use. INSTEAD OF and AFTER Triggers. There are INSTEAD OF and AFTER Triggers in SQL Server 2000. INSTEAD OF triggers are executed instead of the INSERT, UPDATE or DELETE triggering action. AFTER triggers are executed after the triggering action. Cascading Referential Integrity Constraints. There are new ON DELETE and ON UPDATE clauses in the REFERENCES clause of the CREATE TABLE and ALTER TABLE statements. The ON DELETE clause controls what actions are taken if you attempt to delete a row to which existing foreign keys point. The ON UPDATE clause defines the actions that are taken if you attempt to update a candidate key value to which existing foreign keys point. The ON DELETE and ON UPDATE clauses have two options: NO ACTION CASCADE

NO ACTION specifies that the deletion/updation fails with an error. CASCADE specifies that all the rows with foreign keys pointing to the deleted/updated row are also deleted/updated. 32 CPU and 64GB Memory Support. SQL Server 2000 Enterprise Edition on the Windows 2000 DataCenter can support up to 32 CPU and up to 64GB physical memory (RAM) on a computer. XML Support. SQL Server 2000 can use XML to insert, update, and delete values in the database, and database engine can return data as Extensible Markup Language (XML) documents. Objects in a Microsoft SQL Server version 7.0 database are stored as a collection of 8 KB pages. This topic describes how the pages for tables and indexes are organized. The data for each table is stored in a collection of 8 KB data pages. Each data page has a 96-byte header containing system information such as the ID of the table that owns the page and pointers to the next and previous pages for pages

Page of 159

147

MBT Pune
linked in a list. A row offset table is at the end of the page. Data rows fill the rest of the page. Table Indexes A Microsoft SQL Server index is a structure associated with a table that speeds retrieval of the rows in the table. An index contains keys built from one or more columns in the table. These keys are stored in a structure that allows SQL Server to find the row or rows associated with the key values quickly and efficiently. If a table is created with no indexes, the data rows are not stored in any particular order. This structure is called a heap. The two types of SQL Server indexes are: Clustered Clustered indexes sort and store the data rows in the table based on their key values. Because the data rows are stored in sorted order on the clustered index key, clustered indexes are efficient for finding rows. There can only be one clustered index per table, because the data rows themselves can only be sorted in one order. The data rows themselves form the lowest level of the clustered index. The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. If a table has no clustered index, its data rows are stored in a heap. Nonclustered Nonclustered indexes have a structure that is completely separate from the data rows. The lowest rows of a nonclustered index contain the nonclustered index key values and each key value entry has pointers to the data rows containing the key value. The data rows are not stored in order based on the nonclustered key. The pointer from an index row in a nonclustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or are clustered. For a heap, a row locator is a pointer to the row. For a table with a clustered index, the row locator is the clustered index key. The only time the rows in a table are stored in any specific sequence is when a clustered index is created on the table. The rows are then stored in sequence on the clustered index key. If a table only has nonclustered indexes, its data rows are stored in a unordered heap. Indexes can be unique, which means no two rows can have the same value for the index key. Otherwise, the index is not unique and multiple rows can share the same key value. There are two ways to define indexes in SQL Server. The CREATE INDEX statement creates and names an index. The CREATE TABLE statement supports the following constraints that create indexes: PRIMARY KEY creates a unique index to enforce the primary key. UNIQUE creates a unique index.

Page of 159

148

MBT Pune
CLUSTERED creates a clustered index. NONCLUSTERED creates a nonclustered index.

A fill factor is a property of a SQL Server index that controls how densely the index is packed when created. The default fill factor usually delivers good performance, but in some cases it may be beneficial to change the fill factor. If the table is going to have many updates and inserts, create an index with a low fill factor to leave more room for future keys. If the table is a read-only table that will not change, create the index with a high fill factor to reduce the physical size of the index, which lowers the number of disk reads SQL Server uses to navigate through the index. Fill factors are only applied when the index is created. As keys are inserted and deleted, the index will eventually stabilize at a certain density. Indexes not only speed up the retrieval of rows for selects, they also usually increase the speed of updates and deletes. This is because SQL Server must first find a row before it can update or delete the row. The increased efficiency of using the index to locate the row usually offsets the extra overhead needed to update the indexes, unless the table has a lot of indexes.

19.

S Q L

S E R V E R

DBA

p How do you use DBCC statements to monitor various aspects of a SQL server installation? p How do you load large data to the SQL server database? p How do you check the performance of a query and how do you optimize it? p How do SQL server 2000 and XML linked? Can XML be used to access data? p What is SQL server agent? p What is referential integrity and how is it achieved? p Difference between server.transfer and server.execute method? p Difference between Function and Stored Procedure? p Can a stored procedure call another stored procedure. If yes what level and can it be controlled? p Can a stored procedure call itself(recursive). If yes what level and can it be controlled.? p Explain the basic concepts of SQL server architecture? pExplain couple pf features of SQL server? pWhat is data integrity? Explain constraints? pExplain sp_configure commands, set commands?

Page of 159

149

MBT Pune
pExplain what are db_options used for? pWhat is the basic functions for master, msdb, tempdb databases? pWhat is a job? pWhat are tasks? pHow would you Update the rows which are divisible by 10, given a set of numbers in column? pHow do you find the error, how can you know the number of rows effected by last SQL statement? How can you get @@error and @@rowcount at the same time? pQuestions regarding Raiseerror? pQuestions on identity? pIf there is failure during updation of certain rows, what will be the state? Whats the maximum size of a row? 8060 bytes. Dont be surprised with questions like what is the maximum number of columns per table. 1024 columns per table. *****pExplain the architecture of SQL Server? pWhat is RAID and what are different types of RAID configurations? RAID stands for Redundant Array of Inexpensive Disks, used to provide fault tolerance to database servers. There are six RAID levels 0 through 5 offering different levels of performance, fault tolerance. MSDN has some information about RAID levels and for detailed information, check out the RAID advisory boards homepage . What are the steps you will take, if you are tasked with securing an SQL Server? Again this is another open ended question. Here are some things you could talk about: Preferring NT authentication, using server, databse and application roles to control access to the data, securing the physical database files using NTFS permissions, using an unguessable SA password, restricting physical access to the SQL Server, renaming the Administrator account on the SQL Server computer, disabling the Guest account, enabling auditing, using multiprotocol encryption, setting up SSL, setting up firewalls, isolating SQL Server from the web server etc. Read the white paper on SQL Server security from Microsoft website. Also check out My SQL Server security best practices . What is a deadlock and what is a live lock? How will you go about resolving deadlocks? Deadlock is a situation when two processes, each having a lock on one piece of data, attempt to acquire a lock on the others piece. Each process would wait indefinitely for the other to release the lock, unless one of the user processes is terminated. SQL Server detects deadlocks and terminates one users process. A livelock is one, where a request for an exclusive lock is repeatedly denied because a series of overlapping shared locks keeps interfering. SQL Server detects the situation after four denials and refuses further shared locks. A livelock also occurs when read transactions monopolize a table or page, forcing a write transaction to wait indefinitely. Check out SET DEADLOCK_PRIORITY and "Minimizing

Page of 159

150

MBT Pune
Deadlocks" in SQL Server books online. Also check out the article Q169960 from Microsoft knowledge base. What is blocking and how would you troubleshoot it? Blocking happens when one connection from an application holds a lock and a second connection requires a conflicting lock type. This forces the second connection to wait, blocked on the first. Read up the following topics in SQL Server books online: Understanding and avoiding blocking, Coding efficient transactions. Explain CREATE DATABASE syntax Many of us are used to creating databases from the Enterprise Manager or by just issuing the command: CREATE DATABAE MyDB. p But what if you have to create a database with two filegroups, one on drive C and the other on drive D with log on drive E with an initial size of 600 MB and with a growth factor of 15%? Thats why being a DBA you should be familiar with the CREATE DATABASE syntax. Check out SQL Server books online for more information. How to restart SQL Server in single user mode? How to start SQL Server in minimal configuration mode? SQL Server can be started from command line, using the SQLSERVR.EXE. This EXE has some very important parameters with which a DBA should be familiar with. -m is used for starting SQL Server in single user mode and -f is used to start the SQL Server in minimal configuration mode. Check out SQL Server books online for more parameters and their explanations. As a part of your job, what are the DBCC commands that you commonly use for database maintenance? DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC, DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But there are a whole load of DBCC commands which are very useful for DBAs. Check out SQL Server books online for more information. What are statistics, under what circumstances they go out of date, how do you update them? Statistics determine the selectivity of the indexes. If an indexed column has unique values then the selectivity of that index is more, as opposed to an index with non-unique values. Query optimizer uses these indexes in determining whether to choose an index or not while executing a query. Some situations under which you should update statistics: 1) If there is significant change in the key values in the index 2) If a large amount of data in an indexed column has been added, changed, or removed (that is, if the distribution of key values has changed), or the table has been truncated using the TRUNCATE TABLE statement and then repopulated 3) Database is upgraded from a previous version. Look up SQL Server books online for the following commands: UPDATE STATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROP STATISTICS, sp_autostats, sp_createstats, sp_updatestats .

What are the different ways of moving data/databases between servers and databases in SQL Server?

Page of 159

151

MBT Pune
There are lots of options available, you have to choose your option depending upon your requirements. Some of the options you have are: BACKUP/RESTORE, dettaching and attaching databases, replication, DTS, BCP, logshipping, INSERT SELECT, SELECTINTO, creating INSERT scripts to generate data. Explain different types of BACKUPs avaialabe in SQL Server? Given a particular scenario, how would you go about choosing a backup plan? Types of backups you can create in SQL Sever 7.0+ are Full database backup, differential database backup, transaction log backup, filegroup backup. Check out the BACKUP and RESTORE commands in SQL Server books online. Be prepared to write the commands in your interview. Books online also has information on detailed backup/restore architecture and when one should go for a particular kind of backup. What is database replication? What are the different types of replication you can set up in SQL Server? Replication is the process of copying/moving data between databases on the same or different servers. SQL Server supports the following types of replication scenarios: Snapshot replication Transactional replication (with immediate updating subscribers, with queued updating subscribers) Merge replication See SQL Server books online for indepth coverage on replication. Be prepared to explain how different replication agents function, what are the main system tables used in replication etc. How to determine the service pack currently installed on SQL Server? The global variable @@Version stores the build number of the sqlservr.exe, which is used to determine the service pack installed. To know more about this process visit SQL Server service packs and versions.

20. S Q L S E R V E R

L A B

E X C E R C I S E S.

****PDelete all duplicated from query?

Given an Employee table, how would you find out the second highest salary ? Select max(sal) from emp where sal not in (select top n 1 sal from emp group by sal order by sal desc) Here n = the no for which you wish to display e.g. if you want 3rd highest sal then n = 3 Loading Controls Programatically Windows Application: mainPanel.Controls.Add (viewControl); Web Application:

Page of 159

152

MBT Pune
UserControl1 uc=(UserControl1)this.page.LoadControl(usercontrol.ascx); PlaceHolder.Add(uc);

What are Pure Virtual Functions?


Pure Virtual functions are Virtual functions with no implementation code in them. They are declared by setting the Virtual function equals 0. Pure Virtual functions serve the purpose of declaring as class as Abstract- a class that can not have an object of itself. Code Example:
class Vehicle { public: Vehicle(){} Virtual void GetRegistration() = 0; };

Singleton - Creational Design Pattern: Intent (Introduction): There are times, when one need to have a class which can be only instantiated once. Singleton Design Pattern addresses to such situation by providing a design for such classes (known as Singleton class). Description: There are at least two solutions or scenario for implementing Singleton Class. The first solution says that there should be only one shared object and reference to that object should be available only through static method like GetInstance() while making the constructor private. A number of clients can be awarded the reference to such shared object. The second solution says that the constructor should be public (as it appears in most cases) but once an object has been instantiated, an exception should be thrown for each successive constructor call; thus limiting the class to only one object. An Example: First case Singleton can be used in a data repository or data collection where creation of more than one object can be resource wastage. Hence each client is given a reference to a single shared object to operate on. While the second case Singleton can be used in locking mechanisms. Once a client has got the object, no other client can have an object. Class Diagram:

Page of 159

153

MBT Pune

Implementation: Let us first discuss the code of first case Singleton which is like: class Singleton { private static Singleton instance; private static int numOfReference; private string code; private Singleton() { numOfReference = 0; code = "Maasoom Faraz"; } public static Singleton GetInstance() { if(instance == null) { instance = new Singleton(); } numOfReference++; return instance; } public static int Reference { get { return numOfReference; } } public string Code { get { return code; } set { code = value;} }

There are 3 fields in the Singleton class. Static field instance is a reference to shared object in this Singleton class. Static field numOfReference is an integer variable to hold the number of current references to the single shared object of Singleton class. Code is a string value, it is used to demonstrate that the object is shared b/w references and change made to this field through one reference can be realized through other reference. The constructor is made private and used to initialize the numOfReference and default value of code. GetInstance() method checks the instance, if it is null then it assign it an instance of Singleton otherwise return the old reference. GetInstance() also increments the numOfReference each time it is called to keep

Page of 159

154

MBT Pune
track of current number of reference to our shared instance. Property Reference returns the number of reference referencing our shared object while Code property can be used to set/get the code string of shared object. The second case Singleton class (Singleton2) looks like: class Singleton2 { private static int numOfInstance = 0; public Singleton2() { if(numOfInstance == 0) { Console.WriteLine("\r\nCreating First Object of Singleton2 class..."); numOfInstance++; } else { throw new Exception("This class is Singleton, + so only one object of it can be instantiated."); } } } Here we make the constructor public and use a private field numOfInstance which is incremented for each constructor call. If numOfInstance is zero (no object is yet instantiated), a new object is allowed to made. But, if this value is not zero (there is already an object of Singleton2 class, an exception is thrown. Now let us try these with Main() method, the code in main is like: static void Main(string[] args) { Singleton obj1 = Singleton.GetInstance(); obj1.Code = "Faraz Rasheed"; Console.WriteLine("No. of references : " + Singleton.Reference); Console.WriteLine("First Objects code: " + obj1.Code); Singleton obj2 = Singleton.GetInstance(); Console.WriteLine("No. of references : " + Singleton.Reference); Console.WriteLine("Second Objects code: " + obj2.Code); Singleton2 obj3 = new Singleton2(); Singleton2 obj4 = new Singleton2(); } First we called GetInstance() and took the reference to the new object in obj1. The code for this object is changed to Faraz Rasheed which was Maasoom Faraz by default. Then, we check for number of references to this object and code set for this. Next, we get another reference to this object through GetInstance() in obj2. We again check the number of references and code using this reference. If both the references are pointing to the same shared object, the number of references now should be 2 while the code should also be Faraz Rasheed (remember if obj2 points to a new object then code would have been Maasoom Faraz, the default one) which is shown in the output. We also made an object of Singleton2. When constructor is called for the first reference (obj3), the new object is instantiated printing the message on Console.

Page of 159

155

MBT Pune
But when another instance of Singleton2 is attempted to be made through obj4, an exception is thrown saying Singleton class can only be instantiated once. Sample output from the program is: No. of references : 1 First Objects code: Faraz Rasheed No. of references : 2 Second Objects code: Faraz Rasheed Creating First Object of Singleton2 class... Unhandled Exception: System.Exception: This class is Singleton,so only one objec t of it can be instantiated. at Singleton.Singleton2..ctor() in c:\documents and settings\msff\my document s\visual studio projects\singleton\class1.cs:line 75 at Singleton.Client.Main(String[] args) in c:\documents and settings\msff\my documents\visual studio projects\singleton\class1.cs:line 20 Press any key to continue The complete source code is also attached with the article. Take a look at it to understand it to full. Benefits Achieved Through This Pattern: By using Singleton Design Pattern, it is possible for a programmer to control the instantiation of class by allowing only single object to be instantiated when desirable.

Database Normalization Part 1


When creating a database, it is often useful to learn from the mistakes of others. Within the Relational Database Model, a set of rules has been established to aid in the design of tables that are meant to be connected through relationships. This set of rules is known as Normalization. In this Tutorial we will address the first of five normal forms, and the ways in which normalizing your database will help prevent problems as you add to it. The concept of database normalization is not unique to any particular Relational Database Management System. It can be applied to any of several implications of relational databases including Microsoft Access, dBase, Oracle,

Page of 159

156

MBT Pune etc. The benefits of Normalizing your database include:


Avoiding repetitive entries</li> Reducing required storage space</li> Preventing the need to restructure existing tables to accommodate new data.</li> Increased speed and flexibility of queries, sorts, and summaries.</li>

There are five normal forms in all, each progressively building on its predecessor. In order to reach peak efficiency, it is recommended that relational databases be normalized through at least the third normal form. In order to normalize a database, each table should have a primary key field that uniquely identifies each record in that table. A primary key can consist of a single field (an ID Number field for instance) or a combination of two or more fields that together make a unique key (called a multiple field primary key).

The First Normal Form


For a table to be in first normal form, data must be broken up into the smallest units possible. For example, the following table is not in first normal form. Name Sally Singer Address 123 Broadway New York, NY, 11234 Phone (111) 2223345

Jason 456 Jolly Jumper St. (222) 334Jumper Trenton NJ, 11547 5566 To conform to first normal form, this table would require additional fields. The name field should be divided into first and last name and the address should be divided by street, city state, and zip like this. ID First Last Street City State Zip NY Phone

564 Sally Singer 123 Broadway New

11234 (111) 222-

Page of 159

157

MBT Pune York 565 Jason Jumper 3345

456 Jolly (222) 334Trenton NJ 11547 Jumper St. 5566 In addition to breaking data up into the smallest meaningful values, tables in first normal form should not contain repetitions groups of fields such as in the following table. Time Time Client Time Client 2 1 2 3 3 14 hrs Taggarts 26 hrs Kilroy Inc. 9 hrs

Rep Client Representative ID 1 TS89 Gilroy Gladstone US Corp.

RKMary Mayhem Italiana 67 hrs Linkers 2 hrs 56 The problem here is that each representative can have multiple clients not all will have three. Some may have less as is the case in the second record, tying up storage space in your database that is not being used, and some may have more, in which case there are not enough fields. The solution to this is to add a record for each new piece of information. Rep ID Rep First Rep Last Name Name Gladstone Gladstone Gladstone Mayhem Client Time With Client

TS-89 Gilroy TS-89 Gilroy TS-89 Gilroy RK56 Mary

US Corp 14 hrs Taggarts 26 hrs Kilroy Inc. Italiana 9 hrs 67 hrs

RKMary Mayhem Linkers 2 hrs 56 Notice the splitting of the first and last name fields again. This table is now in first normal form. Note that by avoiding repeating groups of fields, we have created a new problem in that there are identical values in the primary key field, violating the rules of the primary key. In order to remedy this, we need to have some other way of identifying each Page of 159 158

MBT Pune record. This can be done with the creation of a new key called client ID. Rep ID* Rep First Name Rep Last Name Gladstone Gladstone Gladstone Mayhem Client ID* 978 665 782 221 Client US Corp Kilroy Inc. Italiana Time With Client 14 hrs

TS-89 Gilroy TS-89 Gilroy TS-89 Gilroy RK-56 Mary

Taggarts 26 hrs 9 hrs 67 hrs

RK-56 Mary Mayhem 982 Linkers 2 hrs This new field can now be used in conjunction with the Rep ID field to create a multiple field primary key. This will prevent confusion if ever more than one Representative were to serve a single client.

Page of 159

159

Das könnte Ihnen auch gefallen