Wednesday, 28 March 2007

Select a random row from a table

It looks like a simple task to read a random record from a table. Many people would spend lot of time try to do this with lot of t-sql code. When I was reading an article, I found this could be easiely achieved by using NewID() function. The use of this function is like this:

SELECT TOP 3 newid(), ProductID, ProductName
FROM Products
order by newid()

Each time you execute this sql, the result will be 3 random records. And you can select one record back by limiting TOP 1.

Friday, 2 March 2007

Change Pocket PC system datetime

There is a need in a mobile device application to change local date time programatically. After a search I found we have to P/Invode Windows API. The API used in SetLocalTime.

To start with, we need to import the library:

[DllImport("kernel32.dll")]
static extern bool SetLocalTime([In] ref SYSTEMTIME lpLocalTime);

Then there is a piece of code from web to change time (http://pinvoke.net/default.aspx/kernel32.SetLocalTime):

using System;
using System.Runtime.InteropServices;

public class MyClass1
{
///
/// SYSTEMTIME structure with some useful methods
///

public struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;

///
/// Convert form System.DateTime
///

///
public void FromDateTime(DateTime time)
{
wYear = (ushort)time.Year;
wMonth = (ushort)time.Month;
wDayOfWeek = (ushort)time.DayOfWeek;
wDay = (ushort)time.Day;
wHour = (ushort)time.Hour;
wMinute = (ushort)time.Minute;
wSecond = (ushort)time.Second;
wMilliseconds = (ushort)time.Millisecond;
}

///
/// Convert to System.DateTime
///

///
public DateTime ToDateTime()
{
return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
}
///
/// STATIC: Convert to System.DateTime
///

///
///
public static DateTime ToDateTime(SYSTEMTIME time)
{
return time.ToDateTime();
}
}

//SetLocalTime C# Signature
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime( ref SYSTEMTIME Time );

//Example
private void Add7Days

{
//Get current time and add 7 days to it
DateTime t = DateTime.Now.AddDays(7);;
//Convert to SYSTEMTIME
SYSTEMTIME st = new SYSTEMTIME();
st.FromDateTime(t);
//Call Win32 API to set time
SetLocalTime(ref st);
}
}