Monday, 21 April 2014

Top 10 ASP.NET Interview Questions and Answers

1.What is the concept of Postback in ASP.NET?
A postback is a request sent from a client to server from the same page user is already working with.
ASP.NET was introduced with a mechanism to post an HTTP POST request back to the same page. It's basically posting a complete page back to server (i.e. sending all of its data) on same page. So, the whole page is refreshed.
Another concept related to this approach is "Callback" that is also asked sometimes during a technical interview question. 

 Difference between a Postback and a Callback in ASP.NET
"postback is a request sent from a client to server from the same page, user is already working with."

ASP.NET was introduced with a mechanism to post an HTTP POST request back to the same page. It's basically posting a complete page back to server (i.e. sending all of its data) on same page. So, the whole page is refreshed.

In order to understand how this postback mechanism works in ASP.NET, follow the simple steps:
  • Add a new ASP.NET web form page to a project e.g. WebForm1.aspx.
  • View the page code in HTML Source view. You will find something like following screen.



    Look the form line of code.
    <form id="form1" runat="server">
    It represents a server-side implementation of form control.
  • Now just run the application to see WebForm1.aspx page and view its source code. HTML source of the page will display form element as follows:
    <form method="post" action="WebForm1.aspx" id="form1">


    You can see that an HTML form element generated with an HTTP method as "POST" and action="WebForm1.aspx". So, if a submit button is clicked, the page will postback to itself by default.

"callback is generally a call for execution of a function after another function has completed." 
But if we try to differentiate it from a postback then we can say: It's a call made to the server to receive specific data instead of whole page refresh like a postback. In ASP.NET, its achieved using AJAX, that makes a call to server and updating a part of the page with specific data received.

Difference between ASP.NET WebForms and ASP.NET MVC?
ASP.NET Web Forms uses Page controller pattern approach for rendering layout. In this approach, every page has it's own controller i.e. code-behind file that processes the request. On the other hand, ASP.NET MVC uses Front Controller approach. In this approach a common controller for all pages, processes the requests.

Please briefly explain ASP.NET Page life Cycle?
ASP.NET page passes through a series of steps during its life cycle. Following is the high-level explanation of life cycle stages/steps.

Initialization: Controls raise their Init event in this stage.Objects and variables are initializes for complete lifecyle of request.

LoadViewState: is a post back stage and loads the view state for the controls that enabled its view state property.

LoadPostBackData: is also a post back stage and loads the data posted for the controls and update them.

Load: In this stage page as well as all the controls raise their Load event. Till this stage all the controls are initialized and loaded. In most of the cases, we are coding this event handler.

RaisePostBackEvent: is again a postback stage. For example, it's raise against a button click event. We can easily put our code here to perform certain actions.

SaveViewState: Finally, controls state is saved in this stage before Rendering HTML.

Render: This is the stage where HTML is generated for the page.

Dispose: Lastly, all objects associated with the request are cleaned up.

What is the difference between custom controls and user controls?
Custom controls are basically compiled code i.e. DLLs. These can be easily added to toolbox, so it can be easily used across multiple projects using drag and drop approach. These controls are comparatively hard to create.
But User Controls (.ascx) are just like pages (.aspx). These are comparatively easy to create but tightly couple with respect to User Interface and code. In order to use across multiple projects, we need to copy and paste to the other project as well.

What is the concept of view state in ASP.NET?
As in earlier question, we understood the concept of postback. So, in order to maintain the state between postbacks, ASP.NET provides a mechanism called view state. Hidden form fields are used to store the state of objects on client side and returned back to server in subsequent request (as postback occurs).

Difference between Response.Redirect and Server.Transfer?
In case of Response.Redirect, a new request is generated from client-side for redirected page. It's a kind of additional round trip. As new request is generated from client, so the new URL is visible to user in browser after redirection.
While in case of Server.Transfer, a request is transferred from one page to another without making a round trip from client. For the end user, URL remains the same in browser even after transferring to another page.

Please briefly explain the usage of Global.asax?
Global.asax is basically ASP.NET Application file. It’s a place to write code for Application-level events such as Application start, Application end, Session start and end, Application error etc. raised by ASP.NET or by HTTP Modules.

There is a good list of events that are fired but following are few of the important events in Global.asax:
  • Application_Init occurs in case of application initialization for the very first time.
  • Application_Start fires on application start.
  • Session_Start fires when a new user session starts
  • Application_Error occurs in case of an unhandled exception generated from application.
  • Session_End fires when user session ends.
  • Application_End fires when application ends or time out.

What are the different types of Validation controls in ASP.NET?

