Thursday, November 6, 2008

Compact Web Server in Compact Framework

Compact Web Server in Compact Framework

Monday, October 22, 2007 @ 15:42
Today I want to write about small class library I wrote some times ago. It is the compact web server written in C#. Class library implements functionality of the single threaded web server, which can run in Windows CE powered system as well as desktop version of Microsoft Windows. Currently only the GET method is supported, but it's possible to pass query strings and process 'em in custom code. Let's see some examples.

Configuring web server

Configuration for web server is stored in WebServerConfiguration class. Here it's possible to setup server root, listening port, IP address etc.. Important thing is the possibility to configure default files like default.html, index.html or other. Do not forget to register MIME types for files that will be handled by the web server. Setting right mime types is necessary for correct response header of the server.

Special files are those files, that need to be treat in custom method and not just send to the client. CompactWeb server supports virtual directories so you can request directory placed outside the server root.

WebServerConfiguration webConf = new WebServerConfiguration();

webConf.IPAddress = IPAddress.Any;
webConf.Port = 80;

// Folder where the web is stored
webConf.ServerRoot = @"\Inetpub";

webConf.AddDefaultFile("default.html");
webConf.AddMimeType(".htm", "text/html");
webConf.AddMimeType(".html", "text/html");
webConf.AddMimeType(".png", "image/png");
webConf.AddMimeType(".jpg", "image/jpg");
webConf.AddMimeType(".gif", "image/gif");
webConf.AddMimeType(".bmp", "image/bmp");
webConf.AddMimeType(".cgi", "text/html");

// .cgi files will be special handled
webConf.AddSpecialFileType(".cgi");

// Register virtual directory
webConf.AddVirtualDirectory("photos", @"\My Documents\Photos");
Necessary step is to setup server root physically in the file system. Simply create the folder and put the website in. file system server root

Start me up

Starting the web server is the easiest thing in whole process. Registering OnLogEvent is fine to track client connections, response sending and exceptions. OnSpecialFileType is raised whenever the file registered as special is requested by client. Delegate for this event can handle output to the client.
webServer = new WebServer(webConf);
webServer.OnLogEvent += new WebServer.LogEvent(webServer_OnLogEvent);
webServer.OnSpecialFileType += new WebServer.SpecialFileType(webServer_OnSpecialFileType);
webServer.Start();
From here, your server is running and ready to serve all files placed in the server root. sample server home page

ASP, PHP, CGI whatever you want

If it's necessary to process some files in special way, you can use delegate to OnSpecialFileType and take the control over processing. Next piece of code handles file with .cgi extension. It takes the content of the file and replace <%=RESULT%> pattern with parameter userName passed in the query string. In case that you will call following URL http://127.0.0.1/form.cgi?userNamer=Joshua the <%=RESULT%> pattern will be replaced with Joshua.
void webServer_OnSpecialFileType(CompactWeb.WebRequest webRequest, out IO.Stream outputStream)
{
outputStream = new MemoryStream();

if (webRequest.FileName == "form.cgi")
{
// Read the requested file template
FileStream sourceFile = new FileStream(webRequest.FullPath, FileMode.Open);
StreamReader streamReader = new StreamReader(sourceFile);
string response = streamReader.ReadToEnd();
streamReader.Close();
sourceFile.Close();

// Parse query string into NameValueCollection
NameValueCollection query = WebServer.ParseQueryString(webRequest.QueryString);

// Replace <%=RESULT%> with the username
string userName = query["userName"];
response = response.Replace("<%=RESULT%>", userName);

// Creat response
byte[] buffer = Encoding.ASCII.GetBytes(response);
outputStream.Write(buffer, 0, buffer.Length);
}
}
file system server root

Download and Conclusion

Complete CompactWeb class library with this sample code is possible to download here CompactWebServer.zip . Even if the code is written in compact framework it can be compiled and used with full version of .NET framework. Usage is NOT limited to windows mobile. Feel free to suggest any ideas and improvements, or change the code for your needs. I believe that you will find this library useful.

