Thursday, January 15, 2009

How to create REG_MULTI_SZ and REG_BINARY in C++ and C#

1. REG_MULTI_SZ

C#:

string[] ConfigurationString = new string[8];
ConfigurationString[0] = Location;
ConfigurationString[1] = LocalCalls;
ConfigurationString[2] = LongDistanceCalls;
ConfigurationString[3] = InternationalCalls;
ConfigurationString[4] = AreaCode;
ConfigurationString[5] = DisableCallWaitingSequence;
ConfigurationString[6] = CountryCode;
ConfigurationString[7] = ToneOrPulse;

RegistryKey rk = Registry.CurrentUser;
using (RegistryKey rk1 = rk.CreateSubKey("ControlPanel\
\Dial\\Locations"))
{
rk1.SetValue(KeyName, ConfigurationString);
rk1.Close();
}

C++: (not tested yet!)

HKEY hKey = NULL;
DWORD dataType = REG_MULTI_SZ;
LONG retVal = 0;
LONG ConfigurationStringSize = 512;
WCHAR *ConfigurationString = new WCHAR[ConfigurationStringSize];
memset(ConfigurationString,'\0',512);

// Build the configuration string.
wcscat(ConfigurationString, Location);
wcscat(ConfigurationString, TEXT("$"));

wcscat(ConfigurationString, LocalCalls);
wcscat(ConfigurationString, TEXT("$"));

wcscat(ConfigurationString, LongDistanceCalls);
wcscat(ConfigurationString, TEXT("$"));

wcscat(ConfigurationString, InternationalCalls);
wcscat(ConfigurationString, TEXT("$"));

wcscat(ConfigurationString, AreaCode);
wcscat(ConfigurationString, TEXT("$"));

wcscat(ConfigurationString, DisableCallWaitingSequence);
wcscat(ConfigurationString, TEXT("$"));

wcscat(ConfigurationString, CountryCode);
wcscat(ConfigurationString, TEXT("$"));

wcscat(ConfigurationString, ToneOrPulse);
wcscat(ConfigurationString, TEXT("$"));

// Format the string correctly.
int ConfigStringLen = wcslen(ConfigurationString);
for(int x = 0; x < ConfigStringLen; ++x)
{
if(ConfigurationString[x] == '$')
ConfigurationString[x] = '\0';
}

// Open the registry key.
retVal = RegOpenKeyEx(HKEY_CURRENT_USER , TEXT("ControlPanel\\Dial\\Locations"), 0, KEY_READ, &hKey);
if(retVal != ERROR_SUCCESS)
{
delete [] ConfigurationString;
return false;
}

// Set the value of the key.
retVal = RegSetValueEx(hKey, KeyName, NULL, dataType, (PBYTE)ConfigurationString, ConfigurationStringSize);
RegCloseKey(hKey);

delete [] ConfigurationString;

return retVal != ERROR_SUCCESS ? false : true;
-------------------------------------------------------------------------------
2. REG_BINARY

C#:
private bool GetBinaryBluetoothAddress(string sBluetoothAddress, ref byte[] bBTAddress)
{
try
{
//00:03:c9:56:0c:EE
string[] sTmp = sBluetoothAddress.Split(':');
bBTAddress[0] = Convert.ToByte(sTmp[5], 16);
bBTAddress[1] = Convert.ToByte(sTmp[4], 16);
bBTAddress[2] = Convert.ToByte(sTmp[3], 16);
bBTAddress[3] = Convert.ToByte(sTmp[2], 16);
bBTAddress[4] = Convert.ToByte(sTmp[1], 16);
bBTAddress[5] = Convert.ToByte(sTmp[0], 16);
bBTAddress[6] = 0;
bBTAddress[7] = 0;

return true;
}
catch
{
return false;
}
}

RegistryKey rk = Registry.LocalMachine;
using (RegistryKey rk1 = rk.CreateSubKey("\\Software\\dx"))
{
byte[] bA = new byte[8];
if (GetBinaryBluetoothAddress("00:03:c9:56:0c:EE", ref bA))
{
rk1.SetValue("dxaddress", bA);
MessageBox.Show("Good!");
}
else
MessageBox.Show("Failed!");

rk1.Close();
}
rk.Close();

