Thursday, 12 January 2012

Exceptions in C#

General Discussion:
  Bug: A bug is a programmer mistake.
  Error: An error is caused by a user action.For eg: the user may enter a number where a letter is    expected.Errors can be catched with validation code.
  Exceptions:Even if you remove all bugs and anticipated errors, you may still run into problems, such as running out of memory or trying to open a file that is no longer exists.You cannot prevent Exceptions, but you can handle them so they do not bring down your program.
Idealy, if the exception is caught and handled, the program can fix the problem and continue. Even if the program cannot continue, by catching the exception you have the opportunity to print the error message and terminate the program in a meaningful way.
If there is code in your program that runs regardless of whether an Exception is occured(for eg: to release resources you have allocated), you can place that code in finally block,where it is certain to run,even in the presence of exceptions.
A try block must always be followed by a catch or finally block.
A finally block can be created with or without catch block, but a finally block requires a try block to execute.
It is an error to exit a finally block with break,continue,exit,gotoetc.
System.Exception
It provides a number of useful methods and properties.
The Message property provides information about the exception. It is read only
The HelpLink property provides a link to the help file associated with the exception. Read/write
The StackTrace property of the exception is used to provide a stack trace for the error statement. Read only

Wednesday, 11 January 2012

C# Strings

String:
C# string implements 3 interfaces.They are IComparable,IClonable and IConvertible.
The implementation of C# class is shown below.
public sealed class String : IComparable , IClonable , IConvertible
IComparable classes implement the CompareTo( ) method to compare two strings.
IClonable interface implement the clone( ) method to create the same value of string into another string.
IConvertible is used to convert the string into other types like int,double etc.eg: Convert.toint32(string).
String verbatim(@):
Strings can be declared with verbatim symbol so that special characters (for eg: //backslash) are also considered as string.
eg: string test = @ " This is a sample string\\D:\\MyFolder";
Verbatim string helps when in cases like when we are specifying the path.
ToString Method:
Another common way to create a method is to call ToString( ) method on an object an assign it to a string.
eg: int Myinteger = 5;
     string Integerstring = Myinteger.ToString( );
String Manipulations:
String Comparison:
When we use string.Compare( ) method , we can compare two strings. The result will be an integer value and is 0 if the two strings  are identical and -1 if string1 is smaller than string2 and +1 if the string1 is bigger than string2.Also comparison is case sensitive. So if we want to compare two strings ignoring their case, then we have to declare third parameter in the compare method to "True"
eg: int result = string.Compare(s1, s2, true);
 Apart from that there are three methods to check whether string1 is equal to string2.
string.equals(s1,s2);
s1.equals(s2);
s1 = = s2;
 LastIndexOf ( ) method
 This is used to find the index of the last word in string.
eg:  string s = "one two three four";
int x =s.LastIndexOf(" ") // Getting the last word index by deviding with space
Substring( ) Method
Using this we can find whatever words present in a string.
eg: string s1 = s.Substring(x + 1); // will give the result as four .
Split( ) Method
For splitting the strings with delimiters like comma,space etc which is an efficient way of string manipulation,
StringBuilder( ) Method
C# reccomends to use StringBuilder method to improve performance. We can manipulate large strings using stringbuilder. It uses AppendFormat method to append new,formatted strings as you created them.

Tuesday, 10 January 2012

Interview Questions

Difference between onBlur and onChange events.
onBlur is when you have moved away from an object without necessarily changing it.
onChange is only called afer you have moved away from an object that you have changed the value of.
Difference between a postback and a callback function.
A Postback occurs when the data (the whole page) on the page is posted from the client to the server..ie the data is posted-back to the server, and thus the page is refreshed (redrawn)...think of it as 'sending the server the whole page (asp.net) full of data'.
On the other hand, a callback is also a special kind of postback, but it is just a quick round-trip to the server to get a small set of data (normally), and thus the page is not refreshed, unlike with the postback...think of it as 'calling the server, and receiving some data back'.For example Update panel is used in asp.net for call backs.

With Asp.Net, the ViewState is not refreshed when a callback is invoked, unlike with a postback.




Suppose I want a function that will work only during initial page load and not during postbacks where to write it?
Inside if(!Page.IsPostBack) condition.
Difference between runtime and compile time?
Compile time
  • Syntax errors
  • Typechecking errors
Run time
  • Division by zero
  • Deferencing a null pointer
  • Running out of memory
  • Trying to open a file that isn't there
Difference between primary key and unique key
A table can have more than one unique key constraint columns but primary key columns should be only one.
Primary key does not allow null values.Unique key allows a null value.
Primary key Supports Auto Increment value but Unique doesn't support auto Increment value.
Difference between stored procedure and User Defined function
Stored procedures are compiled for the first time and executes compiled code whenever it is called. But function is compiled and executed every time when it is called.
Function must return a value but in stored procedure it is optional.
Functions take one input parameter,it is mandatory whereas stored procedure takes 0 to n input parameters.
Functions can be called from select statement whereas stored procedure cannot.
We can use try catch statements in stored procedures but in functions cannot.
We cannot use insert,update,delete and create statements in functions whereas in stored procedure we can.
Functions can be called from procedure.Procedures cannot be called from function.
 Difference between truncate and delete
  • You can use WHERE clause(conditions) with DELETE but you can't use WHERE clause with TRUNCATE .
  • You cann't rollback data in TRUNCATE but in DELETE you can rollback data.TRUNCATE removes(delete) the record permanently.
  • A trigger doesn’t get fired in case of TRUNCATE whereas Triggers get fired in DELETE command.
  • If tables which are referenced by one or more FOREIGN KEY constraints then TRUNCATE will not work.
  • TRUNCATE resets the Identity counter if there is any identity column present in the table where delete not resets the identity counter. 
  • TRUNCATE is faster than DELETE.      
  •  
    Difference between collections and generics 
- Non-Generic collections - These are the collections that can hold elements of different data types. It holds all elements as object type.
So it includes overhead of type conversions.
- Generic collections - These are the collections that can hold data of same type and we can decide what type of data that collections can hold.
Some advantages of generic collections - Type Safe, Secure, reduced overhead of type conversions.
    Collections are enumerable data structures that can be accessed using indexes or keys.Using generic collections,classes provide increased type safety and in some cases,better performance especially when storing value types.
    Difference between compile time polymorphism and runtime polymorphism
     Compile time polymorphism also known as function overloading.In this we can have two or more methods with the same name but different signatures.
    Runtime polymorphism also known as function overriding. In this, we can have two or more methods with the same name,same signature but with different implementation.
    Difference between GET and POST method.
    GET method is not secure since your informations will be appeared in the url.Can transfer only limited data.
    POST method is secure and can transfer unlimited data. 
    Difference between UserControl and ServerControl
    A User Control is a partial web page, created in the same way as any other web page in ASP.NET, except that it has an .ASCX extension, and it can be embedded in your other ASPX pages.
    User controls are registered with the web page in which they are used, like this:
    <%@ Register TagPrefix="UC" TagName="TestControl" Src="test.ascx" %>
    They are then declared in the web page they are to be used in, like this:
    <UC:TestControl id="Test1" runat="server"/>
    Server controls are controls that execute on the server and render markup to the browser. User controls and custom controls are both examples of server controls.
    Difference between char and varchar in sql
      The char is a fixed-length character data type, the varchar is a variable-length character data type.
      Because char is a fixed-length data type, the storage size of the char value is equal to the maximum size for this column. Because varchar is a variable-length data type, the storage size of the varchar value is the actual length of the data entered, not the maximum size for this column.
      You can use char when the data entries in a column are expected to be the same size.(For eg: Phone number).
      You can use varchar when the data entries in a column are expected to vary considerably in size.(For eg: Address).
      Difference between output parameters and return statement in sql stored procedure
       In short, return is used to give the control back to the calling program and also return information like success or failure. Note that this shouldn't be used as a means to return actual user data.
      Output parameter is used to share the user data from the SP to the calling program. One needs to use caution while using this as you don't want to have many output parameters. Also output parameters give only singleton values. And if there are too many, its best to use select statements to return data.
      In addition, the RETURN statement can return only integer value, while output parameters support other data types.
    Useful link:
    
    
    Difference between is and as keyword in c#

The is operator checks if an object can be cast to a specific type.
Example:
if (someObject is StringBuilder) ...
The as operator attempts to cast an object to a specific type, and returns null if it fails.
Example:
StringBuilder b = someObject as StringBuilder;
if (b != null) ...
Also related:
The cast operator attempts to cast an object to a specific type, and throws an exeption if it fails.
Example:
StringBuilder b = (StringBuilder)someObject.
The as keyword attempts to convert one object to another, similar to a cast. If the conversion fails, a null is returned instead of an exception being thrown. For example:
object n=123;
object obj="abc";

string s1=n as string;
string s2=obj as string;
 
The is operator tests whether an object is of a particular type. For example:
object n1=123;

bool b1=n1 is int;
bool b2=n1 is string;

Console.WriteLine("n1 is int ? "+b1.ToString());
Console.WriteLine("n1 is string ? "+b2.ToString()); 



    What is Doctype in html

The <!DOCTYPE> declaration must be the very first thing in your HTML document, before the <html> tag.
The <!DOCTYPE> declaration is not an HTML tag; it is an instruction to the web browser about what version of HTML the page is written in.
The <!DOCTYPE> declaration refers to a Document Type Definition (DTD). The DTD specifies the rules for the markup language, so that the browsers render the content correctly.

If cookies are disabled in client browser, will session work?
No. Identities of client get destroy.
What is the @Register directive used for? What is the purpose of @Register directive in ASP.NET? How to create Web User Controls in ASP.NET?
Directives in ASP.NET are used to set attributes for a page. The @Register directive is a directive used to register user defined controls on a web page. A user created server control has an ascx extension. These controls inherit from the namespace System.Web.UI.UserControl. This namespace inherits from the System.Web.UI.Control.

A user control may be embedded in an aspx web page using the @Register directive. A user control cannot be executed on its own independently, but may be registered on a web page and then used out there. Below is the syntax for registering an @register directive in an aspx page in ASP.NET
<%@ Register TagPrefix="UC1" TagName="UserControl1" Src="UserControl1.ascx" %>
The TagPrefix attributes is used to specify a unique namespace for the user control. The TagName is a name used to refer a user control uniquely by its name. Say we want to use this control in a webpage, we may use the code below...
<UC1:UserControl1 runat="server"/>
What is Global.asax file?
The Global.asax file, also known as the ASP.NET application file, is an optional file that contains code for responding to application-level and session-level events raised by ASP.NET or by HTTP modules.
What is caching?
It is a way to store the frequently used data into the server memory which can be retrieved very quickly. And so provides both scalability and performance. For example if user is required to fetch the same data from database frequently then the resultant data can be stored into the server memory and later retrieved in very less time (better performance).
What are the different sql tuning/optimisation methods?
1) Use column names in select statement instead of '*'.
2) HAVING clause is used to filter the rows after all the rows are selected. It is just like a filter. Do not use HAVING clause for any other purposes.
3)Sometimes you may have more than one subqueries in your main query. Try to minimize the number of subquery block in your query.
4) Use operator EXISTS, IN and table joins appropriately in your query.
a) Usually IN has the slowest performance.
b) IN is efficient when most of the filter criteria is in the sub-query.
c) EXISTS is efficient when most of the filter criteria is in the main query.
5)Use EXISTS instead of DISTINCT when using joins which involves tables having one-to-many relationship.
6)Try to use UNION ALL in place of UNION.

