Thursday, 20 October 2016

Page Events in ASP.NET

In this blog i will show you my work about the order of events when asp.net page is called.

To achieve this i have created a normal asp.net page. There i have added 2 labels and a button and then i have analysed in which order page events called.

HTML: -



Code Behind Page: -



The output of the above code when page loaded first time is: -


When click button then output would be: -

Now you may got confused why after when unload event get called, so the answer is "Response is not available in this event".

Monday, 25 January 2016

Tuesday, 5 May 2015

When to choose handler (ASHX) in ASP.NET

Every .NET developer has hear about Handler but do you know the main purpose of handlers why do we need to use them ? Why do we not replace them with normal ASPX form ?

In simple one line answer i would like to say ASPX pages are good to use when you have some controls on pages ( dynamic HTML controls ) but suppose if there is a requirement of  display dynamic images , views then it would be critical for web pages. In that scenario we use handlers for critical web pages.

There are two most important thing about Handlers that is :

First and foremost, HttpHandlers are far more reusable/portable than pages. Since there’s no visual element to an HttpHandler , they can easily be placed into their own assembly and reused from project to project or even sold as is. Secondly, the Page handler is relatively expensive. Going with the “Hello World” examples, if you do that in a page you’ll end up raising a number of events (onInit, onLoad, onPreRender, onUnload, …) and make use of a number of ASP.NET features such as viewstate and postback. In most cases, the performance hit is negligible, but it nonetheless highlights that you’re using the page framework when you have no need to.


Why not to use HttpHandlers

The biggest and very significant drawback of HttpHandlers is that they can only be used for extensions that are mapped to ASP.NET in IIS. It might be great to create a file download counter for your .zip files using an HttpHandler, but since IIS doesn’t go through ASP.NET to serve .zip files, it isn’t going to work. One solution is to map those extra extension to ASP.NET, but that might have undesirable side effects and might not even be possible for you (many developers don’t have direct access to IIS). In this case, the only solution is to create an ISAPI filter which is much more difficult. IIS 7 promises to let us write ISAPI filters in .NET (or extend HttpHandlers beyond the ASP.NET pipeline depending on how you look at it), but that’s still a ways away.

Monday, 12 January 2015

Get unread emails from Outlook on Web page

After completing my work on sending email web service. I thought if i want to read emails from my outlook then is there any way to display that on a normal HTML page ?

After re-searching about outlook and .net pipe, i have found a way to do that.
For displaying outlook emails on webpage. you have to write macro code on outlook. For this you need to open outlook and press ALT+F11 and write below code :

Sub MyRule(Item As Outlook.MailItem)

Dim strURL As String
Dim oApp As Object
Set oApp = CreateObject("InternetExplorer.Application")
strURL = "http://localhost:51049/Default2.aspx"  //Enter your path
oApp.navigate (strURL)
oApp.Visible = True

End Sub


Save the above code and open your visual studio and add webform :
Add below Javascript in your webform :

<script>
        function PopulateEmails() {
            var objOutlook = new ActiveXObject("Outlook.Application");
            var session = objOutlook.Session;
 
            for (var folderCount = 1; folderCount <= session.Folders.Count; folderCount++) {
                var folder = session.Folders.Item(folderCount);
                if (folder.Name.indexOf("Main folder Name") >= 0) {
                    for (var subFolCount = 1; subFolCount <= folder.Folders.Count; subFolCount++) {
                        var sampleFolder = folder.Folders.Item(subFolCount);
                        if (sampleFolder.Name.indexOf("Folder Name to display unread message") >= 0) {
                            for (var itmCount = 1; itmCount <= sampleFolder.Items.Count; itmCount++) {
                                var itm = sampleFolder.Items.Item(itmCount);
                                if (!itm.UnRead)
                                    continue;
                                var sentBy = itm.SenderName;
                                var sentDate = itm.SentOn;
                                var receivedBy = itm.ReceivedByName;
                                var receivedDate = itm.ReceivedTime;
                                var subject = itm.ConversationTopic;
                                var contents = itm.Body;
 
                                var tbl = document.getElementById('tblContents');
                                if (tbl) {
                                    var tr = tbl.insertRow(tbl.rows.length);
 
                                    if (tbl.rows.length % 2 != 0)
                                        tr.className = "alt";
 
                                    var tdsentBy = tr.insertCell(0);
                                    var tdsentDate = tr.insertCell(1);
                                    var tdreceivedBy = tr.insertCell(2);
                                    var tdreceivedDate = tr.insertCell(3);
                                    var tdsubject = tr.insertCell(4);
                                    var tdcontents = tr.insertCell(5);
 
                                    tdsentBy.innerHTML = sentBy;
                                    tdsentDate.innerHTML = sentDate;
                                    tdreceivedBy.innerHTML = receivedBy;
                                    tdreceivedDate.innerHTML = receivedDate;
                                    tdsubject.innerHTML = subject;
                                    tdcontents.innerHTML = contents;
                                }
                                itm.UnRead = false;
                            }
                            break;
                        }
                    }
                    break;
                }
            }
            return;
        }
 
    </script>


Add below code in body of web form :


<div id="divResult">
           <input type="button" value="Read" onclick="PopulateEmails();" /><br />
           <table cellpadding="3" cellspacing="3" border="1" id="tblContents">
               <tr>
                   <th>Sent By</th>
                   <th>Sent on</th>
                   <th>Recived By</th>
                   <th>Recived on</th>
                   <th>Subject</th>
                   <th>Content</th>
               </tr>
           </table>
       </div>

Now run web form in IE.
If you get an error related to ActiveXObject creation error then follow below steps :

 1) Go To Settings->Internet Options->Security Tabs.
  2)  You will see different zones:i)Internet ii)Local Intranet iii)Trusted Sites iv)Restricted Sites.
  3)  Depending on your requirement select one zone. I am running my application in localhost so i selected Local intranet and then click Custom Level button.
  4) Opens security settings window. Please enable Initialize and script Activex controls not marked as safe for scripting option.It should work.