C++:

unsigned char epwd[9];

//set epwd here

RegSetValueEx(hKey,"keyname",0,REG_BINARY,(LPBYTE)&epwd,8);

Tuesday, January 13, 2009

How to set Bluetooth ActiveSync Connection

Method 1: use ras to setup the dialing parameters
SetActiveSyncDialingParameters();


private void SetActiveSyncDialingParameters
()
{
int dwSize;
char[] bSP = new char[512];
RASENTRY RasEntry;
RasEntry = new RASENTRY();

RASDIALPARAMS RasDialParams;
RasDialParams = new RASDIALPARAMS();

dwSize = Marshal.SizeOf(typeof(RASENTRY));
RasEntry.dwSize = dwSize;
uint temp = 512;


//MessageBox.Show("Attempting RASGetEntries");
uint dwGetEntry = 0;
dwGetEntry = RasConnection.RasGetEntryProperties("", "",
ref RasEntry, ref dwSize, bSP, ref temp);
if (dwGetEntry >= 1)
{
MessageBox.Show("Unable to retrieve information:" + dwGetEntry.ToString()); //passed after readjust struc
//return;

}
///* RASENTRY 'dwfOptions' bit flags.
//*/
//#define RASEO_UseCountryAndAreaCodes 0x00000001
//#define RASEO_SpecificIpAddr 0x00000002
//#define RASEO_SpecificNameServers 0x00000004
//#define RASEO_IpHeaderCompression 0x00000008
//#define RASEO_RemoteDefaultGateway 0x00000010
//#define RASEO_DisableLcpExtensions 0x00000020
//#define RASEO_TerminalBeforeDial 0x00000040
//#define RASEO_TerminalAfterDial 0x00000080
//#define RASEO_ModemLights 0x00000100
//#define RASEO_SwCompression 0x00000200
//#define RASEO_RequireEncryptedPw 0x00000400
//#define RASEO_RequireMsEncryptedPw 0x00000800
//#define RASEO_RequireDataEncryption 0x00001000
//#define RASEO_NetworkLogon 0x00002000
//#define RASEO_UseLogonCredentials 0x00004000
//#define RASEO_PromoteAlternates 0x00008000
//#define RASEO_SecureLocalFiles 0x00010000
//#define RASEO_DialAsLocalCall 0x00020000

//#define RASEO_ProhibitPAP 0x00040000
//#define RASEO_ProhibitCHAP 0x00080000
//#define RASEO_ProhibitMsCHAP 0x00100000
//#define RASEO_ProhibitMsCHAP2 0x00200000
//#define RASEO_ProhibitEAP 0x00400000
//#define RASEO_PreviewUserPw 0x01000000
//#define RASEO_NoUserPwRetryDialog 0x02000000
//#define RASEO_CustomScript 0x80000000

//RasEntry.dwfOptions &= ~(RASEO_SpecificNameServers|RASEO_SpecificIpAddr|
// RASEO_IpHeaderCompression|RASEO_SwCompression|RASEO_UseCountryAndAreaCodes);

RasEntry.dwfOptions &= ~(0x00000004 | 0x00000002 | 0x00000008 | 0x00000200 | 0x00000001);

RasEntry.szDeviceName = "BluetoothSYN";
RasEntry.szDeviceType = "direct";

dwGetEntry = RasConnection.RasSetEntryProperties(null, "Bluetooth", ref RasEntry, dwSize, null, 0);
if (dwGetEntry >= 1)
{
MessageBox.Show("Unable to RasSetEntryProperties:" + dwGetEntry.ToString()); //621;passed after change first parameter from "" to null
//return;
}

RasDialParams.dwSize = (int )Marshal.SizeOf (typeof(RASDIALPARAMS));
RasDialParams.szEntryName = "Bluetooth";
RasDialParams.szUserName = "guest";
RasDialParams.szPassword = "guest";


dwGetEntry = RasConnection.RasSetEntryDialParams(null, ref RasDialParams, false);
if (dwGetEntry >= 1)
{
MessageBox.Show("Unable to RasSetEntryDialParams:" + dwGetEntry.ToString()); //610:passed after change first parameter from "" to null
//return;
}
}

