Saturday, September 18, 2010

Nullable datatype

Nullable types are instances of the System.Nullable struct. A nullable type can represent the normal range of values for its underlying value type, plus an additionalnull value. For example, a Nullable, pronounced "Nullable of Int32," can be assigned any value from -2147483648 to 2147483647, or it can be assigned thenull value. A Nullable can be assigned the values true or false, or null. The ability to assign null to numeric and Boolean types is particularly useful when dealing with databases and other data types containing elements that may not be assigned a value. For example, a Boolean field in a database can store the valuestrue or false, or it may be undefined.


Note: int? is the short syntax for Nullable.
Nullable is a structure that allows a value type to handle a null value.


class NullableExample
{
    static void Main()
    {
        int? num = null;
        if (num.HasValue == true)
        {
            System.Console.WriteLine("num = " + num.Value);
        }
        else
        {
            System.Console.WriteLine("num = Null");
        }

        //y is set to zero
        int y = num.GetValueOrDefault();

        // num.Value throws an InvalidOperationException if num.HasValue is false
        try
        {
            y = num.Value;
        }
        catch (System.InvalidOperationException e)
        {
            System.Console.WriteLine(e.Message);
        }
    }
}

Friday, September 17, 2010

const vs. readonly

const vs. readonly


const and readonly perform a similar function on data members, but they have a few important differences.

const

A constant member is defined at compile time and cannot be changed at runtime. Constants are declared as a field, using the constkeyword and must be initialized as they are declared. For example;
public class MyClass
{
  public const double PI = 3.14159;
}
PI cannot be changed in the application anywhere else in the code as this will cause a compiler error.
Constants must be a value type (sbytebyteshortushortintuintlongulongcharfloatdoubledecimal, orbool), an enumeration, a string literal, or a reference to null.
Since classes or structures are initialized at run time with the new keyword, and not at compile time, you can't set a constant to a class or structure.
Constants can be marked as publicprivateprotectedinternal, or protected internal.
Constants are accessed as if they were static fields, although they cannot use the static keyword.
To use a constant outside of the class that it is declared in, you must fully qualify it using the class name.

readonly

A read only member is like a constant in that it represents an unchanging value. The difference is that a readonly member can be initialized at runtime, in a constructor as well being able to be initialized as they are declared. For example:
public class MyClass
{
  public readonly double PI = 3.14159;
}
or
public class MyClass
{
  public readonly double PI;
 
  public MyClass()
  {
    PI = 3.14159;
  }
}
Because a readonly field can be initialized either at the declaration or in a constructor, readonly fields can have different values depending on the constructor used. A readonly field can also be used for runtime constants as in the following example:
public static readonly uint l1 = (uint)DateTime.Now.Ticks;
Notes
  • readonly members are not implicitly static, and therefore the static keyword can be applied to a readonly field explicitly if required.
  • readonly member can hold a complex object by using the new keyword at initialization.
  • readonly members cannot hold enumerations.

static

Use of the static modifier to declare a static member, means that the member is no longer tied to a specific object. This means that the member can be accessed without creating an instance of the class. Only one copy of static fields and events exists, and static methods and properties can only accessstatic fields and static events. For example:
public class Car
{
  public static int NumberOfWheels = 4;
}
The static modifier can be used with classes, fields, methods, properties, operators, events and constructors, but cannot be used with indexers, destructors, or types other than classes.
static members are initialized before the static member is accessed for the first time, and before the static constructor, if any is called. To access a staticclass member, use the name of the class instead of a variable name to specify the location of the member. For example:
int i = Car.NumberOfWheels;

Index - SQL Server

Indexes are created on columns in tables or views. The index provides a fast way to look up data based on the values within those columns. For example, if you create an index on the primary key and then search for a row of data based on one of the primary key values, SQL Server first finds that value in the index, and then uses the index to quickly locate the entire row of data. Without the index, a table scan would have to be performed in order to locate the row, which can have a significant effect on performance.
You can create indexes on most columns in a table or a view



Clustered Indexes

       A clustered index stores the actual data rows at the leaf level of the index. 
An important characteristic of the clustered index is that the indexed values are sorted in either ascending or descending order. As a result, there can be only one clustered index on a table or view. In addition, data in a table is sorted only if a clustered index has been defined on a table.
Note: A table that has a clustered index is referred to as a clustered table. A table that has no clustered index is referred to as a heap



