Thursday, August 21, 2008

Collections Overview in asp.net 2.0

Collections in .Net is having same use as Arrays,but there are certain limitations of the arrays like
  • The size of an array is always fixed and must be defined at the time of instantiation of an array.
  • An array can only contain objects of the same data type, which we need to define at the time of its instantiation.

So,In .net the concept of collections is very usefull to overcome from this limitaions.

The Namespace for Collections is

using System.Collections

.net 2.0 provides collections which are as described below.

  • ArrayList

ArrayList Provides the collection similar to Arrays,but it grows dynamically as the number of Elements change.

Example

static void Main()

{

ArrayList list = new ArrayList();

list.Add(11);

list.Add(22);

list.Add(33);

foreach(int num in list)

{

Console.WriteLine(num);

}

}

Output

11

22

33

  • Stack

A collection that works on the Last In First Out (LIFO) principle,

i.e., the last item inserted is the first item removed from the collection.

Push - To add element and

Pop – To Remove element

Example

class Test

{

static void Main()

{

Stack stack = new Stack();

stack.Push(2);

stack.Push(4);

stack.Push(6);

while(stack.Count != 0)

{

Console.WriteLine(stack.Pop());

}

}

}

Output

6

4

2

  • Queue

A collection that works on the First In First Out (FIFO) principle,

i.e.,the first item inserted is the first item removed from the collection.

Enqueue - To add element

Dequeue – To Remove element

Example:

static void Main()

{

Queue queue = new Queue();

queue.Enqueue(2);

queue.Enqueue(4);

queue.Enqueue(6);

while(queue.Count != 0)

{

Console.WriteLine(queue.Dequeue());

}

}

Output

2

4

6

  • Dictionaries

Dictionaries are a kind of collection that store items in a key-value pair fashion.

  • HashTable

Provides a collection of key-value pairs that are organizedbased on the hash code of the key.

Example:

static void Main()

{

Hashtable ht = new Hashtable(20);

ht.Add("key", "Hello");

ht.Add("key1", "Hello1");

ht.Add("key2", "Hello2");

Console.WriteLine("Printing Keys...");

foreach(string key in ht.Keys)

{

Console.WriteLine(key);

}

Console.WriteLine("\nPrinting Values...");

foreach(string Value in ht.Values)

{

Console.WriteLine(Value);

}

Console.WriteLine("Size of Hashtable is {0}", ht.Count);

Console.WriteLine(ht.ContainsKey("key"));

Console.WriteLine(ht.ContainsValue("Hello"));

Console.WriteLine("\nRemoving element with key = key1");

ht.Remove("key1");

Console.WriteLine("Size of Hashtable is {0}", ht.Count);

}

Output
Printing Keys...

key

key1

key2

Printing Values...

Hello

Hello1

Hello2

Size of Hashtable is 3

True

True

Removing element with key = key1

Size of Hashtable is 2

  • SortedList

Provides a collection of key-value pairs where the items are sorted according to the key.

The items are accessible by both the keys and the index.

Example:

static void Main()