Method 2: directly go to registry to set up ras phone book
RASPHONEENTRY rs = new RASPHONEENTRY();
#if (UseCOM1)
rs.CreateRasEntry("BluetoothCOM1", 1, ref m_iOldValue1, ref m_sOldValue2);
#else
rs.CreateRasEntry("BluetoothCOM2", 2, ref m_iOldValue1, ref m_sOldValue2);
#endif
//timer start
m_ActiveSyncTimer = new System.Windows.Forms.Timer();
m_ActiveSyncTimer.Tick += new EventHandler(ActiveSyncTimerEventProcessor);
m_ActiveSyncTimer.Interval = 10000;
m_ActiveSyncTimer.Enabled = true;

rs.RunActiveSyncConnection();


void ActiveSyncTimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
//maybe kill repllog.exe???
//MyProcess mp = new MyProcess();
//if (mp.FindProcess("repllog.exe"))
// mp.KillProcess("repllog.exe");


RegistryKey rk = Registry.CurrentUser;
using (RegistryKey rk1 = rk.OpenSubKey("\\ControlPanel\\Comm", true))
{
rk1.SetValue("AutoCnct", m_iOldValue1);
rk1.SetValue("Cnct", m_sOldValue2);
rk1.Close();
}
rk.Close();

}
----------------------From Attched RasPhoneEntry.cs------------------

public Byte[] byteDevCfgCOM1 = {
0x30,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x10,0x03,0x00,0x00,0x00,0xC2,0x01,0x00,
....
}


//step 1: On device, Start->Settings->Control Panel. Choose "Network and Dial-up Connections". Click "Make New Connections".
//Input "com2", "Direct","Cable on COM2:". Click "Configure", set "115200" etc. "Finish"
///
///
//step 2: Use following code to read manual created ras phone entry: PC-115K for COM1 and com2 for COM2.
///
/// GenerateRasEntryFile
///

public void GenerateRasEntryFile()
{
RegistryKey rk = Registry.CurrentUser;
StreamWriter sw = new StreamWriter("\\ras.txt");
using (RegistryKey rk1 = rk.CreateSubKey("\\Comm\\RasBook\\PC-115K"))
{
sw.WriteLine("");
sw.WriteLine("//\\Comm\\RasBook\\PC-115K");
sw.WriteLine("//1. DevCfg");

sw.WriteLine("Byte[] m_byteDevCfg = {");
Byte[] DevCfg = (Byte[])rk1.GetValue("DevCfg");
int i = 1;
foreach (Byte b in DevCfg)
{
if (i != 8)
{
sw.Write("0x" + b.ToString("X2"));
sw.Write(",");
i++;
}
else
{
sw.WriteLine("0x" + b.ToString("X2") + ",");
i = 1;
}
}
sw.WriteLine("};");
sw.WriteLine("");
sw.WriteLine("");
i = 1;

sw.WriteLine("//2. Entry");
sw.WriteLine("Byte[] m_byteEntry = {");
Byte[] Entry = (Byte[])rk1.GetValue("Entry");
foreach (Byte b in Entry)
{
if (i != 8)
{
sw.Write("0x" + b.ToString("X2"));
sw.Write(",");
i++;
}
else
{
sw.WriteLine("0x" + b.ToString("X2") + ",");
i = 1;
}
}
sw.WriteLine("};");
rk1.Close();
}
using (RegistryKey rk1 = rk.CreateSubKey("\\Comm\\RasBook\\com2"))
{
sw.WriteLine("");
sw.WriteLine("//\\Comm\\RasBook\\com2");
sw.WriteLine("//1. DevCfg");
sw.WriteLine("Byte[] m_byteDevCfg = {");
Byte[] DevCfg = (Byte[])rk1.GetValue("DevCfg");
int i = 1;
sw.WriteLine("1. DevCfg");
foreach (Byte b in DevCfg)
{
if (i != 8)
{
sw.Write("0x" + b.ToString("X2"));
sw.Write(",");
i++;
}
else
{
sw.WriteLine("0x" + b.ToString("X2") + ",");
i = 1;
}
}
sw.WriteLine("};");
sw.WriteLine("");
sw.WriteLine("");
sw.WriteLine("//2. Entry");
i = 1;
sw.WriteLine("Byte[] m_byteEntry = {");
Byte[] Entry = (Byte[])rk1.GetValue("Entry");
foreach (Byte b in Entry)
{
if (i != 8)
{
sw.Write("0x" + b.ToString("X2"));
sw.Write(",");
i++;
}
else
{
sw.WriteLine("0x" + b.ToString("X2") + ",");
i = 1;
}
}
sw.WriteLine("};");
sw.Close();
rk1.Close();
}
}