In order to validate user input, ASP.NET provides validation server controls. All validation controls inherits from BaseValidator class which contains the common validation properties and methods like ControlToValidate, Enabled, IsValid, EnableClientScript, ValidationGroup,Validate() etc.

ASP.Net provides a range of validation controls:
  • RequiredFieldValidator validates compulsory/required input.
  • RangeValidator validates the range. Validates that input falls between the given range values.
  • CompareValidator validates or compares the input of a control with another control value or with a fixed value.
  • RegularExpressionValidator validates input value against a defined regular expression pattern.
  • CustomValidator allows to customize the validation logic with respect to our application logic.
  • ValidationSummary displays all errors on page collectively.


What are the types of Authentication in ASP.NET?

There are three types of authentication available in ASP.NET:
  • Windows Authentication: This authentication method uses built-in windows security features to authenticate user.
  • Forms Authentication: authenticate against a customized list of users or users in a database.
  • Passport Authentication: validates against Microsoft Passport service which is basically a centralized authentication service.

What are Session state modes in ASP.NET?

ASP.NET supports different session state storage options:
  • In-Process is the default approach. It stores session state locally on same web server memory where the application is running.
  • StateServer mode stores session state in a process other than the one where application is running. Naturally, it has added advantages that session state is accessible from multiple web servers in a Web Farm and also session state will remain preserved even web application is restarted.
  • SQLServer mode stores session state in SQL Server database. It has the same advantages as that of StateServer.
  • Custom modes allows to define our custom storage provider.
  • Off mode disables session storage.
I strongly believe that every asp.net web developer should prepare and understand the above discussed interview questions.

Asp.net Interview questions -Part 4

Part -4

Security is a huge area of concern, so this part of ASP.NET Interview Questions will continue with Security related Questions. In previous ASP.NET Tutorial i.e. Part 3, we discussed about Authentication and Authorization, different authentication modes in ASP.NET.

What is Passport Authentication?

As we have discussed previously that there are three types of authentications in ASP.NET i.e.
  • Windows Authentication
  • Forms Authentication
  • Passport Authentication
Windows and Forms Authentications are already explained.
Passport Authentication actually validates against a centralized authentication service i.e. Microsoft Passport Service. We don't need to implement our own custom authentication mechanism if implementing .NET Passport Single Sign-In (SSI) service.

Can you briefly explain how Passport Authentication works?

As discussed above that Passport Authentication is a central service. It just authenticate (validate the credentials), no authorization (grant or deny access to a site). So, implementing application will check for the Passport Authentication Cookie. In case of unavailability of Passport Cookie, user is redirected to passport Sign-In page. User provides the credentials on Sign-In page, if validated,  Authentication Cookie is stored on client machine and redirected to the requested page. 

What are the advantages of using Passport Authentication?

Advantages of Passport Authentication are:
  • We don't need to care of authentication mechanism our self, Passport SSI does this for us.
  • Single login credentials can be used to access multiple sites. User don't need to remember separate credentials for individual site.

What is Role-based Security?

We have discussed about authentication in above questions but another different but related concept is Authorization. Authorization is a process of granting privileges or permissions on resources to an authenticated user. So,
 "Role Based Security is a technique we use to implement authorization on the basis of user's roles within an   organization. It's more granular approach to grant or revoke permissions on resources through user's roles."

An example of granting or revoking permissions in configuration file using windows built-in groups as follows:
 <authorization >
     <allow roles=”MyDomain1\Administrators” / >   < !– Allow Admin of this domain — >
     <deny users=”*”  / >                                          < !– Deny anyone else. — >
 </authorization >

What are the different Security Controls in ASP.NET?

ASP.NET provides several security controls which are actually Web Server controls. You can find those in your Visual Studio Toolbox.

Login Control:
In almost every application we need to take user credentials on a typical login page. Login control provides the same standard functionality and reduces the effort for building it from scratch.

LoginName:
After a user successfully logged in to an application, we normally display his/her username to top right or some other place on the page. Now, this functionality is provided by LoginName control.

LoginView Control:
LoginView control displays different view for different users. Using AnonymousTemplate and LoggedInTemplate, different information can be presented to different users.

LoginStatus Control:
LoginStatus control implies whether a user is authenticated or not. For an unathenticated user, it displays a link to login page. On the other hand, for authenticated user, a logout link is displayed.

LoginRecovery Control:
Password recovery is another important functionality simplified through PasswordRecovery control. It sends an email with login credentials to registered user email.

What is Code-Access Security (CAS)?