{

SortedList sl = new SortedList();

sl.Add(18, "Java");

sl.Add(5, "C#");

sl.Add(11, "VB.Net");

sl.Add(1, "C++.Net");

Console.WriteLine("The items in the sorted order are...");

Console.WriteLine("\t Key \t\t Value");

Console.WriteLine("\t === \t\t =====");

for(int i=0; i

{

Console.WriteLine("\t {0} \t\t {1}", sl.GetKey(i),sl.GetByIndex(i));

}

}

Output
Key Value
==

1 C++.Net

5 C#

11 VB.Net

18 Java

Wednesday, August 20, 2008

ASP.Net 2.0 Page Life Cycle Events



  1. The page first retrieves the posted data from the QueryString or Form collection of the Request Object.

  2. The page then checks whether the posted Data collection (the NameValueCollection Form or QueryString) contains an item with the key __CALLBACKID. If it does, it sets its IsCallback Boolean property to true to signal that the page has been posted back to the server through theASP.NET client callback mechanism.

  3. PreInit: The page takes the following actions in the PreInit phase of its life cycle:
    A. Calls its OnPreInit method to raise the PreInit event.
    B. Initializes the theme by using the contents of the App_Themes directory to dynamicallyimplement a class of type PageTheme, compiles the class, creates an instance of thecompiled class, and assigns the instance to its PageTheme property.
    C. Applies the master page.

  4. Init: The page takes the following actions in the Init phase of its life cycle:
    A. Recursively initializes the controls in its Controls collection. This initializationincludes setting the properties of these controls such as Page, ID, NamingContainer,and so on.
    B. Recursively applies these controls’ skins.
    C. Calls its own OnInit method to raise its own Init event and then recursively calls thechild control’s OnInit methods to raise their Init events.
    D. Calls its own TrackViewState to start its own view state tracking and then recursivelycalls the child controls’ TrackViewState methods to start their view state tracking.

  5. InitComplete: The page calls its OnInitComplete method to raise the InitComplete event.This event signals the end of the initialization phase. By this time all controls in the Controlscollection of the page are initialized.

  6. Load Control State (postback only): The page recursively calls the LoadControlState method of those controls in its Controls collection that have called the RegisterRequiresControlState method of the page class to express interest in using their control states.

  7. Load View State (postback only): The page first calls its own LoadViewState method and then recursively calls the LoadViewState method of the controls in its Controls collection to allowthem to load their saved view states.

  8. Load Post Data (postback only - first try): The page calls the LoadPostData method of the controls that implement the IPostBackDataHandler interface and passes the posted data into it.The LoadPostData method of each control must access the posted data and update the respective property of the control accordingly. For example, the LoadPostData method of the TextBoxcontrol assigns the new value of the text box to the Text property of the TextBox control.

  9. PreLoad: The page calls its OnPreLoad method to raise the PreLoad event. This event signalsthe beginning of the load phase of the page life cycle.

  10. Load: The page first calls its own OnLoad method to raise its own Load event and then recursively calls the OnLoad methods of the controls in its Controls collection to raise their Load events. Page developers may register callbacks for the Load event, where they may programmaticallyadd child controls to the Controls collection of the page.

  11. Load Post Data (postback only second try): The page calls the LoadPostData method of those controls that were programmatically added to its Controls collection in the Load phase if theyimplement the IPostBackDataHandler interface.

  12. Raise Post Data Changed Event (postback only): The page calls the RaisePostData ChangedEvent method of those controls whose LoadPostData method returned true. The RaisePostDataChangedEvent method raises post data changed event. For example, the TextBox control raises this event when the new value of the text box is different from the old value.

  13. Raise Postback Event (postback only): The page calls the RaisePostBackEvent method of the control whose associated HTML element submitted the form. For example, the Button control’s associated HTML element posts the page back to the server. The RaisePostBackEvent methodof a control must map the postback event to one or more server-side events. For example, the RaisePostBackEvent method of the Button control maps the postback event to the Command and Click server-side events.

  14. Load Complete: The page calls its OnLoadComplete method to raise the LoadComplete event to signal the completion of all loading activities including loading post data and raising postdata changed event to allow interested controls to update themselves accordingly.

  15. Raise Callback Event (postback and callback only): The page calls the RaiseCallbackEvent method of the control that uses the ASP.NET client callback mechanism to allow a client-side method (such as a JavaScript function) to call a server-side method without having to post theentire page back to the server. The RaiseCallbackEvent method must call the respective server-side methods. If the page is posted back through the client callback mechanism, the pagewill not go through the rest of its life cycle phases.

  16. PreRender: The page takes the following actions in this phase of its life cycle:
    A. Calls its EnsureChildControls method to ensure its child controls are created before the page enters its rendering phase.
    B. Calls its own OnPreRender method to raise its own PreRender event.
    C. Recursively calls the OnPreRender methods of the controls in its Controls collection to raise their PreRender events.

  17. PreRender Complete: The page calls its OnPreRenderComplete method to raise thePreRenderComplete event to signal the completion of all prerendering activities.

  18. Save Control State: The page recursively calls the SaveControlState method of those controls in its Controls collection that have called the RegisterRequiresControlState method ofthe page class to express interest in saving their control states.

  19. Save View State: The page first calls its own SaveViewState method and then calls the SaveViewState method of the controls in its Controls collection to allow them to save their view states.

  20. Save State Complete: The page calls its OnSaveStateComplete method to raise theSaveStateComplete event to signal the completion of all save state activities.

  21. Rendering: The page takes the following actions in this phase of its life cycle:
    A. Creates an instance of the HtmlTextWriter class that encapsulates the output stream of the response.
    B. Calls its RenderControl method and passes the HtmlTextWriter instance into it.The RenderControl method recursively calls the RenderControl methods of the child controls to allow each child control to render its HTML markup text. The HTML markup texts ofchild controls form the final HTML markup text that is sent to the client browser.

Monday, August 4, 2008

Use of sp_help System Stored Procedure

In this blog i am going to explain the use of sp_help system stored procedure.It can be very useful for database developer.

sp_help
It gives information about various database objects i.e. any objects comes under sysobjects table,a user defined data type or a data type supplied by SQL server. It is executable for all public roles.It gives information of the current database only.
Syntax
sp_help [[@objname =] name]
Arguments
[@objname =] name
Is the name of any object, in sysobjects or any user-defined data type in the systypes table. name is nvarchar(776), with a default of NULL. Database names are not acceptable. The argument is optional.
Result Sets
1)Without giving any object name as parameters:It gives summary information of objects of all types that exist in the current database.
Exec sp_Help
Result : It gives columns of Name for Object Name,Owner for object owner and type for object





