//step 3: Based on the entry file: ras.txt to create your own Bluetooth ras phone entry with baud rate 115200 and COM1 or 2.
//Why need this: because I can create ras entry using RasGetEntryProperties,RasSetEntryProperties,RasSetEntryDialParams, but it is very hard to
//set baud rate to 115200.
///
/// CreateRasEntry: create your own Bluetooth ras phone entry with baud rate 115200 and COM1 or 2.
///

///
param>
///
///
///
public void CreateRasEntry(string sNewRasEntryName, int iPort, ref int iOldValue1, ref string sOldValue2)
{
RegistryKey rk = Registry.CurrentUser;
using (RegistryKey rk2 = rk.CreateSubKey("\\Comm\\RasBook\\" + sNewRasEntryName))
{
RASPHONEENTRY rs = new RASPHONEENTRY();
if (iPort == 1)
{
rk2.SetValue("DevCfg", rs.byteDevCfgCOM1);
rk2.SetValue("Entry", rs.byteEntryCOM1);
}
else
{
rk2.SetValue("DevCfg", rs.byteDevCfgCOM2);
rk2.SetValue("Entry", rs.byteEntryCOM2);
}
rk2.Close();
}

using (RegistryKey rk1 = rk.CreateSubKey("\\ControlPanel\\Comm"))
{
iOldValue1 = (int)rk1.GetValue("AutoCnct");
rk1.SetValue("AutoCnct", 1);
sOldValue2 = (string)rk1.GetValue("Cnct");
rk1.SetValue("Cnct", sNewRasEntryName); //need to use this specially already created Bluetooth to connect
rk1.Close();
}
rk.Close();

rk = Registry.LocalMachine;
using (RegistryKey rk1 = rk.CreateSubKey("\\ExtModems\\bluetooth_syn"))
{
rk1.SetValue("port", iPort); //might be 2
rk1.Close();
}
rk.Close();
}

//step 4: run repllog.exe to start active connection
///
/// Run ActiveSync Connection
///

public void RunActiveSyncConnection()
{
//run repllog.exe
//ProcessStartInfo psi = new ProcessStartInfo("\\Windows\\repllog.exe","");
//Process.Start(psi);
Functions f = new Functions();
f.OpenExternalProgram("repllog.exe", "AppRunAtRs232Detect"); //activesync auto start when detects serial port connection
}
----------------------From Attched RasConnection.cs------------------