In one of above ASP.NET security related interview questions, we discussed about Role Based Security that restrict access to resources on the basis of user's role. CAS (Code Access Security) is entirely a different concept. It's .NET CLR's security system that restrict the code to perform an unwanted task by applying security policies. Using CAS (Code Access Security), we can restrict what our code can do? and also what code can call our code?

What are the key functions of Code Access Security?

As per documentation, key functions of Code Access Security are (straight from MSDN):
  • Defines permissions and permission sets that represent the right to access various system resources.
  • Enables code to demand that its callers have specific permissions.
  • Enables code to demand that its callers possess a digital signature, thus allowing only callers from a particular organization or site to call the protected code.
  • Enforces restrictions on code at run time by comparing the granted permissions of every caller on the call stack to the permissions that callers must have.

What .NET Tool can be used to Enable/Disable CAS?

Code Access Security Tool (Caspol.exe) can be used to turn Code Access Security ON or OFF as follows:
  • caspol -security on
  • caspol -security off
We can also list all code groups using following command.
  • caspol -listgroups

What is Impersonation in ASP.NET?

Impersonation is an act of a user to pretend itself to be another user. By default, ASP.NET executes application code using the same user account as that of ASP.NET process i.e. Network Service. But with impersonation enabled, it executes code with the windows identity of the user making the request. 
For example, if a user 'user1' logged in and IIS is setup to run as Network Service. If 'user1' call a piece of code on another computer (may be a web service call), the other computer will see the IIS user instead of 'user1'. But we can enable impersonation to allow 'user1' to access the web service using its windows identity instead of Network Service.

How to configure Impersonation in ASP.NET?

By default, impersonation is disabled in ASP.NET. Impersonation can be Enabled/Disabled as follows:
 </configuration>
      <system.web>
          <identity impersonate="true"/> <! -- To disable set impersonate="false" -->
       </system.web>
 </configuration>

Impersonate a specific user account as:
 <identity impersonate="true" userName="user" password="pwd" />

On completing Part 4 of this ASP.NET Interview Questions and Answers series, we have completed major questions on ASP.NET Security. Hopefully, this series will be beneficial in terms of preparing an ASP.NET Interview.

ASP.NET Interview Questions-Part 3

Part-3

What is Caching and what are the benefits of using it?

Performance has always been a concern for web based applications. So, Caching is a mechanism that improve performance for an application by storing data in memory for fast access. When the application will access data from Cache (i.e. in-memory) instead of fetching it from original data store (may be a database), it will definitely improve performance.

But Caching benefits are not limited to performance only, it also improve application Scalability as well as Availability.
  • Load on server is reduced when data is fetched from Cache instead of original source, thus improving scalability of an application.
  • Caching normally keep serving application data even if the original source is temporarily down, thus improving availability of an application.

Cache Management in ASP.NET?

ASP.NET provided support for Cache Management in almost all versions. In .NET Framework 3.5 and older, the support for caching was provided through classes available in System.Web.Caching. But this support was limited to System.Web meaning for ASP.NET Web Applications only. Now, with .NET Framework 4.0 and later, this support is enhance to non-Web Applications also by providing APIs in System.Runtime.Caching.

ASP.NET supports three types of Caching:
  • Page Output Caching
  • Partial Page Caching
  • Data Caching

Page Output Cache Vs Partial Page Cache Vs Application Data Cache in ASP.NET?

Page Output Cache
In case of Page Output Cache, the output of a complete web page is stored in a cache. So, when that web page is accessed again, it will be loaded from cache instead of fetching page data again from data source.

Partial Page Cache
For Partial Page Cache (also known as Page Fragment Cache), a part or fragment of a web page is stored in Cache as opposed to complete page caching for Page Output Cache. For example, caching a user control on a web page that displays product categories using Page Fragment Cache.

Data Cache
In some scenarios, we may store frequently used objects into cache using ASP.NET Cache API. So, later on, that object will be loaded from cache instead of instantiating object again and fetching data from original source for it.

How to use Page Output Cache in ASP.NET?

Implementing Page Output Cache in ASP.NET is simple. For Page Output Caching, @ OutputCache directive is used on an ASP.NET page as follows:

<%@ OutputCache Duration="50" VaryByParam="None" %>
Duration value is in seconds and it tells the page that how long to cache the contents?
Now, when we will access the page, it will verify that either it exists in Cache? if Yes, then verify that is it expired? If not then fetch it from Cache and render otherwise create a new instance of the page and put it back to Cache.

The other parameter of this directive is "VaryByParam". If it's value is specified to something as follows:
<%@ OutputCache Duration="50" VaryByParam="ProductId" %>
Now, Cache is dependent on the value of this parameter, If the value of parameter remains same, page will be fetched from Cache otherwise it will be refreshed again.