enter image description here

enter image description here









Sunday, 11 January 2015

Interface in C#

Interface is one of the more overloaded and confusing concepts in object oriented programming. This article can help to understand Interfaces for those who have just started programming.

Interface in C#?

Let’s start with the short definitions for Interface:
  • An Interface is a way to achieve runtime polymorphism in C#.
  • An Interface is a collection of properties and methods declarations.
  • An Interface is a type declaration like a class or structure in C#; an Interface itself does not implement members.
  • Interfaces are contract templates in which the contract members are declared.

Characteristics of an Interface

Interfaces cannot be initialized directly as they do not have a definition for members, they should be implemented by either a class or structure.
Interfaces can contain any of the following type members or a combination of these four member types.
  1. Property
  2. Method
  3. Event
  4. Indexer
An Interface can be declared as either public or internal inside a namespace and can’t have any other access modifiers. An Interface can have any access modifier when declared inside a class or structure.
Members of an Interface are public by default and can’t have other access modifiers.
A class implementing an Interface must implement all the members declared in the Interface and they must be marked as public in the Implicit implementation. In the case of Explicit implementation, the Interface members can't have any access modifiers and they are private by default. If the implementing class is signed as abstractthen the members of the Interface can also be signed as abstract in the class.

Why should we use Interfaces in C#?

Let’s start with a real world scenario to understand the Interface implementation.
Consider an application with a logging module to log application errors; the application should be able to address a customer specific error logging method. On the customer's side, Client A may expect the application to write logs to the file system, Client B may expect to log errors in the database, and Client C may go for the Windows Event log.
To address the above scenario, the application design should support swapping of the logging system with less or no developer effort, and this leads to writing a plug-n-play like module for the application.
We can address this scenario with a flexible and extensible software design using Interfaces. The rest of the article will deal with developing the system with notes on handling Interfaces in C#.

How to implement an Interface

Interface declaration

An Interface needs to be declared before it can be implemented in any class. An Interface can be declared inside a namespace or a class with the keyword interface followed by the Interface name.
Example
namespace LoggingModule.Contract
{
    public interface ILogger
    {
        /// <summary>
        /// Write log information to logging source.
        /// </summary>
        void WriteLog(String Message);
    }
}
In the above code, we have declared an Interface called ILogger with a single method WriteLog inside the namespace LoggingModule.Contract. As the name implies, the WriteLog method will have code for writing log information to the configured logging source.

Interface implementation

A class can implement an Interface by suffixing a colon followed by the Interface name. A class can implement multiple interfaces by separating the Interface names with a comma.
Example
namespace FileSystemLoggingModule
{
    public class FileSystemLogger : ILogger
    {
        public void WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> File system Logger is invoked!");
        }
    }
}
The above code shows the implementation of a single Interface ILogger in the FileSystemLogger class. TheWriteLog method is defined with the same input parameters and return type (void) as declared in ILogger.
In the same way we can create a class for database logging and Windows EventLog logging as shown below. All these three classes have implemented the contract ILogger which is demanding the implementation of theWriteLog method.
namespace DatabaseLoggingModule
{
    public class DatabaseLogger: ILogger
    {
        public void WriteLog(String Message)
        {
            Console.WriteLine(Message + " ==> Database Logger is invoked!");
        }
    }
}

namespace WindowsEventLoggingModule
{
    public class WindowsEventLogger: ILogger
    {
        public void WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> Windows event logger is invoked!");
        }
    }
}
Now, let’s see how to use this interface in an application. We have declared an Enum (LoggingType) to expose the available logging types.
The ApplicationLogger class has a LogError method which will check the logging type configuration and load the appropriate logger implementation.
public enum LoggingType
{
    FileSystem = 1,
    Database = 2,
    WindowsEventLog = 3
}
Code for loading logger based on logging type
namespace LearningInterface
{
    public class ApplicationLogger
    {
       public void LogError(String strMessage)
        {
            LoggingType ConfiguredLoggingType = (LoggingType) 
              Convert.ToInt32(ConfigurationManager.AppSettings["LoggingType"]);

            ILogger Logger;

            switch (ConfiguredLoggingType)
            {
                case LoggingType.FileSystem:
                    Logger = new FileSystemLogger();
                    break;
                case LoggingType.Database:
                    Logger = new DatabaseLogger();
                    break;
                case LoggingType.WindowsEventLog:
                    Logger = new WindowsEventLogger();
                    break;
                default:
                    Logger = null;
                    break;
            }

            if (Logger != null)
            {
                Logger.WriteLog(strMessage);
            }

        }
    }
}
The LogError method reads the logging type value in the app settings from web.config. The ILogger object is initialized based on the logging type set in app settings. By initializing ILogger based on configuration settings, we can easily switch the logging type of the application. If we need to change the logging type in future, we don’t need to edit or recompile the application; changing LoggingType key in web.config will switch the application logging process. A new logging type can be added to the application easily in the same way we did for the database, Windows Event loggers.
There are better ways to achieve plug-n-play like software design with Interfaces and IoC. I have chosen the above approach to make it simpler to understand for beginners in C#.

Types of Interface implementation

An Interface implementation can be either Implicit or Explicit. In this article, we have used implicit Interface implementation.

Explicit implementation allows developers to tag the implementation details explicitly to the Interface. Explicitly implemented members are prefixed with the Interface name as shown below.
namespace LearningInterface
{
    public class ExplicitImplementation: ILogger, IErrorLogger
    {
        void ILogger.WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> Explicit implementaion of ILogger.WriteLog() invoked.");
        }