public enum RasFieldSizeConstants
{
RAS_MaxDeviceType = 16,
RAS_MaxPhoneNumber = 128,
RAS_MaxIpAddress = 15,
RAS_MaxIpxAddress = 21,
RAS_MaxEntryName = 20,
RAS_MaxDeviceName = 128,
RAS_MaxCallbackNumber = 48,
RAS_MaxParamKey = 32,
RAS_MaxParamValue = 128,

RAS_MaxAreaCode = 10,
RAS_MaxPadType = 32,
RAS_MaxX25Address = 200,
RAS_MaxFacilities = 200,
RAS_MaxUserData = 200,
RAS_MaxReplyMessage = 1024,
RAS_MaxDnsSuffix = 256,

MAX_PATH = 260,

UNLEN = 256,
PWLEN = 256,
DNLEN = 15
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct RASIPADDR
{
byte a;
byte b;
byte c;
byte d;
}

//Public Enum RasEntryOptions
// RASEO_UseCountryAndAreaCodes = &H1
// RASEO_SpecificIpAddr = &H2
// RASEO_SpecificNameServers = &H4
// RASEO_IpHeaderCompression = &H8
// RASEO_RemoteDefaultGateway = &H10
// RASEO_DisableLcpExtensions = &H20
// RASEO_TerminalBeforeDial = &H40
// RASEO_TerminalAfterDial = &H80
// RASEO_ModemLights = &H100
// RASEO_SwCompression = &H200
// RASEO_RequireEncryptedPw = &H400
// RASEO_RequireMsEncryptedPw = &H800
// RASEO_RequireDataEncryption = &H1000
// RASEO_NetworkLogon = &H2000
// RASEO_UseLogonCredentials = &H4000
// RASEO_PromoteAlternates = &H8000
// RASEO_SecureLocalFiles = &H10000
// RASEO_RequireEAP = &H20000
// RASEO_RequirePAP = &H40000
// RASEO_RequireSPAP = &H80000
// RASEO_Custom = &H100000
// RASEO_PreviewPhoneNumber = &H200000
// RASEO_SharedPhoneNumbers = &H800000
// RASEO_PreviewUserPw = &H1000000
// RASEO_PreviewDomain = &H2000000
// RASEO_ShowDialingProgress = &H4000000
// RASEO_RequireCHAP = &H8000000
// RASEO_RequireMsCHAP = &H10000000
// RASEO_RequireMsCHAP2 = &H20000000
// RASEO_RequireW95MSCHAP = &H40000000
// RASEO_CustomScript = &H80000000
// End Enum

///* RASENTRY 'dwfNetProtocols' bit flags. (session negotiated protocols)
//*/
//#define RASNP_NetBEUI 0x00000001 // Negotiate NetBEUI
//#define RASNP_Ipx 0x00000002 // Negotiate IPX
//#define RASNP_Ip 0x00000004 // Negotiate TCP/IP


///* RASENTRY 'dwFramingProtocols' (framing protocols used by the server)
//*/
//#define RASFP_Ppp 0x00000001 // Point-to-Point Protocol (PPP)
//#define RASFP_Slip 0x00000002 // Serial Line Internet Protocol (SLIP)
//#define RASFP_Ras 0x00000004 // Microsoft proprietary protocol


///* RASENTRY 'szDeviceType' strings
//*/
//#define RASDT_Direct TEXT("direct") // Direct Connect (WINCE Extension)
//#define RASDT_Modem TEXT("modem") // Modem
//#define RASDT_Isdn TEXT("isdn") // ISDN
//#define RASDT_X25 TEXT("x25") // X.25
//#define RASDT_Vpn TEXT("vpn") // PPTP
//#define RASDT_PPPoE TEXT("PPPoE") // PPPoE


//http://msdn.microsoft.com/en-us/library/aa920252.aspx
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct RASENTRY
{
public int dwSize;
public int dwfOptions;
//
// Location/phone number.
//
public int dwCountryID;
public int dwCountryCode;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxAreaCode + 1)]
public string szAreaCode;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxPhoneNumber + 1)]
public string szLocalPhoneNumber;
public int dwAlternateOffset;
//
// PPP/Ip
//
public RASIPADDR ipaddr;
public RASIPADDR ipaddrDns;
public RASIPADDR ipaddrDnsAlt;
public RASIPADDR ipaddrWins;
public RASIPADDR ipaddrWinsAlt;
//
// Framing
//
public int dwFrameSize;
public int dwfNetProtocols;
public int dwFramingProtocol;
//
// Scripting
//
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]//MAX_PATH
public string szScript;
//
// AutoDial
//
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]//MAX_PATH
public string szAutodialDll;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]//MAX_PATH
public string szAutodialFunc;
//
// Device
//
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxDeviceType + 1)]
public string szDeviceType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxDeviceName + 1)]
public string szDeviceName;
//
// X.25
//
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxPadType + 1)]
public string szX25PadType;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxX25Address + 1)]
public string szX25Address;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxFacilities + 1)]
public string szX25Facilities;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxUserData + 1)]
public string szX25UserData;
public int dwChannels;
//
// Reserved
//
public int dwReserved1;
public int dwReserved2;

//it is winCE500 dx
public int dwCustomAuthKey;

}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
struct RASDIALPARAMS
{
public int dwSize;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxEntryName + 1)]
public string szEntryName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxPhoneNumber + 1)]
public string szPhoneNumber;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.RAS_MaxCallbackNumber + 1)]
public string szCallbackNumber;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.UNLEN + 1)]
public string szUserName;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.PWLEN + 1)]
public string szPassword;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = (int)RasFieldSizeConstants.DNLEN + 1)]
public string szDomain;
//public uint dwSubEntry; //no need for WinCE
//public IntPtr dwCallbackId; //no need for WinCE
}

