Online Information Hub…

One stop destination | Indian Education Information

Archive for January, 2009

National Institute of Technology – India

Posted by Admin on January 8, 2009

National Institute of Technology, Calicut

National Institute of Technology, Allahabad

National Institute of Technology, Trichirapalli

National Institute of Technology, Rourkela

National Institute of Technology, Jamshedpur

National Institute of Technology, Patna

National Institute of Technology, Surathkal

National Institute of Technology, Bhopal

National Institute of Technology, Durgapur

National Institute of Technology, Kurukshetra

National Institute of Technology, Jaipur

National Institute of Technology, Nagpur

National Institute of Technology, Srinagar

National Institute of Technology, Surat

National Institute of Technology, Warangal

National Institute of Technology, Raipur

National Institute of Technology, Tripura

National Institute of Technology, Hamirpur

National Institute of Technology, Jalandhar

National Institute of Technology, Silchar

Posted in NIT's | Leave a Comment »

Indian Institute of Management – India

Posted by Admin on January 8, 2009

Indian Institute of Management, Ahemedabad
Indian Institute of Management, Bangalore
Indian Institute of Management, Kozhikode
Indian Institute of Management, Indore
Indian Institute of Management, Lucknow
Indian Institute of Management, Calcutta

Posted in IIM's | Tagged: , , , , , , , , , , , | Leave a Comment »

.Net Intervew Question

Posted by Admin on January 8, 2009

What is .NET?
.NET is essentially a framework for software development.It is similar in nature to any other software development framework (J2EE etc) in that it provides a set of runtime containers/capabilities, and a rich set of pre-built functionality in the form of class libraries and APIs
The .NET Framework is an environment for building, deploying, and running Web Services and other applications. It consists of three main parts: the Common Language Runtime, the Framework classes, and ASP.NET.1. How many languages .NET is supporting now?
When .NET was introduced it came with several languages. VB.NET, C#, COBOL and Perl, etc. The site DotNetLanguages.Net says 44 languages are supported.

2. How is .NET able to support multiple languages?
A language should comply with the Common Language Runtime standard to become a .NET language. In .NET, code is compiled to Microsoft Intermediate Language (MSIL for short). This is called as Managed Code. This Managed code is run in .NET environment. So after compilation to this IL the language is not a barrier. A code can call or use a function written in another language.

3. How ASP .NET different from ASP?
Scripting is separated from the HTML, Code is compiled as a DLL, these DLLs can be executed on the server.

4. What is smart navigation?
The cursor position is maintained when the page gets refreshed due to the server side validation and the page gets refreshed.

5. What is view state?
The web is stateless. But in ASP.NET, the state of a page is maintained in the in the page itself automatically. How? The values are encrypted and saved in hidden controls. this is done automatically by the ASP.NET. This can be switched off / on for a single control

6. How do you validate the controls in an ASP .NET page?
Using special validation controls that are meant for this. We have 6 Validation controls.

7. Can the validation be done in the server side? Or this can be done only in the Client side?
Client side is done by default. Server side validation is also possible. We can switch off the client side and server side can be done.

8. How to manage pagination in a page?
Using pagination option in DataGrid control. We have to set the number of records for a page, then it takes care of pagination by itself.

9. What is ADO .NET and what is difference between ADO and ADO.NET?
ADO.NET is stateless mechanism. I can treat the ADO.Net as a separate in-memory database where in I can use relationships between the tables and select insert and updates to the database. I can update the actual database as a batch.
11. Observations between VB.NET and VC#.NET?
Choosing a programming language depends on your language experience and the scope of the application you are building. While small applications are often created using only one language, it is not uncommon to develop large applications using multiple languages.
For example, if you are extending an application with existing XML Web services, you might use a scripting language with little or no programming effort. For client-server applications, you would probably choose the single language you are most comfortable with for the entire application. For new enterprise applications, where large teams of developers create components and services for deployment across multiple remote sites, the best choice might be to use several languages depending on developer skills and long-term maintenance expectations.

The .NET Platform programming languages – including Visual Basic .NET, Visual C#, and Visual C++ with managed extensions, and many other programming languages from various vendors – use .NET Framework services and features through a common set of unified classes. The .NET unified classes provide a consistent method of accessing the platform’s functionality. If you learn to use the class library, you will find that all tasks follow the same uniform architecture. You no longer need to learn and master different API architectures to write your applications.

In most situations, you can effectively use all of the Microsoft programming languages. Nevertheless, each programming language has its relative strengths and you will want to understand the features unique to each language. The following sections will help you choose the right programming language for your application.

Visual Basic .NET

Visual Basic .NET is the next generation of the Visual Basic language from Microsoft. With Visual Basic you can build .NET applications, including Web services and ASP.NET Web applications, quickly and easily. Applications made with Visual Basic are built on the services of the common language runtime and take advantage of the .NET Framework.

Visual Basic has many new and improved features such as inheritance, interfaces, and overloading that make it a powerful object-oriented programming language. Other new language features include free threading and structured exception handling. Visual Basic fully integrates the .NET Framework and the common language runtime, which together provide language interoperability, garbage collection, enhanced security, and improved versioning support. A Visual Basic support single inheritance and creates Microsoft intermediate language (MSIL) as input to native code compilers.

Visual Basic is comparatively easy to learn and use, and Visual Basic has become the programming language of choice for hundreds of thousands of developers over the past decade. An understanding of Visual Basic can be leveraged in a variety of ways, such as writing macros in Visual Studio and providing programmability in applications such as Microsoft Excel, Access, and Word.

Visual Basic provides prototypes of some common project types, including:

• Windows Application.
• Class Library.
• Windows Control Library.
• ASP.NET Web Application.
• ASP.NET Web Service.
• Web Control Library.
• Console Application.
• Windows Service.
• Windows Service.

Visual C# .NET

Visual C# (pronounced C sharp) is designed to be a fast and easy way to create .NET applications, including Web services and ASP.NET Web applications. Applications written in Visual C# are built on the services of the common language runtime and take full advantage of the .NET Framework.

C# is a simple, elegant, type-safe, object-oriented language recently developed by Microsoft for building a wide range of applications. Anyone familiar with C and similar languages will find few problems in adapting to C#. C# is designed to bring rapid development to the C++ programmer without sacrificing the power and control that are a hallmark of C and C++. Because of this heritage, C# has a high degree of fidelity with C and C++, and developers familiar with these languages can quickly become productive in C#. C# provides intrinsic code trust mechanisms for a high level of security, garbage collection, and type safety. C# supports single inheritance and creates Microsoft intermediate language (MSIL) as input to native code compilers.

C# is fully integrated with the .NET Framework and the common language runtime, which together provide language interoperability, garbage collection, enhanced security, and improved versioning support. C# simplifies and modernizes some of the more complex aspects of C and C++, notably namespaces, classes, enumerations, overloading, and structured exception handling. C# also eliminates C and C++ features such as macros, multiple inheritance, and virtual base classes. For current C++ developers, C# provides a powerful, high-productivity language alternative.

Visual C# provides prototypes of some common project types, including:

• Windows Application.
• Class Library.
• Windows Control Library.
• ASP.NET Web Application.
• ASP.NET Web Service.
• Web Control Library.
• Console Application.
• Windows Service.

12. Advantages of migrating to VB.NET ?
Visual Basic .NET has many new and improved language features — such as inheritance, interfaces, and overloading that make it a powerful object-oriented programming language. As a Visual Basic developer, you can now create multithreaded, scalable applications using explicit multithreading. Other new language features in Visual Basic .NET include structured exception handling, custom attributes, and common language specification (CLS) compliance.
The CLS is a set of rules that standardizes such things as data types and how objects are exposed and interoperate. Visual Basic .NET adds several features that take advantage of the CLS. Any CLS-compliant language can use the classes, objects, and components you create in Visual Basic .NET. And you, as a Visual Basic user, can access classes, components, and objects from other CLS-compliant programming languages without worrying about language-specific differences such as data types.CLS features used by Visual Basic .NET programs include assemblies, namespaces, and attributes.

These are the new features to be stated briefly:

Inheritance
Visual Basic .NET supports inheritance by allowing you to define classes that serve as the basis for derived classes. Derived classes inherit and can extend the properties and methods of the base class. They can also override inherited methods with new implementations. All classes created with Visual Basic .NET are inheritable by default. Because the forms you design are really classes, you can use inheritance to define new forms based on existing ones.

Exception Handling
Visual Basic .NET supports structured exception handling, using an enhanced version of the Try…Catch…Finally syntax supported by other languages such as C++.

Structured exception handling combines a modern control structure (similar to Select Case or While) with exceptions, protected blocks of code, and filters. Structured exception handling makes it easy to create and maintain programs with robust, comprehensive error handlers.

Overloading
Overloading is the ability to define properties, methods, or procedures that have the same name but use different data types. Overloaded 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. Overriding Properties and Methods The Overrides keyword allows derived objects to override characteristics inherited from parent objects. Overridden members have the same arguments as the members inherited from the base class, but different implementations. A member’s new implementation can call the original implementation in the parent class by preceding the member name with MyBase.

Constructors and Destructors
Constructors are procedures that control initialization of new instances of a class. Conversely, destructors are methods that free system resources when a class leaves scope or is set to Nothing. Visual Basic .NET supports constructors and destructors using the Sub New and Sub Finalize procedures.

Data Types
Visual Basic .NET introduces three new data types. The Char data type is an unsigned 16-bit quantity used to store Unicode characters. It is equivalent to the .NET Framework System. Char data type. The Short data type, a signed 16-bit integer, was named Integer in earlier versions of Visual Basic. The Decimal data type is a 96-bit signed integer scaled by a variable power of 10. In earlier versions of Visual Basic, it was available only within a Variant.