For in-depth details on Page Output Cache, follow here.

How to use Page Fragment or Partial Page Cache in ASP.NET?

Page Fragment Caching uses the same @ OutputCache directive with VaryByControl parameter as follows:
<%@ OutputCache Duration="50" VaryByParam="None" VaryByControl="ControlName" %>

In this case, Cache is dependent on the value of Control specified in VaryByControl parameter. For example, content on a page are dependent on the selected values of a dropdownlist, so, VaryByControl will have the dropdownlist control name as value.

How to use Data Cache in ASP.NET?

We have already explained the usage of Data Cache above in this series of ASP.NET Interview Questions that in particular situations, we need to store objects into cache. Adding an object to Cache and accessing it from Cache is simple.
We can use "Add" method to add an object to Cache as:
Cache.Add(key, value, dependencies, absoluteExpiration, slidingExpiration, priority, onRemoveCallback); 

if (Cache["ProductKey"] == null)
       Cache.Add("ProductKey",
                          objProduct,
                          null,
                          DateTime.Now.AddSeconds(60),
                          Cache.NoSlidingExpiration,
                          CacheItemPriority.High,
                          null);

To retrieve it back:
Product objProduct = (Product) Cache["ProductKey"];

Further, in this post and next post, we will be discussing about ASP.NET Security Interview Questions.

Authentication Vs Authorization?

Authentication and Authorization are two key security related concepts that are independent but normally go 
together.
Authentication is a process that verifies the identity of a user. On ther hand, Authorization is the process of 
assigning rights/privileges to already authenticated user.
For example, when a user tries to login a web application. First of all, user identity is verified that either 
he/she is valid registered user of application. If his/her identity validated successfully then appropriate 
privileges are assigned accordingly. Different users may have different privileges on same application, for 
example, user1 can only view/read some records while user2 may have privileges for all CRUD (Create, Read, Update, Delete) operations on same data.

What are the available Authentication modes in ASP.NET?

We have already explained this question in previous ASP.NET Interview Questions and Answers post, don't skip this important questions details.

What is the difference between Windows Authentication and Forms Authentication in ASP.NET?

Windows Authentication is a way to authenticate a user against Windows accounts. Windows authentication mode is suitable for corporate users in windows environment.
In case of Forms Authentication, a separate list of users is maintained for authentication. For example, we can maintain the list in database and authenticate user against it.

We can set authentication mode in web.config as follows:
<authentication mode="Forms">

What is Protected Configuration in ASP.NET?

While developing an ASP.NET application, we normally store a number of important sensitive information in our config files like encryption keys, connection strings etc. Application vulnerability increases if this sensitive information is stored as plane text. So Protected Configuration is an ASP.NET feature that enables to encrypt such sensitive information in configuration files.

Asp.Net Interview Questions- PART 2

Part -2

HTML Server Controls Vs Web Server Controls, Please define?

HTML Server Controls are server-side mapped form of HTML elements. In order to make HTML elements programmable on server-side, ASP.NET framework added runat="server" attribute, so it's accessible in ASP.NET code-behind. A typical HTML Server Control is as follows:
      <input type="text" id="txtFirstName" runat="server" />

On the other hand, Web Server Controls are more feature-rich as compared to HTML server controls and truly designed to provide Win Apps development experience for ASP.NET Web developers. Also, it provides comparatively high level of abstraction. Apart from mapping to existing HTML elements, web server controls provide more rich and complex functionality like Calendar, Grid, Repeater, menu, tree view etc.

So, which one you prefer to use while developing an ASP.NET Web Application?

Although both of these types of controls render HTML elements but Web Server controls being rich in functionality can render additional HTML tags that collectively fulfill control's functionality. On the other hand, HTML Server Controls are comparatively lightweight only producing the corresponding HTML element.

So, preference depends totally on your circumstances. If you are migrating from a classic ASP application to ASP.NET, then only choice is using HTML server controls but if you are going to develop a new application and you wanted to provide rich functionality with ease (i.e. calendar, grid, tree view etc), web server controls are the only choice because we don't have it in HTML server controls.

What is the role of ValidationSummary Control?

Sometimes, we have a requirement that all validation messages need to display at one location (may be top or bottom of a web form). In such scenario, ValidationSummary control displays all validation messages at one place.
DisplayMode property of this control can be used to display in different formats as follows:
  • BulletList
  • List
  • SingleParagraph
We have already provided few questions about Validation Controls in ASP.NET in previous article.


Globalization Vs Localization