        void IErrorLogger.WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> Explicit implementaion of IErrorLogger.WriteLog() invoked.");
        }
    }
}
You will notice that, there are two implementations of the WriteLog method with the prefix of the respective Interface names. Explicit implementation helps identify the members more accurately and avoid shadowing/collision of members in multiple Interface implementations.
You can explicitly implement an Interface in Visual Studio as shown below:
Let’s see a scenario where we need to implement an Interface explicitly.
We know that C# does support multiple Interface implementations in a class. Our application has two interfaces:ILogger and IErrorLogger, for different purposes, and have a method called WriteLog() with identical signature declared in those two interfaces. Now we have to implement those two Interfaces in a class.
First, we shall implement these Interfaces implicitly and see the problem with it.
Interfaces can be implemented implicitly in visual studio as shown in below.
Clicking on “Implement interface ‘ILogger’ will generate a skeleton of ILogger members as shown below and can build successfully.
Let’s modify WriteLog() to test it.
namespace LearningInterface
{
    public class ImplicitImplementation: ILogger, IErrorLogger
    {
        public void WriteLog(string Message)
        {
            Console.WriteLine(Message + " ==> Implicit implementaion of WriteLog() invoked.");
        }
    }
}
The above code shows the implicit implementation of ILogger and IErrorLogger in theImplicitImplementation class. This code will build with no errors as the WriteLog() implementation is compromising both ILogger and IErrorLogger. Doing this way will spoil the purpose of interfaces as we have defined the same behavior for both Interfaces. So, we need to have an option to identify or name Interface members explicitly.
Let’s invoke WriteLog() from ILogger and IErrorLog objects and analyze the output.
Console.WriteLine("Implicit implementaion of an Interface in C#" + Environment.NewLine);

ImplicitImplementation objImplicit = new ImplicitImplementation();

//Create ILogger object
objLogger = (ILogger)objImplicit;

//Create IErrorLogger object
objErrorLogger = (IErrorLogger)objImplicit;

objLogger.WriteLog("Invoking from ILogger");

objErrorLogger.WriteLog("Invoking from IErrorLogger");

Console.ReadLine();
In the above code, we have created an object of the ImplicitImplementaion class and created ILogger andIErrorLogger objects from it. ILogger and IErrorLogger objects are invoking the WriteLog() method.
Output
When you run the code, you will get an output as shown above. Both Interfaces are invoking the same method.
This is not the expected behavior, ILogger and IErrorLogger must implement the WriteLog method differently and we should be able to invoke a specific implementation of the WriteLog method.
Let’s see how we can achieve it with an explicit implementation of ILogger and IErrorLogger.
Console.WriteLine("Explicit implementaion of an Interface in C#" + Environment.NewLine);

ExplicitImplementation objExplicit = new ExplicitImplementation();

//Create ILogger object
objLogger = (ILogger)objExplicit;

//Create IErrorLogger object
objErrorLogger = (IErrorLogger)objExplicit;

objLogger.WriteLog("Invoking from ILogger");

objErrorLogger.WriteLog("Invoking from IErrorLogger");

Console.ReadLine();
We have implemented the WriteLog method for both interfaces with the prefix of the respective Interface names in the ExplicitImplementaion class. An object for the ExplicitImplemenatation class is created and type casted to generate ILogger and IErrorLogger objects.
So, when we invoke Logger.WriteLog()void ILogger.WriteLog(int ErrorCode, string Message)of ExplicitImplementaion should be invoked. In same way, IErrorLogger.WriteLog(int ErrorCode, string Message) should be invoked when ErrorLogger.WriteLog is executed.
Output
As you can see in the output, we are able to identify and invoke specific implementations of WriteLog() forILogger and IErrorLogger.

Difference between explicit and implicit implementations

Implicit implementation
  1. Members are public by default.
  2. Members must be marked as public.
  3. Members can be invoked directly through the object of the implementing class.
  4. Example:
    FileSystemLogger objFileSystemLogger = new FileSystemLogger();
    objFileSystemLogger.WriteLog("");
Explicit implementation
  1. Members are private by default.
  2. Members can't have any access modifiers.
  3. Members can't be accessed directly, an object of the implementing class should be cast to the Interface type to access the members.
  4. Example:
    FileSystemLogger objFileSystemLogger = new FileSystemLogger();
    ILogger objLogger = (ILogger)objFileSystemLogger;
    objLogger.WriteLog("");

Points to consider while designing Interfaces

  1. An Interface should focus on common and related tasks that a module expects. Inclusion of unrelated methods will ruin the purpose of the Interface.
  2. An Interface should not include any method which is specific to a class; if there are specific methods declared in the Interface, it will become hard to implement the same Interface for other classes.
  3. An Interface should not declare too many methods. Too many methods make the implementation of Interfaces harder as the implementing class needs to implement all methods declared by the Interface.
  4. An Interface should be declared when there is need for abstraction by design. Too many abstractions may lead to increased complexity in maintenance and reusability of code.

Thursday, 19 June 2014

ASP.NET Interview Questions

1. What is the difference between Custom Control and User Control?


Custom controls are compiled code (DLLs), easier to use, difficult to create, and can be placed in toolbox. They are drag and drop controls, attributes can be set visually at design time. They can be used by multiple applications (if shared DLLs), even if private can copy to bin directory of web application add reference and use. They are normally designed to provide common functionality independent of consuming application.
User controls are similar to those of ASP include files, easy to create, cannot be placed in the toolbox and dragged - dropped from it. A user control is shared among the single application files.

2. What is the difference between ASP Session State and ASP.NET Session State?

ASP session state relies on cookies, serializes all requests from a client, does not survive process shutdown, cannot be maintained across machines in a Web farm.

3. What is the difference between ASP Session and ASP.NET Session?

ASP.NET session supports cookie less session & it can span across multiple servers.