Interfaces
Interfaces describe the properties and methods of classes, but unlike classes, do not provide implementations. The Interface statement allows you to declare interfaces, while the Implements statement lets you write code that puts the items described in the interface into practice.

Delegates
Delegates objects that can call the methods of objects on your behalf are sometimes described as type-safe, object-oriented function pointers. You can use delegates to let procedures specify an event handler method that runs when an event occurs. You can also use delegates with multithreaded applications. For details, see Delegates and the AddressOf Operator.

Shared Members
Shared members are properties, procedures, and fields that are shared by all instances of a class. Shared data members are useful when multiple objects need to use information that is common to all. Shared class methods can be used without first creating an object from a class.

References
References allow you to use objects defined in other assemblies. In Visual Basic .NET, references point to assemblies instead of type libraries. For details, see References and the Imports Statement. Namespaces Namespaces prevent naming conflicts by organizing classes, interfaces, and methods into hierarchies.

Assemblies
Assemblies replace and extend the capabilities of type libraries by, describing all the required files for a particular component or application. An assembly can contain one or more namespaces.

Attributes
Attributes enable you to provide additional information about program elements. For example, you can use an attribute to specify which methods in a class should be exposed when the class is used as a XML Web service.

Multithreading
Visual Basic .NET allows you to write applications that can perform multiple tasks independently. A task that has the potential of holding up other tasks can execute on a separate thread, a process known as multithreading. By causing complicated tasks to run on threads that are separate from your user interface, multithreading makes your applications more responsive to user input.

13. Advantages of VB.NET

First of all, VB.NET provides managed code execution that runs under the Common Language Runtime (CLR), resulting in robust, stable and secure applications. All features of the .NET framework are readily available in VB.NET.

VB.NET is totally object oriented. This is a major addition that VB6 and other earlier releases didn’t have.

The .NET framework comes with ADO.NET, which follows the disconnected paradigm, i.e. once the required records are fetched the connection no longer exists. It also retrieves the records that are expected to be accessed in the immediate future. This enhances Scalability of the application to a great extent.

VB.NET uses XML to transfer data between the various layers in the DNA Architecture i.e. data are passed as simple text strings.

Error handling has changed in VB.NET. A new Try-Catch-Finally block has been introduced to handle errors and exceptions as a unit, allowing appropriate action to be taken at the place the error occurred thus discouraging the use of ON ERROR GOTO statement. This again credits to the maintainability of the code.

Another great feature added to VB.NET is free threading against the VB single-threaded apartment feature. In many situations developers need spawning of a new thread to run as a background process and increase the usability of the application. VB.NET allows developers to spawn threads wherever they feel like, hence giving freedom and better control on the application.

Security has become more robust in VB.NET. In addition to the role-based security in VB6, VB.NET comes with a new security model, Code Access security. This security controls on what the code can access. For example you can set the security to a component such that the component cannot access the database. This type of security is important because it allows building components that can be trusted to various degrees.

The CLR takes care of garbage collection i.e. the CLR releases resources as soon as an object is no more in use. This relieves the developer from thinking of ways to manage memory. CLR does this for them.

14. Using ActiveX Control in .Net
ActiveX control is a special type of COM component that supports a User Interface. Using ActiveX Control in your .Net Project is even easier than using COM component. They are bundled usually in .ocx files. Again a proxy assembly is made by .Net utility AxImp.exe (which we will see shortly) which your application (or client) uses as if it is a .Net control or assembly.

Making Proxy Assembly For ActiveX Control: First, a proxy assembly is made using AxImp.exe (acronym for ActiveX Import) by writing following command on Command Prompt:

C:> AxImp C:MyProjectsMyControl.ocx

This command will make two dlls, e.g., in case of above command

MyControl.dll
AxMyControl.dll

The first file MyControl.dll is a .Net assembly proxy, which allows you to reference the ActiveX as if it were non-graphical object.
The second file AxMyControl.dll is the Windows Control, which allows u to use the graphical aspects of activex control and use it in the Windows Form Project.

Adding Reference of ActiveX Proxy Assembly in your Project Settings: To add a reference of ActiveX Proxy Assembly in our Project, do this:

o Select ProjectàAdd Reference (Select Add Reference from Project Menu).
o This will show you a dialog box, select .Net tab from the top of window.
o Click Browse button on the top right of window.
o Select the dll file for your ActiveX Proxy Assembly (which is MyControl.dll) and click OK o Your selected component is now shown in the ‘Selected Component’ List Box. Click OK again Some More On Using COM or ActiveX in .Net

.Net only provides wrapper class or proxy assembly (Runtime Callable Wrapper or RCW) for COM or activeX control. In the background, it is actually delegating the tasks to the original COM, so it does not convert your COM/activeX but just imports them.

A good thing about .Net is that when it imports a component, it also imports the components that are publically referenced by that component. So, if your component, say MyDataAcsess.dll references ADODB.dll then .Net will automatically import that COM component too!

The Visual Studio.NET does surprise you in a great deal when u see that it is applying its intellisense (showing methods, classes, interfaces, properties when placing dot) even on your imported COM components!!!! Isn’t it a magic or what?

When accessing thru RCW, .Net client has no knowledge that it is using COM component, it is presented just as another C# assembly.

