Sunday 23 September 2012

Difference between method overloading and method overriding

Method Overloading and Method Overriding are both the techniques used to implement FUNCTIONAL POLYMORPHISM 

Method Overloading (COMPILE TIME Polymorphism)
Method Overloading means having two or more methods with the same name but with different signature(different parameters list and different type of parameters) in same class or in different classes.

Method Overloading forms compile-time polymorphism.

Example :
We will create a method that will calculate the square of a given number having same name but different data type.In this program we have use different methods having same name but different parameters this is called overloading.

 

 

Method overriding (RUN TIME Polymorphism)
Method overriding means having two methods with same name and same signature, one method in base class and other method in derived class.

A subclass inherits methods from a base class. Sometimes, it is necessary for the subclass to modify the methods defined in the base class. This is referred to as method overriding.

This can be achieved by using the virtual and override keywords. we have to use the virtual keyword for the method which in base class and override keyword  for the method in subclass.

By default functions are not virtual in C# and so you need to write “virtual” explicitly.

Example :


    




























Difference between method overloading and method overriding

Overloading Overriding
Having same method name with different Signatures. Methods name and signatures must be same.
Overloading is the concept of compile time polymorphism Overriding is the concept of runtime polymorphism
Two functions having same name and return type, but with different type and/or number of arguments is called as Overloading When a function of base class is re-defined in the derived class called as Overriding
It doesn't need inheritance. It needs inheritance.
Method can have different data types Method should have same data type.
Method can be different access specifies Method should be public.

Friday 21 September 2012

Difference between string and stringbuilder in c#

String is immutable(Non updatable). It means that you can't modify string at all, the result of modification is new string. This is not effective if you plan to append to string

StringBuilder is mutable(Updatable). It can be modified in any way and it doesn't require creation of new instance. When work is done, ToString() can be called to get the string.

Simple example: 










You'll end up creating 2001 strings here, 2000 of which are thrown away. The same example using StringBuilder:











This should place much less stress on the memory allocator.

the final effect is the same, but the StringBuilder will use less memory and will run faster. Instead of creating a new string which is the concatenation of the two, it will create the chunks separately, and only at the end it will unite them.

if you make a lot of string operations like appending,truncating then StringBuilder is a good option.

Differentiate Response. write & Response.output.write?

Response.Write and Response.Output.Write are both used to write messages on the screen. But Using Reponse.Output.Write() you can display formattable output while Response.Write() can only display single character line.

Resopnse.Output.Write()
  • Formatted output will be displayed.
  • It gives String.Format-style formatted output.
  • It writes the HTTP Output Stream.
  • As per specified options it formats the string and then write to web page.

Example :
Response.Output.Write("{0} is {1:d}", "Current Date Time is: ",DateTime.Now);


Response.Write()
  • unformatted output will be displayed.
  • It never gives like that.
  • It writes the text stream
  • It just output a string to web page.

Example :
Response.Write("Current Date Time is "+DateTime.Now.ToString());




What's the difference between CHAR and VARCHAR data types and when do I use them?

CHAR and VARCHAR data types are both non-Unicode character data types with a maximum length of 8,000 characters. 

The main difference between these 2 data types is that a CHAR data type is fixed-length while a VARCHAR is variable-length.  If the number of characters entered in a CHAR data type column is less than the declared column length, spaces are appended to it to fill up the whole length.

Another difference is in the storage size wherein the storage size for CHAR is n bytes while for VARCHAR is the actual length in bytes of the data entered (and not n bytes).

CHAR is faster than VARCHAR when used in joins and queries. 

when do I use them?
You should use CHAR data type when the data values in a column are expected to be consistently close to the same size.  example SSN, SystemIDs, EMPIDs,etc..

On the other hand, you should use VARCHAR when the data values in a column are expected to vary considerably in size.

The above explanation is also applicable to NCHAR and NVARCHAR datatypes.

Thursday 20 September 2012