Nonclustered Indexes

Unlike a clustered indexed, the leaf nodes of a nonclustered index contain only the values from the indexed columns and row locators that point to the actual data rows, rather than contain the data rows themselves. This means that the query engine must take an additional step in order to locate the actual data.

Nonclustered indexes cannot be sorted like clustered indexes; however, you can create more than one nonclustered index per table or view. SQL Server 2005 supports up to 249 nonclustered indexes, and SQL Server 2008 support up to 999. This certainly doesn’t mean you should create that many indexes. Indexes can both help and hinder performance.





Index Types

In addition to an index being clustered or nonclustered, it can be configured in other ways:
  • Composite index: An index that contains more than one column. In both SQL Server 2005 and 2008, you can include up to 16 columns in an index, as long as the index doesn’t exceed the 900-byte limit. Both clustered and nonclustered indexes can be composite indexes.
  • Unique Index: An index that ensures the uniqueness of each value in the indexed column. If the index is a composite, the uniqueness is enforced across the columns as a whole, not on the individual columns. For example, if you were to create an index on the FirstName and LastName columns in a table, the names together must be unique, but the individual names can be duplicated.
A unique index is automatically created when you define a primary key or unique constraint:
    • Primary key: When you define a primary key constraint on one or more columns, SQL Server automatically creates a unique, clustered index if a clustered index does not already exist on the table or view. However, you can override the default behavior and define a unique, nonclustered index on the primary key.
    • Unique: When you define a unique constraint, SQL Server automatically creates a unique, nonclustered index. You can specify that a unique clustered index be created if a clustered index does not already exist on the table.
  • Covering index: A type of index that includes all the columns that are needed to process a particular query. For example, your query might retrieve the FirstName and LastName columns from a table, based on a value in the ContactID column. You can create a covering index that includes all three columns.

Sunday, May 9, 2010

Difference between DELETE & TRUNCATE commands?

TRUNCATE is a DDL command and cannot be rolled back. All of the memory space is released back to the server.
DELETE is a DML command and can be rolled back.

Both commands accomplish identical tasks (removing all data from a table), but TRUNCATE is much faster.

TRUNCATE table can not trigger.

Sunday, May 2, 2010

What’s the difference between trace and debug in ASP.NET?


Debug and trace enables you to monitor the application for errors and exception with out VS.NET IDE. In Debug mode compiler inserts some debugging code inside the executable. As the debugging code is the part of the executable they run on the same thread where the code runs and they do not given you the exact efficiency of the code ( as they run on the same thread). So for every full executable DLL you will see a debug file also as shown in figure ‘Debug Mode’.

Trace works in both debug as well as release mode. The main advantage of using trace over debug is to do performance analysis which can not be done by debug. Trace runs on a different thread thus it does not impact the main code thread.
Note: - There is also a fundamental difference in thinking when we want to use trace and when want to debug. Tracing is a process about getting information regarding program's execution. On the other hand debugging is about finding errors in the code.

Tuesday, April 20, 2010

What is ADO .NET and what is difference between ADO and ADO.NET?

  1.  ADO works with connected data. This means that when you access data such as viewing and updating data it is real-time with a connection being used all the time. This is barring of course you programming special routines to pull all your data into temporary tables. ADO.NET uses data in a disconnected fashion. When you access data ADO.NET makes a copy of the data using XML. ADO.NET only holds the connection open long enough to either pull down the data or to make any requested updates. This makes ADO.NET efficient to use for Web applications. It's also decent for desktop applications.
  2. ADO has one main object that is used to reference data called the Recordset object. This object basically gives you a single table view of your data although you can join tables to create a new set of records. With ADO.NET you have various objects that allow you to access data in various ways. The DataSet object will actually allow you to store the relational model of your database. This allows you to pull up customers and their orders accessing/updating the data in each related table individually.
  3. ADO allows you to create client-side cursors only whereas ADO.NET gives you the choice of either using client-side or server-side cursors. In ADO.NET classes actually handle the work of cursors. This allows the developer to decide which is best. For Internet development this is crucial in creating efficient applications.
  4. ADO allows you to create client-side cursors only whereas ADO.NET gives you the choice of either using client-side or server-side cursors.
  5. Whereas ADO allows you to persist records in XML format ADO.NET allows you to manipulate your data using XML as the primary means. This is nice when you are working with other business applications and also helps when you are working with firewalls because data is passed as HTML and XML.






