DotNET

46
Microsoft .NET .NET Framework: .NET framework is an environment that facilitates Object Oriented Programming Model for multiple languages. It wraps Operating System and insulates Software Development from many Operating System specific tasks such as file handling, memory allocation & management. It has two main components CLR (Common Language Runtime) and .Net BCL (Base Class Libraries). As you can see in Figure, the .NET Framework sits on top of the operating system, which can be a few different flavors of Windows and consists of a number of components. .NET is essentially a system application that runs on Windows. The most important component of the Framework is something called the CLR. If you are a Java programmer, think of the CLR as the .NET equivalent of the Java Virtual Machine (JVM). If you don't know Java, think of the CLR as the heart and soul of the .NET architecture. At a high level, the CLR activates objects, performs security checks on them, lays them out in memory, executes them, and garbage-collects them. Conceptually, the CLR and the JVM are similar in that they are both runtime infrastructures that abstract the underlying platform differences. However, while the JVM currently supports just the Java language, the CLR supports all languages that can be represented in the Common Intermediate Language (CIL). The JVM executes bytecode, so it could technically support many different languages, too. Unlike Java's bytecode, though, IL is never interpreted. Another conceptual difference between the two infrastructures is that Java code runs on multiple platforms with a JVM, whereas .NET code runs only on the Windows platforms with the CLR (at the time of this writing). Microsoft has submitted the Common Language Infrastructure (CLI), which is functional a subset of the CLR, to ECMA, so a third-party vendor could theoretically implement a CLR for a platform other than Windows. An assembly is the basic unit of deployment and versioning, consisting of a manifest, a set of one or more modules, and an optional set of resources.

Transcript of DotNET

Microsoft .NET.NET Framework: .NET framework is an environment that facilitates Object Oriented Programming Model for multiple languages. It wraps Operating System and insulates Software Development from many Operating System specific tasks such as file handling, memory allocation & management. It has two main components CLR (Common Language Runtime) and .Net BCL (Base Class Libraries).

As you can see in Figure, the .NET Framework sits on top of the operating system, which can be a few different flavors of Windows and consists of a number of components. .NET is essentially a system application that runs on Windows.

The most important component of the Framework is something called the CLR. If you are a Java programmer, think of the CLR as the .NET equivalent of the Java Virtual Machine (JVM). If you don't know Java, think of the CLR as the heart and soul of the .NET architecture. At a high level, the CLR activates objects, performs security checks on them, lays them out in memory, executes them, and garbage-collects them. Conceptually, the CLR and the JVM are similar in that they are both runtime infrastructures that abstract the underlying platform differences. However, while the JVM currently supports just the Java language, the CLR supports all languages that can be represented in the Common Intermediate Language (CIL). The JVM executes bytecode, so it could technically support many different languages, too. Unlike Java's bytecode, though, IL is never interpreted. Another conceptual difference between the two infrastructures is that Java code runs on multiple platforms with a JVM, whereas .NET code runs only on the Windows platforms with the CLR (at the time of this writing). Microsoft has submitted the Common Language Infrastructure (CLI), which is functional a subset of the CLR, to ECMA, so a third-party vendor could theoretically implement a CLR for a platform other than Windows.

An assembly is the basic unit of deployment and versioning, consisting of a manifest, a set of one or more modules, and an optional set of resources.

.NET Portable Executable File:A Windows executable, EXE or DLL, must conform to a file format called the PE file format, which is a derivative of the Microsoft Common Object File Format (COFF). Both of these formats are fully specified and publicly available. The Windows OS knows how to load and execute DLLs and EXEs because it understands the format of a PE file. Given this, any compiler that wants to generate Windows executables must obey the PE/COFF specification.

Standard Windows PE files are divided into two major sections. The first section includes the PE/COFF headers that reference the contents within the PE file. In addition to the header section, the PE file holds a number of native image sections, including the .data, .rdata, .rsrc , and .text sections. These are the standard sections of a typical Windows executable, but Microsoft's C/C++ compiler allows you to add your own custom sections into the PE file using a compiler pragma statement. For example, you

can create your own data section to hold encrypted data that only you can read. Taking advantage of this ability, Microsoft has added a few new sections to the normal PE file specifically to support the CLR's functionality. The CLR understands and manages the new sections. For example, the CLR will read these sections and determine how to load classes and execute your code at runtime.

The sections that Microsoft has added to the normal PE format are the CLR header and the CLR data sections. While the CLR header stores information to indicate that the PE file is a .NET executable, the CLR data section contains metadata and IL code, both of which determine how the program will be executed.

Metadata

Metadata is machine -readable information about a resource, or "data about data." Such information might include details on content, format, size, or other characteristics of a data source. In .NET, metadata includes type definitions, version information, external assembly references, and other standardized information.

In order for two components, systems, or objects to interoperate with one another, at least one must know something about the other. In COM, this "something" is an interface specification, which is implemented by a component provider and used by its consumers.

In .NET, metadata is a common mechanism or dialect that the .NET runtime, compilers, and tools can all use. Microsoft .NET uses metadata to describe all types that are used and exposed by a particular .NET assembly. Metadata includes descriptions of an assembly and modules, classes, interfaces, methods, properties, fields, events, global methods, and so forth.

.NET assemblies are deployable units and manifests are the metadata that describes the assemblies.

IL Code:

An assembly contains the IL code that the CLR executes at runtime. The IL code typically uses types defined within the same assembly, but it also may use or refer to types in other assemblies. There is one caveat: each assembly can have at most one entry point, such as DllMain( ), WinMain( ), or Main( ). You must follow this rule because when the CLR loads an assembly, it searches for one of these entry points to start assembly execution.

There are four types of assemblies in .NET:

Static assemblies: These are the .NET PE files that you create at compile time. You can create static assemblies using your favorite compiler: csc, cl, or vbc.Dynamic assemblies: These are PE-formatted, in-memory assemblies that you dynamically create at runtime using the classes in the System.Reflection.Emit namespace.Private assemblies: These are static assemblies used by a specific application.Public or shared assemblies: These are static assemblies that must have a unique shared name and can be used by any application.

Side-by-Side Execution:

The CLR allows any versions of the same-shared DLL (shared assembly) to execute at the same time, on the same system, and even in the same process. This concept is known as side-by-side execution.

Manifests: Assembly MetadataAn assembly manifest is metadata that describes everything about the assembly, including its identity, a list of files belonging to the assembly, references to external assemblies, exported types, exported resources, and permission requests. In short, it describes all the details that are required for component

plug-and-play. Since an assembly contains all these details, there's no need for storing this type of information in the registry, as in the COM world.

An assembly can be a single-module assembly or a multi-module assembly. In a single-module assembly, everything in a build is clumped into one EXE or DLL, an example of which is the hello.exe application that we developed earlier. This is easy to create because a compiler takes care of creating the single -module assembly for you.

A multi-module assembly is one that contains many modules and resource files. To create it you have to use the Assembly Linker (al.exe) that is provided by the .NET SDK. This tool takes one or more IL or resource files and spits out a file with an assembly manifest.

Any .NET language may be converted into IL, so .NET supports multiple languages and perhaps multiple platforms in the future (as long as the target platforms have a CLR).

The Common Type System (CTS):Because .NET treats all languages as equal, a class written in C# should be equivalent to a class written in VB.NET, and an interface defined in Managed C++ should be exactly the same as one that is specified in managed COBOL. Languages must agree on the meanings of these concepts before they can integrate with one another. In order to make language integration a reality, Microsoft has specified a common type system to which every .NET language must abide.

Interfaces: Interfaces support exactly the same concept as a C++ abstract base class (ABC) with only pure virtual functions. An ABC is a class that declares one or more pure virtual functions and thus cannot be instantiated. If you know COM or Java, interfaces in .NET are conceptually equivalent to a COM or Java interface. You specify them, but you don't implement them. A class that derives from your interface must implement your interface. An interface may contain methods, properties, indexers, and events. In .NET, a class can derive from multiple interfaces.

The Common Language Specification (CLS):Microsoft has published the Common Language Specification (CLS). The CLS specifies a series of basic rules that are required for language integration. Since Microsoft provides the CLS that spells out the minimum requirements for being a .NET language, compiler vendors can build their compilers to the specification and provide languages that target .NET. Besides compiler writers, application developers should read the CLS and use its rules to guarantee language interoperation.

CLR Execution:.Net PE Files(Metadata And IL) >> Class Loader >> Verifier >> JIT >> Managed Native Code

Once the class loader has found and loaded the target class, it caches the type information for the class so that it doesn't have to load the class again for the duration of this process.