U can also import COM component thru command prompt (for reference see Professional C# by Wrox)

U can also use your .Net components in COM, i.e., export your .net components (for reference see Professional C# by Wrox)

15. What is Machine.config?
Machine configuration file: The machine.config file contains settings that apply to the entire computer. This file is located in the %runtime install path%Config directory. There is only one machine.config file on a computer. The Machine.Config file found in the “CONFIG” subfolder of your .NET Framework install directory (c:WINNTMicrosoft.NETFramework{Version Number}CONFIG on Windows 2000 installations). The machine.config, which can be found in the directory $WINDIR$Microsoft.NETFrameworkv1.0.3705CONFIG, is an XML-formatted configuration file that specifies configuration options for the machine. This file contains, among many other XML elements, a browserCaps element. Inside this element are a number of other elements that specify parse rules for the various User-Agents, and what properties each of these parsings supports.

For example, to determine what platform is used, a filter element is used that specifies how to set the platform property based on what platform name is found in the User-Agent string. Specifically, the machine.config file contains:

platform=Win95
platform=Win98
platform=WinNT


That is, if in the User-Agent string the string “Windows 95″ or “Win95″ is found, the platform property is set to Win95. There are a number of filter elements in the browserCaps element in the machine.config file that define the various properties for various User-Agent strings.

Hence, when using the Request.Browser property to determine a user’s browser features, the user’s agent string is matched up to particular properties in the machine.config file. The ability for being able to detect a user’s browser’s capabilities, then, is based upon the honesty in the browser’s sent User-Agent string. For example, Opera can be easily configured to send a User-Agent string that makes it appear as if it’s IE 5.5. In this case from the Web server’s perspective (and, hence, from your ASP.NET Web page’s perspective), the user is visiting using IE 5.5, even though, in actuality, he is using Opera.

16. What is Web.config?
In classic ASP all Web site related information was stored in the metadata of IIS. This had the disadvantage that remote Web developers couldn’t easily make Web-site configuration changes. For example, if you want to add a custom 404 error page, a setting needs to be made through the IIS admin tool, and you’re Web host will likely charge you a flat fee to do this for you. With ASP.NET, however, these settings are moved into an XML-formatted text file (Web.config) that resides in the Web site’s root directory. Through Web.config you can specify settings like custom 404 error pages, authentication and authorization settings for the Web sitempilation options for the ASP.NET Web pages, if tracing should be enabled, etc.

The Web.config file is an XML-formatted file. At the root level is the tag. Inside this tag you can add a number of other tags, the most common and useful one being the system.web tag, where you will specify most of the Web site configuration parameters. However, to specify application-wide settings you use the tag.
For example, if we wanted to add a database connection string parameter we could have a Web.config file like so.

17. What is the difference between ADO and ADO.NET?
ADO uses Recordsets and cursors to access and modify data. Because of its inherent design, Recordset can impact performance on the server side by tying up valuable resources. In addition, COM marshalling – an expensive data conversion process – is needed to transmit a Recordset. ADO.NET addresses three important needs that ADO doesn’t address:
1. Providing a comprehensive disconnected data-access model, which is crucial to the Web environment
2. Providing tight integration with XML, and
3. Providing seamless integration with the .NET Framework (e.g., compatibility with the base class library’s type system). From an ADO.NET implementation perspective, the Recordset object in ADO is eliminated in the .NET architecture. In its place, ADO.NET has several dedicated objects led by the DataSet object and including the DataAdapter, and DataReader objects to perform specific tasks. In addition, ADO.NET DataSets operate in disconnected state whereas the ADO RecordSet objects operated in a fully connected state.

In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. A recordset looks like a single table. If a recordset is to contain data from multiple database tables, it must use a JOIN query, which assembles the data from the various database tables into a single result table. In contrast, a dataset is a collection of one or more tables. The tables within a dataset are called data tables; specifically, they are DataTable objects. If a 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, a dataset can mimic the structure of the underlying database.
In ADO you scan sequentially through the rows of the recordset using the ADO MoveNext method. In ADO.NET, rows are represented as collections, so you can loop through a table as you would through any collection, or access particular rows via ordinal or primary key index. A cursor is a database element that controls record navigation, the ability to update data, and the visibility of changes made to the database by other users. ADO.NET does not have an inherent cursor object, but instead includes data classes that provide the functionality of a traditional cursor. For example, the functionality of a forward-only, read-only cursor is available in the ADO.NET DataReader object.
There is one significant difference between disconnected processing in ADO and ADO.NET. In ADO you communicate with the database by making calls to an OLE DB provider. In ADO.NET you communicate with the database through a data adapter (an OleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs provided by the underlying data source.

17. What is the difference between VB and VB.NET?
Now VB.NET is object-oriented language. The following are some of the differences:
Data Type Changes
The .NET platform provides Common Type System to all the supported languages. This means that all the languages must support the same data types as enforced by common language runtime. This eliminates data type incompatibilities between various languages. For example on the 32-bit Windows platform, the integer data type takes 4 bytes in languages like C++ whereas in VB it takes 2 bytes. Following are the main changes related to data types in VB.NET:

. Under .NET the integer data type in VB.NET is also 4 bytes in size.
. VB.NET has no currency data type. Instead it provides decimal as a replacement.
. VB.NET introduces a new data type called Char. The char data type takes 2 bytes and can store Unicode characters.
. VB.NET do not have Variant data type. To achieve a result similar to variant type you can use Object data type. (Since every thing in .NET including primitive data types is an object, a variable of object type can point to any data type).
. In VB.NET there is no concept of fixed length strings.
. In VB6 we used the Type keyword to declare our user-defined structures. VB.NET introduces the structure keyword for the same purpose.
Declaring Variables
Consider this simple example in VB6:
Dim x,y as integer

In this example VB6 will consider x as variant and y as integer, which is somewhat odd behavior. VB.NET corrects this problem, creating both x and y as integers.
Furthermore, VB.NET allows you to assign initial values to the variables in the declaration statement itself:
br> Dim str1 as string = Hello

VB.NET also introduces Read-Only variables. Unlike constants Read-Only variables can be declared without initialization but once you assign a value to it, it cannot be changes.

Initialization here
Dim readonly x as integer
In later code
X=100
Now x can’t be changed
X=200 *********** Error **********
Property Syntax
In VB.NET, we anymore don’t have separate declarations for Get and Set/Let. Now, everything is done in a single property declaration. This can be better explained by the following example.
Public [ReadOnly | WriteOnly] Property PropertyName as Datatype
Get
Return m_var
End Get
Set
M_var = value
End Set
End Property

Example:
Private _message as String
Public Property Message As String
Get
Return _message
End Get
Set
_message = Value
End Set
End Property

ByVal is the default – This is a crucial difference betwen VB 6.0 and VB.NET, where the default in VB 6.0 was by reference. But objects are still passed by reference.

Invoking Subroutines In previous versions of VB, only functions required the use of parentheses around the parameter list. But in VB.NET all function or subroutine calls require parentheses around the parameter list. This also applies, even though the parameter list is empty.

User-Defined Types – VB.NET does away with the keyword Type and replaces it with the keyword Structure
Public Structure Student
Dim strName as String
Dim strAge as Short
End Structure

Procedures and Functions

In VB6 all the procedure parameters are passed by reference (ByRef) by default. In VB.NET they are passed by value (ByVal) by default. Parantheses are required for calling procedures and functions whether they accept any parameters or not. In VB6 functions returned values using syntax like: FuntionName = return_value. In VB.NET you can use the Return keyword (Return return_value) to return values or you can continue to use the older syntax, which is still valid.

Scoping VB.NET now supports block-level scoping of variables. If your programs declare all of the variables at the beginning of the function or subroutine, this will not be a problem. However, the following VB 6.0 will cause an issue while upgrading to VB .NET

Do While objRs.Eof
Dim J as Integer
J=0
If objRs(“flag”)=”Y” then
J=1
End If
objRs.MoveNext
Wend
If J Then
Msgbox “Flag is Y”
End If

In the above example the variable J will become out of scope just after the loop, since J was declared inside the While loop.

Exception Handling

The most wanted feature in earlier versions of VB was its error handling mechanism. The older versions relied on error handlers such as “On Error GoTo and On Error Resume Next. VB.NET provides us with a more stuructured approach. The new block structure allows us to track the exact error at the right time. The new error handling mechanism is refered to as Try…Throw…Catch…Finally. The following example will explain this new feature.

Sub myOpenFile()
Try
Open “myFile” For Output As #1
Write #1, myOutput
Catch
Kill “myFile”
Finally
Close #1
End try
End Sub

The keyword SET is gone – Since everything in VB.NET is an object. So the keyword SET is not at all used to differentiate between a simple variable assignment and an object assignment. So, if you have the following statement in VB 6.0

Set ObjConn = Nothing
Should be replaced as
ObjConn = Nothing.
Constructor and Destructor

The constructor procedure is one of the many new object-oriented features of VB.NET. The constructor in VB.NET replaces the Class_Initialize in VB 6.0. All occurance of Class_Initialize in previous versions of VB should now be placed in a class constructor. In VB.NET, a constructor is added to a class by adding a procedure called New. We can also create a class destructor, which is equivalent to Class_Terminate event in VB 6.0, by adding a sub-procedure called Finalize to our class. Usage of Return In VB.NET, we can use the keyword return to return a value from any function. In previous versions, we used to assign the value back with the help of the function name itself. The following example explains this:

Public Function Sum (intNum1 as Integer, intNum2 as Integer) as Integer
Dim intSum as Integer
intSum = intNum1 + intNum2
Return intSum
End Function
Static Methods

VB.NET now allows you to create static methods in your classes. Static methods are methods that can be called without requiring the developer to create instance of the class. For example, if you had a class named Foo with the non-static method NonStatic() and the static method Static(), you could call the Static() method like so:

Foo.Static()

However, non-static methods require than an instance of the class be created, like so:

Create an instance of the Foo class
Dim objFoo as New Foo()
Execute the NonStatic() method
ObjFoo.NonStatic()

To create a static method in a VB.NET, simply prefix the method definition with the keyword Shared.

Posted in .Net, Interview Question | Tagged: , , , , , , , , , | Leave a Comment »

ASP.NET Interview Question

Posted by Admin on January 8, 2009

Q1.what are the new features in ASP.NET 2.0?

A1. ASP.NET is a programming framework built on the common language runtime that can be used on a server to build powerful Web applications. The first version of ASP.NET offered several important advantages over previous Web development models. ASP.NET 2.0 improves upon that foundation by adding support for several new and exciting features in the areas of developer productivity, administration and management, extensibility, and performance.

1) New Server Controls: ASP.NET 2.0 introduces many new server controls that enable powerful declarative support for data access, login security, wizard navigation, menus, treeviews, portals, and more. Many of these controls take advantage of core application services in ASP.NET for scenarios like data access, membership and roles, and personalization.

* Data Controls: gridview, detailsview, and formview

* Navigation Controls: treeview, menu, and sitemappath

* Login Controls: login forms, create user forms, password retrieval, and custom UI for logged in users or roles

* Web Part Controls

2) Master Pages: This feature provides the ability to define common structure and interface elements for your site, such as a page header, footer, or navigation bar, in a common location called a “master page”, to be shared by many pages in your site.

In one simple place you can control the look, feel, and much of functionality for an entire Web site. This improves the maintainability of your site and avoids unnecessary duplication of code for shared site structure or behavior.

3) Themes and Skins. The themes and skins features in ASP.NET 2.0 allow for easy customization of your site’s look-and-feel. You can define style information in a common location called a “theme”, and apply that style information globally to pages or controls in your site. Like Master Pages, this improves the maintainability of your site and avoid unnecessary duplication of code for shared styles.

4) Personalization. Using the new personalization services in ASP.NET 2.0 you can easily create customized experiences within Web applications. The Profile object enables developers to easily build strongly-typed, sticky data stores for user accounts and build highly customized, relationship based experiences. At the same time, a developer can leverage Web Parts and the personalization service to enable Web site visitors to completely control the layout and behavior of the site, with the knowledge that the site is completely customized for them. Personalizaton scenarios are now easier to build than ever before and require significantly less code and effort to implement.
5) Localization. Enabling globalization and localization in Web sites today is difficult, requiring large amounts of custom code and resources. ASP.NET 2.0 and Visual Studio 2005 provide tools and infrastructure to easily build Localizable sites including the ability to auto-detect incoming locale’s and display the appropriate locale based UI. Visual Studio 2005 includes built-in tools to dynamically generate resource files and localization references. Together, building localized applications becomes a simple and integrated part of the development experience.
6) Administration and Management – New tools like Configuration API, ASP.NET MMC Admin Tool, Pre-compilation Tool, Health Monitoring and Tracing have been introduced.

Q2. What is Visual Web Developer? Is it Different from Visual Studio 2005?

A2. Visual Web Developer 2005 Express Edition is part of the Microsoft Visual Studio 2005 family, and is the best development tool for building data driven web applications with ASP.NET 2.0. As part of the Express family, Visual Web Developer provides a seamless upgrade path to Visual Studio Standard, Professional, and Team System.

Yes its different from Visual Studio 2005, this one is available as a free download while Visual Studio 2005 has several versions that may be purchased from MS. ¼br>
Q3. What are features of Visual Web Developer?

A3. Intellisense Everywhere – the popup code hints which appear while you type — has a dramatic impact on your productivity as a developer. While support for Intellisense in Visual Studio .NET 2003 is excellent today, support for Intellisense in Visual Web Developer gets even better.

In Visual Web Developer, Intellisense pops up everywhere. For example, you can take full advantage of Intellisense within the script blocks in single file ASP.NET pages. In addition, Visual Web Developer also supports Intellisense for ASP.NET Page Directives and for inline CSS style attributes within a page.

Visual Web Developer also provides Intellisense for all sections within a Web.Config configuration file, as well as any generic XML file that contains a DTD or XML Schema reference.

HTML Source Preservation
Visual Web Developer respects your HTML. The formatting of your HTML markup — including all white space, casing, indention, carriage returns, and word wrapping — is now preserved exactly as originally written, even when switching back and forth between the design view and source view of the page. You can completely trust Visual Web Developer to never modify your markup.

HTML Formatting Options
Visual Web Developer enables you to precisely control the format of all HTML and ASP.NET Server Control markup generated using the WYSIWYG designer. You can now configure the tag casing, attribute quotation, indention style and word wrap characteristics of every html or server control tag in a page. You can set these formatting options as defaults for all markup, as well as optionally override each formatting option on a per tag/control basis. This provides you with the flexibility to fully control exactly how you want your markup to be generated.