Wednesday, April 7, 2010

What is diff between pointer and references?


1. Pointer can refer NULL, refernce cannot be NULL
2. Pointer can derefernce to another address, Reference 
once initialized stays that way till it dies.
3. pointer may not associate with a legitimate memory but 
References should associate with certain memory.
4. pointer may not be initialized while created but 
refernce has to intialized when it is created.

Tuesday, April 6, 2010

What is difference between for and foreach loop in c#?


The for loop executes a statement or a block of statements repeatedly until a specified expression evaluates to false.  there is need to specify the loop bounds( minimum or maximum).
int j = 0;
for (int i = 1; i <= 5; i++)
{
j = j + i ;
}

The foreach statement repeats a group of embedded statements for each element in an array or an object collection.you do not need to specify the loop bounds minimum or maximum.
int j = 0;
int[] tempArr = new int[] { 0, 1, 2, 3, 5, 8, 13 };
foreach (int i in tempArr )
{
j = j + i ;
}

Saturday, April 3, 2010

What is data integrity? Explain constraints?


A constraint is a property assigned to a column or the set 
of columns in a table that prevents certain types of 
inconsistent data values from being placed in the column
(s). Constraints are used to enforce the data integrity. 
This ensures the accuracy and reliability of the data in 
the database. The following categories of the data 
integrity exist:


Entity Integrity 
Domain Integrity 
Referential integrity 
User-Defined Integrity

Entity Integrity ensures that there are no duplicate rows 
in a table.

Domain Integrity enforces valid entries for a given column 
by restricting the type, the format, or the range of 
possible values.

Referential integrity ensures that rows cannot be deleted, 
which are used by other records (for example, corresponding 
data values between tables will be vital).

User-Defined Integrity enforces some specific business 
rules that do not fall into entity, domain, or referential 
integrity categories.

Each of these categories of the data integrity can be 
enforced by the appropriate constraints. Microsoft SQL 
Server supports the following constraints:


PRIMARY KEY 
UNIQUE 
FOREIGN KEY 
CHECK 
NOT NULL

A PRIMARY KEY constraint is a unique identifier for a row 
within a database table. Every table should have a primary 
key constraint to uniquely identify each row and only one 
primary key constraint can be created for each table. The 
primary key constraints are used to enforce entity 
integrity.

A UNIQUE constraint enforces the uniqueness of the values 
in a set of columns, so no duplicate values are entered. 
The unique key constraints are used to enforce entity 
integrity as the primary key constraints.

A FOREIGN KEY constraint prevents any actions that would 
destroy link between tables with the corresponding data 
values. A foreign key in one table points to a primary key 
in another table. Foreign keys prevent actions that would 
leave rows with foreign key values when there are no 
primary keys with that value. The foreign key constraints 
are used to enforce referential integrity.

A CHECK constraint is used to limit the values that can be 
placed in a column. The check constraints are used to 
enforce domain integrity.

A NOT NULL constraint enforces that the column will not 
accept null values. The not null constraints are used to 
enforce domain integrity, as the check constraints.

Friday, April 2, 2010

Index - Clustered & Non Clustered Index

An index is a physical structure containing pointers to the data. Indices are created in an existing table to locate rows more quickly and efficiently. It is possible to create an index on one or more columns of a table, and each index is given a name. The users cannot see the indexes; they are just used to speed up queries. Effective indexes are one of the best ways to improve performance in a database application. A table scan happens when there is no index available to help a query. In a table scan SQL Server examines every row in the table to satisfy the query results. Table scans are sometimes unavoidable, but on large tables, scans have a terrific impact on performance.


Clustered Indexes: A clustered when defined on a column of a table, the data of the table in the data pages are sorted in order of the column on which index is defined. This column is referred as an Index Key. Since the data is sorted physically on the disk, the leaf page of the index pages are the data pages of the table. 