The verifier is responsible for verifying that:1. The metadata is well formed, meaning the metadata must be valid.2. The IL code is type safe, meaning type signatures are used correctly.

The JIT compilers convert IL to native code so that it can execute on the target operating system. For optimization reasons, JIT compilation occurs only the first time a method is invoked. Recall that the class loader adds a stub to each method during class loading. At the first method invocation, the VEE reads the information in this stub, which tells it that the code for the method has not been JIT compiled. At this indication, the JIT compiler compiles the method and injects the address of the managed native method into this stub. During subsequent invocations to the same method, no JIT compilation is needed because each time the VEE goes to read information in the stub, it sees the address of the native method. Because the JIT compiler only performs its magic the first time a method is invoked, the methods you don't need at runtime will never be JIT compiled. The compiled, native code lies in

memory until the process shuts down and until the garbage collector clears off all references and memory associated with the process. This means that the next time you execute the process or component, the JIT compiler will again perform its magic.

If you want to avoid the cost of JIT compilation at runtime, you can use a special tool called ngen, which compiles your IL during installation and setup time. Using ngen, you can JIT-compile the code once and cache it on the machine so that you can avoid JIT compilation at runtime (this process is referred to as Pre-JITting). In the event that the PE file has been updated, you must PreJIT the PE file again. Otherwise, the CLR can detect the update and dynamically command the appropriate JIT compiler to compile the assembly.

All .NET assemblies are essentially binary components. You can treat each .NET assembly as a component that you can plug into another component or application, without the need for source code, since all the metadata for the component is stored inside the .NET assembly. While you have to perform a ton of plumbing to build a component in COM, you need to perform zero extra work to get a component in .NET, as all .NET assemblies are components by nature. Remember, we're using the term "component" as a binary, deployable unit, not as a COM class.

Shared Components:Unlike application-private assemblies, shared assemblies - ones that can be used by any client application - must be published or registered in the system Global Assembly Cache (GAC). When you register your assemblies against the GAC, they act as system components, such as a system DLL that every process in the system can use. A prerequisite for GAC registration is that the component must possess originator and version information. In addition to other metadata, these two items allow multiple versions of the same component to be registered and executed on the same machine. Again, unlike COM, we don't have to store any information in the system registry for clients to use these shared assemblies.

Object Pooling:A pool is technical term that refers to a group of resources, such as connections, threads, and objects. Putting a few objects into a pool allows hundreds of clients to share these few objects (you can make the same assertion for threads, connections, and other objects). Pooling is therefore a technique that minimizes the use of system resources, improves performance, and helps system scalability.

ADO.NET Architecture:Microsoft ADO.NET's object model encompasses two distinct groups of classes: content components and managed-provider components. The content components include the DataSet class and other supporting classes such as DataTable, DataRow, DataColumn, and DataRelation. These classes contain the actual content of a data exchange. The managed-provider components assist in data retrievals and updates. Microsoft provides two managed providers in its current release of ADO.NET: OLE DB and SQL. The OLE DB managed provider comes with OleDbConnection, OleDbCommand, OleDbParameter, and OleDbDataReader. The SQL Server managed provider comes with a similar set of objects, whose names start with SqlClient instead of OleDb. Developers can use the connection, command, and data reader objects to directly manipulate data.

We might think that setting up and tearing down connections is not a good idea since the cost of establishing a connection is usually high. This is a concern only in the absence of connection pooling. ADO.NET automatically keeps connections to a data source in a pool, so when an application thinks it is tearing down a connection, it's actually returning it to the resource pool. This allows connections to be reused, avoiding the cost of reconstructing new connections from scratch.

Because ADO.NET framework classes are managed code, developers can inherit and extend these classes to their custom needs.

A data reader is a new object providing fast, forward-only, and read-only access to data. This is similar to an ADO Recordset with server-side, forward - only, and read-only cursor types. Since this is a server

–side cursor, the connection to the server is open throughout the reading of data.

Even though each DataAdapter maps only one DataTable in the DataSet, you can have multiple adapters to fill the DataSet object with multiple DataTables. Managed Code: The .Net framework provides several core run-time services to the programs that run within it. For example exception handling and security. For these services to work the code must provide a minimum level of information to runtime. Such code is called Managed Code.

Managed Data:This is data for which memory management is done by .Net runtime’s garbage collector this includes tasks for allocation de-allocation. We can call garbage collector to collect un-referenced data by executing System.GC.Collect().

What is an Assembly?Assemblies are fundamental building blocks of .Net Framework. They contain the type and resources that are useful to make an application. Assemblies enables code reuse, version control, security and deployment. An assembly consist of: Manifest , Type Metadata, MSIL and resource file.

Assemblies are Private and Shared. Private are used for a single application and installed in application’s install directory or its sub-directory. Shared assembly is one that can be referenced by multiple application and resides in GAC(local cache for assemblies managed by .Net Framework). gacutil /i myDll.dll can see and %windir%\assembly

Metadata and Manifest:Manifest describes the assembly itself. Assembly name, version, culture, strong name, list of files, type reference and reference assembly. While Metadata describes contents within the assembly like classes, namespaces, interfaces, scope, properties, methods and their parameters etc.

Application Domain: It is a virtual process that serves to isolate an application. All object created within the same application scope are created within same application domain.

Garbage Collection: It is Automatic Memory Manager for .Net Framework. It manages the memory allocated to .Net Framework.When a variable is defined it gets a space in memory (stack) and when an object is created memory for the object is allocated in heap. When an object is assigned to a variable it increments the reference counts for the object and when program control comes out of the function the scope of variable gets ended Or NULL is assigned to variable it decrements the reference count of object by 1. When reference count of one object becomes zero GC acts call destructor of object and then releases the memory acquired by the object.

Can .Net Components can be used from a COM? Yes, can be used. But There are few restrictions such as COM needs an object to be created. So static methods, parameterized constructor can not be used from COM. These are used by COM using a COM Callable Wrapper (CCW). TlbImp.exe and TlbExp.exe

How does .NET Remoting work?It involves sending messages along channels. Two of the standard channels are HTTP and TCP. TCP is for LANs only and HTTP can be used on LANs or WANs (internet). TCP uses binary serialization and HTTP uses SOAP (.Net Runtime Serialization SOAP Formatter).

There are 3 styles of remote access:SingleCall: Each incoming request is handled by new instance.Singleton: All requests are served by single server object.Client-Activated Object: This is old state-full DCOM model. Where client receives reference to the remote object and keep until it finished with it.

DLL-HELL: Situations where we have to put same name Dlls in single directory where are Dlls are of different versions.

Versioning: MajorVersion.MinorVersion.BuildNumber.Revision

Boxing and Un-Boxing:Implicit(automatic) conversion of value type to reference type is known as Boxing And Explicit (manual) conversion of Reference type to value type is said to be Un-boxing. (conversion of Integer variable to object type)

.Net Object Oriented Programming Concepts

Class: Class is concrete representation of an entity. It represents a group of objects, which posses similar attributes and behavior.Provides Abstraction and Encapsulations. A category name that can be given to group of objects of similar kind.

Object: Object represents/resembles a Physical/real entity. An object is simply something you can give a name.

Object Oriented Programming: It is a Style of programming that represents a program as a system of objects and enables code-reuse.

Encapsulation: Binding of attributes and behaviors. Hiding the implementation and exposing the functionality.

Abstraction: Hiding the complexity. Defining communication interface for the functionality and hiding rest of the things. In .Net destructor can not be abstract. Can define Either Finalize / Destructor. For Destructor access specifiers can not be assigned. It is Private.

Overloading: Adding a new method with the same name in same/derived class but with different number/types of parameters. Implements Polymorphism.

Overriding: When we need to provide different implementation than the provide by base class, We define the same method with same signatures in the derived class. Method must be Protected/Protected-Friend/Public for this purpose. (Base class routine can be called by Mybase.Method, base.Method).

Shadowing: When the method is defined as Final/sealed in base class and not overridable and we need to provide different implementation for the same. We define method with Shadows/new.

Inheritance: Gives you ability to provide is-a relationship. Acquires attributes and behaviors from another. When a class acquires attributes and behaviors from another class. (must not be Final or sealed class in .Net)

Abstract Class: Instance can not be created. Optionally can have one or more abstract methods but not necessary. Can provide body to Classes.

Interface: What a Class must do, But not how-to. Bridge for the communication when the caller does not know to whom he is calling. Describes externally visible behavior of element.Only Public members which defines the means of the communication with the outer world. Can-be-Used-As Relationship. Can not contain data but can declare property. There can be no implementation. Interface can be derived from another interface.

