Code Repo    |     RSS
MD's Technical Sharing



Sunday, April 26, 2009

Mount a Virtual PC's VHD disk image

Virtual Server 2005 R2 SP1 Beta 2 includes 'vhdmount' - a tool to allow you to mount a virtual hard disk directly on your host operating system. While vhdmount is provided as a command line tool - a very small amount of work will allow you to mount VHDs by just double clicking on them. By creating a .reg file with the following contents:


Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Virtual.Machine.HD]

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Virtual.Machine.HD\shell]

@="Mount"

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Virtual.Machine.HD\shell\Dismount]

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Virtual.Machine.HD\shell\Dismount\command]

@="\"C:\\Program Files\\Microsoft Virtual Server\\Vhdmount\\vhdmount.exe\" /u \"%1\""

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Virtual.Machine.HD\shell\Mount]

[HKEY_LOCAL_MACHINE\SOFTWARE\Classes\Virtual.Machine.HD\shell\Mount\command]

@="\"C:\\Program Files\\Microsoft Virtual Server\\Vhdmount\\vhdmount.exe\" /p \"%1\""

[HKEY_CLASSES_ROOT\.vhd]

@="Virtual.Machine.HD"


And then double clicking on the .reg file (to load it into your registry) you will be able to double click a VHD to mount it, and right click on it to dismount it.


Reference: http://blogs.msdn.com/virtual_pc_guy/archive/2006/09/01/734435.aspx

Read More »

Building First Windows Embedded Image

This guide will show you how to build the simplest Windows Embedded image running on Microsoft Virtual PC. You must first download the Windows Embedded Evaluation version as well as Microsoft Virtual PC 2007
  1. Create a Virtual PC running Windows XP or Windows Server 2003.
  2. Copy C:\Program Files\Windows Embedded\utilities\tap.exe to a folder on the Virtual PC
  3. Run tap.exe (Target Analyser Probe). This will analyse the configuration of the hardware, in this case, the Virtual PC, and save it into a .pmq file.
  4. Run Target Designer (insite Programs/Microsoft Windows Embedded Studio) and create a new .slx target file (File/New)
  5. Import the .pmq configuration file we created ealier (File/Import). This may take a few minutes
  6. Target Designer will then proceed to add all the components required to run Windows Embedded on the targeted hardware onto our image.
  7. Now check if any required components are missing via Configuration/Check Dependencies
  8. If any components are missing, Target Designer will flag them as error under Task List. Double click on each task and follow the on-screen instructions to add the required components
  9. Repeat Step 7 and 8 until no more errors are flagged.
  10. Now build the target image via Configuration/Build Target Image. The build output is by default located at C:\Windows Embedded Images
  11. Now create a new Virtual PC machine having a new virtual hard disk.
  12. Use Drive Management available under Control Panel/Administrative Tools/Computer Management to format this the virtual hard disk of the newly created machine. Remember to mark the partition as primary and active.
  13. Copy the build output of step 10 onto the formatted hard disk. This can either be done by attaching the virtual hard disk to another Virtual PC, or by using a tool such as WinImage
  14. Start the Virtual PC we created in step 11. Windows Embedded will boot up with First Boot Agent doing all the installation process.
  15. Done!
Read More »

Saturday, April 18, 2009

Corrupted Outlook Personal Folders

Symptoms:

"Microsoft Office Outlook: The set of folders could not be opened."

There is a [Show Help >>] button. If clicked, it says:

"This error usually appears if the OST or PST file you are using is:

- Unavailable

- Protected with file permissions

- On a share on a server and the network is down

- Corrupt

To correct this problem, store the OST or PST file on the local computer. You may also want to run the scanost.exe and scanpst.exe tools to verify file integrity. More information about this error message online."


Solution:

1. Quit outlook.

2. Go to

C:\Documents and Settings\Username\Local Settings\Application Data\Microsoft\Outlook

3. Delete the PST file which corresponds to the corrupted folder.

4. Restart Outlook.


Reference

http://www.computing.net/answers/office/corrupted-outlook-personal-folders/4940.html>

Read More »

Outlook on the Desktop