class RasConnection
{

[DllImport("coredll.dll", CharSet = CharSet.Auto)]
static extern uint RasDial(
[In]RASDIALEXTENSIONS lpRasDialExtensions,
[In]string lpszPhonebook,
[In]RASDIALPARAMS lpRasDialParams,
uint dwNotifierType,
Delegate lpvNotifier,
ref IntPtr lphRasConn);

//[DllImport("coredll.dll")]
//public static extern uint RasDial(IntPtr dialExtensions, IntPtr
//phoneBookPath, IntPtr rasDialParam, uint NotifierType,
//IntPtr notifier, ref IntPtr pRasConn);

[DllImport("coredll.dll")]
public static extern uint RasHangUp(IntPtr pRasConn);

[DllImport("coredll.dll")]
public static extern uint RasGetEntryProperties(string
lpszPhoneBook, string szEntry, ref RASENTRY lpEntry, ref int dwsize,
char[] lpb, ref uint lpdwSize);

//public static extern uint RasGetEntryProperties(string
//lpszPhoneBook, string szEntry, ref RASENTRY lpEntry, ref int dwsize,
//int lpbDeviceInfo, int lpdwSize);

[DllImport("coredll.dll")]
public static extern uint RasSetEntryProperties(string
lpszPhoneBook, string szEntry, ref RASENTRY lpEntry, int dwEntrySize,
char[] lpb, int dwSize);

[DllImport("coredll.dll")]
public static extern uint RasSetEntryDialParams(string
lpszPhoneBook, ref RASDIALPARAMS lpRasDialParams, bool
fRemovePassword);

[DllImport("coredll.dll", SetLastError = true)]
public static extern uint RasGetEntryDialParams(
string lpszPhonebook,
[In, Out] ref RASDIALPARAMS lprasdialparams,
out bool lpfPassword);
//[DllImport("coredll.dll")]
//public static extern uint RasSetEntryDialParams(string
//lpszPhoneBook, ref RASDIALPARAMS lpRasDialParams, bool
//fRemovePassword);


[StructLayout(LayoutKind.Sequential)]
internal class RasEapInfo
{
public Int32 dwSize = Marshal.SizeOf(typeof(RasEapInfo));
public Byte[] pbEapInfo = null;
}

[StructLayout(LayoutKind.Sequential)]
internal class RASDIALEXTENSIONS
{
public readonly int dwSize = Marshal.SizeOf(typeof(RASDIALEXTENSIONS));
public uint dwfOptions = 0;
public int hwndParent = 0;
public int reserved = 0;
public int reserved1 = 0;
public RasEapInfo RasEapInfo = new RasEapInfo();
}
//public void Connect()
//{
// // Define the dial parameters
// RasDialParams parms = new RasDialParams();
// parms.szDomain = this.Domain;
// parms.szUserName = this.UserName;
// parms.szPassword = this.Password;
// parms.szEntryName = this.PhonebookEntry;

// System.UInt32 retVal =
// RasDial(null, null, dialParms, 0, null, ref RasConnectionHandle);
//}
}

Thursday, November 6, 2008

Services for Windows Mobile in managed code

Services for Windows Mobile in managed code

Friday, April 18, 2008 @ 23:57

Services in Windows Mobile and Windows CE are DLL libraries loaded by service.exe and then run as ..... well as a services. Unfortunately these DLLs has to be written in native code. But why to use native code when man just needs little "invisible" application, that will survive Windows Mobile memory management?

ServiceApplication class

I wrote ServiceApplication class that is used in similar way as Application class in Windows Forms. In fact it is the console application with main loop that processes system messages. ServiceApplication can be controlled from outside world by interprocess messages. Simple WM_USER windows messages. The easiest service can look like this.

const int WM_USER = 0x400;
const int WM_QUIT_SERVICE = WM_USER + 5001;
const int WM_CLEAR_LOG = WM_USER + 5002;