Polymorphism: Mean by more than one form. Ability to provide different implementation based on different no./type of parameters. A method behaves differently based on the different input parameters. Does not depend on the Return-Type.

Pure-Polymorphism: Make an method abstract/virtual in base class. Override it in Derived Class. Declare a variable of type base class and assign an object of derived class to it. Now call the virtual/abstract method. The actual method to be called is decided at runtime.

Early-Binding: Calling an non-virtual method decides the method to call at compile time is known as Early-Binding.

Late-Binding: Same as pure-polymorphism.

Identifiers/Access Specifies and scope:VB.NET: Private, Protected, Friend, Protected Friend, Public.C#: private, protected, internal, protected internal, public.

What is a Delegate?A strongly typed function pointer. A delegate object encapsulates a reference to a method. When actual function needs to be called will be decided at run-time.

Static Variable and Its Life-Time:VB.NET: Public Shared VAR As Type.C#: public static Type VAR;Life time is till the class is in memory.

Constructor: Special Method Always called whenever an instance of the class is created.

Destructor/Finalize: Called by GC just before object is being reclaimed by GC.

ASP.Net

Different Types of Caching?Output Caching: stores the responses from an asp.net page.Fragment Caching: Only caches/stores the portion of page (User Control)Data Caching: is Programmatic way to Cache objects for performance.

Authentication and Authorization:Authentication is identifying/validating the user against the credentials (username and password) and Authorization performs after authentication. Authorization allowing access of specific resource to user.

Different Types of Directives:Page, Register, Control, OutputCache, Import, Implements, Assembly, Reference

Difference between Server-Side and Client-Side:Server-Side code is executed on web-server and does not transmitted to client, while client-side code executed on client(browser) and is rendered to client along with the content.

Difference Server.Transfer and Response.Redirect:Both ends the processing for the current request immediately. Server.Transfer start executing the another resource specified as parameter without acknowledgement to client(browser) while Response.Redirect intimate client that your requested resource is available at this location and then client request for that resource.

Different Types of Validators and Validation Controls:RequiredFieldValidator, RangeValidator, RegularExpressionValidator, CompareValidator, CustomValidator, ValidationSummary

How to Manage State in ASP.Net?Client based: ViewState, QueryString and Cookies Server based: Session, Application.

Difference between User Control and Custom Control:CUSTOM Controls are compiled code (Dlls), easier to use, difficult to create, and can be placed in toolbox. Drag and Drop controls. Attributes can be set visually at design time. Can be used by Multiple Applications (If Shared Dlls), Even if Private can copy to bin directory of webApp add reference and use. Normally designed to provide common functionality independent of consuming Application.

3 Types of Session State Modes?InProc(cookieless, timeout),StateServer (Server, Port stateConnectionString="tcpip=server:port"),SQLServer (sqlconnectionstring) and Off.

What is ViewState and How it is managed, Its Advantages/Benefits?ViewState is a special object that ASP.NET uses to maintain the state of page and all webcontrols/ServerControls within it. It is in this object preserves the states of various FORM elements during post-backs. It is rendered to client(browser) as a Hidden variable __VIEWSTATE under <form>tag. We can also add custom values to it.

What is web.config and machine.config:machine.config is default configuration for all applications running under this version, located in %WinDir%\Microsfot.Net\Framework\Version. Settings can be overridden by Web.Config for an specific application Web.Config resides in application’s root/virtual root and exists in sub-sequent folders.

Role of Global.asax:Optional file contains the code to handle Application level events raised by ASP.Net or By HttpModule. This file resides in application root directory. Application_Start, _End, _AuthenticateRequest, _Error, Session_Start, _End, BeginRequest, EndRequest. This file is parsed and compiled into dynamically generated class derived from HttpApplication.

Page Life Cycle:Init, LoadViewState, LoadPostBackData, Load, RaisePostBackDataChangedEvent, RaisePostBackEvents, Pre-Render, SaveViewState, Render, Unload, (IpostBackDataChangedEventHandler and IpostBackEventHandler) Error, CommitTransaction, AbortTransaction, Abort inetinfo.exe, aspnet_isapi.dll aspnet_wp.exe, HttpModules (OutputCache, Session, Authentication, Authorization, Custom Modules Specified) and Then HttpHandlers PageHandlerFactory for *.aspx

Can the action attribute of a server-side <form>tag be set to a value and if not how can you possibly pass data from a form to a subsequent Page?No assigning value will not work because will be overwritten at the time of rendering. We can assign value to it by register a startup script which will set the action value of form on client-side. Rest are Server.Transfer and Response.Redirect.

ASP.Net List Controls and differentiate between them?RadioButtonList, CheckBoxList, DropDownList, Repeater, DataGrid, DataList

Type Of Code in Code-Behind class:Server-Side Code.

What might be best suited to place in the Application_Start and Session_Start: Application level variables and settings initialization in App_StartUser specific variables and settings in Session_Start

Difference between inline and code-behind. Which is best?Inline is mixed with html and code-behind is separated. Use code-behind, Because Inline pages are loaded, parsed, compiled and processed at each first request to page and remains in compiled code remains in cache until it expires, If expires it again load, parse and compile While code-behind allows to be pre-compiled and provide better performance.

Which Template must provide to display data in Repeater?ItemTemplate.

How to Provide Alternating Color Scheme in Repeater?AlternatingItemTemplate

What base class all Web Forms inherit from?System.Web.UI.Page

What method do you use to explicitly kill a user’s Session?HttpContext.Current.Session.Abandon()

How do you turn off cookies in one page of your asp.net application?We will not use it. But can not turn off cookies from server. To allow or not is a client side functionality.

Which two properties are on every validation control?ControlToValidate and Text, ErrorMessage

How do you create a permanent cookie?Set expires property to Date.MaxValue (HttpCookie.Expires = Date.MaxValue)

What is the standard you use to wrap up a call to a Web Service?SOAP

Which method do you use to redirect to user to another page without performing a round trip to Client? Server.Transfer(“AnotherPage.aspx”)

What is transport protocol you use to call a Web-Service SOAP?HTTP-POST

A Web Service can only be written in .NET?

FALSE

Where on internet would you look for Web services?www.uddi.org

How many classes can a single .NET DLL contain?Unlimited

How many namespaces are in .NET version 1.1?124

What is a bubbled event?When you have a complex control like DataGrid. Writing an event processing routine for each object (cell, button, row etc.). DataGrid handles the events of its constituents and will raise its own defined custom events.

Difference between ASP Session State and ASP.Net Session State?ASP: relies on cookies, Serialize all requests from a client, Does not survive process shutdown, Can not maintained across machines in a Web farm/garden.

Layouts of ASP.NET Pages:GridLayout and FlowLayout

Web User Control:Combines existing Server and HTML controls by using VS.Net. to create functional units that encapsulate some aspects of UI. Resides in Content Files, which must be included in project in which the controls are used.

Composite Custom Control:combination of existing HTML and Server Controls.

Rendered custom control:create entirely new control by rendering HTML directly rather than using composition.

Where do you store the information about user’s Locale?Page.Culture

Should Validation occur on Client/Server Side for Date Input?Both. Client-side reduces extra round-trip. Server-Side ensures prevention against hacking and failure against automated requests.

HTTP GET and HTTP POST:As their names imply, both HTTP GET and HTTP POST use HTTP as their underlying protocol. Both of these methods encode request parameters as name/value pairs in the HTTP request. The GET method creates a query string and appends it to the script's URL on the server that handles the request. For the POST method, the name/value pairs are passed in the body of the HTTP request message.

Web Services Discovery:Even though advertising of a web service is important, it is optional. Web services can be private as well as public. Depending on the business model, some business-to -business (B2B) services would not normally be advertised publicly. Instead, the web service owners would provide specific instructions on accessing and using their service only to the business partner. To advertise web services publicly, authors post discovery files on the Internet. Potential web services clients can browse to these files for information about how to use the web services—the WSDL (Web Service Description Language). Think of it as the yellow pages for the web service. All it does is point you to where the actual web services reside and to the description of those web services. The process of looking up a service and checking out the service description is called Web

Service discovery. There are two ways of advertising the service: static and dynamic. In both of these, XML onveys the locations of web services.

Static discovery is easier to understand because it is explicit in nature. If you want to advertise your web service, you must explicitly create the .disco discovery file and point it to the WSDL.

As opposed to explicitly specifying the URL for all web services your site supports, you can enable dynamic discovery, which enables all web services underneath a specific URL on your web site to be listed automatically. For your web site, you might want to group related web services under many different directories and then provide a single dynamic discovery file in each of the directory.