Inserting a new row in a table with clustered index defined, SQL Server ensures that the row is placed in the correct physical location in key
sequence order. Structure of the Clustered Index is as given below:Non-Clustered Indexes: A Non-clustered index contain only the index key (column on which non-clustered index is defined) and a reference to find the data. The items in the index are stored in the order of the index key values, but the information in the table is stored in a different order (which can be dictated by a clustered index). If no clustered index is created on the table, the rows are not guaranteed to be in any particular order.
Non-clustered index structure is depicted as:At any given level in the index, the pages are linked together as shown in Figure below, and this is true regardless of whether the index is a Clustered index or a Non-clustered index.
Both the clustered and non-clustered indexes can be defined on one or more columns of a table, to serve the frequent database queries. However there can be only one clustered index defined on a table while there can be 249 non-clustered indexes created on a table.



A table can have one of the following index configurations:
• No indexes
•A clustered index
•A clustered index and many nonclustered indexes
•A nonclustered index
•Many nonclustered indexes

Tuesday, March 30, 2010

ASP.NET Page Life Cycle


A page in an ASP.NET application consists of several server controls. These are the fundamental building blocks of an ASP.NET application. The Life cycle of an ASP.NET page, depends on whether the page is requested for the first time or it is a postback. Postback is a process by which a page can request for itself.

When the Page is requested for the first time

The Life Cycle of a page when requested for the first time:
Initializing: During this phase, the server creates an instance of the server control
Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.
PreRendering: During this phase, the control is updated with the changes made to it. This prepares the control for rendering.
Saving: During this phase, the state information of the control is saved. For example, if a value is set for the control during the Load event, it is embedded in the HTML tag that will be returned to the browser.
Rendering: During this phase, the server creates the corresponding HTML tag for the control.
Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.
Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control

Life cycle when the page processed during a postback event

The processing sequence in which a page is processed during a postback event is:


Initializing: During this phase, the server creates an instance of the server control
Loading view state: During this phase, the view state of the control posted by the client is reloaded into the new instance of the control.
Loading: During this phase, the instance of the control is loaded onto the page object in which it is defined.
Loading the postback data: During this phase, the server searches any data corresponding to the control that is loaded in the data posted by the client.
PreRendering: During this phase, the control is updated with the changes made to it. This prepares the control for rendering.
Saving state: During this phase, the change in the state of control between the current request and the previous request of the page is saved. For each change, the corresponding event is raised. For example, if the text of a textbox is changed, the new text is saved and a text_change event is raised.
Rendering: During this phase, the server creates the corresponding HTML tag for the control.
Disposing: During this phase, all cleanup tasks, such as closing files and database connections opened by the control are performed.
Unloading: During this phase, all cleanup tasks, such as destroying the instances of server control are performed. This is the final event in the life cycle of a server control
The events associated with the relevant page cycle phases are:

  • Page Initialization: Page_Init

  • View State Loading:LoadViewState

  • Postback data processing: LoadPostData

  • Page Loading: Page_Load

  • PostBack Change Notification: RaisePostDataChangedEvent

  • PostBack Event Handling: RaisePostBackEvent

  • Page Pre Rendering Phase: Page_PreRender

  • View State Saving: SaveViewState

  • Page Rendering: Page_Render

  • Page Unloading: Page_UnLoad
The following figure illustrates how the server controls on an ASP.NET page is processed by the server:



Thursday, March 25, 2010

Virtual Function Members Vs Abstract Function Members


This series is going to be a C# refresher that reminds you of C# features you sometimes forget.
A function can be marked as virtual when you don’t want your sub-classes to compulsorily provide implementation of some specialized form. So you can treat virtual as opposite of abstract, where you have to compulsorily provide implementation.
Consider this small fragment :
   1: public abstract class Person
   2: {
   3:     public abstract string Name {get;}
   4:     public virtual decimal TotalDebts
   5:     {
   6:         get
   7:         {
   8:             return 0;
   9:         }
  10:     }
  11: }
  12:  
  13: public class RichPerson : Person
  14: {
  15:     public override string Name 
  16:     {
  17:         get {return "I am Rich";}
  18:     }
  19: }
  20:  
  21: public class PoorPerson : Person
  22: {
  23:     public override string Name 
  24:     {
  25:         get {return "I am just a Poor guy";}
  26:     }
  27:     
  28:     public override decimal TotalDebts
  29:     {
  30:         get{return 1000000;}
  31:     }
  32: }
In this example the property “Name” declared in Line 3 is abstract while property “TotalDebts” in Line 4 is virtual.  The difference is while it is compulsory for deriving class to override “Name”, it is optional for deriving class to override “TotalDebts”. In this particular case PoorPerson is under heavy debt and implements TotalDebts to return his TotalDebts.