Simulate keystrokes in Windows Mobile

Simulate keystrokes in Windows Mobile

Thursday, August 2, 2007 @ 00:39
I must say that I'am always amazed how many useful things you can perform just by simulating the keystrokes in Windows Mobile. In Windows CE SDK is the function keybd_event which generates WM_KEYUP or WM_KEYDOWN message. In fact it means, that you can "broadcast" the key press through whole system. It's unbelievable how many functions is binded to the keys even if it's not physically present on the device.

On this page in MSDN you can find list of many keys supported in Windows CE systems. There are interesting keys like VK_OFF, VK_NONAME, VK_ESC, VK_KEYLOCK. To be honest much better list is in book Programming Microsoft WindowsCe .Net. So let's look on some of the keys and how to play with them.

Sending application into background

Dreaming of minimizing application in Smartphone? If you want to send your application into background, just like the the back-button do - why not press it from application. Just send the VK_ESC key (0x1B).

Showing the Today screen

How to show today screen? Simulate the "home" button which is represented by F4 key. This VK_F4 has value of 0x73.

Lock the device keys

If you want to lock the device, just like it happens after idle time - you can perform it also by key press. On the Smartphone you need VK_APP6 key (0xC6). On the Pocket PC you will use VK_F22 or VK_KEYLOCK key (0x85). Windows Mobile 6.0 has the API function SHDeviceLockAndPrompt which puts device into a lock state as well.

Preventing the device from locking or sleeping

If you are using for instance TomTom navigation and PIN lock on your device, than you are probably fed up by the screen locking after idle time. You can prevent this locking by simulating key press, so the device will think you are still working on your device. But what key to press? You may think about shift or caps-lock, BUT thEn yOyR uSeR INpuTs WiLL loOk liKE tHiS. It must be the key without affects on the input. The VK_NONAME key (0xFC). Key actually does nothing and is reserved for the future use. In my opinion, the time is here.

Turn off the device

I was really surprised that you can simulate press of the key like power button is. The VK_OFF key (0xDF) performs soft reset on Smartphone and screen off on the Pocket PC.

Activate the Speakerphone

If you will read this post from Peter Foot, you will find how VK_F16 key (0x7F) can be useful, when you want to toggle Speakerphone while talking.

Putting it into C# class

Following class encapsulates SendKey function which simulates press of specified key. Function do two P/Invoke calls to keyb_event with KEYUP and KEYDOWN parameters set. You can use this class in Compact Framework 1.0.

using System.Runtime.InteropServices;

...

public class SystemCalls
{
//See more at http://msdn2.microsoft.com/en-us/library/ms927178.aspx
public const byte VK_NONAME = 0xFC; // Do nothing
public const byte VK_ESC = 0x1B; // Smartphone back-button
public const byte VK_F4 = 0x73; // Home Screen
public const byte VK_APP6 = 0xC6; // Lock the keys on Smartphone
public const byte VK_F22 = 0x85; // Lock the keys on PocketPC (VK_KEYLOCK)
public const byte VK_F16 = 0x7F; // Toggle Speakerphone
public const byte VK_OFF = 0x7F; // Power button

///
/// Puts `key` into to global keyboard buffer
///

///
public static void SendKey(byte key)
{
const int KEYEVENTF_KEYUP = 0x02;
const int KEYEVENTF_KEYDOWN = 0x00;
keybd_event(key, 0, KEYEVENTF_KEYDOWN, 0);
keybd_event(key, 0, KEYEVENTF_KEYUP, 0);
}

[DllImport("coredll", SetLastError = true)]
private static extern void keybd_event(byte bVk, byte bScan, int dwFlags, int dwExtraInfo);
}
The class is static so the usage is obvious.
SystemCalls.SendKey(SystemCalls.VK_F22);

Creating shortcuts in Windows Mobile Smartphone

http://bansky.net/blog/2007/07/creating-shortcuts-in-windows-mobile-smartphone/

Creating shortcuts in Windows Mobile Smartphone