Web Services and Security:We incorporate security into web service in two ways: system security and application security. System -level security allows for restricting access to the web services from unauthorized clients. It is done in a declarative fashion, whereas application - level security is more flexible. With system-level security, you will most likely have the list of authorized clients' IP addresses that you will let access your web service through the use of some configuration - management tools. With application-level security, you will incorporate the authentication into your web service, thus providing a more flexible configuration.

In system – level security client send a user name and password to web server. This pair can be in plain text format or in some encrypted format. Once server authenticates the user it can access the services available to server.

In application – level security mode your web services involves taking security into your own hands. You can program your web services so that all of their methods require an access token, which can be obtained from the web service after sending in the client's username and password. The client credentials can be sent to the server through SSL (Secure Sockets Layer), which eliminates the risk of sending clear-text passwords across the wire. Through this SSL channel, the server returns an access token to the caller, who can use it to invoke all other web service methods.

Web Form EventsThe first event that happens in the life of a Web Form is the Init event. This is raised so that we can have initialization code for the page. The controls on the page are not yet created at this point. This event is raised once for each user of the page.

The Load event follows the Init event. Subsequently, it is raised each time the page is requested. When this event is raised, all child controls of the Web Form are loaded and accessible. You should be able to retrieve data and populate the controls so that they can render themselves on the page when sent back to the client.

The PreRender event happens just before the page is rendered and sent back to the client. We don't often handle this event; however, it depends on the situation.

The last event in the life of a Web Form is the Unload event. This happens when the page is unloaded from memory. Final cleanup should be done here.

Lifecycle Of A Web Form:In ASP .NET, the web page starts its life when a client requests a particular page. IIS parses and runs the scripts on the ASP page to render HTML content. As soon as the page rendering is complete, the page's life ceases; only the view states of the page persist between requests to the page. These view states allow the controls on the server to appear as if they are still present to handle server events.

Using Web Services:In Visual Studio.NET IDE, you can choose Project >> Add Web Reference and then type in the URL where the web service resides. For example, we'll point to the web service we created on local server, than is PubsWS (suppose). The URL to this web service on our server is http://localhost/PubsWS/PubsWS.asmx.

After adding the web reference, you can access the proxy object to the web service you are calling via the type servername.proxyObjectName. For your case, it is localhost.PubsWS.

The following code excerpt demonstrates how to use the web service through the proxy. We create an instance of the proxy object and then ask it to relay the message to the real web service to get the list of authors. The result will be streamed back in XML format, which is reconstructed into a DataSet object.

[C#] localhost.PubsWS ws = new localhost.PubsWS( ); DataSet ds = ws.GetAuthors( );

ASP.NET Session-State Management:ASP.NET improves upon ASP session-state management by moving to an out-of-process model. By having all web servers in the farm pointing to a common server that hosts the out-of-process state manager, the web client can be redirected around the farm without losing the session states. By using an out-of-process model, we no longer have the problem of losing session states when the IIS process is cycled. This means that if the web server application crashed for whatever reason and restarted within the session time-out duration, the web clients could still have all their session states intact. Of course, if the out-of-process state manager crashed, that is a whole different issue. This leads to the next improvement of ASP.NET—the ability to persist session state to a database.There are two levels of configuration: machine and application. Machine-level configuration associates with the machine.config file stored in WinNT\Microsoft.NET\ Framework\\CONFIG\machine.config, while the application-level configuration uses the web.config file in the application root directory. The application-level configuration overrides the machine -level configuration.

Acronyms

CCW COM Callable Wrapper

CLICommon Language Infrastructure. This is a subset of the CLR and base class libraries that Microsoft has submitted to ECMA so that a third-party vendor can build a .NET runtime on another platform.

CLR Common Language Runtime

CLS Common Language Specification

COFF Common Object File Format

COM Component Object Model

CTS Common Type System

DISCODiscovery of Web Services. A Web Service has one or more. DISCO files that contain information on how to access its WSDL.

DNA Distributed interNet Applications Architecture.

DOM Document Object Model

GDI Graphical Device Interface

GAC Global Assembly Cache

GUID Globally Unique Identifier

HTTP Hyper Text Transfer Protocol

IDL Interface Definition Language

IL Intermediate Language

MSIL Microsoft Intermediate Language

MS- Microsoft Distributed Transaction Coordinator

DTC

N-Tier Multi-Tier

OLTP Online Transaction Processing

OLAP Online Analytical Processing

PE Portable Executable

RAD Rapid Application Development

RCW Runtime Callable Wrapper

SMTP Simple Mail Transfer Protocol

SOAP Simple Object Access Protocol

TCP Transport Control Protocol

TLB Type Library

UDF Uniform Data Format

UI User Interface

URL Uniform Resource Locator

UDDI Universal Description, Discovery and Integration

WAP Wireless Access Protocol

WSDL Web Services Definition Language

WML Wireless Markup Language

XML Extensible Markup Language

SQL Server

What is normalization? Explain different levels of normalization?

Check out the article Q100139 from Microsoft knowledge base and ofcourse, there's much more information available in the net. It'll be agood idea to get a hold of any RDBMS fundamentals text book,especially the one by C. J. Date. Most of the times, it will be okayif you can explain till third normal form.

What is denormalization and when would you go for it?

As the name indicates, denormalization is the reverse process ofnormalization. It's the controlled introduction of redundancy in tothe database design. It helps improve the query performance as thenumber of joins could be reduced.

How do you implement one-to-one, one-to-many and many-to-manyrelationships while designing tables?

One-to-One relationship can be implemented as a single table andrarely 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 withthe keys from both the tables forming the composite primary key of thejunction table.

It will be a good idea to read up a database designing fundamentalstext book.

What's the difference between a primary key and a unique key?

Both primary key and unique enforce uniqueness of the column on whichthey are defined. But by default primary key creates a clustered indexon the column, where are unique creates a nonclustered index bydefault. Another major difference is that, primary key doesn't allowNULLs, but unique key allows one NULL only.

What are user defined datatypes and when you should go for them?

User defined datatypes let you extend the base SQL Server datatypes byproviding a descriptive name, and format to the database. Take forexample, in your database, there is a column called Flight_Num whichappears in many tables. In all these tables it should be varchar(8).In this case you could create a user defined datatype calledFlight_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 what's the information that can be storedinside a bit column?

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

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 thetable has more than one candidate key, one of them will become theprimary key, and the rest are called alternate keys.

A key formed by combining at least two or more columns is calledcomposite key.

What are defaults? Is there a column to which a default can't be bound?

A default is a value that will be used by a column, if no value issupplied to that column while inserting data. IDENTITY columns and

timestamp columns can't have defaults bound to them. See CREATEDEFUALT in books online.

SQL Server architecture       (top)

What is a transaction and what are ACID properties?

A transaction is a logical unit of work in which, all the steps mustbe performed or none. ACID stands for Atomicity, Consistency,Isolation, Durability. These are the properties of a transaction.

Explain different isolation levels

An isolation level determines the degree of isolation of data betweenconcurrent transactions. The default SQL Server isolation level isRead Committed. Here are the other isolation levels (in the ascendingorder of isolation): Read Uncommitted, Read Committed, RepeatableRead, Serializable.

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 clusteredindex gets created on the primary key, unless specified otherwise.

What's the maximum size of a row?

8060 bytes. Don't be surprised with questions like 'what is themaximum number of columns per table'. Check out SQL Server booksonline for the page titled: "Maximum Capacity Specifications".

Explain Active/Active and Active/Passive cluster configurations

Hopefully you have experience setting up cluster servers. But if youdon't, at least be familiar with the way clustering works and the twoclusterning configurations Active/Active and Active/Passive. SQLServer books online has enough information on this topic and there isa good white paper available on Microsoft site.

Explain the architecture of SQL Server

This is a very important question and you better be able to answer itif consider yourself a DBA. SQL Server books online is the best placeto read about SQL Server architecture. Read up the chapter dedicatedto SQL Server Architecture.

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 tablelocks). 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-grainlocks. Lock escalation threshold was definable in SQL Server 6.5, butfrom SQL Server 7.0 onwards it's dynamically managed by SQL Server.

What's the difference between DELETE TABLE and TRUNCATE TABLE commands?

DELETE TABLE is a logged operation, so the deletion of each row getslogged in the transaction log, which makes it slow. TRUNCATE TABLEalso deletes all the rows in a table, but it won't log the deletion ofeach row, instead it logs the deallocation of the data pages of thetable, which makes it faster. Of course, TRUNCATE TABLE can be rolledback.