static void Main(string[] args)
{
// Set register name
ServiceApplication.Name = "MyFirstService";

// Register messages
ServiceApplication.RegisterMessage(Interprocess.WM_QUIT_SERVICE);
ServiceApplication.RegisterMessage(Interprocess.WM_CLEAR_LOG);

// Set event handler for registered messages
ServiceApplication.OnRegisteredMessage +=
new ServiceApplication.RegisteredMessageEventHandler(ServiceApplication_OnRegisteredMessage);

// Start main application loop
ServiceApplication.Run();
}

There is a service name set, which is actually name of MessageWindows that represents the service. All messages to control the service is send to this MessageWindow. All messages that should be processed by service has to be registered. Whenever the registered message arrived, event is fired. Event handler may look like this.

static void ServiceApplication_OnRegisteredMessage(ref Microsoft.WindowsCE.Forms.Message message)
{
switch (message.Msg)
{
case Interprocess.WM_QUIT_SERVICE:
ServiceApplication.Exit();
break;

case Interprocess.WM_CLEAR_LOG:
ClearLogFile();
break;
}
}

Talking to service

As I mentioned earlier, service is controlled through windows messages. Following code sends message to the service.
const int WM_USER = 0x400;
const int WM_QUIT_SERVICE = WM_USER + 5001;
const int WM_CLEAR_LOG = WM_USER + 5002;

public void StopService()
{
IntPtr hwnd = FindWindow(IntPtr.Zero, "MyFirstService");
Message msg = Message.Create(hwnd, WM_QUIT_SERVICE, (IntPtr)0, (IntPtr)0);
MessageWindow.SendMessage(ref msg);
}

[DllImport("coredll.dll", EntryPoint = "FindWindow")]
public static extern IntPtr FindWindow(IntPtr lpClassName, string lpWindowName);

Example application

ServiceApplication class is bundled in little demo application. Whole solution consists of three projects. Fisrt project CallLoggerLib is library containing ServiceApplication class and Interprocess class for communication with service. Second project is service implementation itself. Very simple CallLoggerService thats logs information about last phone call into the file. Third project CallLogger is a simple UI application which is used to start and stop the service.

When deploying to the device all files has to be in same directory!!

Download file: CallLogger.zip [60 Kb]

CODEPLEX library

Updated at 9th June 2008.Peter Nowak did some improvements on my sample code and publish it as a complete library on Codeplex: Managed Services for Windows Mobile.

Firing thread safe events in Compact Framework

Firing thread safe events in Compact Framework

Friday, December 7, 2007 @ 09:54
Threading is one of the most important thing in application development on Windows platform. Almost none of the serious applications can run in single thread. You will always need to perform some operations on background. The only problem with threads is, when they try to share some critical resources. One of the typical case are UI elements. Whenever you try to change some UI control from different thread than UI thread you will end up with the exception.

Changing UI from thread

Before we look at the events, lets have a look at possibilities for changing UI from thread. All UI controls has methods Invoke and/or BeginInvoke. These methods accepts delegates as parameters. Invoking means, that the delegate given as the parameter will be exceuted in thread that is owner of the UI control. This will not cause parallel access to the UI resource, so no exception will be thrown.

The first option for invoking uses BeginInvoke method and WaitCallback delegate.

public partial class Form1 : Form
{
Thread thr;

public Form1()
{
InitializeComponent();
thr = new Thread(new ThreadStart(ThreadWorker2));
thr.Start();
}

private void ThreadWorker()
{
int i = 0;

while(true)
{
string message = string.Format("Value of i={0}", i++);
UpdateStatus(message);

Thread.Sleep(1000);
}
}

private void UpdateStatus(object status)
{
if (this.InvokeRequired)
{
this.BeginInvoke(new WaitCallback(UpdateStatus), status);
return;
}

label1.Text = (string)status;
}
}
This solution is suitable for most situations where simple status reporting is required. Disadvantage of this solution is the only one argument of WaitCallback delegate. In case of multiple informations to be given, you will need to pass structure or array as the argument. Anyway, I'am still using this solution a lot.

Second option offers more scalability and more arguments to be passed, because of custom delegate instead of the WaitCallback. Following code is also part of the previous Form1 class.

public delegate void StatusEventHandler(DateTime date, string message);