Tag Navigator
The HTML source editor within Visual Web Developer ships with a new Tag Navigator feature that enables developers to easily track their location and navigate within a complicated HTML document. The Tag Navigator displays the current “path” within the source of an HTML page by displaying a list of all the HTML tags which contain the tag where your cursor is currently located. Clicking on any of the nodes enables developers to optionally change the source level selection, and quickly move up and down a deep HTML hierarchy.

Tag Outlining
Tag Outlining enables you to work more effectively with large HTML documents. With Tag Outlining, you can right-click any HTML tag in the source editor and select Collapse Tag to hide the entire contents of the tag. Collapsing different regions of the HTML source code contained in a page makes it easier to focus on the particular region of the page which you need to edit.
Flexible Browser Targeting and Validation
Visual Web Developer enables you to easily target a specific HTML standard or browser when writing your HTML pages. For example, you can target your HTML pages to work with a particular browser such as Netscape Navigator 4.0 or Internet
Explorer 6.0. Alternatively, you can target a particular HTML standard such as XHTML 1.0 Strict or XHTML 1.0 Transitional.

Q4. What is Code Refactoring?

A4. Its a feature of Visual Web Express & Visual Studio 2005. Code Refactoring
Code Refactoring enables you to easily and systematically make changes to your code. Code Refactoring is supported everywhere that you can write code including both code-behind and single-file ASP.NET pages. For example, you can use Code Refactoring to automatically promote a public field to a full property.

Q5. What is Intellitask?

A5. Intellitask is like a super smart clipboard designed for working with code. Intellitask improves your productivity by enabling you to easily apply standard code snippets anywhere within the source editor. Simply by right-clicking, you can inject common code into your pages. Visual Web Developer will ship with more than 200 web specific Intellitask code snippets out of the box. Better yet, you can add your own code templates to Intellitask so that you can quickly modify your code in the future.

Q6. How to we edit templates & tables while developing applications in ASP.NET 2.0?

A6. Visual Web Developer has better designer support for editing templates. You can take advantage of the new template editing features when working with data controls such as the DataList and GridView controls.

When adding a control to a template in the designer, you can easily specify the databound expressions to associate with the control properties. For example, if you drag a TextBox control onto a template, you can bind the TextBox control’s Text property to a particular field from the data control’s data source. The Edit Databindings dialog box provided by the Visual Web Developer template editing designer enables you to easily bind particular fields by name.

Visual Web Developer has better HTML table editing features. The improved Insert Table dialog box enables you to quickly control the look and feel of the new table when it is added to the designer surface. In addition, Visual Web Developer provides the ability to resize tables, table columns and table rows graphically within the designer surface (just click and hold down the appropriate element to size it).

Q7. Do we need FrontPage Server Extensions with ASP.NET 2.0 applications?

A7. When we create ASP.NET 2.0 applications on Visual Web Developer OR Visual Studio 2005, We dont need Frontpage Server Extensions as we required in ASP.NET 1.1. When you create a new IIS project, you can now view all of the Web sites and applications configured on your machine. You can even create new IIS Web applications or virtual directories directly from the New Web Site dialog box.

Frontpage Server Extensions (FPSE) are no longer required for locally developed IIS web applications. You can create and fully manage your websites without having to install or configure them.

Q8. Can we develop web pages directly on an FTP server?

A8. Yes. Visual Web Developer now has built-in support for editing and updating remote web projects using the standard File Transfer Protocol (FTP). You can quickly connect to a remote Web site using FTP within the New Web Site and Open Web Site dialog box.

Q9. What is precompilation in ASP.NET 2.0? What is a pre-compiled website?

A9. When the first request arrives at your web application there is a mind-numbing amount of work to do. The worker process starts, the runtime initializes, ASPX pages are parsed and compiled to intermediate language, methods are just-in-time compiled to native code – and the list goes on and on. If you want to cut out some of the overhead and improve the startup time of your application, then you’ll want to look at the precompile features in ASP.NET 2.0.

Although pre-compilation will give our site a performance boost, the difference in speed will only be noticeable during the first request to each folder. Perhaps a more important benefit is the new deployment option made available by the precompile – the option to deploy a site without copying any of the original source code to the server. This includes the code and markup in aspx, ascx, and master files.

There are 2 types of pre-compilation:
(i) In Place Precompilation
(ii) Precompilation for Deployment

In Place Precompilation -> By default, ASP.NET dynamically parses and compiles all the ASPX pages in a folder when the first request arrives for a page inside that folder. ASP.NET also needs to compile applicable files in the special folders, like App_Code, on the first request, and any code-behind files associated with ASPX and ASCX files. The runtime caches all the compilation results in order to quickly process later requests, and does not need to recompile again unless someone edits a file. This behavior gives us a great deal of flexibility, including the flexibility to change code and arkup and instantly have the changes reflected in the next browser request.

The price for this flexibility is the performance hit on the first request. Some people have found their ASP.NET applications to be slow starters. These people usually work in the sales department and perform software demos in front of customers. In place pre-compilation makes the “first hit” to a web application and forces all pages and code in the application to compile.

The tool to use for pre-compilation is the aspnet_compiler executable, which you can find in the %WINDIR%\Microsoft.NET\Framework\v2.x.xxxx directory. If we have a web application in the WebSite1 virtual directory under IIS, we could use the following command line to compile the pplication.

C:\Windows\Microsoft.NET\Framework\v2.0.50215>aspnet_compiler -v /Website1

The –v parameter specifies that we are passing a virtual path to our web site. On servers with multiple websites you may need

to use the –m parameter and specify the full IIS metabase path to the application (-m /LM/W3SVC/1/Root/WebSite1).

The pre-compiled code will end up inside of the Temporary ASP.NET File directory, just as it would when the runtime compiles files for a browser request. Inside of the bin directory for the compiled site, you’ll find the assemblies (dll files). The compiler generates special filenames to avoid naming collisions. In the shot below, the dll starting with App_Code contains the code from the App_Code directory – not too surprising. Each folder containing aspx, or ascx files will compile into a dll prefixed with App_Web. The files with a .compiled extension contain XML with information about which original source code file maps to which assembly.

You may find these files in the following location of your computer.
C:\windows\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files

With the compiled files in place your web application should have a slightly better startup time, but a primary benefit to in place pre-compilation will be the ability to ensure the web application is error free. If you happen to modify a class or web form and leave an error in the file, the aspnet_compiler will fail and display the compiler error. The tool will also display any warnings, but warning will not stop compilation.
Pre-compilation For Deployment –> Pre-compilation for deployment creates an ‘executable’ (no source code) version of your web application. With pre-compilation for deployment you give the aspnet_compiler the path to your source code, and the path to a target directory for the compilation results, like below.

aspnet_compiler -p “C:\MyDevelopment\WebSite1″ -v / C:\MyStage

This command will compile the site and place the result in C:\Staging. You must still specify –v as a parameter, even though we are not using a virtual path as either a source or a destination. Instead, the compiler will use this parameter to resolve application root references (~).

The pre-compilation for deployment step will recreate your web site’s folder structure in the destination directory. All of the static files (HTML files, image files, configuration files) are copied into the folder structure exactly as they appear in the source folder hierarchy. A bin directory will appear in the target directory with all of the assemblies and .compiled files.

The target directory will contain no source code. All of the classes in the App_Code folder are now compiled into one or more assemblies in the bin directory, and no .cs or .vb files will exist in the target directory. Master page files will also compile to the bin directory and not exist. All the code and markup in ASPX, ASCX, and ASHX files, along with any associated code-behind files, will live inside of one or more assemblies in the bin directory, although these files will still exist in the target directory, they exist as nearly empty ‘marker’ files. If you open an ASPX file in a pre-compiled target directory you’ll see the following content:

This is a marker file generated by the precompilation tool, and should not be deleted!

Once the application finishes compiling you can FTP or XCOPY the target directory to a web server (or map a virtual directory to the target directory), and the application will be ready to run. A benefit to pre-compilation for deployment is that no one can make changes to the web application by tweaking the source code – no source code exists! In fact, you can’t even place a new ASPX file into the existing application directory structure without causing an error.

Q10. If a web application is pre-compiled, How do you make changes to it?

A10. Making a change to your site will require you to make a change in the original source code, pre-compile the application again, and redeploy all files to the server.

When we recompile an already pre-compiled website, what should be kept in mind?

Pre-compilation generates unique filenames for some assemblies in the bin folder, and these filenames will change each time the pre-compiler executes. The first time you run aspnet_compiler you might see App_Web_murhs6vm.dll in the bin directory, the next time you might see App_Web_gvohdjw.dll with the same compiled code, even though no source file has changed. This means you might have unneeded dlls in your bin directory if you keep repeatedly copy files to the server without cleanup.¼br>
Q11. Is Visual Web Developer XHTML compliant?

A11. Yes.

Q12. What are server controls?

A12. ASP.NET pages can contain server controls, which are programmable server-side objects that typically represent a UI element in the page, such as a textbox or image. Server controls participate in the execution of the page and produce their own markup rendering to the client. The principle advantage of server controls is that they enable developers to get complex rendering and behaviors from simple building-block components, dramatically reducing the amount of code it takes to produce a dynamic Web page. Another advantage of server controls is that it is easy to customize their rendering or behavior. Server controls expose properties that can be set either declaratively (on the tag) or programmatically (in code). Server controls (and the page itself) also expose events that developers can handle to perform specific actions during the page execution or in response to a client-side action that posts the page back to the server (a “postback”). Server controls also simplify the problem of retaining state across round-trips to the server, automatically retaining their values across successive postbacks.