Explain the storage models of OLAP

Check out MOLAP, ROLAP and HOLAP in SQL Server books online for moreinfomation.

What are the new features introduced in SQL Server 2000 (or the latestrelease of SQL Server at the time of your interview)? What changedbetween the previous version of SQL Server and the current version?

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

What are constraints? Explain different types of constraints.

Constraints enable the RDBMS enforce the integrity of the databaseautomatically, 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 pagestitled: "Constraints" and "CREATE TABLE", "ALTER TABLE"

Whar is an index? What are the types of indexes? How many clusteredindexes can be created on a table? I create a separate index on eachcolumn of a table. what are the advantages and disadvantages of thisapproach?

Indexes in SQL Server are similar to the indexes in books. They helpSQL Server retrieve the data quicker.

Indexes are of two types. Clustered indexes and non-clustered indexes.When you create a clustered index on a table, all the rows in thetable are stored in the order of the clustered index key. So, therecan be only one clustered index per table. Non-clustered indexes havetheir own storage separate from the table data storage. Non-clusteredindexes are stored as B-tree structures (so do clustered indexes),with the leaf level nodes having the index key and it's row locater.The row located could be the RID or the Clustered index key, dependingup on the absence or presence of clustered index on the table.

If you create an index on each column of a table, it improves thequery performance, as the query optimizer can choose from all theexisting indexes to come up with an efficient execution plan. At thesame time, data modification operations (such as INSERT, UPDATE,DELETE) will become slow, as every time data changes in the table, allthe indexes need to be updated. Another disadvantage is that, indexesneed disk space, the more indexes you have, more disk space is used.

Database administration       (top)

What is RAID and what are different types of RAID configurations?

RAID stands for Redundant Array of Inexpensive Disks, used to providefault tolerance to database servers. There are six RAID levels 0through 5 offering different levels of performance, fault tolerance.MSDN has some information about RAID levels and for detailedinformation, check out the RAID advisory board's homepage

What are the steps you will take to improve performance of a poorperforming query?

This is a very open ended question and there could be a lot of reasonsbehind the poor performance of a query. But some general issues thatyou could talk about would be: No indexes, table scans, missing or outof date statistics, blocking, excess recompilations of storedprocedures, procedures and triggers without SET NOCOUNT ON, poorlywritten query with unnecessarily complicated joins, too muchnormalization, excess usage of cursors and temporary tables.

Some of the tools/ways that help you troubleshooting performanceproblems are: SET SHOWPLAN_ALL ON, SET SHOWPLAN_TEXT ON, SETSTATISTICS IO ON, SQL Server Profiler, Windows NT /2000 Performancemonitor, Graphical execution plan in Query Analyzer.

Download the white paper on performance tuning SQL Server fromMicrosoft web site. Don't forget to check out sql-server-performance.com

What are the steps you will take, if you are tasked with securing anSQL Server?

Again this is another open ended question. Here are some things youcould talk about: Preferring NT authentication, using server, databaseand application roles to control access to the data, securing thephysical database files using NTFS permissions, using an unguessableSA password, restricting physical access to the SQL Server, renamingthe Administrator account on the SQL Server computer, disabling theGuest account, enabling auditing, using multiprotocol encryption,setting up SSL, setting up firewalls, isolating SQL Server from theweb 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 aboutresolving deadlocks?

Deadlock is a situation when two processes, each having a lock on onepiece of data, attempt to acquire a lock on the other's piece. Eachprocess would wait indefinitely for the other to release the lock,unless one of the user processes is terminated. SQL Server detectsdeadlocks and terminates one user's process.

A livelock is one, where a request for an exclusive lock isrepeatedly denied because a series of overlapping shared locks keepsinterfering. SQL Server detects the situation after four denials andrefuses further shared locks. A livelock also occurs when readtransactions monopolize a table or page, forcing a write transactionto wait indefinitely.

Check out SET DEADLOCK_PRIORITY and "Minimizing Deadlocks"  in SQLServer books online. Also check out the article Q169960 from Microsoftknowledge base.

What is blocking and how would you troubleshoot it?

Blocking happens when one connection from an application holds a lockand a second connection requires a conflicting lock type. This forcesthe second connection to wait, blocked on the first.

Read up the following topics in SQL Server books online: Understandingand avoiding blocking, Coding efficient transactions.

Explain CREATE DATABASE syntax

Many of us are used to creating databases from the Enterprise Manageror by just issuing the command: CREATE DATABAE MyDB. But what if youhave 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 MBand with a growth factor of 15%? That's why being a DBA you should befamiliar with the CREATE DATABASE syntax. Check out SQL Server booksonline for more information.

How to restart SQL Server in single user mode? How to start SQL Serverin 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 befamiliar with. -m is used for starting SQL Server in single user modeand -f is used to start the SQL Server in minimal confuguration mode.Check out SQL Server books online for more parameters and theirexplanations.

As a part of your job, what are the DBCC commands that you commonlyuse for database maintenance?

DBCC CHECKDB, DBCC CHECKTABLE, DBCC CHECKCATALOG, DBCC CHECKALLOC,DBCC SHOWCONTIG, DBCC SHRINKDATABASE, DBCC SHRINKFILE etc. But thereare 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, howdo you update them?

Statistics determine the selectivity of the indexes. If an indexedcolumn has unique values then the selectivity of that index is more,as opposed to an index with non-unique values. Query optimizer usesthese indexes in determining whether to choose an index or not whileexecuting a query.

Some situations under which you should update statistics:1) If there is significant change in the key values in the index2) If a large amount of data in an indexed column has been added,changed, or removed (that is, if the distribution of key values haschanged), or the table has been truncated using the TRUNCATE TABLEstatement and then repopulated3) Database is upgraded from a previous version

Look up SQL Server books online for the following commands: UPDATESTATISTICS, STATS_DATE, DBCC SHOW_STATISTICS, CREATE STATISTICS, DROPSTATISTICS, sp_autostats, sp_createstats, sp_updatestats

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

There are lots of options available, you have to choose your optiondepending upon your requirements. Some of the options you have are:BACKUP/RESTORE, detaching and attaching databases, replication, DTS,

BCP, logshipping, INSERT...SELECT, SELECT...INTO, creating INSERTscripts to generate data.

Explian different types of BACKUPs avaialabe in SQL Server? Given aparticular scenario, how would you go about choosing a backup plan?

Types of backups you can create in SQL Sever 7.0+ are Full databasebackup, differential database backup, transaction log backup,filegroup backup. Check out the BACKUP and RESTORE commands in SQLServer books online. Be prepared to write the commands in yourinterview. Books online also has information on detailedbackup/restore architecture and when one should go for a particularkind of backup.

What is database replicaion? What are the different types ofreplication you can set up in SQL Server?

Replication is the process of copying/moving data between databases onthe same or different servers. SQL Server supports the following typesof 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. Beprepared to explain how different replication agents function, whatare 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 thesqlservr.exe, which is used to determine the service pack installed.To know more about this process visit SQL Server service packs andversions.

Database programming       (top)

What are cursors? Explain different types of cursors. What are thedisadvantages of cursors? How can you avoid cursors?

Cursors allow row-by-row prcessing of the resultsets.

Types of cursors: Static, Dynamic, Forward-only, Keyset-driven.

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 arealso costly because they require more resources and temporary storage(results in more IO operations). Further, there are restrictions onthe SELECT statements that can be used with some types of cursors.

Most of the times, set based operations can be used instead ofcursors. Here is an example:

If you have to give a flat hike to your employees using the followingcriteria:

Salary between 30000 and 40000 -- 5000 hikeSalary between 40000 and 55000 -- 7000 hikeSalary between 55000 and 65000 -- 9000 hike

In this situation many developers tend to use a cursor, determine eachemployee's salary and update his salary according to the aboveformula. But the same can be achieved by multiple update statements orcan be combined in a single UPDATE statement as shown below:

UPDATE tbl_emp SET salary =CASE WHEN salary BETWEEN 30000 AND 40000 THEN salary + 5000WHEN salary BETWEEN 40000 AND 55000 THEN salary + 7000WHEN salary BETWEEN 55000 AND 65000 THEN salary + 10000END

Another situation in which developers tend to use cursors: You need tocall a stored procedure when a column in a particular row meetscertain condition. You don't have to use cursors for this. This can beachieved using WHILE loop, as long as there is a unique key toidentify each row. For examples of using WHILE loop for row by rowprocessing, check out the 'My code library' section of my site orsearch for WHILE.

Write down the general syntax for a SELECT statements covering all theoptions.

