Voices from the Code Collective
Wednesday, July 23, 2003
 
A link to a good tutorial on Regular Expression

Link

Thanks Reinout Hillmann on Codeproject

Thursday, July 17, 2003
 
A program (with code) from intel that allows you to see if Hyperthreading is on, and how many phyisical processors are actually in the system...


Link

Saturday, July 12, 2003
 
A link on CodePoject to a C# data structures and algorithm book...

Link

Thanks leppie...

Monday, July 07, 2003
 
This is a snippet of C++ code that returns the CPU Speed in mhz. This has only been tested on Windows computers.

// returns the CPU speed of the processor in the system

int GetCPUSpeed(void)
{
LARGE_INTEGER ulFreq, ulTicks, ulValue,
ulStartCounter, ulEAX_EDX, ulResult;

// it is number of ticks per seconds
QueryPerformanceFrequency(&ulFreq);

// current valueofthe performance counter
QueryPerformanceCounter(&ulTicks);

// calculate one second interval
ulValue.QuadPart = ulTicks.QuadPart + ulFreq.QuadPart;

// read time stamp counter
// this asm instruction load the highorder 32 bit of the register into EDX
// and the lower order 32 bits into EAX
_asm {
rdtsc
mov ulEAX_EDX.LowPart, EAX
mov ulEAX_EDX.HighPart, EDX
}

// start no of ticks
ulStartCounter.QuadPart = ulEAX_EDX.QuadPart;

// loop for 1 second
do {
QueryPerformanceCounter(&ulTicks);
} while (ulTicks.QuadPart <= ulValue.QuadPart);

// get the actual no of ticks
_asm {
rdtsc
mov ulEAX_EDX.LowPart, EAX
mov ulEAX_EDX.HighPart, EDX
}

// calculate result
ulResult.QuadPart = ulEAX_EDX.QuadPart - ulStartCounter.QuadPart;

return (int)ulResult.QuadPart / 1000000;
}


Tuesday, July 01, 2003
 
An article about using a PocketPC for a remote of another computer.

Article
Monday, June 30, 2003
 
This fixes the problem of flickering controls when doing GDI+ in the on paint event.

Taken from dotnetmagic tips.

Flicker free drawing in Controls

You have just spent several days writing a beautiful looking custom control but are faced with one last problem that is spoiling the whole effect. Whenever the control is redrawn it flickers. This is most obvious when the control is being resized and so redrawn many times in succession.
Solving this problem is very easy with the .NET Framework. If you come from a C++ and GDI background then the solution was to create a memory based bitmap, draw the control onto the bitmap and then blit this to the screen (otherwise known as double buffering). This is such a common requirement that the UserControl class actually implements this functionality for you. All you need to do is include the following two lines of code into your class constructor.


SetStyle(ControlStyles.DoubleBuffer, true);
SetStyle(ControlStyles.AllPaintingInWmPaint, true);


The first line will request that double buffering be used whenever the OnBackground or OnPaint methods are called. This will reduce the amount of flicker but may not remove it completely as painting the whole control still results in two separate blitting operations.
The second line of code above is used to ensure that only a single blitting operation occurs when drawing. This occurs when the underlying windows WM_PAINT message is processed. When this happens it will create the memory bitmap, call the OnBackground method, call the OnPaint method and then finally blit the result to the screen.

The only drawback to this technique is the greater use of resources. However, most controls are relatively small in screen size and so this is unlikely to be an issue.



 
A post on the compact framework talking about writing functions that are unmanaged for use in Managed code... ie writing C++ dlls that are usable in the compact framework...

Link to article
 
Yet another thing MS left from the compact framework :)


Link to Article


using System;
using System.Runtime.InteropServices;