Server controls are declared within an .aspx file using custom tags or intrinsic HTML tags that contain a runat=”server” attribute value. Intrinsic HTML tags are handled by one of the controls in the System.Web.UI.HtmlControls namespace. Any tag that doesn’t explicitly map to one of the controls is assigned the type of System.Web.UI.HtmlControls.HtmlGenericControl.

Q13. How do server control handle events?

A13. ASP.NET server controls can optionally expose and raise server events, which can be handled by page developers. A page developer may accomplish this by declaratively wiring an event to a control (where the attribute name of an event wireup indicates the event name and the attribute value indicates the name of a method to call).

Sub EnterBtn_Click(Sender As Object, E As EventArgs)
Message.Text = “Hi ” & Name.Text & “, wazzup there!”
End Sub

Q14. How to Navigate to another page?

A14. The following sample demonstrates how to use the <asp:hyperlink runat=server> control to navigate to another page (passing custom query string parameters along the way). The sample then demonstrates how to easily get access to these query string parameters from the target page.

<asp:hyperlink id=”hl_Link” runat=server text=”click here” NavigateUrl=”www.somelink.com“>
</asp:hyperlink>

This navigation triggers when a click is made on the hyperlink. If we want navigation to trigger through code, we may use response.redirect(URL) or server.transfer(URL)

Q15. What is Simplified Code Behind Model in ASP.NET 2.0?

A15. ASP.NET 2.0 introduces an improved runtime for code-behind pages that simplifies the connections between the page and code. In this new code-behind model, the page is declared as a partial class, which enables both the page and code files to be compiled into a single class at runtime. The page code refers to the code-behind file in the CodeFile attribute of the <%@ Page %> directive, specifying the class name in the Inherits attribute. Note that members of the code behind class must be either public or protected (they cannot be private).

Example

Codebehind

Partial Class CodeBehind_vb_aspx
Inherits System.Web.UI.Page

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Label1.Text = “Hello ” & TextBox1.Text
End Sub
End Class

Inline Code

<%@ page language=”VB” CodeFile=”CodeBehind_vb.aspx.vb” Inherits=”CodeBehind_vb_aspx” %>

<html>
<head>
<title>ASP.NET CodeBehind Pages</title>
</head>
<body>
<form runat=”server”>
<h1>Welcome to ASP.NET 2.0!</h1>
<b>Enter Your Name:</b>
<asp:TextBox ID=”TextBox1″ Runat=”server”/>
<asp:Button ID=”Button1″ Text=”Click Me” OnClick=”Button1_Click” Runat=”server”/>
<br />
<br />
<asp:Label ID=”Label1″ Text=”Hello” Runat=”server” />
</form>
</body>
</html>

Q16. Whats the advantage of Simplified Code Behind model?

A16. The advantage of the simplified code-behind model over previous versions is that you do not need to maintain separate declarations of server control variables in the code-behind class. Using partial classes (new in 2.0) allows the server control IDs of the ASPX page to be accessed directly in the code-behind file. This greatly simplifies the maintenance of code-behind pages.

Q17. Whats the use of App_Code directory in ASP.NET 2.0?

A17. Just as pages can be compiled dynamically at runtime, so can arbitrary code files (for example .cs or .vb files). ASP.NET 2.0 introduces the App_Code directory, which can contain standalone files that contain code to be shared across several pages in your application. Unlike ASP.NET 1.x, which required these files to be precompiled to the Bin directory, any code files in the App_Code directory will be dynamically compiled at runtime and made available to the application. It is possible to place files of more than one language under the App_Code directory, provided they are partitioned in subdirectories (registered with a particular language in Web.config).

Q18. Can we put code created in different languages in the same App_Code directory?

A18. By default, the App_Code directory can only contain files of the same language. However, you may partition the App_Code directory into subdirectories (each containing files of the same language) in order to contain multiple languages under the

App_Code directory. To do this, you need to register each subdirectory in the Web.config file for the application.

<configuration>
<system.web>
<compilation>
<codeSubDirectories>
<add directoryName=”Subdirectory”/>
</codeSubDirectories>
</compilation>
</system.web>
</configuration>

Q19. Whats the difference between Bin folder and App_Code folder?

A19. The Bin directory is like the Code directory, except it can contain precompiled assemblies. This is useful when you need to use code that is possibly written by someone other than yourself, where you don’t have access to the source code (VB or C# file) but you have a compiled DLL instead. Simply place the assembly in the Bin directory to make it available to your site.

By default, all assemblies in the Bin directory are automatically loaded in the app and made accessible to pages. You may need to Import specific namespaces from assemblies in the Bin directory using the @Import directive at the top of the page.

<@ Import Namespace=”MyCustomNamespace”>

Q20. How to register Assemblies in GAC (Global Assembly Cache)?

A20. The .NET Framework 2.0 includes a number of assemblies that represent the various parts of the Framework. These assemblies are stored in the global assembly cache, which is a versioned repository of assemblies made available to all applications on the machine (not just a specific application, as is the case with Bin and App_Code). Several assemblies in the Framework are automatically made available to ASP.NET applications. You can register additional assemblies by registration in a Web.config file in your application.

<configuration>
<compilation>
<assemblies>
<add assembly=”System.Data, Version=1.0.2411.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089″/>
</assemblies>
</compilation>
</configuration>

Note that you still need to use an @Import directive to make the namespaces in these assemblies available to individual pages.

Q21. Can we bind data to Server Controls without writing code in ASP.NET 2.0?

A21. Yes. ASP.NET 2.0 enables a declarative solution for data binding which requires no code at all for the most common data scenarios, such as:
Selecting and displaying data
Sorting, Paging and Caching Data
Updating, Inserting and Deleting Data
Filtering or Master-Details Using Parameters

ASP.NET 2.0 introduces two types of server controls that participate in this declarative data binding model. These two types of data controls handle the complexity of the stateless Web model for data scenarios, so developers don’t need to understand page request lifecycle events just to perform data binding. Another benefit of this control-based model is that it can be easily extended to support additional data access storage providers.

Q22. What are data source controls?

A22. Data source controls have no rendering, but instead represent a particular backend data store, for example a database, business object, XML file, or XML Web Service. Data source controls also enable rich capabilities over data – such as sorting, paging, filtering, updating, deleting, and inserting – that data-bound UI controls can automatically use. ASP.NET includes the following server controls out-of-the-box:

SqlDataSource Enables binding to a SQL database represented by an ADO.NET provider, such as Microsoft™ SQL Server, OLEDB, ODBC, or Oracle.
ObjectDataSource Enables binding to a middle-tier object such as a data access layer or business component.
AccessDataSource Enables binding to a Microsoft™ Access (Jet) database.
SiteMapDataSource Enables binding to the hierarchy exposed by an ASP.NET 2.0 site navigation provider.
XmlDataSource Enables binding to an XML file or document.

Q23. What are data bound controls?

A23. Data-bound controls are UI controls that render data as markup to the requesting client device or browser. A data-bound control can auto-bind to data exposed from a data source and will fetch data at the appropriate time in the page request lifecycle. These controls can optionally take advantage of data source capabilities such as sorting, paging, filtering, updating, deleting, and inserting. A data-bound control connects to a data source control through its DataSourceID property.

You may be familiar with some of the data-bound controls in ASP.NET v1.x, such as DataGrid, DataList, Repeater, and list controls like DropDownList. ASP.NET 2.0 contains several new data-bound controls as well, such as:

GridView Renders data in a grid format. This control is an evolution of the DataGrid control, and can automatically take advantage of data source capabilities.
DetailsView Renders a single data item in a table of label/value pairs, similar to the form view in Microsoft™ Access. This control can also automatically take advantage of data source capabilities.
FormView Renders a single data item at a time in a form defined by a custom template. Renders a single data item in a table of label/value pairs, similar to the form view in Microsoft™ Access. This control can also automatically take advantage of data source capabilities.
TreeView Renders data in a hierarchical tree view of expandable nodes.
Menu Renders data in a hierarchical dynamic menu (including flyouts).

Q24. What is a Master Page? How do we use it?

A24. A Master Page is a page that contains markup and controls that should be shared across multiple pages in your site. For example, if all of your pages should have the same header and footer banners or the same navigation menu, you could define this in a Master Page once, and then all pages associated to this Master Page would inherit those common elements. The advantage of defining the header, footer, and navigation in a Master Page is that these elements need only be defined once, instead of multiple times in duplicate code across the pages in your site.

Defining a Master Page is just like defining a normal page. Master Pages can contain markup, controls, or code, or any combination of these elements. However, a Master Page can contain a special type of control, called a ContentPlaceHolder control. A ContentPlaceHolder defines a region of the master page rendering that can be substituted with content from a page associated to the master. A ContentPlaceHolder can also contain default content, just in case the derive page does not need to override this content. The syntax of a ContentPlaceHolder control is given below:

<%– ContentPlaceHolder control –%>
<asp:contentplaceholder id=”FlowerText” runat=”server”/>

<%– ContentPlaceHolder with default content –%>
<asp:contentplaceholder id=”FlowerText” runat=”server”>
<h3>Welcome to my florist website!</h3>
</asp:contentplaceholder>

To differentiate a Master Page from a normal page, a Master Page is saved under the .master file extension. A page can derive from a Master Page by defining a MasterPageFile attribute on its Page directive, as demonstrated below. A page that is associated to a Master Page is called a Content Page.

<%@ Page MasterPageFile=”Site.master” %>

Q25. What is a Content Page? How do we use it?

A25. A Content Page can declare Content controls that specifically override content placeholder sections in the Master Page. A Content control is associated to a particular ContentPlaceHolder control through its ContentPlaceHolderID property. A Content Page may only contain markup and controls inside Content controls; it cannot have any top-level content of its own. It can, however, have directives or server-side code.

<%@ Page MasterPageFile=”Site.master” %>

<asp:content id=”Content1″ contentplaceholderid=”FlowerText” runat=”server”>
Santa Clause will definitely meet you this Christmas!
</asp:content>
<asp:content id=”Content2″ contentplaceholderid=”FlowerPicture” runat=”server”>
<asp:Image id=”image1″ imageurl=”~/images/santa.jpg” runat=”server”/>
</asp:content>

Q26. How does Content page access a master page?

A26. In addition to overriding content, it is possible for a Content Page to programmatically access its Master Page. A Content Page creates a strongly-typed reference to the Master Page using the <%@ MasterType %> directive, specifying the virtual path to the master page:

<%@ MasterType VirtualPath=”Site.master” %>

The Content Page can then reference the Master Page using the Master property of the Page class:

Master.FooterText = “This is my custom footer”
Dim adr As AdRotator = Master.FindControl(“MyAdRotator”)

In the code example above, FooterText is a public property exposed on the Master Page, while MyAdRotator is a control on the Master Page.

Q27. Can we have multiple number of Master pages in an ASP.NET 2.0 web application?

A27. Yes.

Q28. Can we have multiple SiteMapPath controls in an ASP.NET 2.0 web application?

A28. Yes.

Q29. How to create a read-only Data Report using GridView?

A29. The simplest type of data-driven page is a read-only report, which displays data but does not allow the user to manipulate the presentation or modify the data. To create a read-only report against a SQL database, first configure a SqlDataSource on the page and then connect a data-bound control such as GridView to the data source by specifying its DataSourceID property. The example below shows a GridView control associated to a SqlDataSource control.

<form runat=”server”>
<asp:GridView ID=”GridView1″ DataSourceID=”SqlDataSource1″ runat=”server”/>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
SelectCommand=”SELECT [au_id], [au_lname], [au_fname] FROM [authors]“
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />
</form>

The SqlDataSource ConnectionString property specifies the connection string to the database and the SelectCommand property specifies the query to execute to retrieve data. The connection string can be specified literally in the page, but in this case the property is assigned using a new expression syntax that retrieves the value from Web.config.

<configuration>
<connectionStrings>
<add name=”Pubs” connectionString=”Server=(local);Integrated Security=True;Database=UrDatabaseName;”
providerName=”System.Data.SqlClient” />
</connectionStrings>
</configuration>

Q30. How do we sort data in a GridView?

A30. The SqlDataSource control supports sorting when its DataSourceMode property is set to “DataSet”. To enable the sorting UI in the GridView, set the AllowSorting property to true. This causes the GridView to render link buttons for its column headers that can be clicked to sort a column. The GridView control passes the SortExpression associated with the column field to the data source control, which returns the sorted data to the GridView.
Q31. Can we sort data from a SQLDataSource when mode is set to DataReader?

A31. No. Sorting is only supported by SqlDataSource when in DataSet mode.

Inline Code looks like this…

<asp:GridView ID=”GridView1″ AllowSorting=”true” runat=”server” DataSourceID=”SqlDataSource1″
AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors]“
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />

Q32. How do we enable paging in a GridView?

A32. You can enable paging UI in the GridView by setting the AllowPaging property to true. The GridView can automatically page over any return value from a data source that supports the ICollection interface. The DataView returned by SqlDataSource when in DataSet mode supports this interface, so GridView can page over the result. When in DataReader mode, the GridView cannot page over the data returned by SqlDataSource.

Inline Code looks like this…

<asp:GridView ID=”GridView1″ AllowSorting=”true” AllowPaging=”true” PageSize=”3″ runat=”server”
DataSourceID=”SqlDataSource1″ AutoGenerateColumns=”False”>
<PagerSettings Mode=”NextPreviousFirstLast” Position=”TopAndBottom” FirstPageImageUrl=”~/Images/First.gif”
LastPageImageUrl=”~/Images/Last.gif” NextPageImageUrl=”~/Images/Next.gif” PreviousPageImageUrl=”~/Images/Prev.gif” />
<PagerStyle ForeColor=”White” HorizontalAlign=”Right” BackColor=”#284775″ />
<Columns>
<asp:BoundField HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server” SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors]“
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />

Q33. How do we set the number of Records in a GridView to display?

A33. Use the PageSize property. It Gets or sets the number of records to display on a page in a GridView control.

Q34. What is the TopPagerRow property of a GridView?

A34. Gets a GridViewRow object that represents the top pager row in a GridView control.

Q35. Describe the Hotspot class?

A35. It implements the basic functionality common to all hot spot shapes. Its Namespace: System.Web.UI.WebControls

You cannot directly create instances of the abstract HotSpot class. Instead, this class is inherited by the CircleHotSpot, RectangleHotSpot, and PolygonHotSpot classes to provide the common basic functionality for a hot spot. You must derive from the HotSpot class to create a custom hot spot class that represents a unique shape that you define. However, you can define most shapes using the CircleHotSpot, RectangleHotSpot, and PolygonHotSpot classes. Its used in an ImageMap control.

Q36. What is ImageMap Control?

A36. It is a control that displays an image on a page. When a hot spot region that is defined within the ImageMap control is clicked, the control either generates a postback to the server or navigates to a specified URL.

Inline code example…

<asp:ImageMap
AccessKey=”string”
AlternateText=”string”
BackColor=”color name|#dddddd”
BorderColor=”color name|#dddddd”
BorderStyle=”NotSet|None|Dotted|Dashed|Solid|Double|Groove|Ridge|
Inset|Outset”
BorderWidth=”size”
CssClass=”string”
DescriptionUrl=”uri”
Enabled=”True|False”
EnableTheming=”True|False”
EnableViewState=”True|False”
ForeColor=”color name|#dddddd”
GenerateEmptyAlternateText=”True|False”
Height=”size”
HotSpotMode=”NotSet|Navigate|PostBack|Inactive”
ID=”string”
ImageAlign=”NotSet|Left|Right|Baseline|Top|Middle|Bottom|
AbsBottom|AbsMiddle|TextTop”
ImageUrl=”uri”
OnClick=”Click event handler”
OnDataBinding=”DataBinding event handler”
OnDisposed=”Disposed event handler”
OnInit=”Init event handler”
OnLoad=”Load event handler”
OnPreRender=”PreRender event handler”
OnUnload=”Unload event handler”
runat=”server”
SkinID=”string”
Style=”string”
TabIndex=”integer”
Target=”string”
ToolTip=”string”
Visible=”True|False”
Width=”size”
>
<asp:CircleHotSpot
AccessKey=”string”
AlternateText=”string”
HotSpotMode=”NotSet|Navigate|PostBack|Inactive”
NavigateUrl=”uri”
PostBackValue=”string”
Radius=”integer”
TabIndex=”integer”
Target=”string|_blank|_parent|_search|_self|_top”
X=”integer”
Y=”integer” />
<asp:PolygonHotSpot
AccessKey=”string”
AlternateText=”string”
Coordinates=”string”
HotSpotMode=”NotSet|Navigate|PostBack|Inactive”
NavigateUrl=”uri”
PostBackValue=”string”
TabIndex=”integer”
Target=”string|_blank|_parent|_search|_self|_top”
/>
<asp:RectangleHotSpot
AccessKey=”string”
AlternateText=”string”
Bottom=”integer”
HotSpotMode=”NotSet|Navigate|PostBack|Inactive”
Left=”integer”
NavigateUrl=”uri”
PostBackValue=”string”
Right=”integer”
TabIndex=”integer”
Target=”string|_blank|_parent|_search|_self|_top”
Top=”integer” />
</asp:ImageMap>


Q37. How do we Update & Delete data in a GridView?

A37. GridView control can automatically render UI for modifying data through Update and Delete operations, provided the associated data source is configured to support these capabilities. The SqlDataSource control supports Update operations when its UpdateCommand property is set and Delete operations when its DeleteCommand property is set to a valid update or delete command or stored procedure. The UpdateCommand or DeleteCommand should contain parameter placeholders for each value that will be passed by the GridView control (more on this below). You can also specify an UpdateParameters or DeleteParameters collection to set properties for each parameter, such as the parameter data type, input/output direction, or default value.

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
ConnectionString=”<%$ ConnectionStrings:Pubs %>”
SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors]“
UpdateCommand=”UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [state] = @state WHERE [au_id] =
@au_id”
DeleteCommand=”DELETE FROM [authors] WHERE [au_id] = @au_id”/>

To enable the UI in the GridView for Updates or Deletes, you can either set the AutoGenerateEditButton and AutoGenerateDeleteButton properties to true, or you can add a CommandField to the GridView control and enable its ShowEditButton and ShowDeleteButton properties. The GridView supports editing or deleting one row at a time. For editing, the user places the row in edit mode by clicking the Edit button, and then confirms the Update by clicking the Update button while the row is in edit mode. The user can also click the Cancel button to abort the edit operation and return to read-only mode.

Inline code example…

<asp:GridView ID=”GridView1″ AllowSorting=”true” AllowPaging=”true” Runat=”server”
DataSourceID=”SqlDataSource1″ AutoGenerateEditButton=”true” DataKeyNames=”au_id”
AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField ReadOnly=”true” HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ Runat=”server” SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone],
[address], [city], [state], [zip], [contract] FROM [authors]“
UpdateCommand=”UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =
@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id”
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />

Notice the naming convention for parameters in the Update statement assigned to UpdateCommand. The automatic capability of GridView and other data-bound controls to invoke the Update operation relies on this naming convention in order to work.

Parameters are expected to be named the same as the associated field values returned by the SelectCommand. Using this naming convention makes it possible to align the values passed by the data-bound control to the data source with the parameters in the SQL update statement.

Q38. What is the DataKeyNames property?