Here's the basic syntax: (Also checkout SELECT in books online foradvanced 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] ]

What is a join and explain different types of joins.

Joins are used in queries to explain how different tables are related.Joins also let you select data from a table depending upon data fromanother table.

Types of joins: INNER JOINs, OUTER JOINs, CROSS JOINs. OUTER JOINs arefurther classified as LEFT OUTER JOINS, RIGHT OUTER JOINS and FULLOUTER JOINS.

Can you have a nested transaction?

Yes, very much. Check out BEGIN TRAN, COMMIT, ROLLBACK, SAVE TRAN and@@TRANCOUNT

What is an extended stored procedure? Can you instantiate a COM objectby using T-SQL?

An extended stored procedure is a function within a DLL (written in aprogramming language like C, C++ using Open Data Services (ODS) API)that can be called from T-SQL, just the way we call normal storedprocedures using the EXEC statement. See books online to learn how tocreate 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 seebooks online for sp_OAMethod, sp_OAGetProperty, sp_OASetProperty,sp_OADestroy. For an example of creating a COM object in VB andcalling it from T-SQL, see 'My code library' section of this site.

What is the system function to get the current user's 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 are triggers? How many triggers you can have on a table? How toinvoke a trigger on demand?

Triggers are special kind of stored procedures that get executedautomatically when an INSERT, UPDATE or DELETE operation takes placeon a table.

In SQL Server 6.5 you could define only 3 triggers per table, one forINSERT, one for UPDATE and one for DELETE. From SQL Server 7.0onwards, this restriction is gone, and you could create multipletriggers per each action. But in 7.0 there's no way to control theorder in which the triggers fire. In SQL Server 2000 you could specifywhich trigger fires first or fires last using sp_settriggerorder

Triggers can't be invoked on demand. They get triggered only when anassociated action (INSERT, UPDATE, DELETE) happens on the table onwhich 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 oftriggers, as constraints are much faster.

Till SQL Server 7.0, triggers fire only after the data modificationoperation happens. So in a way, they are called post triggers. But inSQL Server 2000 you could create pre triggers also. Search SQL Server2000 books online for INSTEAD OF triggers.

Also check out books online for 'inserted table', 'deleted table' andCOLUMNS_UPDATED()

There is a trigger defined for INSERT operations on a table, in anOLTP system. The trigger is written to instantiate a COM object andpass the newly insterted rows to it for some custom processing. Whatdo you think of this implementation? Can this be implemented better?

Instantiating COM objects is a time consuming process and since youare doing it from within a trigger, it slows down the data insertionprocess. Same is the case with sending emails from triggers. Thisscenario can be better implemented by logging all the necessary datainto a separate table, and have a job which periodically checks thistable and does the needful.

What is a self join? Explain it with an example.

Self join is just like any other join, except that two instances ofthe same table will be joined in the query. Here is an example:Employees table which contains rows for normal employees as well asmanagers. So, to find out the managers of all the employees, you needa 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 t2WHERE t1.mgrid = t2.empid

Here's an advanced query using a LEFT OUTER JOIN that even returns theemployees without managers (super bosses)

SELECT t1.empname [Employee], COALESCE(t2.empname, 'No manager') [Manager]FROM emp t1LEFT OUTER JOINemp t2ONt1.mgrid = t2.empid

-    How do you manage session in ASP and ASP.NET-    How do you handle session management in ASP.NET and how do you implement them. How do  you handle in case of SQLServer mode.-    What are different authentication types. How do  you retreive user id in case of windows authentication-    For a server control, you need to have same properties like color maxlength, size, and allowed character throughout the application. How do you handle this. -    What is custom control. What is the difference between custom control and user control-    What is the syntax for datagrid and specifying columns-    How do you add a javascript function for a link button in a datagrid.-    Does C# supports multi-dimensional arrays-    How to transpose rows into columns and columns into rows in a multi-dimensional array-     What are object oriented concepts-    How do you create multiple inheritance in C#-    ADO and ADO.NET differences-    Features and disadvantages of dataset-    What is the difference between and ActiveX dll and control-    How do you perform validations-    What is reflection and disadvantages of reflection-    What is boxing and how it is done internally-    Types of authentications in IIS-    What are the security issues if we send a query from the application-    Difference between ByVal and ByRef-    Disadvantages of COM components -    How do we invoke queries from the application-    What is the provider and namespaces being used to access oracle database-    How do you load XML document and perform validation of the document-    How do you access elements in XML document-    What is ODP.NET-    Types of session management in ASP.NET-    Difference between datareader and dataset-    What are the steps in connecting to database-    How do you register a .NET assembly-    Usage of web.config-    About remoting and web services. Difference between them-    Caching techniques in .NET-    About CLS and CTS-    Is overloading possible in web services

-    Difference between .NET and previous version-    Types of chaching. How to implement caching-    Features in ASP.NET-    How do you do validations. Whether client-side or server-side validations are better-    How do you implement multiple inheritance in .NET-    Difference between multi-level and multiple inheritance-    Difference between dataset and datareader-    What are runtime hosts-    What is an application domain-    What is viewstate-    About CLR, reflection and assemblies-    Difference between .NET components and COM components-    What does assemblyinfo.cs consists-    Types of objects in ASP

#61607;    Database

-    What are the blocks in stored procedure-    How do you handle exceptions. Give the syntax for it-    What is normalization and types of normalization-    When would you denormalize-    Difference between a query and strored procedure-    What is clustered and non-clustered indexes-    Types of joins-    How do you get all records from 2 tables. Which join do you use-    Types of optimization-    Difference between inline query and stored procedure

Difference between VB dll and assemblies in .NET-    What is machine.config and web.config-    Tell about WSDL-    About web methods and its various attributes-    What is manifest-    Types of caching-    What does connection string consists of-    Where do you store connection string-    What is the difference between session state and session variables-    How do you pass session values from one page to another-    What are WSDL ports-    What is dataset and tell about its features. What are equivalent methods of previous, next etc. Of ADO in ADO.NET-    What is abstract class-    What is difference between interface inheritance and class inheritance-    What are the collection classes -    Which namespace is used for encryption-    What are the various authentication mechanisms in ASP.NET-    What is the difference between authentication and autherization-    What are the types of threading models-    How do you send an XML document from client to server-    How do you create dlls in .NET-    What is inetermediate language in .NET-    What is CLR and how it generates native code-    Can we store PROGID informatoin in database and dynamically load the component-    Is VB.NET object oriented? What are the inheritances does VB.NET support.-    What is strong name and what is the need of it

-    Any disadvantages in Dataset and in reflection-    Advantage of vb.net over vb-    What is runtime host-    How to send a DataReader as a parameter to a remote client-    How do you consume a webservice-    What happens when a reference to webservice is added-    How do you reference to a private & shared assembly-    What is the purpose of System.EnterpriseServices namespace-    About .Net remoting-    Difference between remoting and webservice-    Types of statemanagement techniques-    How to register a shared assembly-    About stateless and statefull webservice-    How to invoke .net components from com components,give the sequence-    How to check null values in dataset-    About how soap messages are sent and received in webservice-    Error handling and how this is done-    Features in .net framework 1.1-    Any problem found in vs.et-    Optimization  technique description-    About disco and uddi-    What providers does ado.net uses internally-    Oops concepts-    Disadvantages of vb-    XML serialization-    What providers do you use to connect to oracle database?-    About .NET Framework-    About Assembly in .NET, types of assemblies, their difference, How to register into GAC. How to generate the strong names & its use.-    What is side by side Execution?-    What is serialization?-    Life cycle of ASP.NET page when a request is made.-    If there is submit button in a from tell us the sequence what happens if submit is clicked and in form action is specified as some other page.-    About a class access specifiers and method access specifiers.-    What is overloading and how can this be done.-    How to you declare connection strings and how to you make use of web.config.-    How many web.copnfig can exists in a web application & which will be used.-    About .NET Remoting and types of remoting-    About Virtual functions and their use.-    How do you implement Inheritance in dot net-    About ado.net components/objects. Usage of data adapters and tell the steps to retrieve data.-    What does CLR do as soon as an assembly is created-    How do you retrieve information from web.config.-    How do you declare delegates and are delegates and events one and the same and explain how do you declare delegates and invoke them.-    If I want to override a method 1 of class A and in class b then how do you declare?-    What does CLR do after the IL is generated and machine language is generated .Will it look for main method-    About friend and Protected friend-    About multi level and multiple inheritance how to achieve in .net-    Sequence to connect and retrieve data from database useig dataset-    About sn.exe-    What was the problem in traditional component why side by side execution is