There are situations when we need to build an application that work for multiple cultures e.g en-USar-SA etc, this process of designing and building applications that work for more than one cultures is called globalization. However, customizing an application for a specific culture is localization. Both globalization and localization normally go together.

How to access information about a user's locale in ASP.NET?

User's locale information can be accessed through System.Web.UI.Page.Culture property.

Difference between Culture and UICulture properties in ASP.NET?

CultureInfo class plays an important role for localizing our application pages. Culture is specific in localizing
non-visual parts of the page like DateTime, Currency, number formatting etc. while on the other hand, UICulture is specific in localizing visual part of a webpage like Language being used to display the contents of the web page.


Difference between Local and Global resources?

Resources for a localized ASP.NET application can be stored locally as well as globally. Local resources are specific to web page and stored in a folder App_LocalResources. It can be accessible to that specific page only. Global resources are accessed by almost all application pages and stored in App_GlobalResources foler.

What is a Neutral Culture? and how its different from a Specific Culture?

As we have seen earlier that a culture has two things i.e. Language and Country/Region. For example, en-Us represents English - United States; en-GB represents English - Great Britain; and ar-SA represents Arabic - Saudi Arabia. So, we can easily understand that first page is language while second is country/region.

A neutral culture is one that is associated only with part-1 i.e. language and not with part-2 i.e. country/region. For example, ar is the neutral name for Arabic culture while ar-SA is specific to Saudi Arabian Arabic culture.


Difference between Response.Write() and Response.Output.Write()?

Difference between Response.Write() and Response.Output.Write() is that the later provide formatting capability through String.Format-Style which the former doesn't have.
In case of Response.Write(), HttpResponse calls directly the following method:
      public void Write(object obj)
     {  
this._writer.Write(obj);
     }
Above method internally calls it TextWriter's write() method.
However, in case of Response.Output.Writer(), HttpResponse actually get reference to TextWriter through
Reponse.Output and then after getting control TextWtiter, call other overloaded method that helps to format the string.
       Response.Output.Write("This is an {0} test at {1:d}", "amazing", DateTime.Now);

Asp.net Interview Question-Part 1

ASP.NET Interview Questions for Beginners and Professionals - Part 1

This ASP.NET Tutorial is an extension to my previous tutorial "Top 10 ASP.NET Interview Questions and Answers". In previous tutorial, focus was to present you with the most important and top ASP.NET Interview Questions that are normally asked during an ASP.NET developer Interview. Here in this article, I'll try to further extend those important questions as well as add more important questions.

Basically, this is how an interviewer normally does. Interviewer asked a question about a technical concept at high level. If he gets a right answer, he further goes into details related to that particular concept and its implementation details. For example, in previous article, we asked about the concept of View State in ASP.NET but in this tutorial, we will further explore the View State concept with more questions. But we will not repeat the questions already presented in previous post, so it's highly recommended to go through that ASP.NET Interview Questions tutorial first.

What are HttpHandlers and HttpModules in ASP.NET?

In order to fully comprehend the concept of HttpHandlers and HttpModules, I have written a detailed ASP.NET Tutorial. Here I am defining both the concepts as follows:

HttpHandler: ASP.NET Engine uses HttpHandlers to handle specific requests on the basis of it's extensions. ASP.NET Page Handler handles all requests coming for (.aspx) pages. We can define our own custom HttpHandler to handle a specific request with a specific extension, say .jpeg, .gif, or .ahmad. But there will always be only one handler for a specific request.

HttpModule: ASP.NET Engine uses HttpModules to inject some specific functionality along with ASP.NET default functionality for all incoming requests regardless of its extensions. There are a number of built-in modules already available in ASP.NET HTTP Pipeline. But we can write our own custom HTTP module to perform some additional functionality (for example, URL rewriting or implementing some security mechanism) for all incoming requests.

What is State Management?

HTTP is a stateless protocol by nature. So, we need some mechanism to preserve state (i.e. state of a webpage, a control or an object etc.) between subsequent requests to server from one or more clients. And this mechanism is referred as State Management.

What are the State Management Techniques used in ASP.NET?

State Management techniques used in ASP.NET can be categorized in two types:
  1. Client-Side State Management
    • View State
    • Control State
    • Hidden Fields
    • Cookies
    • Query String
  2. Server-Side State Management
    • Application State
    • Session State
    • Profile Properties

What is ViewState? or Explain ViewState as State Management Technique?