Tuesday, July 24, 2007 @ 10:44
Sometimes people ask me about differencies in Windows Mobile for Smartphone and PocketPC. Hmm, I should say Windows Mobile Standard and Professional. Well, the most significant differences are in UI, and now I know the next one. In Smartphone you are not able to create shortcuts to file on your file system. To be precise you have no option how to create it.

On pocket PC it's quite easy, just select the file in explorer, tap and click Copy. Then go to the folder where you want to place the shortcut, tap and click Paste Shortcut. Unfortunately Smartphones has no Paste Shortcut option. So, it was only matter of time when someone will ask me how to fix this glitch.

How the shortcut works?

In Windows CE (so Windows Mobile) the shortcut file is very simple plain text file. If you open some *.lnk file in notepad, you will see something like this:

42#"\Program Files\Total Commander\cecmd.exe"
The number 42 is of course Answer to Life, the Universe, and Everything. But in this case it is the length of the command placed in shortcut. So that Program Files\Total Commander\cecmd.exe without the quotes. The quotes are neccesary when the path contains spaces. Don't think that you can put qoutes everywhere. If the path has no spaces than put no quotes. Like in this example:
18#\Windows\notes.exe
The # sign is just the delimiter. In cases you want to pass some arguments to the exacutable, you can add it right after the path. Don't forget to add length of the parameters to begining number. Following examples shows executing with parameters. First one executes Total Commander and pass \Windows as the parametr. Second one executes autoprof and pass two parameters. Quotes are NOT count to the length.
51#"\Program Files\Total Commander\cecmd.exe" \Windows


27#\Windows\autoprof -s Silent

Do it from C#

The principles mentioned above is obviously very easy to rewrite into the C# code. So here is the method and example how to place short cut to Total Commander into the start menu.
/// 
/// Creates the link file
///

/// Destination of the shortcut
/// Shortcut file name
/// Parameters

/// true if link was created
private bool CreateLink(string destination, string shortCut, string parameters)
{
try
{
bool isQuoted = false;

// when path contains spaces the set quote
destination = destination.Trim();
if (destination.IndexOf(' ') > -1) isQuoted = true;


// count length. +1 for space between path and arguments
string link = destination;
int len = destination.Length + parameters.Length + 1;

// add quotes when neccesary
if (isQuoted)
link = """ + link + """;

// add parametrs if any
if (parameters != null && parameters.Length > 0)
link += " " + parameters;

// write everything into the file
FileStream fs = new FileStream(shortCut, FileMode.Create,
FileAccess.Write, FileShare.ReadWrite);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine(len.ToString()+"#"+link);
sw.Close();
fs.Close();
}
catch
{
// Your exception handling here
return false;
}

return true;
}
Usage:
CreateLink(@"\Program Files\Total Commander\cecmd.exe",
@"\Windows\Start Menu\go windows.lnk", "\Windows");

Complete application

I wrote application called ShortcutMaker as the complete solution for creating shortcuts in smartphones. It is written in C# and uses Compact Framework 1.0, so that it will run without other requirements on WM 2003 and above. Since CF 1.0 has no support for standard file-open and folder-browsing dialogs, I utilize the one from Peter Foot. You can download it from here with examples. Those are now implementeted in OpenNETCF.

Download the instalation cabinet file: ShortcutMakerInstall.cab

Monday, October 20, 2008

How to control bluetooth OBEX default service on/off?

To control the Infrared state (on/off) or bluetooth OBEX default service in a similar way as in the control pannel, and to get the current state of the infrared module use the code below:

Code:

//set irda service status
HRESULT OBEXIOCTL(DWORD dwIOCTL)
{
HANDLE hService;
BOOL fRet;
hService = CreateFile(TEXT("OBX0:"),GENERIC_READ|GENERIC_WRITE,0,
NULL,OPEN_EXISTING,0,NULL);
if (INVALID_HANDLE_VALUE == hService)
{
CloseHandle(hService);
return FALSE;
}
fRet = DeviceIoControl(hService,dwIOCTL,0,0,0,0,NULL,0);
CloseHandle(hService);
return (0 == fRet)?E_FAIL:S_OK;
}