Error Handling in .Net

What is Exception?
An exception is unexpected error or problem.

"EXCEPTION IS A RUNTIME ERROR WHICH ARISES BECAUSE OF ABNORMAL CONDITION IN A CODE SEQUENCE. "

Exception handling uses the try, catch, and finally keywords to attempt actions that may not succeed, to handle failures, and to clean up resources afterwards.Exceptions can be generated by the common language runtime (CLR), by third-party libraries, or by the application code using the throw keyword.

When your application encounters an exceptional circumstance, such as a division by zero or low memory warning, an exception is generated. If no exception handler for a given exception is present, the program stops executing with an error message. If a catch block defines an exception variable, you can use it to get more information on the type of exception that occurred.

Exception objects contain detailed information about the error, including the state of the call stack and a text description of the error.


What is Exception Handling?
Method to handle error and solution to recover from it, so that program works smoothly.

There are three ways to handle exceptions/errors in ASP.NET:

    Try/catch/finally block
    Using Error Events 
    Using Custom Error Page


1. Try/catch/finally block

try Block
try Block consist of code that might generate error and it's must be associated with one or more catch block or by finally block. It's need not necessarily have a catch Block associated with it but in that case it must have a finally Block associate with it.

Example of try Block

Example 1
try
{
//Code that might generate error
}
catch(Exception errror)
{
}

Example 2
try
{
//Code that might generate error
}
catch(ExceptionA errror)
{
}
catch(ExceptionB error)
{
}

Example 3
try
{
//Code that might generate error
}
finally
{
}


Catch Block

catch Block is used to recover from error generated in try Block. In case of multiple catch Block, only the first matching catch Block is executed. when you write multiple catch block you need to arrange them from specific exception type to more generic type. When no matching catch block are able to handle exception, the default behavior of web page is to terminate the processing of the web page.


Example of catch Block

Example 1



Example 2




















finally Block
The finally block is useful for cleaning up any resources that are allocated in the try block, and for running any code that must execute even if an exception occurs in the try block.

When to use finally Block? - You should use finally block to write cleanup code. i.e. you can write code to close files, database connections, etc.

Only One finally block is associated with try block. finally block must appear after all the catch block. If you use transfer control statement in finally block, you will receive compile time error.

Example of finally Block

Example 1
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handles error and have solution to recover from it.
}
finally
{
//Code to dispose all allocated resources.
}

Example 2
try
{
//Code that might generate error
}
finally
{
//Code to dispose all allocated resources.
}



What is throw statement?
The throw statement is used to signal the occurrence of an anomalous situation (exception) during the program execution.

Usually the throw statement is used with try-catch or try-finally statements. When an exception is thrown, the program looks for the catch statement that handles this exception.

throw exception;

You can also rethrow a caught exception using the throw statement

Example of throw statement
try
{
//Code that might generate error
}
catch(Exception errror)
{
//Code that handles error and have solution to recover from it.

throw; //Rethrow of exception to Add exception details in event log or sending email.
}


Explain using statement?
using statement is used similar to finally block i.e. to dispose the object. using statement declares that you are using a disposable object for a short period of time. As soon as the using block ends, the CLR release the corresponding object immediately by calling its dispose() method.

Example of using statement
//Write code to allocate some resource
//List the allocated resource in a comma-seperated list inside
//the parantheses of the using block

using(...)
{
//use the allocated resource.
}

//here dispose method is called for all the object referenced without writing any additional code.


Best Practices for Handling Exceptions
When you are develop any type of .NET Application, the Exception handling is important for all to prevent unwanted crashing of applications. Exceptions are runtime errors which might be caused by some operation illegal to the application.

The following list contains suggestions on best practices for handling exceptions:

Know when to set up a try/catch block. For example, you can programmatically check for a condition that is likely to occur without using exception handling. In other situations, using exception handling to catch an error condition is appropriate.