Column name


Data type


Description


Name


nvarchar(128)


Object name


Owner


nvarchar(128)


Object owner


Object_type


nvarchar(31)


Object type




2)Give table name as an object name:
Exec sp_help tablename
Result: It gives datasets containing various information like table name.Owner,Created date time,object type, Column names,Column length,Column Data type,Nullable or not,Collations,Identity,Keys ,Constraint name,Constraint type,Constraint keys,Foreign key related information etc.





























Column name


Data type


Description


Name


nvarchar(128)


Table name


Owner


nvarchar(128)


Table owner


Type


nvarchar(31)


Table type


Created_datetime


datetime


Date table created

Depending on the database object specified, sp_help returns additional result sets.
If object name is a system table, user table, or view, sp_help returns these result sets (except the result set describing where the data file is located on a file group is not returned for a view).




















































Column name


Data type


Description


Column_name


nvarchar(128)


Column name.


Type


nvarchar(128)


Column data type.


Computed


varchar(35)


Indicates whether the values in the column are computed: (Yes or No).


Length


int


Column length in bytes.


Prec


char(5)


Column precision.


Scale


char(5)


Column scale.


Nullable


varchar(35)


Indicates whether NULL values are allowed in the column: Yes or No.


TrimTrailingBlanks


varchar(35)


Trim the trailing blanks (yes or no).


FixedLenNullInSource


varchar(35)


For backward compatibility only.





























Column name


Data type


Description


Identity


nvarchar(128)


Column name whose data type is declared as identity.


Seed


numeric


Starting value for the identity column.


Increment


numeric


Increment to use for values in this column.


Not For Replication


int


IDENTITY property is not enforced when a replication login, such as sqlrepl, inserts data into the table:

1 = True

0 = False















Column name


Data type


Description


RowGuidCol


sysname


Name of the global unique identifier column















Column name


Data type


Description


Data_located_on_filegroup


nvarchar(128)


The file group in which the data is located (Primary, Secondary, or Transaction Log)

























Column name


Data type


Description


index_name


sysname


Index name


Index_description


varchar(210)


Description of the index


index_keys


nvarchar(2078)


Column name(s) on which the index is built






































Column name


Data type


Description


constraint_type


nvarchar(146)


Type of constraint.


constraint_name


nvarchar(128)


Name of the constraint.


status_enabled


varchar(8)