ViewState is one of the Client-Side State Management techniques that provides page-level state management, which means state is preserved between subsequent requests to same page. By using this technique, state of the page along with its controls is stored in a hidden form field  i.e. "__VIEWSTATE" and this field is again available on server when page is posted back with HTTP Request.
You can find this hidden field by looking into view source of an .ASPX page as:
<input type="hidden" name="__VIEWSTATE" value="wEPDwUKMTM4OTIxNTEzNA9kFgJmD2QWAgIBD2QWAgIDDxYCHgVzdHlsZQV" />
ViewState data is encoded in Base64 String encoded format.


Can we Enable/Disable ViewState?

Yes, ViewState can be enabled or disable at different levels:
  • Control Level
    ViewState for a specific control can be enabled or disabled by setting EnableViewState property as follows:
    aControl.EnableViewState = false;
  • Page Level
    We can enable/disable ViewState for a complete page as follows:
    <%@ Page Language="C#" EnableViewState="false" %>
  • Application Level
    For whole application, we can enable/disable views in configuration file as follows:
    <pages enableViewState="false">
        ....
    </pages>


What is the difference between Session.Clear() and Session.Abandon() in ASP.NET?

As we understand that Session is a Collection and it stores data as Key/Value pair. So,
 Session.Clear() clears all the session values but doesn't destroy the Session. however, 
 Session.Abandon() destroys the session object.
In other words, Session.Clear() is like deleting all files inside a folder (say "Root") but Session.Abandon() means deleting the "Root" folder.

What is the difference between Application and Session State?

Application state is basically a common data repository for an application's all users and their all sessions. On the other hand, Session state is specific to a single user session.
So, we can store data in application state object that is common for all users of a particular application as follows:
//Set Value
Application["UsersCounter"] = Convert.ToInt32(Application["UsersCounter"]) + 1;
//Retrieve Value
lblUsersCounter.Text = Application["UsersCounter"].ToString();
It's recommended to store smaller size values in application object.

Session object can store data for a specific session of user. Storage and retrieval is also simple just as for application object.
//Set Value
Session["ProductsCount"] = Convert.ToInt32(Session["ProductsCount"]) + 1;
//Retrieve Value
lblProductsCounter.Text = Session["ProductsCount"].ToString();

Interview Questions about Session State Modes and Session_Start/Session_End events in Global.asax are already explained here.


What is the difference between Label Control and Literal Control?

A Label control in ASP.NET renders text inside <span> tags while a Literal Control renders just the text without any tags.
With Label controls we can easily apply styles using it's CssClass property, however, if we don't want to apply style/formatting, it's better to go for a Literal control.

Hyperlink Vs LinkButton in ASP.NET?

A Hyperlink just redirects to a given URL identified by "NavigateURL" property. However a LinkButton which actually displays a Hyperlink style button causes a postback to the same page but it doesn't redirect to a given URL.

Validation Controls related Interview Questions are already given in previous post here.

Hopefully, this pool of ASP.NET Interview Questions and Answers along with previous list of Top 10 will be helpful for ASP.NET Developers.

dot net tips

Strong and Weak Typed Languages

C# is a strongly typed language. All variables in a program must be declared as being of a specific type. The variable's behaviour is defined by the chosen type. For example, an integer variable can only contain whole numbers. If a number in an integer variable needs a fractional part, it must first be converted to a different type, possibly being stored in a new variable as a part of the translation.
The alternative to a strongly typed language is a weakly typed language. An example would be VBScript used by many classic ASP developers. In VBScript, the type of the variable is not declared and the behaviour of the variable may appear to change from one line of code to the next.

Variable Declaration and Assignment

A variable can be declared with one line of code, specifying the variable type and its name. In the following code, an integer variable is declared using the data type int.
 int numberofArticles;