namespace PocketGuid
{
///
/// Generate GUIDs on the .NET Compact Framework.
///

public class PocketGuid
{
// guid variant types
private enum GuidVariant
{
ReservedNCS = 0x00,
Standard = 0x02,
ReservedMicrosoft = 0x06,
ReservedFuture = 0x07
}

// guid version types
private enum GuidVersion
{
TimeBased = 0x01,
Reserved = 0x02,
NameBased = 0x03,
Random = 0x04
}

// constants that are used in the class
private class Const
{
// number of bytes in guid
public const int ByteArraySize = 16;

// multiplex variant info
public const int VariantByte = 8;
public const int VariantByteMask = 0x3f;
public const int VariantByteShift = 6;

// multiplex version info
public const int VersionByte = 7;
public const int VersionByteMask = 0x0f;
public const int VersionByteShift = 4;
}

// imports for the crypto api functions
private class WinApi
{
public const uint PROV_RSA_FULL = 1;
public const uint CRYPT_VERIFYCONTEXT = 0xf0000000;

[DllImport("coredll.dll")]
public static extern bool CryptAcquireContext(
ref IntPtr phProv, string pszContainer, string pszProvider,
uint dwProvType, uint dwFlags);

[DllImport("coredll.dll")]
public static extern bool CryptReleaseContext(
IntPtr hProv, uint dwFlags);

[DllImport("coredll.dll")]
public static extern bool CryptGenRandom(
IntPtr hProv, int dwLen, byte[] pbBuffer);
}

// all static methods
private PocketGuid()
{
}

///
/// Return a new System.Guid object.
///

public static Guid NewGuid()
{
IntPtr hCryptProv = IntPtr.Zero;
Guid guid = Guid.Empty;

try
{
// holds random bits for guid
byte[] bits = new byte[Const.ByteArraySize];

// get crypto provider handle
if (!WinApi.CryptAcquireContext(ref hCryptProv, null, null,
WinApi.PROV_RSA_FULL, WinApi.CRYPT_VERIFYCONTEXT))
{
throw new SystemException(
"Failed to acquire cryptography handle.");
}

// generate a 128 bit (16 byte) cryptographically random number
if (!WinApi.CryptGenRandom(hCryptProv, bits.Length, bits))
{
throw new SystemException(
"Failed to generate cryptography random bytes.");
}

// set the variant
bits[Const.VariantByte] &= Const.VariantByteMask;
bits[Const.VariantByte] |=
((int)GuidVariant.Standard << Const.VariantByteShift);

// set the version
bits[Const.VersionByte] &= Const.VersionByteMask;
bits[Const.VersionByte] |=
((int)GuidVersion.Random << Const.VersionByteShift);

// create the new System.Guid object
guid = new Guid(bits);
}
finally
{
// release the crypto provider handle
if (hCryptProv != IntPtr.Zero)
WinApi.CryptReleaseContext(hCryptProv, 0);
}

return guid;
}
}
}

 
Just found this for the compact framework. It allows a developer to find the application path of the currently executing application (C#). Seems MS left this off the framework api.


private void button1_Click(object sender, System.EventArgs e)
{
string path;
path = System.IO.Path.GetDirectoryName(
System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );
MessageBox.Show( path );
}

Sunday, June 29, 2003
 
Came across this code at CodeProject.com. This makes it easy to use a SingleInstance Application.

using System;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;

namespace SingleInstance
{
///
/// Summary description for SingleApp.
///

public class SingleApplication
{
public SingleApplication()
{

}
///
/// Imports
///


[DllImport("user32.Dll")]
private static extern int EnumWindows(EnumWinCallBack callBackFunc, int lParam);

[DllImport("User32.Dll")]
private static extern void GetWindowText(int hWnd, StringBuilder str, int nMaxCount);

[DllImport("user32.dll",EntryPoint="SetForegroundWindow")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern Boolean ShowWindow(IntPtr hWnd,Int32 nCmdShow);

///
/// EnumWindowCallBack
///

///
///
///
private static bool EnumWindowCallBack(int hwnd, int lParam)
{
windowHandle = (IntPtr)hwnd;

StringBuilder sbuilder = new StringBuilder(256);
GetWindowText((int)windowHandle, sbuilder, sbuilder.Capacity);
string strTitle = sbuilder.ToString();

if(strTitle == sTitle)
{
ShowWindow(windowHandle, SW_RESTORE);
SetForegroundWindow(windowHandle);
return false;
}
return true;
}//EnumWindowCallBack

///
/// Execute a form base application if another instance already running on
/// the system activate previous one
///

/// main form
/// true if no previous instance is running
public static bool Run(System.Windows.Forms.Form frmMain)
{
sTitle = frmMain.Text;

if( EnumWindows (new EnumWinCallBack(EnumWindowCallBack), 0) == 0)
{
return false;
}
Application.Run(frmMain);
return true;
}

///
///
///

///
public static bool Run()
{
Process pr = Process.GetCurrentProcess();
string strProcessName = pr.ProcessName;
if(System.Diagnostics.Process.GetProcessesByName(strProcessName).Length > 1)
{
return false;
}
return true;
}

const int SW_RESTORE = 9;
static string sTitle;
static IntPtr windowHandle;
delegate bool EnumWinCallBack(int hwnd, int lParam);
}
}

Friday, June 27, 2003
 
Hehe, my first post was VB.NET... Here is the same thing in C#... Oh and look at all the pretty colors :)


private static void FileCopy(string srcdir, string destdir, bool recursive)
{
DirectoryInfo dir;
FileInfo[] files;
DirectoryInfo[] dirs;
string tmppath;

//determine if the destination directory exists, if not create it
if (! Directory.Exists(destdir))
{
Directory.CreateDirectory(destdir);
}

dir = new DirectoryInfo(srcdir);

//if the source dir doesn't exist, throw
if (! dir.Exists)
{
throw new ArgumentException("source dir doesn't exist -> " + srcdir);
}

//get all files in the current dir
files = dir.GetFiles();

//loop through each file
foreach(FileInfo file in files)
{
//create the path to where this file should be in destdir
tmppath=Path.Combine(destdir, file.Name);

//copy file to dest dir
file.CopyTo(tmppath, false);
}

//cleanup
files = null;

//if not recursive, all work is done
if (! recursive)
{
return;
}

//otherwise, get dirs
dirs = dir.GetDirectories();

//loop through each sub directory in the current dir
foreach(DirectoryInfo subdir in dirs)
{
//create the path to the directory in destdir
tmppath = Path.Combine(destdir, subdir.Name);

//recursively call this function over and over again
//with each new dir.
FileCopy(subdir.FullName, tmppath, recursive);
}

//cleanup
dirs = null;

dir = null;
}

 
Yuck, my first post is about VB (atleast it is VB.NET). I came upon the need for this while working in Visual Studio .NET and wanted to write a macro that would do some of the monotonous build stuff for me. Enjoy...



' Usage:
' Copy Recursive with Overwrite if exists.
' RecursiveDirectoryCopy("C:\Data", "D:\Data", True, True)
' Copy Recursive without Overwriting.
' RecursiveDirectoryCopy("C:\Data", "D:\Data", True, False)
' Copy this directory Only. Overwrite if exists.
' RecursiveDirectoryCopy("C:\Data", "D:\Data", False, True)
' Copy this directory only without overwriting.
' RecursiveDirectoryCopy("C:\Data", "D:\Data", False, False)

' Recursively copy all files and subdirectories from the specified source to the specified
' destination.
Private Sub RecursiveDirectoryCopy(ByVal sourceDir As String, ByVal destDir As String, ByVal fRecursive As Boolean, ByVal overWrite As Boolean)
Dim sDir As String
Dim dDirInfo As IO.DirectoryInfo
Dim sDirInfo As IO.DirectoryInfo
Dim sFile As String
Dim sFileInfo As IO.FileInfo
Dim dFileInfo As IO.FileInfo
' Add trailing separators to the supplied paths if they don't exist.
If Not sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
sourceDir &= System.IO.Path.DirectorySeparatorChar
End If
If Not destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
destDir &= System.IO.Path.DirectorySeparatorChar
End If
'If destination directory does not exist, create it.
dDirInfo = New System.IO.DirectoryInfo(destDir)
If dDirInfo.Exists = False Then dDirInfo.Create()
dDirInfo = Nothing
' Recursive switch to continue drilling down into directory structure.
If fRecursive Then
' Get a list of directories from the current parent.
For Each sDir In System.IO.Directory.GetDirectories(sourceDir)
sDirInfo = New System.IO.DirectoryInfo(sDir)
dDirInfo = New System.IO.DirectoryInfo(destDir & sDirInfo.Name)
' Create the directory if it does not exist.
If dDirInfo.Exists = False Then dDirInfo.Create()
' Since we are in recursive mode, copy the children also
RecursiveDirectoryCopy(sDirInfo.FullName, dDirInfo.FullName, fRecursive, overWrite)
sDirInfo = Nothing
dDirInfo = Nothing
Next
End If
' Get the files from the current parent.
For Each sFile In System.IO.Directory.GetFiles(sourceDir)
sFileInfo = New System.IO.FileInfo(sFile)
dFileInfo = New System.IO.FileInfo(Replace(sFile, sourceDir, destDir))
'If File does not exist. Copy.
If dFileInfo.Exists = False Then
sFileInfo.CopyTo(dFileInfo.FullName, overWrite)
Else
'If file exists and is the same length (size). Skip.
'If file exists and is of different Length (size) and overwrite = True. Copy
If sFileInfo.Length <> dFileInfo.Length AndAlso overWrite Then
sFileInfo.CopyTo(dFileInfo.FullName, overWrite)
'If file exists and is of different Length (size) and overwrite = False. Skip
ElseIf sFileInfo.Length <> dFileInfo.Length AndAlso Not overWrite Then
Debug.WriteLine(sFileInfo.FullName & " Not copied.")
End If
End If
sFileInfo = Nothing
dFileInfo = Nothing
Next
End Sub


Powered by Blogger