supported in .net-    How .net assemblies are registred as private and shared assembly-    All kind of access specifiers for a class and for methods-    On ODP.net-    Types of assemblies that can be created in dotnet -    About namespaces-    OOPs concept-    More on CLR

Impersonation is the process of assigning a user account to an unknown user

Windows integrated authentication. Identifies and authorizes users based on the server' s users list. Access to resources on the server is then granted or denied based on the user account' s privileges. This works the same way as regular Windows network security.

Forms authentication. Directs users to a logon Web form that collects user name and password information, and then authenticates the user against a user list or database that the application maintains.

Passport authentication. Directs new users to a site hosted by Microsoft so that they can register a single user name and password that will authorize their access to multiple Web sites. Existing users are prompted for their Passport user name and password, which the application then authenticates from the Microsoft Passport user list.

Application typeUse this type of authentication

Description

Public Internet Web application

AnonymousThis is the common access method for most Web sites. No logon is required and you secure restricted resources using NTFS file permissions.

Intranet Web application

Windows integrated

Windows authentication authenticates network users through the domain controller. Network users have access to Web application resources as determined by their user privileges on the server.

Private corporate Web application

Windows integrated

Corporate users can access the Web application using their corporate network user names and passwords. User accounts are administered using the Windows network security tools.

Commercial Web application

FormsApplications that need to collect shipping and billing information should implement Forms authentication to gather and store customer information.

Multiple commercial Web applications

Passport Passport authentication allows users to sign in once through a central authority. The user' s identity is then available to any application using the Passport SDK. Customer

Application typeUse this type of authentication

Description

information is maintained in a Passport Profile, rather than in a local database.

Storing Session State InProc

To store session state in the ASP.NET worker process, select InProc from the session state mode control. Your application will retrieve and store session information very quickly, but it will be available only to your application (and not on a Web form).

Storing Session State in a State Server

To have ASP.NET store session state on another server on your network, select StateServer from the SessionState mode control. When you select this item, the dialog box will enable the Connection String text box and the network timeout text box. Insert the protocol, IP address, and port for the state server in the Connection String text box. For example, the string:

tcpip=127.0.0.1:42424

will store the session state on the local machine over port 42424. If you want to store the session state on a machine other than your local server, change the IP address. Before session state is stored on a machine, you need to make sure the ASP.NET state server is running on that machine. You may get to it via the Services panel under the control panel.

Storing Session State in a Database

The final option for storing session state is to use a SQL Server database. Select SQLServer from the ASP.NET session state mode combo box. You'll be asked to enter the connection string to the SQL Server state database. Here's the string they provide by default:

data source=127.0.0.1;Integrated Security=SSPI

You may point ASP.NET so it references a database on another machine. Of course, you need to have SQL Server installed on the target machine to make this work. In addition, you'll find some SQL scripts to create the state databases in your .NET system directory (C:\WINDOWS\[[<img src="images/shy.gif"/>]]Microsoft.NET\Framework\v2.0.50215 on this machine at the time of this writing). The Aspnet_regsql.exe tool will set up the databases for you.

Caching

At the outset, turning on output caching is easy. To set up caching, place the OutputCache directive on the page. It's a separate directive, like the Page directive. The OutputCache directive enables caching and provides certain control over its behavior. The following exercise introduces caching output.For pages that are expensive to generate and that don't change very

often, caching the content represents an enormous performance boost for your Web site—especially as the number of clients increases.

Serialization is a process of taking an object and converting into a form so that it can be transported across the network or can be persisted in the storage location. This storage location can be physical file, database or ASP.NET Cache. The form contains the state of the object so that by this format, we can construct the same object a later point in time, which is called Deserialization.

There are three formats of serialization

Binary Serialization            : Light andcompact used in RemotingSOAP Serialization :interoperableuse SOAP and used in web ServicesXML Serialization :Custom Serialization

Introduction

Serialization in .NET allows the programmer to take an instance of an object and convert it into a format that is easily transmittable over the network, or even stored in a database or file system. This object will actually be an instance of a custom type, including any properties or fields you may have set.

A few examples I can think of include the ability to send an instance of your object to another portion of a local or remote application, such as over a Web service. Another example of when to choose to serialize objects is for data within objects that would normally be stored in a database, but these pieces of data do not need to be stored individually (their own fields in your tables). Streamline the database design by only holding those pieces of data for each record you need to query on, and the rest of the pieces can simply be serialized within a custom type and stored as a complete object within the database.

Let's take a scheduling object as an example. The scheduling object, enables an application to trigger events based on a very specific schedule. There could be numerous settings involved when building this, such as intervals, date and time restrictions, etc. Normally each piece of data would require the creation of a separate field in your table, when really the only important piece of information is the exact date/time when the next event should be triggered. Instead, serialize this entire scheduling object, and save that into the database, along with the one piece of information that is needed, the next event date/time. This cuts down the entire database schema to about three fields, not to mention the time saved from writing complex Save and Load methods.

This article covers the two formats in which you can serialize objects to --: XML or binary -- and the many advantages/disadvantages of each. It also covers the two ways that one can serialize, Basic and Custom. And, finally, the article will end with a sample project demonstrating how to send a custom object over the wire with Web Services.

This piece focuses on the .NET Framework's System.Runtime.Serialization namespace (see http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemRuntimeSerialization.asp).

The first step in any serialization process is to take the instance of the object and convert it to a memory stream. From there we have the ability to perform any number of operations with (file IO, database IO, etc.). Examine Figure 1.1 (below) which demonstrates four methods for performing serialization, including serializing and de-serializing in binary format, and the same in XML format. The next section will cover the differences between binary and XML serialization.

Figure 1.1 Core Serialization Methods

#region Binary Serializerspublic static System.IO.MemoryStream SerializeBinary(object request) {System.Runtime.Serialization.Formatters.Binary.BinaryFormatter serializer =new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();System.IO.MemoryStream memStream = new System.IO.MemoryStream();serializer.Serialize(memStream, request);return memStream;}

public static object DeSerializeBinary(System.IO.MemoryStream memStream) {memStream.Position=0;System.Runtime.Serialization.Formatters.Binary.BinaryFormatter deserializer =new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();object newobj = deserializer.Deserialize(memStream);memStream.Close();return newobj;}#endregion

#region XML Serializers

public static System.IO.MemoryStream SerializeSOAP(object request) {System.Runtime.Serialization.Formatters.Soap.SoapFormatter serializer =new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();System.IO.MemoryStream memStream = new System.IO.MemoryStream();serializer.Serialize(memStream, request);return memStream;}

public static object DeSerializeSOAP(System.IO.MemoryStream memStream) {object sr;System.Runtime.Serialization.Formatters.Soap.SoapFormatter deserializer =new System.Runtime.Serialization.Formatters.Soap.SoapFormatter();memStream.Position=0;sr = deserializer.Deserialize(memStream);memStream.Close();return sr;}#endregion