private void ThreadWorker2()
{
int i = 0;

StatusEventHandler statusHandler = UpdateStatus2;

while (true)
{
string message = string.Format("Value of i={0}",i++);
this.Invoke(statusHandler, new object[] { DateTime.Now, message});
Thread.Sleep(1000);
}
}

private void UpdateStatus2(DateTime date, string message)
{
label1.Text = date.ToShortTimeString();
label1.Text += " " + message;
}

Firing thread safe events

Applications are usually splited into two or three layers, where UI and business logic are different layers. When event comes from business layer to UI layer we need to update some status or information. Problem is, if logic in business layer is running in thread. In that case, we need to catch the event and pass the status into thread safe Invokation described above. Such a design is really lousy, because UI logic must in fact rethrow the event to itself and layers are no more strictly separated.

It is necessary to fire event in business layer thread safe way, so that UI layer can immidiately show the status. Since delegates and events in Compact Framework has no Target property as it's in full .NET Framework, we need some workaround. Let's have a look at following class. It is simple worker class representing business layer. Class has UIControl property which represent the UI control that will be Invoked. So FireStatusUpdate method Invokes the control and fires the event. This means, the event will be fired in thread which owns the UIControl.

using System;
using System.Windows.Forms;
using System.Threading;

namespace ThreadTest
{
public class WorkerClass
{
private Thread thr;

// UI control for update
public Control UIControl { get; set; }

public delegate void StatusUpdate(DateTime dateTime, string message);
public event StatusUpdate OnStatusUpdate;

// Starts thread
public void Start()
{
thr = new Thread(new ThreadStart(MainWorker));
thr.Start();
}

// Main thread worker
public void MainWorker()
{
int i = 0;

while (true)
{
string message = string.Format("Value of i={0}", i++);
FireStatusUpdate(DateTime.Now, message);

Thread.Sleep(1000);
}
}

// Fire thread safe event
private void FireStatusUpdate(DateTime dateTime, string message)
{
// UIControl is set and OnStatusUpdate has subscriber
if (UIControl != null && OnStatusUpdate != null)
{
if (UIControl.InvokeRequired)
{
UIControl.Invoke(new StatusUpdate(FireStatusUpdate),
new object[] { dateTime, message });
return;
}

OnStatusUpdate(dateTime, message);
}
}
}
}

Following code is simple UI layer for WorkingClass.

using System;
using System.Drawing;
using System.Windows.Forms;

namespace ThreadTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();

WorkerClass worker = new WorkerClass();
// add event handler
worker.OnStatusUpdate += new WorkerClass.StatusUpdate(worker_OnStatusUpdate);
// add UI control to invoke
worker.UIControl = this;
worker.Start();
}

void worker_OnStatusUpdate(DateTime dateTime, string message)
{
label1.Text = dateTime.ToLongTimeString();
label1.Text += " " + message;
}
}

Thread safe events in full framework

Following snippet shows the modification of the FireStatusUpdate method, to be used in full .NET Framework. There is no need for UIControl property, because delegates contains automaticaly filled property Target.
// Fire thread safe event
private void FireStatusUpdate(DateTime dateTime, string message)
{
// if OnStatusUpdate has subscriber
if (OnStatusUpdate != null)
{
// List all handlers
foreach (StatusUpdate handler in OnStatusUpdate.GetInvocationList())
{
// if handler target is control then Invoke it
if (handler.Target is Control)
(handler.Target as Control).Invoke(handler, new object[] { dateTime, message });
else
handler(dateTime, message);
}
}
}

Input mode in smart phone application

Input mode in smart phone application

Friday, October 5, 2007 @ 14:03
If you ever used TextBox control in smart phone application, you may found a bit confusing that input mode is selected to numbers. Entering alphabetic strings is then quite uncomfortable. Solution for this behavior is already included in .NET Compact Framework, but not so many coders knows about it.

InputModeEditor

Microsoft.WindowsCE.Forms namespace contains class InputModeEditor with single static method SetInputMode that takes two arguments. First parametr is the object that takes the input (usually TextBox), second one is the enumeration InputMode which contains values like AlphaABC, AlphaT9, Numeric etc.. Usage is obvious:
using Microsoft.WindowsCE.Forms;

......

InputModeEditor.SetInputMode(textBox1, InputMode.AlphaABC);

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);