This is a free software to show your Outlook calendar, notes and tasks on your Windows desktop.
  • Places fully functional Microsoft Outlook Calendar on your Desktop.
  • The Outlook Calendar is pinned to your desktop so that no windows can get stuck behind it.
  • The Calendar's position, size and opacity are all adjustable via a very intuitive GUI.
  • A tray Icon (complete with the day of the month) is provided to to configure the app and perform other actions.
  • Multiple-Monitor Support.
  • Ability to switch between calendar, inbox, contacts, tasks and notes views.
Reference: http://www.outlookonthedesktop.com/
Read More »

Friday, April 17, 2009

KeyTweak - Remap system keys

Keytweak is a free keyboard remapper for Windows NT/2000/XP/Vista/Win 7. It makes use of Microsoft's Scancode Map registry key to remap your keyboard.


KeyTweak cannot affect the Fn key on most laptops since that key doesn't generate scancodes.


A reboot is required for changes to key mapping to take effect.


Reference:
http://webpages.charter.net/krumsick

Read More »

Showing Outlok appointments, tasks, notes on the desktop

Requirements

- Active Desktop Calendar 5.6 or later
- Microsoft® Outlook® 2000, XP, 2003, 2007

Active Desktop Calendar can read appointments and tasks directly from Outlook and show them on the desktop.

You will get all tasks and next seven days of appointments from Outlook's default calendar visible both in Active Desktop Calendar and on the desktop together with other information you might have in Active Desktop Calendar's data layers.


Reference: http://xemico.com/adc/infocenter/outlook.html

Read More »

Monday, April 13, 2009

Form.Show() and Form.ShowDialog()

Form.Show() is an asynchronous call. Subsequent section of codes will run while the form is being loaded. Form.ShowDialog() is a blocking call - it will block until the form is closed.


In VB.NET, if we access a form directly without creating any instance (e.g. Form.Show()), .NET will automatically create 1 instance of the form for use. Even if the form is not visible, the instance continue to stay in memory until we call Form.Close().


This is not possible in C#, however. In C#, we must explicitly declare an instance of the form:


Form myForm = new Form();
myForm.Show()

Read More »

Bring an application's active window to foreground

1. On Windows CE/Windows Mobile only 1 instance of any executable file is allowed to run at a time. The following will start the application if it's not running, OR bring its active window to the foreground if it's already running


Process.Start(Assembly.GetExecutingAssembly().GetModules(0).FullyQualifiedName, "")


The code can be called by the application itself, or by a different application. It will not work if the application is busy at the time the code is executed.


2. On both Windows CE and Windows XP, we can do so by finding the active window handle and call SetForegroundWindow


This makes use of the MainWindowHandle property of the .NET's Process class to retrieve the handle to the active window of the current process.


SetForegroundWindow(Process.GetCurrentProcess().MainWindowHandle)


3. In Win32 C++


Making a window the foreground window requires more than just calling the SetForegroundWindow API. You must first determine the foreground thread and attach it to your window, using AttachThreadInput, then call SetForegroundWindow. That way they can share input states.


First I call GetForegroundWindow to get the handle of the current foreground window. Then a few calls to GetWindowThreadProcessId retrieve the threads associated with the current foreground window and the window I want to bring to the foreground. If these threads are the same a simple call to SetForegroundWindow is all that is necessary. Otherwise, the foreground thread is attached to the window that I am bringing to the front and detached from what was the current foreground window. The AttachThreadInput API handles this.


Once this is accomplished, the state of the window is determined. If IsIconic says that the window is minimized, I restore it by issuing ShowWindow with the SW_RESTORE flag. Otherwise ShowWindow is called with the SW_SHOW flag.


Reference:


Simulate Window's Alt-Tab List and
Bring a Window to the Foreground, http://www.thescarms.com/vbasic/alttab.aspx

Read More »

Saturday, April 11, 2009

Retrieve ICC-ID (printed on SIM card) using SIM APIs

The ICCID (also known as the SIM Serial Number, SSN) is the 19-digit number printed on the plastic housing surrounding the SIM module.

It's not too difficult to retrieve this number and you can use the SIM Manager API to do it. The 3 functions in the SIM Manager API that we are interested in are SimInitialize, SimDeinitialize, and SimReadRecord.

SimReadRecord is a privileged function. You either need to lower the security configuration on your
device to
Prompt One Tier or lower using the Device Security Manager, or sign your code with a privileged certificate.