What are temporary tables?
 Temporary tables are created in tempdb database.There are two types of temp tables, local temporary tables and global temporary tables.
 Local temp table starts with a symbol "#" and they are visible only in the current session. They gets deleted when the user disconnects from instance of microsoft sql server.Global temp tables are written with "##" and they are visible to all sessions or any user.They gets deleted when all users disconnect from sql.
For Example:
If you create a table named employees, the table can be used by any person who has the security permissions in the database to use it, until the table is deleted. If you create a local temporary table named #employees, you are the only person who can work with the table, and it is deleted when you disconnect. If you create a global temporary table named ##employees, any user in the database can work with this table. If no other user works with this table after you create it, the table is deleted when you disconnect. If another user works with the table after you create it, SQL Server deletes it when both of you disconnect. SQL statements for creating the temporary table using the CREATE TABLE statement:

What is the default session timeout in asp.net?
20 min
Difference between varchar and nvarchar in sql?
The key difference between the two data types is how they're stored. VARCHAR is stored as regular 8-bit data. But NVARCHAR strings are stored in the database as UTF-16 — 16 bits

Saturday, 7 January 2012

C# Collections

Arrays:
Arrays are reference types created on the heap.
Multidimensional Arrays:
C# supports two kinds of multidimensional arrays.They are Rectangular array and Jagged array.
In a rectangular array, every row is of same length.In jagged array rows can be of different length.
Arraylist:
Arraylist solves the issue of arrays where we have to specify the array to a fixed size.Arraylist is a dynamic array.We can use Add( ) method to insert values in array dynamically. 
Dictionary:
Dictionary class uses key value pairs to add and retrieve data. An example for dictionary is Hashtable. Here with the help of keys, we can access the specific values.
ICollection Interface:
To retrieve values from collections.
eg: ICollection key = hashtable.Keys;
     ICollection Val = hashtable.Values; // where hashtable is Hashtable object.