A38. An important property that plays a special role in Update and Delete operations is the DataKeyNames property. This property is typically set to the names of fields from the data source that are part of a primary key used to match a given row in the data source. Multiple keys are comma-separated when specifying this property declaratively, although it is common to only have one primary key field. The values of fields specified by the DataKeyNames property are round-tripped in viewstate for the sake of retaining original values to pass to an Update or Delete operation, even if that field is not rendered as one of the columns in the GridView control. When the GridView invokes the data source Update or Delete operation, it passes the values of these fields to the data source in a special Keys dictionary, separate from the Values dictionary that contains new values entered by the user while the row is in edit mode (for update operations). The contents of the Values dictionary are obtained from the input controls rendered for the row in edit mode. To exclude a value from this dictionary, set the ReadOnly property to true on the corresponding BoundField in the Columns collection. If you are using the GridView designer in Visual Studio, the ReadOnly property is set to true for primary key fields by default.

Q39. How do we filter GridView data in ASP.NET 2.0 as compared to Datagrid in ASP.NET 1.1?

A39. A common scenario in data-driven pages is the ability to filter data in a report. For example, suppose the user could select from a set of field values in a DropDownList to filter the report grid to only display rows with a matching field value. In ASP.NET v1.x, you would have needed to perform the following steps in code:
Cancel databinding in Page_Load if the request is a postback
Handle SelectedIndexChanged event
Add DropDownList SelectedValue to command’s Parameters collection
Execute the command and call DataBind

In ASP.NET 2.0, this code is eliminated through the use of declarative Data Parameter objects. A data parameter allows external values to be declaratively associated with data source operations. These parameters are usually associated with a variable in a command expression or property, for example a parameter in a SQL statement or stored procedure for

SqlDataSource. Data source controls expose parameter collection properties that can contain parameter objects for each supported data operation. For example:

<asp:DropDownList ID=”DropDownList1″ … runat=”server”/>

<asp:SqlDataSource ID=”SqlDataSource1″ runat=”server”
ConnectionString=”<%$ ConnectionStrings:Pubs %>”
SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [state] FROM [authors] WHERE [state] = @state”>
<SelectParameters>
<asp:ControlParameter Name=”state” ControlID=”DropDownList1″ PropertyName=”SelectedValue” />
</SelectParameters>
</asp:SqlDataSource>

Inline code example…

<asp:GridView ID=”GridView1″ AllowSorting=”True” AllowPaging=”True” Runat=”server”
DataSourceID=”SqlDataSource1″ AutoGenerateEditButton=”True” DataKeyNames=”au_id”
AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField ReadOnly=”true” HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ Runat=”server” SelectCommand=”SELECT [au_id], [au_lname], [au_fname], [phone],

[address], [city], [state], [zip], [contract] FROM [authors] WHERE [state] = @state”
UpdateCommand=”UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =

@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id”
ConnectionString=”<%$ ConnectionStrings:Pubs %>”>
<SelectParameters>
<asp:QueryStringParameter Name=”state” QueryStringField=”state” DefaultValue=”CA” />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name=”au_lname” />
<asp:Parameter Name=”au_fname” />
<asp:Parameter Name=”phone” />
<asp:Parameter Name=”address” />
<asp:Parameter Name=”city” />
<asp:Parameter Name=”state” />
<asp:Parameter Name=”zip” />
<asp:Parameter Name=”contract” />
<asp:Parameter Name=”au_id” />
</UpdateParameters>
</asp:SqlDataSource>


Q40. How do we enabling Caching for a DataSource Control?

A40. To enable caching for the SqlDataSource control (and also ObjectDataSource), set the EnableCaching property to true. You can specify the length of time (in seconds) to store an entry in the cache using the CacheDuration property. You can also set the CacheExpirationPolicy property to either Sliding or Absolute just as you can do from the cache API. Caching is only supported on the SqlDataSource control when the DataSourceMode property is set to “DataSet”. For example, if you set CacheDuration to 5 and SlidingExpiration to Absolute, the SqlDataSource will retrieve data from the database on the first request to the page and store this data in the cache. For subsequent requests, the SqlDataSource will attempt to retrieve the cache entry to serve the request without going back to the original database. After 5 seconds (or perhaps earlier, if cache memory pressure is high), the cache entry will be purged and a subsequent request to the page causes SqlDataSource to go back to the database again (repeating the caching process with the new data).

If you instead set CacheDuration to 5 and SlidingExpiration to Sliding, the cached data will have its time-to-live periodically refreshed as long as the data source requests the cached data once every 5 seconds. If a page requests the cached data at least once every 5 seconds, and there is no cache memory pressure, the cached data effectively remains in the cache forever. On the other hand, if no requests are made for the cached data within a 5 second time period, then the cached item is purged and the next time a request occurs the SqlDataSource control will go back to the original database again.

The example below demonstrates caching with the SqlDataSource control. The TimeStamp column updates each time the query is executed, so you can see how often the data is retrieved from the database versus retrieved from the cache. Note that approximately every five seconds, the TimeStamp updates.

Inline Code Example of Caching…

<asp:DropDownList ID=”DropDownList1″ DataSourceID=”SqlDataSource2″ AutoPostBack=”true”
DataTextField=”state” Runat=”server” />
<asp:SqlDataSource ID=”SqlDataSource2″ Runat=”server” SelectCommand=”SELECT DISTINCT [state] FROM [authors]“
ConnectionString=”<%$ ConnectionStrings:Pubs %>” />
<br />
<br />
<asp:GridView ID=”GridView1″ AllowSorting=”True” AllowPaging=”True” Runat=”server”
DataSourceID=”SqlDataSource1″ AutoGenerateEditButton=”True” DataKeyNames=”au_id”
AutoGenerateColumns=”False”>
<Columns>
<asp:BoundField DataField=”TimeStamp” HeaderText=”TimeStamp” ReadOnly=”True”>
<ItemStyle Font-Bold=”True” />
</asp:BoundField>
<asp:BoundField ReadOnly=”True” HeaderText=”ID” DataField=”au_id” SortExpression=”au_id” />
<asp:BoundField HeaderText=”Last Name” DataField=”au_lname” SortExpression=”au_lname” />
<asp:BoundField HeaderText=”First Name” DataField=”au_fname” SortExpression=”au_fname” />
<asp:BoundField HeaderText=”Phone” DataField=”phone” SortExpression=”phone” />
<asp:BoundField HeaderText=”Address” DataField=”address” SortExpression=”address” />
<asp:BoundField HeaderText=”City” DataField=”city” SortExpression=”city” />
<asp:BoundField HeaderText=”State” DataField=”state” SortExpression=”state” />
<asp:BoundField HeaderText=”Zip Code” DataField=”zip” SortExpression=”zip” />
<asp:CheckBoxField HeaderText=”Contract” SortExpression=”contract” DataField=”contract” />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID=”SqlDataSource1″ Runat=”server” SelectCommand=”SELECT DatePart(second, GetDate()) As TimeStamp,

[au_id], [au_lname], [au_fname], [phone], [address], [city], [state], [zip], [contract] FROM [authors] WHERE [state] =

@state”
UpdateCommand=”UPDATE [authors] SET [au_lname] = @au_lname, [au_fname] = @au_fname, [phone] = @phone, [address] =
@address, [city] = @city, [state] = @state, [zip] = @zip, [contract] = @contract WHERE [au_id] = @au_id”
ConnectionString=”<%$ ConnectionStrings:Pubs %>” CacheDuration=”5″ EnableCaching=”True”>
<SelectParameters>
<asp:ControlParameter Name=”state” ControlID=”DropDownList1″ />
</SelectParameters>
<UpdateParameters>
<asp:Parameter Name=”au_lname” />
<asp:Parameter Name=”au_fname” />
<asp:Parameter Name=”phone” />
<asp:Parameter Name=”address” />
<asp:Parameter Name=”city” />
<asp:Parameter Name=”state” />
<asp:Parameter Name=”zip” />
<asp:Parameter Name=”contract” />
<asp:Parameter Name=”au_id” />
</UpdateParameters>
</asp:SqlDataSource>

Q41. How to do a language switch in the Masterpage?

A41. Declare a dropdown as usual in the master page. Instead of overriding the InitializeCulture() place the same code in the Application_BeginRequest event handler in the global.asax. It is very similar to InitializeCulture() in the sense that it occurs early and no controls are ready yet. We have a little problem though, now the control is declared in a template and its name and id attributes rendered differently.

Another collection like the form variables collection that is also not originally server collection is the cookies collection. I use the cookie but it can be any of the ways for cross page communication that do not depend on server controls, like profile, session, querystring etc. We cannot use a cookie to carry the culture name value which comes from the dropdown selected item value, because the culture would always be a step behind. It would be set early on but later the dropdown selection change it but the resources for the previous culture come up. So normally only the page containing the dropdown would be a step behind, but because the dropdown is in the master page it appears that the whole site is ALWAYS ONE STEP BEHIND.

If, however, in the cookie, we pass the control name (which is information that never changes, so we can never be behind), instead of the culture name( which we can never keep up with), and then use that key to get the form variable value, we have pieced ourselves a workaround.

in the master page:

<asp:DropDownList runat=”server” ID=”DropDownList1″ AutoPostBack=”true”

OnSelectedIndexChanged=”DropDownList1_SelectedIndexChanged”>
<asp:ListItem Value=”en” Text=”English” />
<asp:ListItem Value=”fr” Text=”French” />
<asp:ListItem Value=”de” Text=”German” />
</asp:DropDownList>

protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e){
HttpCookie cookie = new HttpCookie(“DropDownName”);
cookie.Value=DropDownList1.UniqueID;
Response.SetCookie(cookie);
}

In global.asax

void Application_BeginRequest(Object sender, EventArgs e){
string lang = string.Empty;//default to the invariant culture
HttpCookie cookie = Request.Cookies["DropDownName"];

if (cookie != null && cookie.Value != null)
lang = Request.Form[cookie.Value];

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo(lang);
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(lang);
}