4. Can you explain the difference between an ADO.NET Dataset and an ADO Recordset? (Repeated but more explanatory)

In ADO, the in-memory representation of data is the recordset. In ADO.NET, it is the dataset. There are important differences between them.
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. A dataset usually also contains relationships. A relationship within adataset is analogous to a foreign-key relationship in a database —that is, it associates rows of the tables with each other. For example, if a dataset contains a table about investors and another table about each investor’s stock purchases, it could also contain a relationship connecting each row of the investor table with the corresponding rows of the purchase table. Because the dataset can hold multiple, separate tables and maintain information about relationships between them, it can hold much richer data structures than a recordset, including self-relating tables and tables with many-to-many relationships.
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. DataRelation objects maintain information about master and detail records and provide a method that allows you to get records related to the one you are working with. For example, starting from the row of the Investortable for "Nate Sun," you can navigate to the set of rows of the Purchase table describing his purchases. 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 DataReaderobject.
Minimized Open Connections: In ADO.NET, you open connections only long enough to perform a database operation, such as a Select or Update. You can read rows into a dataset and then work with them without staying connected to the data source. In ADO, the recordset can provide disconnected access, but ADO is designed primarily for connected access. 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. The important difference is that in ADO.NET the data adapter allows you to control how the changes to the dataset are transmitted to the database — by optimizing for performance, performing data validation checks, or adding any other extra processing. Data adapters, data connections, data commands, and data readers are the components that make up a .NET Framework data provider. Microsoft and third-party providers can make available other .NET Framework data providers that can be integrated into Visual Studio.
Sharing Data between Applications. Transmitting an ADO.NET dataset between applications is much easier than transmitting an ADO disconnected recordset. To transmit an ADO disconnected recordset from one component to another, you use COM marshalling. To transmit data in ADO.NET, you use adataset, which can transmit an XML stream.
Richer data types. COM marshalling provides a limited set of data types — those defined by the COM standard. Because the transmission of datasets in ADO.NET is based on an XML format, there is no restriction on data types. Thus, the components sharing the dataset can use whatever rich set of data types they would ordinarily use.
Performance. Transmitting a large ADO recordset or a large ADO.NET dataset can consume network resources; as the amount of data grows, the stress placed on the network also rises. Both ADO and ADO.NET let you minimize which data is transmitted. But ADO.NET offers another performance advantage, in that ADO.NET does not require data-type conversions. ADO, which requires COM marshalling to transmit records sets among components, does require that ADO data types be converted to COM data types.
Penetrating Firewalls. A firewall can interfere with two components trying to transmit disconnected ADO recordsets. Remember, firewalls are typically configured to allow HTML text to pass, but to prevent system-level requests (such as COM marshalling) from passing.

5. Which class does the web page belong to in ASP.NET?

System.Web.UI.Page

6. Which class deals with the user’s locale information?

System.Web.UI.Page.Culture

7. What data type does the RangeValidator control support?

Integer, Date and String.

8. What is the difference between Server.Transfer and Response.Redirect?

Server.Transfer transfers the control of a web page, posting a form data, while Response.Redirect simply redirects a page to another page, it cannot post a form data to another page. Server.Transfer is more efficient over the Response.Redirect, because Response.Redirect causes a round trip to server as the page is processed once again on the client and a request is made to server thereafter.

9. Can you give an example of what might be best suited to place in the Application_Start and Session_Start subroutines?

All the global declarations or the variables used commonly across the application can be deployed underApplication_Start. All the user specific tasks or declarations can be dealt in the Session_Start subroutine.

10. What are the differences between Classic ASP and ASP.NET?


ASP is Interpreted language based on scripting languages like Jscript or VBScript
ASP has mixed HTML and coding logic
Limited development and debugging tools available
Limited OOPS support
Limited session and application state management
Poor Error handling system
No in-built support for XML
No fully distributed data source support
while
ASP.NET is supported by compiler and has compiled language support
Separate code and design logic possible
Variety of compilers and tools available including the Visual studio.NET
Completely Object Oriented
Complete session and application state management
Full proof error handling possible
Full XML Support for easy data exchange
Fully distributed data source support

11. What’s the difference between Response.Write () and Response.Output.Write ()?

Response.Outout.Write allows us to write the formatted output.

12. What is the difference between static or dynamic assemblies?

Assemblies can be static or dynamic. Static assemblies can include .NET Framework types (interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files, and so on). Staticassemblies are stored on disk in portable executable (PE) files. You can also use the .NET Framework to createdynamic assemblies, which are run directly from memory and are not saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

13. What are the differences between dataset.clone and dataset.copy?

dataset.clone copies just the structure of dataset (including all the datatables, schemas, relations and constraints.); however it doesn’t copy the data. On the other hand, dataset.copy copies both the datasetstructure and the data.

14. Describe the difference between inline and code behind.

Inline code is written along with the HTML and design blocks in an .aspx page. Code-behind is code written in a separate file (.cs or .vb) and referenced by the .aspx page.

15. What is ViewState?

ViewState is a .NET mechanism to store the posted data among post backs. ViewState allows the state of objects to be stored in a hidden field on the page, saved on client side and transported back to server whenever required.

16. What is the lifespan for items stored in ViewState?

Items stored in a ViewState exist for the life of the current page, including the post backs on the same page.

17. Can we disable ViewState, If, yes how?

ViewState can be disabled by using "EnableViewState" property set to false.

18. What’s a bubbled event?

When a complex control like datalist or datagrid, which contains a child control, using an itemcommand can listen to the events raised by the child control in the main control. The process of listening to the child control in the main or parent control is called as event bubbling.

19. Which method do you invoke on the DataAdapter control to load your generated dataset with data?

DataAdapter’s fill() method is used to fill load the data in dataset.

