Nov 18, 2008

Schedule a task using C# code

I needed to schedule a task to run every day at 9:00 p.m. in the night. I had an addition al requirement that the task be scheduled only if the FileSystemwatcher alerts us of new files being available for processing.

Thus the files could be recieved anytime during the day, but despite that the task should be schduled to run exactly at 9:00 p.m. in the night.

So I used the following code to schedule a task(using System.Threading.Timer and TimeSpan classes)

DateTime d = DateTime.Now;

timer = new Timer(new TimerCallback(Update), null,
TimeSpan.FromMinutes(21 * 60 - (d.Hour * 60 + d.Minute)),
TimeSpan.FromMilliseconds(-1));


Note I used TimeSpan.FromMillisecnods(-1) to disable periodic signalling

kick it on DotNetKicks.com

Nov 13, 2008

Compare 2 SQL queries for equality

DECLARE @check1 bigint
DECLARE @check2 bigint

Select @check1 = CHECKSUM_AGG(CHECKSUM(*))
FROM
(
SELECT *
FROM dbo.Orders (nolock)
)
AS Source

Select @check2 = CHECKSUM_AGG(CHECKSUM(*))
FROM
(
SELECT *
FROM dbo.Orders (nolock)
WHERE IsSuccessful = 1
)
As Comparison

IF @check1 = @check2
PRINT 'Queries are Equal'
ELSE
PRINT 'Queries are NOT Equal'


Note:
If order of rows is different it will not effect the result
It does not do execution plan comparisons, simply checks if the rows returned by the two queries are the same or not

More info

kick it on DotNetKicks.com

Nov 12, 2008

Converting SQL2005 DBTimeStamp to Long for Comparison (Convert from Hex to long and decimal to Hex)

If you need to Convert SQL 2005 DB TimeStamp values to Long then follow these steps:
1. Retrieve the DB TimeStamp value in a Byte Array (8 bytes long).
2. Convert the byte array into a Hexadecimal string
3. Convert the hexadecimal string to a long
private long BytesToLong(byte[] bytes)
{
string ts = null;
foreach (byte b in bytes)
ts += b.ToString("X").PadLeft(2,Convert.ToChar("0"));
return Convert.ToInt64(ts, 16);
}


There is another method to convert the DBTimeStamp to Long, but I dont prefer this method since it can return negative values. The method is:

1. Retrieve the DB TimeStamp value in a Byte Array (8 bytes long).
2. Use BitConverter class to convert the byte array into long
long result = BitConverter.ToInt64(dbTimestamp, 0); 

Inorder to remedy this use the following to generate the same long value as in step 1:


public static long FromDbTimestamp(byte[] dbTimestamp)
{
long result = 0;
if (dbTimestamp != null)
{
Array.Reverse(dbTimestamp);
result = BitConverter.ToInt64(dbTimestamp, 0);
}

return result;
}

Finally to convert a long into the correct DBTimeStamp use this:

public static byte[] ToDbTimestamp(long timestamp)
{
byte[] result = BitConverter.GetBytes(timestamp);
Array.Reverse(result);
return result;
}

kick it on DotNetKicks.com