Indicates whether the constraint is enabled: Enabled, Disabled or N/A. (Only applicable to CHECK and FOREIGN KEY constraints.


status_for_replication


varchar(19)


Indicates whether the constraint is for replication. (Only applicable to CHECK and FOREIGN KEY constraints.)


constraint_keys


nvarchar(2078)


Names of the columns that make up the constraint or, in the case for defaults and rules, the text that defines the default or rule.


















Column name


Data type


Description


Table is referenced by


nvarchar(516)


Identifies other database objects that reference the table.


If object name is a system stored procedure or an extended stored procedure, sp_help returns this result set.
Exec sp_help spname
Result :It gives datasets containing sp name sp type ,sp owner,sp's Created datetime,Parameter names,Parameter types,Parameter length,Collations etc.













































Column name


Data type


Description


Parameter_name


nvarchar(128)


Stored procedure parameter name


Type


nvarchar(128)


Data type of the stored procedure parameter


Length


smallint


Maximum physical storage length (in bytes)


Prec


int


Precision (total number of digits)


Scale


int


Number of digits to the right of the decimal point


Param_order


smallint


Order of the parameter










Saturday, August 2, 2008

Calculate Age from given Birthdate

As there was a requirement in my project to calculate age(Age in Year,Age in Month,Age in days) of an entity from his/her birthdate to the present date.

I have created one function in javascript which will calculate age(Age in Year,Age in Month,Age in days) from given birthdate.

The function is as given below.


1function CalculateAgeFromBirthdate(birthdate)
2
{
3

4 var birthdate;
5 birthdate = new
Date(birthdate);
6

7 var bYear = birthdate.getFullYear();//Year of birth

8 var bMonth = birthdate.getMonth() + 1; //Month of Birth

9 var bDay = birthdate.getDate(); //Day of Birth

10

11 var date = new Date(); // get current date

12 var cYear = date.getFullYear(); //Get current year

13 var cMonth = date.getMonth() + 1;//Get current month

14 var cDay = date.getDate();//Get Current Date
15

16 var g31Day=new Array(1,3,5,7,8,10,12);//Array of the months of 31 days

17 var g30Day=new Array(2,4,6,9,11); //Array of the months of 30 days

18 var gMonth=12
;
19 var
gDay;
20

21 var getCurentMont=cMonth//get current month

22 var getCurrentYear=cYear//get current year
23

24 for(var i=0;i < g31Day.length;i++
)
25
{
26

27

28 if (g31Day[i]==
getCurentMont)
29
{
30 gDay=31
;
31 break
;
32 }

33

34 }

35 for(var i=0;i < g30Day.length; i++
)
36 {

37

38 if(g30Day[i] ==
getCurentMont)
39
{
40 if(getCuurentMont=2
)
41
{
42 //For leap year

43 if(getCurrentYear % 4 == 0 (getCurrentYear % 100 != 0 && getCurrentYear % 4 == 0
))
44
{
45 gDay=29
;
46 break
;
47 }

48 else

49
{
50 gDay=28
;
51 break
;
52 }

53

54 }

55 else

56
{
57 gDay=30
;
58 break
;
59 }

60 }

61 }

62

63 var
years;
64 var
Day;
65 var
Month;
66

67 years = (cYear) -
parseInt(bYear);
68

69 Day = parseInt(cDay)-
parseInt(bDay);
70

71 Month = (cMonth)-
parseInt(bMonth);
72

73

74 if( Month < 0
)
75

76
{
77

78 gMonth=parseInt(gMonth)+
parseInt(Month) ;
79

80 Month=
gMonth;
81 years--
;
82 flag=true
;
83

84 }

85 if( Day < 0
)
86

87
{
88

89 gDay=parseInt(gDay)+
parseInt(Day) ;
90

91 Day=
gDay;
92

93 }

94

95 alert("I am of "+years+" years, "+Month+" month and "+Day +" days"
);
96

97 }


By passing Birthdate as Parameter it will calculate the age.

Calculate Birthdate From Given Age

As there was a requirement in my project to calculate birthdate from age(Age in Year,Age in Month,Age in days) given.

I have created one function in javascript which will give the birthdate in dd/mm/yyyy format.
The function is as given below.



1 function CalculateBirthDateFromAge(AgeInYear,AgeInMonth,AgeInDays)
2
{
4 var currentDate=new
Date();
5 var getCMonth=(currentDate.getMonth()); //Get current month

6 var getCYear=currentDate.getFullYear(); //Get current Year
7 var getCDate=currentDate.getDate(); //Get Current Date
8 var getAgeInDays =
AgeInDays;
9 var getAgeInMonth =
AgeInMonth;
10 var getAgeInYear =
AgeInYear;
12 var yd =
getCYear;
13 var md = getCMonth +1
;
14 var mLength ="0"
;
15 var mon=0
;
16 var mb=0
;
17 var yb=0
;
18 var
db
19 if(getAgeInDays!=""
)
20
{
21 db = getCDate-
getAgeInDays;
22
var g31Day=new Array(1,3,5,7,8,10,12);
26 var g30Day=new Array(2,4,6,9,11
);
27 var gMonth=12
;
28 var gDay=0
;
29 var getCurentMont=(getCMonth +1 );//get current month

30 var getCurrentYear=getCYear;//get current year
31
for(var i=0;i < g31Day.length;i++)
33
{
34 if (g31Day[i]==
(getCurentMont))
35
{
36 gDay=31
;
37 break
;
38 }

39
}

41 if(gDay==0
)
42
{
43 for(var i=0;i < g30Day.length; i++
)
44
{
45
if(g30Day[i] == getCurentMont)
47
{
48 if(getCurentMont==2
)
49
{
50 if(getCurrentYear % 4 == 0 (getCurrentYear % 100 != 0 && getCurrentYear % 4 == 0
))
51
{
52 gDay=29
;
53 break
;
54 }

55 else

56
{
57 gDay=28
;
58 break
;
59 }

61 }

62 else

63
{
64 gDay=30
;
65 break
;
66 }

67 }

68 }

69 }

73 if( db <= 0
)
74
{
76 db=db+
parseInt(gDay);
77 }

80}

81else

82db=01
;
85 if(getAgeInMonth!=""
)
86 mb = md -getAgeInMonth;//month

87 else

88 mb = 01;//month

89
if(mb <= 0)
91
{
92 yd--
;
93 mb=mb+12
;
94 }

96if(getAgeInYear!=""
)
97 yb = yd -
getAgeInYear;
98 else

99 yb =
getCYear;
100 alert("My BirthDate Is "+db+"/"+mb+"/"+
yb);
101
}



You have to pass the Age in years,age in month and age in days as Parameters to the given function.