//query irda service status
DWORD OBEXQuery()
{
HANDLE hService;
BOOL fRet;
DWORD dwStatus;
hService = CreateFile(TEXT("OBX0:"),GENERIC_READ|GENERIC_WRITE,0,
NULL,OPEN_EXISTING,0,NULL);
if (INVALID_HANDLE_VALUE == hService)
{
CloseHandle(hService);
return FALSE;
}
fRet = DeviceIoControl(hService,IOCTL_SERVICE_STATUS,0,0,&dwStatus,sizeof(DWORD),0, 0);
CloseHandle(hService);
if(0 == fRet)
return 0xFFFFFFFF;
else
return dwStatus;
}

bool GetIRDAState()
{
switch(OBEXQuery())
{
case SERVICE_STATE_SHUTTING_DOWN:
case SERVICE_STATE_UNLOADING:
case SERVICE_STATE_UNINITIALIZED:
case SERVICE_STATE_OFF:
return 0;
break;

case SERVICE_STATE_STARTING_UP:
case SERVICE_STATE_ON:
return 1;
break;
default:
break;
};
return 0;
}

Friday, October 10, 2008

C# TrayIcon Class

using System;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
using Microsoft.Win32;
using System.Windows.Forms;

namespace XXXX
{
public class TrayIcon
{
//Declare click event
public event System.EventHandler Click;

private WindowSink windowSink;
private int uID = 11000;

//Constructor
public TrayIcon()
{
//Create instance of the MessageWindow subclass
windowSink = new WindowSink(this);
windowSink.uID = uID;
}

//Destructor
~TrayIcon()
{
Remove();
}


public void Add(IntPtr hIcon)
{
TrayMessage(windowSink.Hwnd, NIM_ADD, (uint)uID, hIcon);
}

public void Remove()
{

TrayMessage(windowSink.Hwnd, NIM_DELETE, (uint)uID, IntPtr.Zero);
}

public void Modify(IntPtr hIcon)
{

TrayMessage(windowSink.Hwnd, NIM_MODIFY, (uint)uID, hIcon);

}

private void TrayMessage(IntPtr hwnd, int dwMessage, uint uID, IntPtr hIcon)
{
NOTIFYICONDATA notdata = new NOTIFYICONDATA();

notdata.cbSize = 152;
notdata.hIcon = hIcon;
notdata.hWnd = hwnd;
notdata.uCallbackMessage = WM_NOTIFY_TRAY;
notdata.uFlags = NIF_MESSAGE | NIF_ICON;
notdata.uID = uID;

int ret = Shell_NotifyIcon(dwMessage, ref notdata);
}

#region API Declarations

internal const int WM_LBUTTONDOWN = 0x0201;
internal const int WM_RBUTTONUP = 0x0205;
//User defined message
internal const int WM_NOTIFY_TRAY = 0x0400 + 2001;

internal const int NIM_ADD = 0x00000000;
internal const int NIM_MODIFY = 0x00000001;
internal const int NIM_DELETE = 0x00000002;

const int NIF_MESSAGE = 0x00000001;
const int NIF_ICON = 0x00000002;


internal struct NOTIFYICONDATA
{
internal int cbSize;
internal IntPtr hWnd;
internal uint uID;
internal uint uFlags;
internal uint uCallbackMessage;
internal IntPtr hIcon;
//internal char[] szTip = new char[64];
//internal IntPtr szTip;
}

[DllImport("coredll.dll")]
internal static extern int Shell_NotifyIcon(
int dwMessage, ref NOTIFYICONDATA pnid);

[DllImport("coredll.dll")]
internal static extern int SetForegroundWindow(IntPtr hWnd);

[DllImport("coredll.dll")]
internal static extern int ShowWindow(
IntPtr hWnd,
int nCmdShow);

[DllImport("coredll.dll")]
internal static extern IntPtr GetFocus();

#endregion


#region WindowSink

internal class WindowSink : Microsoft.WindowsCE.Forms.MessageWindow
{
//Private members
private int m_uID = 0;
private TrayIcon trayIcon;

//Constructor
public WindowSink(TrayIcon tIcon)
{
trayIcon = tIcon;
}

public int uID
{
set
{
m_uID = value;

}
}

protected override void WndProc(ref Microsoft.WindowsCE.Forms.Message msg)
{

if (msg.Msg == WM_NOTIFY_TRAY)
{
switch ((int)msg.LParam)
{
case WM_LBUTTONDOWN:
if ((int)msg.WParam == m_uID)
{
//If somebody hooked, raise the event
if (trayIcon.Click != null)
trayIcon.Click(trayIcon, null);

}
break;

case WM_RBUTTONUP:
{
MessageBox.Show("R Button Up");
}
break;
}
}

}
}
#endregion

}
}

