April 19, 2012

Get last day of a given month in SQL Server

One way to find the last day of a given month is to get the next month’s first day and then get the previous day of the particular day. The complete SQL query has given below. The query is not much complex but you may need to do some date calculation here. The query can be written as:


declare @mm varchar(2), @yy varchar(4), @dd varchar(2), @date datetime
set @date=convert(datetime, '4/16/2012')
Set @mm=(Select datepart(M, @date))
Set @yy=(Select datepart(YYYY, @date))
Set @dd= (Select Day(DATEADD(month, 1, DateAdd(day, 1-day(@date), @date))-1))
Select DATENAME(DW, ''+@mm+'/'+@dd+'/'+@yy+'')


Output:

For: 4/16/2012 :- Monday
For: 5/16/2012:- Thursday
etc..

March 25, 2012

Object reference not set to an instance of an object

With C# .Net, many times you may need to typecast an object value to string. And you might have noticed that it throws null reference exception as ”Object reference not set to an instance of an object”. This is a run time exception & will occur mostly when you try to typecast a null value to string.

For example:
String userId = Session[“user”].ToString();

Above code will run fine until Session[“user”] have some value but throw exception when it has null value. You can sort out these problem by casting it through Convert.ToString().

For example:
String userId = Convert.ToString(Session[“user”]);

Now your code will not throw any such exception even when it has null value and will cast null value to empty string.


Code project reference