Notice, there is absolutely no code in any of the content pages. Thats it ten lines of code and we are done for the whole site. This is not complete code, just a tip and trick of using master page and the .net event model to globalize code.
Q42. How to send a mail using System.Net.Mail?

Imports

System.Net.Mail
Public

Class MailHelper
”’ <summary>
”’ Sends an mail message
”’ </summary>
”’ <param name=”from”>Sender address</param>
”’ <param name=”recepient”>Recepient address</param>
”’ <param name=”bcc”>Bcc recepient</param>
”’ <param name=”cc”>Cc recepient</param>
”’ <param name=”subject”>Subject of mail message</param>
”’ <param name=”body”>Body of mail message</param>
Public Shared Sub SendMailMessage(ByVal from As String, ByVal recepient As String, ByVal bcc As String, ByVal cc As

String, ByVal subject As String, ByVal body As String)
‘ Instantiate a new instance of MailMessage
Dim mMailMessage As New MailMessage()
‘ Set the sender address of the mail message
mMailMessage.From = New MailAddress(from)
‘ Set the recepient address of the mail message
mMailMessage.To.Add(New MailAddress(recepient))

‘ Check if the bcc value is nothing or an empty string
If Not bcc Is Nothing And bcc <> String.Empty Then
‘ Set the Bcc address of the mail message
mMailMessage.Bcc.Add(New MailAddress(bcc))
End If

‘ Check if the cc value is nothing or an empty value
If Not cc Is Nothing And cc <> String.Empty Then
‘ Set the CC address of the mail message
mMailMessage.CC.Add(New MailAddress(cc))
End If

‘ Set the subject of the mail message
mMailMessage.Subject = subject
‘ Set the body of the mail message
mMailMessage.Body = body

‘ Set the format of the mail message body as HTML
mMailMessage.IsBodyHtml = True
‘ Set the priority of the mail message to normal
mMailMessage.Priority = MailPriority.Normal

‘ Instantiate a new instance of SmtpClient
Dim mSmtpClient As New SmtpClient()
‘ Send the mail message
mSmtpClient.Send(mMailMessage)
End Sub
End Class

Web.config

<?

xml version=”1.0″?>
<configuration>
<system.net>
<mailSettings>
<smtp from=”
defaultEmail@yourdomain.com“>
<network host=”smtp.yourdomain.com” port=”25″ userName=”yourUserName” password=”yourPassword”/>
</smtp>
</mailSettings>
</system.net>
</configuration>

Q43. Does the ASP.NET Development Server support running web pages from a computer other than the local computer?

A43. No. It will not serve pages to another computer. Additionally, it will not serve files that are outside of the application scope. The ASP.NET Development Server provides an efficient way to test pages locally before you publish the pages to a production server running IIS.

Q44. Whats the difference between running pages on ASP.NET Development Server and IIS?

A44. An important difference between the ASP.NET Development Server and IIS is the security context in which the respective servers run your ASP.NET pages. This difference can affect your testing because of differences in how the pages run.

When you run a page using the ASP.NET Development Server, the page runs in the context of your current user account. For example, if you are running as an administrator-level user, a page running in the ASP.NET Development Server will have administrator-level privileges. In contrast, in IIS, ASP.NET by default runs in the context of the special user (ASPNET or NETWORK SERVICES) that typically has limited privileges. The ASPNET or NETWORK SERVICES accounts are local to the server computer (not domain accounts), which restricts access to resources on other computers.

If you are simply reading and running the code in ASP.NET pages, this difference is not very important. However, the different security contexts for the two Web servers can affect your testing of the following:

  • Access to other resources that the page requires This can include reading and writing files other than Web pages, reading and writing the Windows registry, and so on.
  • Database access When working with the ASP.NET Development Server, you can typically rely on Windows Integrated authentication to access SQL Server. However, when the same page runs in IIS under the ASPNET or NETWORK SERVICES account, the page is running in the context of a local user, and you often have to configure the page to use a connection string that includes information about a user and password.
  • Code access security If your page involves access to resources that are protected under different zones, the page might run differently under the ASP.NET Development Server and IIS.

Posted in ASP.Net, Interview Question | Tagged: , , , , , , , , , | 1 Comment »

C# .NET interview questions

Posted by Admin on January 8, 2009

  1. Are private class-level variables inherited?

Yes, but they are not accessible, so looking at it you can honestly say that they are not inherited. But they are.

  1. Why does DllImport not work for me?

All methods marked with the DllImport attribute must be marked as public static extern.

  1. Why does my Windows application pop up a console window every time I run it?

Make sure that the target type set in the project properties setting is set to Windows Application, and not Console Application. If you’re using the command line, compile with /target:winexe, not /target:exe.

  1. Why do I get an error (CS1006) when trying to declare a method without specifying a return type?

If you leave off the return type on a method declaration, the compiler thinks you are trying to declare a constructor. So if you are trying to declare a method that returns nothing, use void. The following is an example: // This results in a CS1006 error public static staticMethod (mainStatic obj) // This will work as wanted public static void staticMethod (mainStatic obj)

  1. Why do I get a syntax error when trying to declare a variable called checked?

The word checked is a keyword in C#.

  1. Why do I get a security exception when I try to run my C# app?

Some security exceptions are thrown if you are working on a network share. There are some parts of the frameworks that will not run if being run off a share (roaming profile, mapped drives, etc.). To see if this is what’s happening, just move the executable over to your local drive and see if it runs without the exceptions. One of the common exceptions thrown under these conditions is System.Security.SecurityException. To get around this, you can change your security policy for the intranet zone, code group 1.2, (the zone that running off shared folders falls into) by using the caspol.exe tool.

  1. Why do I get a CS5001: does not have an entry point defined error when compiling?

The most common problem is that you used a lowercase ‘m’ when defining the Main method. The correct way to implement the entry point is as follows: class test { static void Main(string[] args) {} }

  1. What optimizations does the C# compiler perform when you use the /optimize+ compiler option?

The following is a response from a developer on the C# compiler team: We get rid of unused locals (i.e., locals that are never read, even if assigned). We get rid of unreachable code. We get rid of try-catch with an empty try. We get rid of try-finally with an empty try. We get rid of try-finally with an empty finally. We optimize branches over branches: gotoif A, lab1 goto lab2: lab1: turns into: gotoif !A, lab2 lab1: We optimize branches to ret, branches to next instruction, and branches to branches.

  1. What is the syntax for calling an overloaded constructor within a constructor (this() and constructorname() does not compile)?

The syntax for calling another constructor is as follows: class B { B(int i) { } } class C : B { C() : base(5) // call base constructor B(5) { } C(int i) : this() // call C() { } public static void Main() {} }

  1. What is the equivalent to regsvr32 and regsvr32 /u a file in .NET development?

Try using RegAsm.exe. Search MSDN on Assembly Registration Tool.

  1. What is the difference between a struct and a class in C#?

From language spec: The list of similarities between classes and structs is as follows. Longstructs can implement interfaces and can have the same kinds of members as classes. Structs differ from classes in several important ways; however, structs are value types rather than reference types, and inheritance is not supported for structs. Struct values are stored on the stack or in-line. Careful programmers can sometimes enhance performance through judicious use of structs. For example, the use of a struct rather than a class for a Point can make a large difference in the number of memory allocations performed at runtime. The program below creates and initializes an array of 100 points. With Point implemented as a class, 101 separate objects are instantiated-one for the array and one each for the 100 elements.

  1. My switch statement works differently than in C++! Why?

C# does not support an explicit fall through for case blocks. The following code is not legal and will not compile in C#:

   switch(x)
{
case 0: // do something
case 1: // do something as continuation of case 0
default: // do something in common with
//0, 1 and everything else
break;
   }

To achieve the same effect in C#, the code must be modified as shown below (notice how the control flows are explicit):

class Test
{
public static void Main() {
int x = 3;
switch(x)
{
case 0: // do something
goto case 1;
case 1: // do something in common with 0
goto default;
default: // do something in common with 0, 1, and anything else
break;
}
}
}
  1. Is there regular expression (regex) support available to C# developers?

Yes. The .NET class libraries provide support for regular expressions. Look at the System.Text.RegularExpressions namespace.

  1. Is there any sample C# code for simple threading?

Yes:

using System;
using System.Threading;
class ThreadTest
{
public void runme()
{
Console.WriteLine("Runme Called");
}
public static void Main(String[] args)
{
ThreadTest b = new ThreadTest();
Thread t = new Thread(new ThreadStart(b.runme));
t.Start();
}
}
  1. Is there an equivalent of exit() for quitting a C# .NET application?

Yes, you can use System.Environment.Exit(int exitCode) to exit the application or Application.Exit() if it’s a Windows Forms app.

  1. Is there a way to force garbage collection?

Yes. Set all references to null and then call System.GC.Collect(). If you need to have some objects destructed, and System.GC.Collect() doesn’t seem to be doing it for you, you can force finalizers to be run by setting all the references to the object to null and then calling System.GC.RunFinalizers().

  1. Is there a way of specifying which block or loop to break out of when working with nested loops?

The easiest way is to use goto:

using System;
class BreakExample
{
public static void Main(String[] args) {
for(int i=0; i<3; i++)
{
Console.WriteLine("Pass {0}: ", i);
for( int j=0 ; j<100 ; j++ )
{
if ( j == 10)
goto done;
Console.WriteLine("{0} ", j);
}
Console.WriteLine("This will not print");
}
done:
Console.WriteLine("Loops complete.");
}
}
  1. Is it possible to restrict the scope of a field/method of a class to the classes in the same namespace?

There is no way to restrict to a namespace. Namespaces are never units of protection. But if you’re using assemblies, you can use the ‘internal’ access modifier to restrict access to only within the assembly.

Posted in C#, Interview Question | Tagged: , , , , , , , , , , | Leave a Comment »