Tuesday, October 7, 2008

How to set device clock (set system time)?

http://msdn.microsoft.com/en-us/library/ms172517.aspx

To get or set the system time of the device, use platform invoke to call the native GetSystemTime or SetSystemTime functions.

Note that the GetSystemTime function returns Coordinated Universal Time (UTC, also known as Greenwich Mean Time). To get your local time, you must add or subtract the number of hours between your time zone and UTC. For example, 24:00 (midnight) in UTC is 19:00 in New York--an offset of minus 5 hours (UTC–5).

To determine the UTC offset for your time zone, see the Time Zone tab of Date and Time Properties.

Some device emulators do not initially set daylight-saving time correctly, which could affect your result.

Visual Basic

Public Structure SYSTEMTIME
Public wYear As UInt16
Public wMonth As UInt16
Public wDayOfWeek As UInt16
Public wDay As UInt16
Public wHour As UInt16
Public wMinute As UInt16
Public wSecond As UInt16
Public wMilliseconds As UInt16
End Structure

Declare Function GetSystemTime Lib "CoreDll.dll" _
(ByRef lpSystemTime As SYSTEMTIME) As UInt32

Declare Function SetSystemTime Lib "CoreDll.dll" _
(ByRef lpSystemTime As SYSTEMTIME) As UInt32

Public Sub GetTime
' Call the native GetSystemTime method
' with the defined structure.
Dim st As New SYSTEMTIME
GetSystemTime(st)

' Show the current time.
MessageBox.Show("Current Time: " & st.wHour.ToString() _
& ":" & st.wMinute.ToString())
End Sub

Public Sub SetTime
' Call the native GetSystemTime method
' with the defined structure.
Dim st As New SYSTEMTIME
GetSystemTime(st)

' Set the system clock ahead one hour.
st.wHour = Convert.ToUInt16(((CInt(st.wHour) + 1)) Mod 24)
SetSystemTime(st)

End Sub


C#

[DllImport("coredll.dll")]
private extern static void GetSystemTime(ref SYSTEMTIME lpSystemTime);

[DllImport("coredll.dll")]
private extern static uint SetSystemTime(ref SYSTEMTIME lpSystemTime);


private 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;
}

private void GetTime()
{
// Call the native GetSystemTime method
// with the defined structure.
SYSTEMTIME stime = new SYSTEMTIME();
GetSystemTime(ref stime);

// Show the current time.
MessageBox.Show("Current Time: " +
stime.wHour.ToString() + ":"
+ stime.wMinute.ToString());
}
private void SetTime()
{
// Call the native GetSystemTime method
// with the defined structure.
SYSTEMTIME systime = new SYSTEMTIME();
GetSystemTime(ref systime);

// Set the system clock ahead one hour.
systime.wHour = (ushort)(systime.wHour + 1 % 24);
SetSystemTime(ref systime);
MessageBox.Show("New time: " + systime.wHour.ToString() + ":"
+ systime.wMinute.ToString());
}







Thursday, September 25, 2008

Copying files from Desktop to a CE device

http://blogs.msdn.com/harsh/archive/2008/05/08/copying-files-from-desktop-to-a-ce-device.aspx