The P/Invoke prototypes for these functions are pretty self-explanatory and don't require any
complex marshaling. Here they are in all their glory:

<DllImport("cellcore.dll")> _
Shared Function SimInitialize( _
ByVal dwFlags As Integer, _
ByVal lpfnCallback As IntPtr, _
ByVal dwParam As Integer, _
ByRef lphSim As IntPtr) As Integer
End Function

<DllImport(
"cellcore.dll")> _
Shared Function SimDeinitialize( _
ByVal hSim As IntPtr) As Integer
End Function

<DllImport(
"cellcore.dll")> _
Shared Function SimReadRecord( _
ByVal hSim As IntPtr, _
ByVal dwAddress As Integer, _
ByVal dwRecordType As Integer, _
ByVal dwIndex As Integer, _
ByVal lpData() As Byte, _
ByVal dwBufferSize As Integer, _
ByRef dwSize As Integer) As Integer
End Function

The key to retrieving
the ICCID is the call to
SimReadRecord.
This will allow us to retrieve a elementary file from the SIM's EEPROM.
SimReadRecord takes an address of the record we want to read. This address is
defined as
EF_ICCID below:

Dim EF_ICCID As Integer = &H2FE2
Dim SIM_RECORDTYPE_TRANSPARENT As Integer = 1

With the infrastructure code out of the way, we're now ready to execute the sequence to
retrieve the ICCID.

Dim hSim As IntPtr
Dim iccid(9)As Byte
SimInitialize(0, IntPtr.Zero, 0, hSim)
SimReadRecord(hSim, EF_ICCID, SIM_RECORDTYPE_TRANSPARENT, 0, iccid,
iccid.Length, 0)
SimDeinitialize(hSim)
Dim SimSerialNumber AsString = FormatAsSimString(iccid)

FormatAsSimString is a method that I wrote to convert the ICCID byte array into the same format as printed on the SIM card. SimSerialNumber will be formatted string that looks something like this:

111111 22222 3333 4444

If you compare the bytes in the ICCID array to the digits printed on the SIM card, you'll note they don't quite match up. This is because the ICCID array is an array of 4-bit unsigned integers in little endian order. For example, if the first 6 digits of your ICCID is 894412, they will appear as 0x98, 0x44, 0x21 in the byte array. The helper method below will convert a pair of 4-bit integers (i.e, a byte) into
a string.

Read More »

C++ String Code Snippets

Split a string


http://bytes.com/forum/thread221760.html

http://msdn.microsoft.com/en-us/library/2c8d19sb(VS.80).aspx


We are going to use wcstok to split string into tokens using separators. This function modifies the original string. Therefore, the original string cannot be declared as below:


wchar_t *testStr = L"Hello world";


This will cause Access Violation when wcstok attempts to modify the string since the pointer returned by L"" is a constant pointer. We must declare a string buffer and copy a string constant into that buffer as followed:

wchar_t *testStr = new wchar_t[100];

LPTSTR testStr2 = _T("Hello World;Hello World 1;Hello World 2;Hello World 3;Hello World 4");

wcscpy(testStr, testStr2);

const wchar_t *seps = _T(";");


Or alternatively:


WCHAR testStr2[] = _T("Hello World;Hello World 1;Hello World 2;Hello World 3;Hello World 4");

const WCHAR seps = ';';


The rest is straightforward:


// Establish string and get the first token:

wchar_t* token = wcstok(testStr, seps);

// print the first and the next tokens, if any

while (token != NULL)

{

printf("%S\n", token);

token = wcstok(NULL, seps);

}


Concatenate strings & compare strings:


//Result: szPath contains 'C:\Program Files\app.exe'

LPCTSTR pszInstallDir = L"C:\\Program Files";

const wchar_t *appExecutable = _T("app.exe");

TCHAR szPath[MAX_PATH];

_tcscpy(szPath, pszInstallDir);

_tcscat(szPath, _T("\\"));

_tcscat(szPath, appExecutable);

//returns TRUE since szPath contains appExecutable

BOOL contains = _tcsstr(szPath, appExecutable);


Load a string from resource:


LPWSTR str = new wchar_t[MAX_PATH];

LoadString(GetModuleHandle(IMAGENAME), IDS_str, str, MAX_PATH);


IMAGENAME: name of the executabe/dll owning the resource file