The following example uses an if statement to check whether a connection is closed. You can use this method instead of throwing an exception if the connection is not closed.

















2. Error handling events 

• Page_Error: This is page event and is raised when any unhandled exception occur in the page.

• Application_Error: This is application event and is raised for all unhandled exceptions in the ASP.NET application and is implemented in global.asax


3. Using Custom error page
The <customErrors> section in web.config has two attributes that affect what error page is shown: defaultRedirect and mode. The defaultRedirect attribute is optional. If provided, it specifies the URL of the custom error page and indicates that the custom error page is shown instead of the Runtime Error. The mode attribute is required and accepts three values: On, Off, and RemoteOnly. These values have the following behavior:

<customErrors mode="On" defaultRedirect="/ErrorPages/AppError.html">
    <error statusCode="404" redirect="/ErrorPages/404.html" />
</customErrors>

On - indicates that the custom error page or the Runtime Error is shown to all visitors, regardless of whether they are local or remote.

Off - specifies that the Exception Detail is displayed to all visitors, regardless of whether they are local or remote.

RemoteOnly - indicates that the custom error page or the Runtime Error that is shown to remote visitors, while the Exception Detail is shown to local visitors.






Difference between ASP and ASP.NET

ASP and ASP.Net are very different programming languages. ASP is a scripting language, where as ASP.NET is the web formulation of a compiled language (Visual Basic, C#, J#, C++.Net). Moreover, unlike ASP, ASP.NET is an object-oriented language.

ASP is run under the inetinfo.exe(IIS) process space and is therefore susceptible to application crashes due to IIS being stopped or restarted.

On the other hand, the ASP.NET worker process is a distinct process (aspnet_wp.exe) separate from the IIS process inetinfo.exe. The process model in ASP.NET is unrelated to process isolation settings in IIS.

Difference between ASP and ASP.NET

ASP.NET:
  • ASP.NET purely object oriented
  • ASP.NET is compiled.
  • asp.net html and coding part are separated by code behind files which contains all event handling code.
  • ASP.Net web forms inherit the class written in code behind.
  • ASP.Net web forms use full fledged programming language
  • ASP.Net web applications are configurable (web.config)
  • ASP.Net webforms can use custom controls through the @ register directive
  • ASP.Net web forms have ADO.Net which supports XML integration and integration of data from two or more data sources
  • ASP.NET full XML Support for easy data exchange

ASP:
  • ASP is partially object oriented.
  • ASP is interpreted
  • ASP has Mixed HTML and coding logic
  • ASP does not have the concept of inheritance.
  • ASP pages use scripting language.
  • ASP applications are not.
  • It is not available with ASP.
  • while ASP has ADO which is a simple COM object with limited facilities.
  • ASP No in-built support for XML

Tuesday 18 September 2012

To Avoid ThreadAbortException in ASP.NET while Redirect

If you use the Response.End, Response.Redirect, or Server.Transfer method in your code then a ThreadAbortException occurs and the response is ended/aborted immediately.

For example, the line:
Response.Redirect("MyHome.aspx") //your response will be aborted

The ThreadAbortException is thrown when you make a call to Response.Redirect(url) because the system aborts processing of the current web page thread after it sends the redirect to the response stream. Response.Redirect(url) actually makes a call to Response.End() internally, and it's Response.End() that calls Thread.Abort() which bubbles up the stack to end the thread.Under rare circumstances the call to Response.End() actually doesn't call Thread.Abort(), but instead calls HttpApplication.CompleteRequest().

 Response.Redirect(String, Boolean) - Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.
 Response.Redirect(string url, bool endResponse)

using Response.Redirect(url, false),

You don't need to put the redirect in a try-catch block. Just replace all calls to Response.Redirect(url) with the following lines:

Response.Redirect(url, false);

When endResponse is false the client is sent the redirect url, but the internal call to Response.End is skipped. This completely avoids the code that would throw the exception, but the cost is that this thread doesn't stop executing the Application events.

The way to get over this problem is to specify Response.Redirect(URL,false) , this will tell .NET framework not to stop the execution of the current thread and hence the error will be resolved.

“ThreadAbortException” is a special kind of an exception even if you catch it in a catch block even then it will be raised again at the end of the catch block. When this exception is raised, the runtime executes all the finally blocks before killing the thread.


If endResponse=true (or if the other overload is used), the exception is thrown and the current request will immediately be terminated. A true will just kill the thread so nothing further will execute, which in turn throws a ThreadAbortException.


Difference between Response.Redirect(String) Vs Response.Redirect(String, Boolean) in ASP.NET


Response.Redirect(String) - Redirects a client to a new URL and specifies the new URL.
Response.Redirect(string url)

Response.Redirect(String, Boolean) - Redirects a client to a new URL. Specifies the new URL and whether execution of the current page should terminate.
Response.Redirect(string url, bool endResponse)

Response.Redirect(url, true) - The client will be sent the redirect for the new page and present page will immediately stop processing as a thread abort will occur.  This is the default behavior of a redirect.

Response.Redirect(url, false) – In this overload method, the second parameter tells the system whether to make the internal call to Response.End() or not. Parameter should be false to make the client is sent to redirect url but call to Response.End is skipped. This is one way to avoid the exception, but the cost is that this thread doesn’t stop executing the Application events!

If you are doing a redirect in Page_Init (or any page events) and call Response.Redirect(url, false) the page will only redirect once the current page is done executing.  This means that any server side processing you are performing on that page WILL get executed.

Monday 17 September 2012

difference between response.redirect and server.transfer in asp.net

We can transfer current users page request to another page with two methods:

    * Response.Redirect (HttpResponse.Redirect Method)
    * Server.Transfer (HttpServerUtility.Transfer Method)


Response.Redirect()

Response.Redirect method is by far the simplest method of redirecting processing from a source page to a different destination or target page in the same or even across different applications. When the web server receives a request for redirection, it sends a response header to the client that causes the client to send a new request back to the server. In other words, a redirect causes two request/response cycles: one for the original and one for the new redirected request.

The main difference is the posted previous page values can't be accessable. Here also the data can pass through server variables and query string. It simply redirect the page from one page to another.




















Example: Response.Redirect("Default.aspx")


Server.Transfer()


Instead of relying on the client to make a request to a new page, Server.Transfer is a server-side redirection technique that simply changes the code's "focus" on the web server to a new page. Server.Transfer is far more efficient than Response.Redirect when the target page resides on the same web server, because it avoids the extra roundtrip and uses only server resources for the redirection.

The main advantage of this transfer the first page to second page with better performance. The data can pass through variables, query string and also can retrive from the previous page control value.

















Example : Server.Transfer("example.aspx")




Response.Redirect should be used when:

  •     we want to redirect the request to some plain HTML pages on our server or to some other web server
  •     we don't care about causing additional roundtrips to the server on each request
  •     we do not need to preserve Query String and Form Variables from the original request
  •     we want our users to be able to see the new redirected URL where he is redirected in his browser (and be able to bookmark it if its necessary)



Server.Transfer should be used when:
  •     we want to transfer current page request to another .aspx page on the same server
  •     we want to preserve server resources and avoid the unnecessary roundtrips to the server
  •     we want to preserve Query String and Form Variables (optionally)
  •     we don't need to show the real URL where we redirected the request in the users Web Browser


Friday 7 September 2012

Case Sensitive SQL Query Search with Collate - SQL SERVER


A default SQL Server installation is case insensitive, which means that SQL Server will not differentiate between upper and lower case characters/letters.That is, "Shindu" is the same as "SHINDU" or "shindu".

If you are using SQL Server, check out the COLLATE clause to make searches case sensitive

The COLLATE clause allows us to specify a particular collation for an expression. In the following examples, we will use COLLATE to make our search case sensitive. We need to specify a case sensitive collation along with COLLATE. The following example uses the collation SQL_Latin1_General_CP1_CS_AS. If you are working with non-English data, choose an appropriate collation.

Example :

Table : Tbl_Login




 The above example print 'Invalid Login Name or Password!', because the input provided is in all lower case, while the data in the table is stored in mixed case.


Changing the collation of the column permanently

Changing the collation of the column permanently, so that all comparisons are case sensitive by default.

Default Collation of the SQL Server installation SQL_Latin1_General_CP1_CI_AS is not case sensitive.

To change the collation of the any column for any table permanently run following query.

ALTER TABLE
<Table_Name> ALTER COLUMN <Column_Name> VARCHAR(50)
COLLATE Latin1_General_CS_AS

Thursday 6 September 2012

Object reference not set to an instance of an object exception with accessing session variable

The "Object reference not set to an instance of an object" exception usually happens when you try to address an object that has not been set.

You can avoid the "Object reference not set to an instance of an object" exception  by checking each object to make sure it is a valid object before attempting to access it.

Example :

if (Session["VeriableName"] != null)
  {
     //Access the session value
  }


When they say "initialize" the session they mean setting an intial value for a session variable (not like initializing a class). the best place to do it is Session_Start though you can do it anywhere.

Difference between User-defined functions and stored procedure in SQL Server

What is Stored Procedures

A stored procedure is a group of Transact-SQL statements compiled into a single execution plan. The stored procedure mechanism to simplify the database development process by grouping Transact-SQL statements into manageable blocks.

Stored procedures can also improve performance. Many tasks are implemented as a series of SQL statements. Conditional logic applied to the results of the first SQL statements determines which subsequent SQL statements are executed. If these SQL statements and conditional logic are written into a stored procedure, they become part of a single execution plan on the server. The results do not have to be returned to the client to have the conditional logic applied; all of the work is done on the server. 

Benefits of Stored Procedures
  • Precompiled execution : SQL Server compiles each stored procedure once and then reutilizes the execution plan. This results in tremendous performance boosts when stored procedures are called repeatedly.

  • Reduced client/server traffic : If network bandwidth is a concern in your environment, you'll be happy to learn that stored procedures can reduce long SQL queries to a single line that is transmitted over the wire.

  • Efficient reuse of code and programming abstraction : Stored procedures can be used by multiple users and client programs. If you utilize them in a planned manner, you'll find the development cycle takes less time.

  • Enhanced security controls : You can grant users permission to execute a stored procedure independently of underlying table permissions.

What is User-defined functions

Functions in programming languages are subroutines used to encapsulate frequently performed logic. Any code that must perform the logic incorporated in a function can call the function rather than having to repeat all of the function logic.

SQL Server supports two types of functions:
  • Built-in functions : Operate as defined in the Transact-SQL Reference and cannot be modified. The functions can be referenced only in Transact-SQL statements using the syntax defined in the Transact-SQL Reference.  

  • User-defined functions : Allow you to define your own Transact-SQL functions using the CREATE FUNCTION statement. User-defined functions take zero or more input parameters, and return a single value. Some user-defined functions return a single, scalar data value, such as an int, char, or decimal value.

Benefits of User-defined functions
  • They allow modular programming : You can create the function once, store it in the database, and call it any number of times in your program. User-defined functions can be modified independently of the program source code.

  • They allow faster execution : Similar to stored procedures, Transact-SQL user-defined functions reduce the compilation cost of Transact-SQL code by caching the plans and reusing them for repeated executions. This means the user-defined function does not need to be reparsed and reoptimized with each use resulting in much faster execution times. CLR functions offer significant performance advantage over Transact-SQL functions for computational tasks, string manipulation, and business logic. Transact-SQL functions are better suited for data-access intensive logic.

  • They can reduce network traffic :  An operation that filters data based on some complex constraint that cannot be expressed in a single scalar expression can be expressed as a function. The function can then invoked in the WHERE clause to reduce the number or rows sent to the client.

Difference between stored procedure and User-defined functions

Stored Procedure User-defined functions
Its may or may not return a value Function must return a value(scalar,inline table or multi statement table)
SP can create table but won’t return Table Variables Not returning output parameter but returns Table variables
SP can not be used with Select statement and have to use EXEC or EXECUTE Function can be used with Select statement
SP can be used to change server configuration(in terms of security-i.e. setting granular permissions of user rights) function can't be used for this
XML and output parameters can be passed to SP XML and output parameters can't be passed to functions
transaction related statement can be handled in SP it can't be in function
stored procedures can call a function or another SP similarly a function can call another function and a SP .The catch with function is that no user defined SP can be called.Only extended/system defined procs can be called

Tuesday 4 September 2012

How to increase default File Upload size in ASP.Net ?


By default, the maximum size of a file to be uploaded to a server using the ASP.NET FileUpload control is 4MB. You cannot upload anything that is larger than this limit.

This value can be increased by modifying the maxRequestLength attribute in the web application's configuration file (web.config)

To change this size limit, you have to make some changes in the application's web.config:
<configuration>
  <system.web>
    <httpRuntime maxRequestLength="1048576" executionTimeout="3600" />
  </system.web>
</configuration>

maxRequestLength - This attribute is used to limit the size of uploads by rejecting any which exceed a certain limit. The limit refers to the total size of the HTTP upload in KB (approximately equal to the sum of all the files being upload). You should set a sensible limit here to stop malicious visitors using up your bandwidth by uploading excessively large files.

If the size of an upload is too great the server will refuse to accept it. Because the server is refusing the request the uploading browser will report that the submission page is not available. This is a client side error message rather than a server side error message and it means that you cannot normally provide a sensible error message to users if they submit files which are too large.

The default is "4096" (4 MB).

Max value is "1048576" (1 GB) for .NET Framework 1.0/1.1 and "2097151" (2 GB) for .NET Framework 2.0.

ExecutionTimeout -  The execution time-out refers to the number of seconds an ASP.NET page is given before the operation is assumed to have failed and the page terminated. If you are uploading a large file the code that is receiving the transfer may time out before the file has been completely uploaded.

What's the difference between “Layers” and “Tiers”?

Layers are a logical separation and tiers are a physical separation


Layers

Layers are a means of logical separation, and are an architectural pattern to separate concerns. Logical layers help you organize your code better.

For example an application can have the following layers.

1)Presentation Layer or UI Layer
2)Business Layer or Business Logic Layer
3)Data Access Layer or Data Layer

When deploying an application, these layers might exist either on one machine, or on multiple machines.

  In no way is it implied that these layers might run on different computers or in different processes on a single computer or even in a single process on a single computer. All we are doing is discussing a way of organizing a code into a set of layers defined by specific function.
 
The above three layers reside in their own projects, may be 3 projects or even more. When we compile the projects we get the respective layer DLL. So we have 3 DLL's now.

Depending upon how we deploy our application, we may have 1 to 3 tiers. As we now have 3 DLL's, if we deploy all the DLL's on the same machine, then we have only 1 physical tier but 3 logical layers.

If we choose to deploy each DLL on a separate machine, then we have 3 tiers and 3 layers.




Tiers:

Physical tiers however, are only about where the code runs. Specifically, tiers are places where layers are deployed and where layers run. In other words, tiers are the physical deployment of layers.

Single Tier : Every thing was stored in a single system like  three layers( UI, BL, DAL) are in one system. Users need to access this centralized machine.

Two Tier  : Two tier means the user interface is in one system, and BL and DAL is in one system.

Three Tier : Three tier means three layers are in different, different systems

N-Tier :  means which is having many systems..like a banking project ,suppose a Debit card project, which deals with the many locations ,the card holder will swipe somewhere, the bank server is somewhere in the system