So I have this problem, where I need to create a tool that creates a folder with a bunch of files on the PC and then copies all these files over to a CE device. The method of choice here was via ActiveSync over USB. One of the design goals was to be able to copy these files to a number of devices simultaneously. However, research revealed that this is not really possible since, activesync only supports one active connection at a time. So much for the great idea.

So now we are faced with this problem of copying files over to the device over ActiveSync. Since the app had a lot of GUI, I created that in C#. The .NET framework exposes excellent API for file manipulation based on paths. The problem with ActiveSync connections is when the device is cradled, there is no drive letter associated with the connection. So all device paths are then \My Documents\ or \Program Files\ etc.

This creates a problem as far as the File manipulation API in System.IO. Since these methods accept relative as well as fully qualified paths, any path like the above, would be treated as a relative path and not a fully qualified path, thereby causing a lot of grief.

The only way to get past this so far has been to use RAPI.

RAPI stands for Remote Application Programming Interface, and was created ages ago with the first wave of activesync and windows mobile products.

RAPI has some documentation on MSDN at: http://msdn.microsoft.com/en-us/library/aa458022.aspx

However since RAPI is a native API, almost all the documentation is geared towards native implementation.

After searching the intertubes for a suitable solution, I couldn’t find one that was recent, and that was guaranteed to work.

Below is the solution:




using System;
using System.Threading;
using System.Runtime.InteropServices;
using COMTYPES = System.Runtime.InteropServices.ComTypes;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Logger = Microsoft.MobileDevices.Tools.Utilities.Logger;