Whenever you want an object to be able to be serialized, mark it as [Serializable()], with a custom attribute on the class (http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemserializableattributeclasstopic.asp). In the same solution provided here, the "Schedule" class in the "Serialization" project, you will see this attribute in use. Also consider the field attribute named "[NonSerialized()]" (see http://msdn.microsoft.com/library/en-us/cpref/html/frlrfsystemnonserializedattributeclasstopic.asp). It can be applied to any field from within your class to prevent it from being serialized. This would be useful if you had a variable within the class that was not needed or you did not want to have serialized into the final product. Simply add the NonSerialized() attribute to that variable because the system will not automatically serialize it for you.

Keep in mind that the [Serializable()] attribute applies to the class entirely. So if you want the entire class to be able to support serialization, you must add that attribute, where the [NonSerialized()] attribute applies to the fields within a class that is marked as [Serializable()]. Note that using the [NonSerialized()] is sometimes called "Selective Serialization."

Lastly, note that in order to use the System.Runtime.Serialization.Formatters.Soap.SoapFormatter, you must add a reference to the System.Runtime.Serialization.Formatters.Soap.dll.

Before proceeding, take time to look over our Schedule class listed in Figure 1.2 (below).

Figure 1.2 Schedule Class

using System;

namespace FifteenSeconds {/// <summary>/// Allow us to represent a schedule/// </summary>[Serializable()]public class Schedule {protected System.DateTime start;protected System.DateTime end;

//number of milliseconds to increment @ each intervalprotected long interval;

public System.DateTime Start {get{return start;}set{start=value;}}public System.DateTime End {get{return end;}set{end=value;}}public long Interval {get{return interval;}set{interval=value;}}public Schedule(System.DateTime Start, System.DateTime End, long Interval) {start=Start;end=End;interval=Interval;}//return the next runtime, and if the schedule has ended, return the end timepublic System.DateTime NextRunTime {get {System.TimeSpan ts = new System.TimeSpan(end.Ticks-System.DateTime.Now.Ticks);if(ts.Milliseconds>0) {//our end time is in the future stillreturn System.DateTime.Now.AddMilliseconds(interval);} else {return end;}}}}

}

This is the class referred to in the remainder of this article. Download code for this article

Binary vs. XML Serialization

As demonstrated above, the choice between XML and Binary serialization is not dependent on the actual implementation of the code. Both methods are very easy to implement. Consider the advantages offered by both.

Advantages of Binary Serialization

1. All members, no matter if they are read-only will be serialized.2. Greater performance*

Advantages of XML Serialization

1. Greater flexibility of object sharing and usage (interoperability)2. No strict binary dependence3. Human readable

After reviewing the code in Figure 1.1, notice that serialization in either binary or XML simply depends only on choosing your Formatter. Also notice that the difference between serialization and deserialization is the difference between calling the Serialize() method or the Deserialize() method with the appropriate parameters. The above code can easily be copied into any of your applications as is; it will be the core of most of your serialization needs. Consider taking a look at the attached ZIP file for this article. I have included those methods listed above, along with a few other methods.

*I have included a spreadsheet that shows my test results for groups of iterations of Basic Serialization. Also take a look at the "SpeedTests" project in the solution, which you can use to run your own tests. For one simple iteration to serialize it was more than 1,000 percent faster to use binary serialization over XML, and for deserialization it was only 380 percent faster.

Basic Serialization vs. Custom

The .NET Framework provided the ability to perform serialization in two ways. Keep in mind that "performing" serialization is not the same as the "format" in which we serialize. Performing serialization refers to the actual way in which to instruct Framework to take our object and pack it into the final result of the serialization, regardless of the format (see section on Binary vs. XML Serialization, above). The easiest way is to allow Framework to automatically serialize the object on its own; this is typically called "Basic Serialization." Basic Serialization only requires that your object has the [Serializable()] class attribute. Framework will take your class and convert it to the given formatter used. The only control you have over this process is by using the [NonSerialized()] field attributes to stop any field from being serialized. You do not have any control over exactly how each item in your class is serialized.

If you desire greater control, then move into the world of "Custom Serialization." This is where you can specify exactly which items will be serialized, and exactly how it will be done. In the sample solution provided, I have created a class named "ScheduleCustom" to demonstrate exactly how this is done.

When using Basic Serialization, versioning your objects plays a major role. To serialize our schedule object to disk, and then change that object (for example, by adding an additional field), will lead to problems with deserialization. The error will be similar to:

"Wrong number of Members. Object FifteenSeconds.Schedule has 4 members, number of members deserialized is 3."

If you do run into this issue, consider changing to Custom Serialization. Since you are exactly specifying how to handle all members of your class during the serialization process, you can avoid these versioning problems.

Custom Serialization

The first thing we must do is obviously mark our class as [Serializable()]. Next, our class must implement the System.Runtime.Serialization.ISerializable interface (http://msdn.microsoft.com/library/en-us/cpref/html/frlrfSystemRuntimeSerializationISerializableClassTopic.asp). So our class definition looks like:

[Serializable()]public class ScheduleCustom : System.Runtime.Serialization.ISerializable {

Within this interface we see the following single method:

void GetObjectData(SerializationInfo info, StreamingContext context);

In order for our class to satisfy supporting the interface, we must also implement this GetObjectData() method:

public void GetObjectData(SerializationInfo info,StreamingContext context) {//use the info object to add the items you want serializedinfo.AddValue("start", start);info.AddValue("end", end);info.AddValue("interval", interval);}

Given this extremely simple demonstration you may not be able to see the actual power of using Custom Serialization, so I will add to the class to demonstrate the flexibility it adds to your serialization needs.

If we were to examine the output of the "start" DateTime value during the serialization process, we would see it default to the Framework DateTime format:

2002-08-19T14:09:13.3457440-07:00

If you plan on sharing this object with others who are not using the .NET Framework and are internationally distributed, it may be wise to represent the DateTime value in Greenwich Mean Time (GMT). Let's modify the GetObjectData() method to convert "start" and "end" times into GMT.

public void GetObjectData(SerializationInfo info,StreamingContext context) {//use the info object to add the items you want serialized//in order for better partnering we will convert our times to GMT times//"Universal Time" AKA "Coordinated Universal Time" AKA GMTinfo.AddValue("start", System.TimeZone.CurrentTimeZone.ToUniversalTime(start));info.AddValue("end", System.TimeZone.CurrentTimeZone.ToUniversalTime(end));info.AddValue("interval", interval);info.AddValue("timeformat", "utc");}

Now the "start" time, when serialized, will be in the GMT format of:

8/19/2002 9:09:13 PM

Also notice the additional property I added named "timeformat". This item will be used later for us to determine which type of DateTime formats were used for the serialization process.

Also consider other formats for outputting the dates. Consider what the System.Globalization.DateTimeFormatInfo could offer, or even converting the DateTime to time since Unix epoch (January 1, 1970, see http://www.wikipedia.com/wiki/Unix_epoch) for easier integration with non-Microsoft platforms. You could add an optional property to our class to indicate which type of format the DateTime will be in once it has been serialized, of course indicate this by using the "timeformat" value we added to the items being serialized.

Custom Deserialization

If you want to allow your object to be deserialized in a custom manner, use a custom constructor. The definition of this constructor looks similar to:

public ScheduleCustom (SerializationInfo info,StreamingContext context) {}

As usual, you must implement this method. For our schedule class, our implementation will convert the UTC time back into a local DateTime format.

public ScheduleCustom (SerializationInfo info,StreamingContext context) {//let's bring back our date/times into local timesthis.start = info.GetDateTime("start").ToLocalTime();this.end = info.GetDateTime("end").ToLocalTime();this.interval = info.GetInt32("interval");}

As I indicated in the Custom Serialization process previously, the additional item "timeformat" could be used to specify exactly how you would convert the serialized time into the DateTime needed for the local object. But since this example simply covers the conversion to and from UTC, our task is very easy.

Serialization with Web Services

When learning a new aspect of technology, it's useful to see that technology in use. In this section we will create one Web Service with two methods. The first method will enable Framework to return our custom serialized schedule object in binary format. The second method will return the same object in XML format. This example will be a quick one because we will build on top of the foundation we already built. In my solution, I have simply added a new C# Web Service project, with a reference to our "serialization" project. We will next add the two methods as described above.

FifteenSeconds.ScheduleCustom customSchedule =new FifteenSeconds.ScheduleCustom(System.DateTime.Now, System.DateTime.Now.AddHours(5), 10000);

[WebMethod]public byte[] Get_Binary_Schedule() {return FifteenSeconds.Serializer.Serialize( customSchedule,FifteenSeconds.Serializer.SerializationFormat.Binary).ToArray();}[WebMethod]public string Get_XML_Schedule() {

return FifteenSeconds.Serializer.ConvertStreamToString(FifteenSeconds.Serializer.Serialize( customSchedule,FifteenSeconds.Serializer.SerializationFormat.Xml));}

Notice both methods are using the same instance of the FifteenSeconds.ScheduleCustom object and simply return back either the byte[], in the case of the binary transfer, or the string, in the case of the XML. Don't forget Framework will automatically serialize your objects for you, simply by having the return type on your method your custom type. But what happens if you need to send a collection of somewhat unrelated objects over the wire? It really depends on your needs and your imagination. Take time now to review the project named "Serialization" in the solution. It also has a few methods that you may find useful if you ever need to serialize these objects to a file on your disk.

Assembly :An assembly is the smallest unit that you use to define the version of an application. The version of an assembly determines the version of the types and the other resources that it contains. The .NET Framework allows the execution of multiple versions of the same assembly on the same machine. The side-by-side execution of assemblies overcomes the problem known as "DLL hell," which is one of the major problems associated with COM applications.

DLL:A Dynamic Link Library (DLL) is a file that is loaded at runtime, and its functions linkeddynamically at that time. This allows for multiple applications that use the same library functionsto all share one DLL, and if the code in the DLL needs to be fixed, the DLL can be replaced, and allapplications that use it will get the benefit of the update. Static libraries are different fromDLLs in that each application gets its own copy of the functions, and they are embedded into the Exeat compile/link time. If the library functions need to be fixed, every application that uses themmust be recompiled to get the fixes.