A variable can be given a value using the assignment operator, (=). The variable to the left of the operator is assigned the value to the right. The following code shows a variable being declared and assigned a value.
int numberofArticles;
numberofArticles=3;
You do not need to assign a value to a new variable immediately. There may be many lines of code between the declaring a variable and giving it a value. However, if you do wish to declare a variable and assign a value at the same time, this can be achieved in a single statement. For example:
int numberofArticles=3; 
It is possible to declare multiple variables of the same type in a single line of code. You can also assign the same value to multiple variables in one statement. To complicate things further (or to show the elegance of C#, depending on your viewpoint), these operations can be combined. The following code shows three examples.
NB: Multiple variables can be assigned the same value in this manner because the assignment operation returns the value that has been assigned.

Assignment Problems

Definite Assignment

The C# compiler enforces a rule known as definite assignment. This states that a variable may not be read until a value has been assigned. This prevents you from writing code that reads a variable with an undefined value, as this could give unpredictable results.
The following code fails to compile, displaying the error "Use of unassigned variable numberOfArticles".


  











 

 

 

 

  Numeric Data Type Reference

I will end this article with a quick reference to the numeric data types. For integer types, the declaration keyword, a description of the type, the range of possible values and the number of bits used to represent the value are given. For non-integers, the scale and the number of digits of accuracy are given, rather than minimum and maximum. This allows you to determine which data type should be used for any numeric variable.
The Boolean type is included, which although not technically numeric, fits well in this table. The Boolean type can hold either true or false. It is named after the mathematician, George Boole.

c# Components

 

Namespace and Assemblies


The first line of the “Hello, C# World!” program was this:

using System;

This line adds a reference to the System namespace to the program. After adding a reference to a namespace, you can access any member of the namespace. As mentioned, in .NET library references documentation, each class belongs to a namespace. But what exactly is a namespace?

To define .NET classes in a category so they’d be easy to recognize, Microsoft used the C++ class-packaging concept know as namespaces. A namespace is simply a grouping of related classes. The root of all namespaces is the System namespace. If you see namespaces in the .NET library, each class is defined in a group of similar category. For example, The System.Data namespace only possesses data-related classes, and System.Multithreading contains only multithreading classes.

When you create a new application using visual C#, you see that each application is defined as a namespace and that all classes belong to that namespace. You can access these classes from other application by referencing their namespaces.

 For example, you can create a new namespace MyOtherNamespace with a method Hello defined in it. The Hello method writes “Hello, C# World!” to the console. Listing2 shows the namespace.

Listing 2 Namespace wrapper for the hello class


// Called namespace
namespace MyOtherNamespace
{
class MyOtherClass
{
public void Hello()
{
Console.WriteLine ("Hello, C# World!");
}
}
}

In listing 3, you’ll see how to reference this namespace and call MyOtherClass’s Hello method from the main program.

In listing 2, the MyOtherClass and its members can be accessed from other namespaces by either placing the statement using MyOtherNamespace before the class declaration or by referring to the class my other namespace before the class declaration or by referring to the class as MyOtherNamespace.Hello, as shown in listing 3 and listing 4.

Listing 3. Calling my other Namespace Name space members

using System;
using MyOtherNamespace;

 // Caller namespace
namespace HelloWorldNamespace
{
      class Hello
      {
            static void Main()
            {
                  MyOtherClass cls = new MyOtherClass();

                  cls.Hello();
            }
      }
}

// Called namespace
namespace MyOtherNamespace
{
      class MyOtherClass
      {
            public void Hello()
            {
                  Console.WriteLine("Hello, C# World!");
            }
      }
}

As you have seen in listing 3, you include a namespace by adding the using directly. You can also reference a namespace direct without the using directive. Listing 4 shows you how to use MyOtherClass of MyOtherNamespace.

Listing 4. Calling the HelloWorld namespace member from the MyOtherNamespace

// Caller namespace
namespace HelloWorldNamespace
{
class Hello
{
static void Main()
{
   MyOtherNamespace.MyOtherClass cls =
       new MyOtherNamespace.MyOtherClass();
   cls.Hello();
}
}
}

Standard Input and Output Streams


The System.Console class provides the capability to read streams from and write streams to the System console. It also defines functionality for error streams. The Read operation reads data from the console to the standard input stream, and the Write operation writes data to the standard output stream. The standard error stream is responsible for storing error data. These streams are the automatically associated with the system console.

The error, in, and out properties of the Console class represents standard error output, standard input and standard output streams. In the standard output stream, the Read method reads the next character, and the ReadLine method reads the next line. The Write and WriteLine methods write the data to the standard output stream. Table 1 describes some of the console class methods.

Table 1. The System.Console Class methods

METHOD

DESCRIPTION

EXAMPLE

Read
Reads a single character
int i = Console.Read();
ReadLline
Reads a line
string str = Console.ReadLine();
Write
Writes a line
Console.Write ("Write: 1");
WriteLine
Writes a line followed by a line terminator
Console.WriteLine("Test Output Data with Line");




Listing 5 shows you how to use the Console class and its members

Listing 5. Console class example

using System;
namespace ConsoleSamp
{
class Classs1
{
static void Main(string[ ] args )
{
 Console.Write("Standard I/O Sample");
 Console.WriteLine("");
 Console.WriteLine ("= = = = = = = = ");
 Console.WriteLine ("Enter your name . . .");
 string name = Console.ReadLine();
 Console.WriteLine("Output: Your name is : "+ name);
}
}
}

Figure2 shows the output of listing 5.



Figure 2. The console class methods output


The Object Class


­­­­­­­­­­­­­­As described, in the .NET framework, all types are represented as objects and are derived from the Object class. The Object class defines five methods: Equals, ReferenceEquals GetHashCode, GetType and ToString. Table 2 describes these methods, which are available to all types in the .NET library.

Table 2. Object class methods

METHOD
DESCRIPTION
GetType
Return type of the object.
Equals
Compares two object instances. Returns true if they’re Equal; otherwise false.
ReferenceEquals
Compares two object instances. Returns true if both are Same instance; otherwise false.
ToString
Converts an instance to a string type.
GetHashCode
Return hash code for an object.



The following sections discuss the object class methods in more detail.

The GetType method


You can use the Type class to retrieve type information from the object. The GetType method of an object return a type object, which you can use to get information on an object such as its name, namespace, base type, and so on. Listing 6 retrieves the information of objects. In Listing 6, you get the type of the Object and System.String classes.

 

Listing 6 GetType example


using System;
class TypeClass
{
static void Main(string [] args)
{
//create object of type object and string
Object cls1 = new Object ();
System.String cls2 = "Test string";
// Call Get Type to return the type
Type type1 = cls1.GetType( );
Type type2 =cls2.GetType( );
// Object class output
Console.WriteLine(type1.BaseType);
Console.WriteLine(type1.Name);
Console.WriteLine(type1.FullName);
Console.WriteLine(type1.Namespace);

// String output
Console.WriteLine(type2.BaseType);
Console.WriteLine(type2.Name);
Console.WriteLine(type2.FullName);
Console.WriteLine(type2.Namespace);
}
}

Figure  shows the output of listing 6.



Figure 3. Output of listing

The Equals and ReferenceEqual Methods


The Equals method in the Object class can compare two objects. The ReferenceEqual method can compare the two objects’ instances. For example:

Console.WriteLine(Object.Equals(cls1, cls2));
Console.WriteLine(Object.Equals(str1, str2));

See listing 7 get type, equal, and reference Equals

Listing 7. Get Type, Equal, and ReferenceEquals

using System;
namespace TypesSamp
{
//define class 1
public class Class1: object
{
private void Method1()
{
 Console.WriteLine("1 method");
}
}

// Define class 2
public class Class2: Class1
{
private void Method2( )
{
 Console.WriteLine("2 method");
}
}

class TypeClass
{
static void Main(string [] args)
{
Class1 cls1 = new Class1();
Class2 cls2 = new Class2();
Console.WriteLine ("= = = = = = = = = = ");
Console.WriteLine ("Type Information");
Console.WriteLine ("= = = = = = = = = =");
// Getting type information
Type type1 =cls1.GetType( );
Type type2 = cls2.GetType( );
Console.WriteLine(type1.BaseType);
Console.WriteLine(type1.Name);
Console.WriteLine(type1.FullName);
Console.WriteLine(type1.Namespace);

// Comparing two objects
string str1 = "Test";
string str2 = "Test";
Console.WriteLine(" = = = = = = = = = = = ");
Console.WriteLine("comparison of two objects");
Console.WriteLine(object.Equals(cls1, cls2));
Console.WriteLine(object.Equals(str1, str2));
}
}
}

Figure 4 shows the output of listing 7.



Figure 4 get type and compare objects code output


The ToString Method and String Conversion


The ToString method of the Object class converts a type to a string type.


Listing 8 shows an example of the ToString method.

 

Listing 8. ToString method example


using System;
namespace ToStringSamp
{
class Test
{
static void Main(string [] args)
{
  int num1 =8;
  float num2 =162.034f;
  Console.WriteLine(num1.ToString( ));
  Console.WriteLine(num2.ToString( ));
}
 }
}

The GetHashCode method


A hashtable (also commonly known as a map or dictionary) is a data structure that stores one or more key- value pairs of data. Hashtables are useful when you want fast access to a list of data through a key (which can be a number, letter, string, or any object). In .NET the HashTable class represents a hashtable, which is implemented based on a hashing algorithm. This class also provides methods and constructors to define the size of the hash table. You can use the Add and Remove methods to add and remove items from a hashtable. The Count property of the HashTable class returns the number of items in a hashtable.

The GetHashCode method returns the hash code of an object. To return a hash code for a type, you must override the GetHashCode method. An integer value is returned, which represents whether an object is available in a hashtable.

Two other useful methods of the object class are MemberWiseClone and Finalize methods. The MemberWiseClone method creates a shallow copy of an object, which can be used as a clone of an object. The Finalize method acts as a destructor and can clean up the resources before the garbage collector calls the object. You need to override this method and write your own code to clean up the resources. The garbage collector automatically calls the Finalize method if an object is no longer in use.