20. Can you edit data in the Repeater control?

No, it just reads the information from its data source.

21. Which template is to be provided in the Repeater control in order to display a data? Which template will display every other row in another color?

ItemTemplate, AlternatingItemTemplate

22. What are the most important property and most important method of a Repeater control?

The DataSource property and DataBind() method.

23. What is Authentication and Authorization?

Authentication is the process of identifying users. Authentication is identifying/validating the user against the credentials (username and password) and Authorization performs after authentication. Authorization is the process of granting access to those users based on identity. Authorization is allowing access of specific resource to user.

24. What are the types of Authentication? Describe.


There are 3 types of Authentication - Windows, Forms and Passport Authentication.
Windows authentication uses the security features integrated into the Windows NT and Windows XP operating systems to authenticate and authorize Web application users.
Forms authentication allows you to create your own list/database of users and validate the identity of those users when they visit your Web site.
Passport authentication uses the Microsoft centralized authentication provider to identify users. Passport provides a way for users to use a single identity across multiple Web applications. To use Passport authentication in your Web application, you must install the Passport SDK.

25. What are the types of comment in C#?

There are 3 types of comments in C#.
Single line (//), Multi line (/* */) and Page/XML Comments (///).

26. What is an ArrayList?

The ArrayList object is a collection of items containing single data type values.

27. What is a HashTable?

The Hashtable object contains items in key/value pairs. The keys are used as indexes, and very quick searches can be made for values by searching through their keys.

28. What is SortedList?

The SortedList object contains items in key/value pairs. A SortedList object automatically sorts items in alphabetic or numeric order.

29. What is a Literal Control?

The Literal control is used to display text on a page. The text is programmable. This control does not let you apply styles to its content!

30. What is Side-by-Side Execution?

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

31. What are the different types of Caching?

There are three types of Caching:
Output Caching: stores the responses from an ASP.NET page
Fragment Caching: Only caches/stores the portion of page (User Control)
Data Caching: is programmatic way to Cache objects for performance

32. What are the different types of Validation Controls?

There are six types of validation controls available:
RequiredFieldValidator
RangeValidator
RegularExpressionValidator
CompareValidator
CustomValidator
ValidationSummary

33. How to Manage State in ASP.NET?

There are several ways to manage a state.
ViewState
QueryString
Cookies
Session
Application

34. What base class all Web Forms inherit from?

System.Web.UI.Page

35. What method do you use to explicitly kill a user’s Session?

HttpContext.Current.Session.Abandon()

36. What are the layouts of ASP.NET Pages?

GridLayout and FlowLayout. GridLayout positions the form object on absolute x and y co-ordinates of the screen. FlowLayout positions the form objects relative to each other.

37. What is the Web User Control?

Combines existing server and/or HTML controls by using VS.NET to create functional units that encapsulate some aspects of UI. Resides in Content Files, which must be included in project in which the controls are used.

38. What is the Composite Custom Control?

It is a combination of existing HTML and Server Controls.

39. If I’m developing an application that must accommodate multiple security levels though secure login and my ASP.NET web application is spanned across three web-servers (using round-robin load balancing), what would be the best approach to maintain login-in state for the users?

You can use the security state maintained using a database. (Use Authentication mode as database.)

40. What’s the difference between Codebehind="MyCode.aspx.cs" and Src="MyCode.aspx.cs"?

Visual Studio uses the Codebehind attribute to distinguish the page source or programming logic from the design. Also the src attribute will make the page compile on every request. That is, the page will not be compiled in advance and stored in the bin as a DLL, instead it will be compiled at run time.

41. Suppose you want a certain ASP.NET function executed on MouseOver over a certain button or textbox. Where do you add an event handler?


Every web control has an ability to add the attributes on client side which will execute on client side and run a client side script like a JavaScript function.
btnSubmit.Attributes.Add(&ldquo;onMouseOver&rdquo;,&rdquo;someClientCode();&rdquo;) //For on mouse over of a button
TextBox1.Attributes.Add(&ldquo;onFocus&rdquo;,&ldquo;ClearText();&rdquo;) //For on focus of a text box

42. Explain what a diffgram is and a good use for one?

The DiffGram is one of the two XML formats that you can use to render DataSet object contents to XML. For reading database data to an XML file to be sent to a Web Service.

43. Name two properties common in every validation control?

ControlToValidate and Text property.

44. What tags do you need to add within the Datagrid tags to bind columns manually?

Set AutoGenerateColumns property to false on the Datagrid tag.

45. What tag do you use to add a hyperlink column to the DataGrid?

<asp:HyperLinkColumn></asp:HyperLinkColumn>

46. What is the transport protocol you use to call a Web service?

SOAP (Simple Object Access Protocol) is the preferred protocol.

47. Where on the Internet would you look for Web services?

http://www.uddi.org

48. Which control would you use if you needed to make sure the values in two different controls matched?

CompareValidator control

49. What are the assembly entry points? An Assembly can have how many entry points at a time?

An assembly can have only one entry point from DllMain, WinMain or Main.

50. What does an assembly contain?


Manifest - The metadata describing the information below.
Assembly name - Aids in versioning and visibility scope.
Version information - The version number is integrated into the assembly's identity.
Types - Boundaries and scopes of methods, classes, properties, events and attributes.
Locale - Information describing language/culture.
Cryptographic Hash - Public key encoded hash acting as version/security check.
Security Permissions - The permissions within the assembly determine the permissions that can be granted for all aspects of the assembly contents.

51. What does an assembly manifest contain?

It contains assembly name, version number (major.minor.build.revision) and culture information. It also specifies the strong name information, which is useful for shared assemblies, and list of files, an assembly contains. It also provides information for type references in an assembly and other referenced assemblies.

52. Which tool is used to deploy an assembly, so as the assembly is available to all the application?

The GacUtil.exe is the tool, which allows us to add any assembly to the windows GAC (Global Assembly Catche).


53. How many catch statements can be associated with a single try statement?

There can be zero or more catch statements for each try statement. So it has no limit to the number ofcatch statements per try statement.


54. What is Console and System a Class/a Data Member/a routine/a namespace or a type?

Console is a class and System is namespace.


55. How many values can be returned from a method in C#?

Only one value can be returned from a method, however you can use ref or out parameters to change more than one value in called method.


56. How to declare a variable named “this” in C#, with data type string?

string @this;


57. Can we change the dimension of Array at run time like Array [3, 4]?

Yes, We can change only the first position of array dimension.


58. What keyword is used to accept a variable number of parameters in a method?

“params” keyword is used as to accept variable number of parameters.


59. What is a Namespace? What is the use of a namespace?

Namespaces are logical grouping of classes and other types in hierarchical structure. Namespaces are useful to avoid collision or ambiguity among the classes and type names. Another use of the namespace is to arrange a group of classes for a specific purpose.


60. What does a keyword using works for?

Using is just a convention or a short-cut method which allows us to access the classes in a namespace by referencing it once. So whenever we want to use the classes or methods in them, we can avoid typing the entire namespace hierarchy. However it is not a good practice when there are likely chances to have name ambiguity or collision of class names.


61. What is Enums in C#?

Enums or Enumerators are used to declare a set of related constants (default start with 0); they are only available with primitive data types like int and short, etc.


62. What are Delegates?

Delegates are a type-safe, object-oriented implementation of function pointers and are used in many situations where a component needs to call back to the component that is using it. Delegates are generally used as basis of events, which allow any delegate to easily be registered for as event.


63. Which are the namespaces that are imported automatically by Visual Studio in ASP.NET?


There are 7 namespaces which are imported automatically.
System
System.Collections
System.IO
System.web
System.web.UI
System.web.UI.HTMLControls
System.web.UI.WebControls


64. Which namespaces are used for data access?


System.Data
System.Data.OleDB
System.Data.SQLClient


65. What do you mean by boxing and un-boxing?


C# provides us with Value types and Reference Types. Value Types are stored on the stack and Reference types are stored on the heap. The conversion of value type to reference type is known as boxing and converting reference type back to the value type is known as un-boxing.
Example:
int x = 10;
object o = x ; // Implicit boxing
object o = (object) x; // Explicit Boxing
x = o; // Implicit Un-Boxing
x = (int)o; // Explicit Un-Boxing


66. What are the different methods available under sqlcommand class to access the data?


ExecuteReader – Used where one or more records are returned – SELECT Query.

ExecuteNonQuery – Used where it affects a state of the table and no data is being queried - INSERT,UPDATE, DELETE, CREATE and SET queries.

ExecuteScalar – Used where it returns a single record (a single value normally) – SQL Functions likeMIN(), MAX()

67. What are the different types of Session state management options available with ASP.NET?


ASP.NET provides In-Process & Out-of-Process state management.
Also known as "In-Proc" and "Out-Proc". In-Proc stores the session in memory of the web server, that is on the same server the ASP.NET page is.
On the other hand, Out-Proc session state management stores the session data on external data source, which can be a SQL Server or Server State Service. Out-of-Process state management requires the objects stored in session, must be serializable.


68. What is Remoting? Give an example.

Remoting is a means by which one operating system process, or program, can communicate with another process. The two processes can exist on the same computer or on two computers connected by a LAN or the Internet. Web services are probably the best known type of remoting, but they are not the only option.


69. When would you use .NET Remoting and when Web services?

Use remoting for more efficient exchange of information when you control both ends of the application. Use Web services for open-protocol-based information exchange when you are just a client or a server with the other end belonging to someone else.


70. What’s a proxy of the server object in .NET Remoting?

It’s a fake copy of the server object that resides on the client side and behaves as if it was the server. It handles the communication between real server object and the client object. This process is also known as marshaling.


71. What are remotable objects in .NET Remoting?


Remotable objects are the objects that can be marshaled across the application domains. You can marshal by value, where a deep copy of the object is created and then passed to the receiver. You can also marshal by reference, where just a reference to an existing object is passed.


72. What is Marshalling?


Marshaling is a process of making an object in one process (the server) available to another process (the client). There are two ways to achieve the marshalling.
Marshal by value: The server creates a copy of the object passes the copy to the client. When a client makes a call to an object marshaled by value (MBV), the server creates an exact copy and sends that copy to the client. The client can then use the object's data and executable functionality directly within its own process or application domain without making additional calls to the server. Objects that the application accesses frequently are best remoted using MBV.
Marshal by reference: The client creates a proxy for the object and then uses the proxy to access the object. When a client makes a call to an object marshaled by reference (MBR), the .NET framework creates a proxy in the client's application domain and the client uses that proxy to access the original object on the server. Large objects that the application accesses relatively infrequently are good candidates for MBR.


73. What is a Static class? What are its features?


Static class is a class which can be used or accessed without creating an instance of the class.
Important Features:
Static class only contains static members and a private constructor.
Static class cannot be instantiated.
Static classes are sealed by default and therefore cannot be inherited.


74. What is sealed class? What are its features?


Sealed classes are those classes which cannot be inherited and thus any sealed class member cannot be derived in any other class. A sealed class cannot also be an abstract class.
In C#, structs are implicitly sealed; therefore, they cannot be inherited.


75. Can we declare a method as sealed?


In C#, a method can't be declared as sealed. However when we override a method in a derived class, we can declare the overridden method as sealed. By declaring it as sealed, we can avoid further overriding of this method.
Example:
using System;
class MyClass1
{
public int x;
public int y;
public virtual void Method() {
Console.WriteLine("virtual method"); }
}
class MyClass : MyClass1
{
public override sealed void Method() {
Console.WriteLine("sealed method"); }
}
class MainClass
{ public static void Main() {
MyClass1 mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
mC.Method(); }
}


76. What is a DataSet ?

A DataSet is an in memory representation of data loaded from any data source.


77. What is a DataTable?

A DataTable is a class in .NET Framework and in simple words a DataTable object represents a table from a database.


78. If you want to view an Assembly, how do you go about it? What is ILDASM?

You can use the MSIL Disassembler (Ildasm.exe) to view Microsoft intermediate language (MSIL) information in a file. If the file being examined is an assembly, this information can include the assembly's attributes, as well as references to other modules and assemblies. This information can be helpful in determining whether a file is an assembly or part of an assembly, and whether the file has references to other modules or assemblies.


79. Where is version information stored of an assembly?

The version number is stored in the assembly manifest along with other identity information, including the assembly name and public key, as well as information on relationships and identities of other assemblies connected with the application.


80. Is versioning applicable to private assemblies?

No


81. How to create a shared assembly or add an assembly to GAC?


There are several ways an assembly can be added to GAC.
Use .msi installer designed to work with the global assembly cache.
Use GACUtil.exe provided by the .NET Framework SDK.
Use Windows Explorer to drag assemblies into the cache.


82. What is a Page Life Cycle of an ASP.NET page?


There are various stages described as under:
Init
LoadViewState
LoadPostBackData
Load
RaisePostBackDataChangedEvent
RaisePostBackEvents
Pre-Render
SaveViewState
Render
Unload


83. Can the action attribute of a server-side <form>tag be set to a value and if not, how can you possibly pass data from a form to a subsequent Page?

No, assigning value will not work because it will be overwritten at the time of rendering. We can assign value to it by register a startup script which will set the action value of form on client-side. On the other hand, we can use Server.Transfer or Response.Redirect.


84. How do you turn off cookies in one page of your ASP.NET application?

We may not use them at the max, however to allow the cookies or not, is client side functionality.


85. Which method do you use to redirect the user to another page without performing a round trip to Client?

Server.Transfer(&ldquo;AnotherPage.aspx&rdquo;)


86. How many namespaces are in .NET version 1.1?

124.


87. Should Validation occur on Client/Server Side for Date Input?

Both. Client-side reduces extra round-trip. Server-Side ensures prevention against hacking and failure against automated requests.


88. What are the web form events?


The first event that occurs in the life of a Web Form is the Init event. This is raised so that we can have initialization code for the page. The controls on the page are not yet created at this point. This event is raised once for each user of the page.
The Load event follows the Init event. Subsequently, it is raised each time the page is requested. When this event is raised, all child controls of the Web Form are loaded and accessible. You should be able to retrieve data and populate the controls so that they can render themselves on the page when sent back to the client.
The PreRender event happens just before the page is rendered and sent back to the client. We don't often handle this event; however, it depends on the situation.
The last event in the life of a Web Form is the Unload event. This happens when the page is unloaded from memory. Final cleanup should be done here.


89. Why main function is static?

To ensure there is only one entry point to the application.


90. How CCW (COM Callable Wrapper) and RCW (Runtime Callable Wrapper) work?


CCW: The .NET Framework includes support for COM clients to use .NET components. When a COM client needs to create a .NET object, the CLR creates the managed object and a COM callable wrapper (CCW) that wraps the object. The COM client interacts with the managed object through the CCW. The runtime creates only one CCW for a managed object, regardless of how many COM clients are using it.
RCW: The .NET Framework includes extensive support for COM interoperability. To allow .NET clients to interact with a COM component, .NET uses an RCW—a special .NET proxy class that sits between your .NET code and the COM component. The RCW handles all the details, including marshaling data types, using the traditional COM interfaces, and handling COM events.


91. How to generate XML from a dataset and vice versa?

We can use WriteXml() and ReadXml() methods of DataSet Object.


92. What is Session State Management? Describe.

You can apply state management to your applications in a number of ways. Session State Management determines how the sessions are stored by the ASP.NET application. The default option is InProc. Other options include Off, StateServer, and SQLServer. Running sessions in-process (InProc) means that the sessions are stored in the same process as the ASP.NET worker process. Therefore, if IIS is shut down and then brought up again, all the sessions are destroyed and unavailable to end users. StateServer means that sessions are stored out-of-process by a Windows service called ASPState. SQLServer is by far the most secure way to deal with your sessions. It stores them directly in SQL Server itself. Although it is the most secure method, it is also the least performance-efficient method.


93. What base class do all web forms inherit from?

System.Web.UI.Page


94. Which two properties are on every validation control?

ControlToValidate and ErrorMessage


95. How do you create a permanent cookie?

Set the expiry date as datetime.maxvalue.


96. What does WSDL stand for?

Web Services Description Language.


97. How is a property designated as read-only?

Use only the get accessor.


98. Which control would you use if you needed to make sure the values in two different controls matched?

CompareValidator


99. To test a Web Service, you must create a Windows application or web application to consume this service? It is True/False?

Every web service by default generates a test page, we need not create or consume the Web service in order to test it.


100. What is the maximum length of a varchar in SQL Server?


Varchar: It can store maximum 8000 Non-Unicode characters (i.e. maximum storage capacity is 8000 bytes of storage)
and varchar(255) means it can store 255 characters (non-unicode).


101. Is string a value type or a reference type?

String is the reference type.


102. Can multiple catch blocks be executed?

No, once an exception fall under a catch block, the control will never be passed to the next catch block. Instead, it will be passed to the finally block (if any or/and) the code next to the finally block.


103. How do you generate documentation from the C# file commented properly with a command-line compiler?

Compile it with a /doc switch.


104. What debugging tools come with the .NET SDK?

CorDBG – command-line debugger, and DbgCLR – graphic debugger. Visual Studio .NET uses the DbgCLR. To use CorDbg, you must compile the original C# file using the /debug switch.


105. What does assert () do?

In debug compilation, assert takes in a Boolean condition as a parameter, and shows the error dialog if the condition is false. The program proceeds without any interruption if the condition is true.


106. What’s the difference between the Debug class and Trace class?

Documentation looks the same. Use Debug class for debug builds, use Trace class for both debug and release builds.


107. How do you debug an ASP.NET Web application?

Attach the aspnet_wp.exe process to the DbgClr debugger.


108. Name the 4 .NET authentication methods.


ASP.NET, in conjunction with Microsoft Internet Information Services (IIS), can authenticate user credentials such as names and passwords using any of the following authentication methods:
Windows: Basic, digest, or Integrated Windows Authentication (NTLM or Kerberos)
Microsoft Passport authentication
Forms authentication
Client Certificate authentication


109. Explain what a diffgram is and a good use for one?

A DiffGram is an XML format that is used to identify current and original versions of data elements. TheDataSet uses the DiffGram format to load and persists its contents, and to serialize its contents for transport across a network connection. When a DataSet is written as a DiffGram, it populates the DiffGram with all the necessary information to accurately recreate the contents, though not the schema, of the DataSet, including column values from both the Original and Current row versions, row error information, and row order.


110. Where would you use an iHTTPModule, and what are the limitations of any approach you might take in implementing one?

One of ASP.NET’s most useful features is the extensibility of the HTTP pipeline, the path that data takes between client and server. You can use them to extend your ASP.NET applications by adding pre- and post-processing to each HTTP request coming into your application. For example, if you wanted custom authentication facilities for your application, the best technique would be to intercept the request when it comes in and process the request in a custom HTTP module.


111. What method do you use to explicitly kill a user’s session?


The Abandon method destroys all the objects stored in a Session object and releases their resources.
If you do not call the Abandon method explicitly, the server destroys these objects when the session times out.
Syntax: Session.Abandon


112. How do you turn off cookies for one page in your site?

Use the Cookie.Discard property which gets or sets the discard flag set by the server. When true, this property instructs the client application not to save the Cookie on the user’s hard disk when a session ends.


113. Which method do you use to redirect the user to another page without performing a round trip to the client?

Server.transfer()


114. Where do you store the information about the user’s locale?

System.Web.UI.Page.Culture


115. What’s the difference between Codebehind="MyCode.aspx.cs" andSrc="MyCode.aspx.cs"?

CodeBehind is relevant to Visual Studio.NET only.


116. What data type does the RangeValidator control support?

Integer, String and Date.


117. What is cookie less session? How does it work?


By default, ASP.NET will store the session state in the same process that processes the request, just as ASP does. If cookies are not available, a session can be tracked by adding a session identifier to the URL. This can be enabled by setting the following:
<sessionState cookieless="true" />


118. What is State Management in .NET and how many ways are there to maintain a state in .NET? What is view state?


Web pages are recreated each time the page is posted to the server. In traditional Web programming, this would ordinarily mean that all information associated with the page and the controls on the page would be lost with each round trip.
To overcome this inherent limitation of traditional Web programming, the ASP.NET page framework includes various options to help you preserve changes — that is, for managing state. The page framework includes a facility called view state that automatically preserves property values of the page and all the controls on it between round trips.
However, you will probably also have application-specific values that you want to preserve. To do so, you can use one of the state management options.
Client-Based State Management Options:
View State
Hidden Form Fields
Cookies
Query Strings
Server-Based State Management Options
Application State
Session State
Database Support


119. What are the different modes for the sessionstates in the web.config file?


Off indicates that session state is not enabled.
Inproc indicates that session state is stored locally.
StateServer indicates that session state is stored on a remote server.
SQLServer indicates that session state is stored on the SQL Server.


120. In a Webservice, we need to display 10 rows from a table. So DataReader or DataSet is the best choice?

WebService will support only DataSet.


121. What is singleton and what is singlecall?


Singleton types never have more than one instance at any one time. If an instance exists, all client requests are serviced by that instance.
Single Call types always have one instance per client request. The next method invocation will be serviced by a different server instance, even if the previous instance has not yet been recycled by the system.


122. What is the difference between Compiler and Interpreter?


Compiler
A compiler is a program that translates program (called source code) written in some high level language into object code. The compiler derives its name from the way it works, looking at the entire piece of source code and collecting and reorganizing the instructions. A compiler translates high-level instructions directly into machine language and this process is called compiling.
Interpreter
An interpreter translates high-level instructions into an intermediate form, which it then executes. Interpreter analyzes and executes each line of source code in succession, without looking at the entire program; the advantage of interpreters is that they can execute a program immediately. Compilers require some time before an executable program emerges. However, programs produced by compilers run much faster than the same programs executed by an interpreter.
Compiled programs generally run faster than interpreted programs. The advantage of an interpreter, however, is that it does not need to get through the compilation stage during which machine instructions are generated. This process can be time-consuming if the program is long. The interpreter, on the other hand, can immediately execute high-level programs. For this reason, interpreters are sometimes used during the development of a program, when a programmer wants to add small sections at a time and test them quickly. Because compilers translate source code into object code, which is unique for each type of computer, many compilers are available for the same language. For example, there is a C compiler for PCs and another for UNIX computers.


123. Describe the role of inetinfo.exe, aspnet_isapi.dll andaspnet_wp.exe in the page loading process.

inetinfo.exe is the Microsoft IIS server running, handling ASP.NET requests among other things.When an ASP.NET request is received (usually a file with .aspx extension),the ISAPI filter aspnet_isapi.dll takes care of it by passing the request to the actual worker process aspnet_wp.exe.