IDS_str: name of the resource

Str: the resource value


ANSI string to and from wide string

char* ch = "Hello";

wchar_t *wa = new wchar_t[50];

mbstowcs(wa, ch, 50);

wchar_t *wa = L"Hello";

char* ch = new char[MAX_PATH];

wcstombs(ch, wa, MAX_PATH);


String to Integer and vice versa


In C:

char *a = "137.5";

float b = 0;

sscanf(a, "%f", &b);

printf("b = %f", b);


In C++:

std::string a = "137.5";

std::istringstream b(a);

float f;

b >> f;


Using _itoa/itow for integer to string and _atoi64/_itoa64 for string to integer


Syntax



wchar_t * _itow(int value, wchar_t (&str)[size], int radix );

value

Number to be converted.

str

String result.

Radix

which must be in the range 2–36


Sample:


char buffer[65];

int r;

_itoa(137.5, buffer, 10);

Read More »

Thursday, April 9, 2009

Useful Conversion in C++

BYTE[] to DWORD:

BYTE tzValue[4];

DWORD value = tzValue[3]*16*16*16 + tzValue[2]*16*16 + tzValue[1]*16 + tzValue[0];


Print hexadecimal:

printf("Value: 0x%08lx\n", value);


BYTE[] to WCHAR:

BYTE tzValue[MAX_PATH];

WCHAR* strDest = (WCHAR*) &tzValue[0];


Merge 2 WORDs into a DWORD:

WORD wLow;

WORD wHigh;

DWORD dw = wLow + 0x1000*wHigh;


BSTR to (char*)

BSTR st;

char* st = (const char*)_bstr_t(st);



Read More »

Sunday, April 5, 2009

Configuring Visual Studio to Debug .NET Framework Source Code

1. Install the Visual Studio 2008 QFE. Note this functionality is not available on the Express versions of the Visual Studio 2008 products.

2. Start Visual Studio 2008 and bring up Tools > Options > Debugging > General. If you are running under the Visual Basic Profile, you will need to check the box on the lower left of the Options Dialog marked "Show All Settings" before continuing (other profiles won't have this option).

Set the following two settings:
Turn OFF the "Enable Just My Code" setting
Turn ON the "Enable Source Server Support" setting

3. Next, bring up the "Symbols" Page and set the symbols download URL and a cache location. Specifically, set the three settings below:

Set the symbol file location to be: http://referencesource.microsoft.com/symbols
Set a cache location. Make sure this is a location that your account has read/write access to. A good option for this is to place this path somewhere under your user hive (e.g. c:\users\sburke\symbols)

Alternatively, use NetMassDownloader for the .Net Framework which allows you do download .Net Framework source code in batch mode.


Reference


Full reference source code for .NET framework: http://referencesource.microsoft.com/netframework.aspx

Read More »

Saturday, April 4, 2009

Validate text using RegEx

'Email address:
Regex.IsMatch(
Me.txtEmail.Text, "\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*")

'Alpha-numeric (no space):
Regex.IsMatch(
Me.txtUsername.Text, "^[0-9a-zA-Z]+$")

'Alpha-numeric with space, at least 5 chars:
Regex.IsMatch(
Me.txtUsername.Text, "[0-9a-zA-Z' ']{5,} )

Read More »

Friday, April 3, 2009

.NET Useful Cast & Conversions

Memory Stream to String

Dim str As String = New StreamReader(stream).ReadToEnd


Byte Array to String and vice versa

Dim SMSCData(0 To 50) As Byte
Dim smsc as String = Encoding.ASCII.GetString(SMSCData, 0, SMSCData.Length)
Dim password As String
Dim passwArray As Byte() = Encoding.ASCII.GetBytes(password)

Read More »

Wednesday, April 1, 2009

Application.DoEvents and MessageBox

If the user clicks 'Yes', the following will close the messagebox first before doing any other thing.


Private Sub TestMsgBox()
If MessageBox.Show("Do Work?", "Confirm?") = Windows.Forms.DialogResult.Yes Then
'this close the MessageBox first
Application.DoEvents()

'start to do work
……………..
End If
End Sub


Without the call to Application.DoEvents (), the messagebox will still be visible after the user clicks Yes; it will only be closed after the Sub has finished.


An alternative is to do the work in a separate thread.

Read More »