T-Sql ROW_NUMBER:
Returns the sequential number of a row within a partition of a result set, starting at 1 for the first row in each partition. This row number can be used to eliminate duplicate rows using CTE.


Wednesday, 4 January 2012

Some OOPS Curry Part 2

Sealed Class:
*A sealed class does not allow classes to derive from it.
*Classes are more often marked sealed to prevent accidental inheritance.
*You cannot create a new protected member in a sealed class.
Static Class:
* A static class cannot be instantiated. It is called like calssname.method( )
* A static class contains only static members.
* Is sealed.
* They cannot have constructor, although we can still declare a static constructor.

Boxing and Unboxing:
Boxing and Unboxing are the processes that enable value type(eg: int) to be treated as reference types.
Boxing is implicit conversion of value type to type object.Usually value types are stored in stack.When value types are converted into objects, it gets stored in heap.
eg: int i = 123;
     object o = i;
Boxing is implicit.
Unboxing:
To return the boxed object back to a value type you must explicitly unbox it.
eg: int i= 123;
     object o = i;  //Up-to this is boxing
int j = ( int )o;  //Explicit conversion Unboxing.

Structs:
A struct is a simple user-defined type,a lightweight alternative to classes.
Structs are similar to classes in that they have propertties,methods,fields etc.
Difference between classes and structs
Structs dont support destructors and inheritance.
A class is a reference type whereas a struct is a value type.
Multiple Inheritance:
Multiple inheritance is the feature in which a class can inherit behaviour and features of more than one super class.
Why C# does not support multiple inheritance?
It is because multiple inheritance adds too much complexity to the languafe while providing too little benefit.
Difference between stack and heap
 Stack memory is referred to as temporary memory. If you come out of the program, the memory of the  variable will no more be there.Used for local variables.
Heap memory is referred to as Permanent memory. Memory allocated for the object will be maintained even if we came out of the program.
Retrieving second table in Datareader
In dataset we can use ds.tables(1) and in datareader we can use dr.NextResult()

Some OOPS Curry

The default access specifier of class is internal and for the class members and methods is private.
Inheritance is accessing the basic class behavior and characteristics and we can also add additional behavior and characteristics in derived class. The two main concepts of inheritance are code reuse and polymorphism.
To create a method that supports polymorphism you need to mark the method in base class using keyword virtual.
Abstract Classes
To require subclasses to implement a method of their base, you need to designate that method as abstract.
An abstract method has no implementation.It creates a method name and signature that must be implemented on all the derived classes.It is not legal to instantiate an object of an abstract class.Once you create a method to be abstract, you prohibit the creation of any instances of that class.If the derived class failed to implement the abstract method, then that class will also become abstract class and no instances of that class is possible.
If one or more methods are abstract then the class definition should also be marked abstract.
eg: abstract public class Window