namespace Microsoft.MobileDevices.Tools.RAPILibrary
{
public class RAPILibrary
{
# region RAPI EXTERN
// -------------------------------------------------------
// RAPI.DLL Definitions
// -------------------------------------------------------

public const int MAX_PATH = 260;
public const uint MAXDWORD = 0xFFFFFFFF;
public const uint S_OK = 0;

public struct RAPIINIT
{
public int cbSize;
public IntPtr heRapiInit;
public int hrRapiInit;
};

// From WINBASE.H -- for CeCreateFile
public enum ACCESS : uint
{
READ = 0x80000000,
WRITE = 0x40000000,
}
// From WINBASE.H -- for CeCreateFile
public enum SHARE
{
READ = 0x00000001,
WRITE = 0x00000002,
}
// From WINBASE.H -- for CeCreateFile
public enum ACTION
{
CREATE_NEW = 1,
CREATE_ALWAYS = 2,
OPEN_EXISTING = 3,
OPEN_ALWAYS = 4,
TRUNCATE_EXISTING = 5
}

// From WINBASE.H -- for CeCreateFile
public enum FILEFLAGATT : uint
{
ATTRIBUTE_READONLY = 0x00000001,
ATTRIBUTE_HIDDEN = 0x00000002,
ATTRIBUTE_SYSTEM = 0x00000004,
ATTRIBUTE_DIRECTORY = 0x00000010,
ATTRIBUTE_ARCHIVE = 0x00000020,
ATTRIBUTE_INROM = 0x00000040,
ATTRIBUTE_ENCRYPTED = 0x00000040,
ATTRIBUTE_NORMAL = 0x00000080,
ATTRIBUTE_TEMPORARY = 0x00000100,
ATTRIBUTE_SPARSE_FILE = 0x00000200,
ATTRIBUTE_REPARSE_POINT = 0x00000400,
ATTRIBUTE_COMPRESSED = 0x00000800,
ATTRIBUTE_OFFLINE = 0x00001000,
ATTRIBUTE_ROMSTATICREF = 0x00001000,
ATTRIBUTE_NOT_CONTENT_INDEXED = 0x00002000,
ATTRIBUTE_ROMMODULE = 0x00002000,
FLAG_WRITE_THROUGH = 0x80000000,
FLAG_OVERLAPPED = 0x40000000,
FLAG_NO_BUFFERING = 0x20000000,
FLAG_RANDOM_ACCESS = 0x10000000,
FLAG_SEQUENTIAL_SCAN = 0x08000000,
FLAG_DELETE_ON_CLOSE = 0x04000000,
FLAG_BACKUP_SEMANTICS = 0x02000000,
FLAG_POSIX_SEMANTICS = 0x01000000,
}


///
/// Closes handle passed in
///

/// handle to be closed
///
[DllImport("rapi.DLL", CharSet = CharSet.Unicode)]
public static extern int CeCloseHandle(IntPtr hObject);

///
/// Creates file on device
///

/// path of file
/// Read/Write
/// Share mode
///
/// File creation options
/// Flags and attributes
///
/// pointer to the created file
[DllImport("rapi.DLL", CharSet = CharSet.Unicode)]
public static extern IntPtr CeCreateFile(string lpFileName, ACCESS dwDesiredAccess, SHARE dwShareMode, int Res1, ACTION dwCreationDisposition, FILEFLAGATT dwFlagsAndAttributes, int Res2);

///
/// Reads the file
///

/// handle to the file
/// buffer to copy data to
/// file size to read
/// file size read
///
///
[DllImport("rapi.DLL", CharSet = CharSet.Unicode)]
public static extern int CeReadFile(IntPtr hFile, IntPtr lpBuffer, int nNumberOfBytesToRead, ref int lpNumberOfBytesRead, int Reserved);

///
/// Writes file to device
///

/// handle of file to write to
/// data to write
/// length of buffer
/// length of file on device
///
///
[DllImport("rapi.DLL", CharSet = CharSet.Unicode)]
public static extern int CeWriteFile(IntPtr hFile, IntPtr lpBuffer, int nNumberOfBytesToWrite, ref int lpNumberOfBytesWritten, int Reserved);

///
/// Copies file from desktop to device
///

/// Full path of file on the desktop including filename
/// Path of file name on the device. '\' denotes root
public static void CopyFiletoDevice(string deskFile, string devFilePath)
{
try
{
int numTries=0;
// Verify file exists on desktop
FileInfo fInfo = new FileInfo(deskFile);
if (fInfo.Exists)
{
IntPtr devFileHandle;
// create a file on the device
do // force valid handle in the loop
{
devFileHandle = CeCreateFile(devFilePath, ACCESS.READ | ACCESS.WRITE, SHARE.READ | SHARE.WRITE, 0, ACTION.CREATE_ALWAYS, FILEFLAGATT.ATTRIBUTE_NORMAL, 0);
if (devFileHandle.ToInt32() < 0)
{
CeCloseHandle(devFileHandle);
}
} while (devFileHandle.ToInt32() < 0);


// read file from desktop into a byte buffer
Byte[] buffer;
ReadFileAsBinary(deskFile, out buffer);

int numBytesWritten = 0;
unsafe
{
fixed(byte* bufferPtr = buffer)
{
int retVal = CeWriteFile(devFileHandle, (IntPtr)(bufferPtr), (int)fInfo.Length, ref numBytesWritten, 0);
if (retVal == 0)
{
throw new IOException("RAPILibrary:CopyFileToDevice() Error Writing file on device. " + CeGetLastError().ToString());
}
}
}

// close handles
CeCloseHandle(devFileHandle);
}
else
{
Logger.WriteLog("RAPILibrary:CopyFileToDevice() File does not exist on desktop: " + deskFile);
}

}
catch (IOException ioEx)
{
Logger.WriteLog(ioEx.Message);
}
catch (Exception ex)
{
Logger.WriteLog(ex.ToString());
}
}

///
/// Reads file and returns byte[]
///

/// Full path of file
/// byte array for file data
private static void ReadFileAsBinary(string path, out Byte[] buffer)
{
Logger.WriteLog("RAPILibrary:ReadFileAsBinary() Reading the file " + path);
FileInfo fInfo = new FileInfo(path);
long fileLength = fInfo.Length;
buffer = new Byte[fileLength];
FileStream fs = fInfo.OpenRead();
fs.Read(buffer, 0, (int)fileLength);
fs.Close();
Logger.WriteLog("RAPILibrary:ReadFileAsBinary() Exit");
}
}
}